@capxul/sdk 1.0.0-alpha.9 → 1.2.0

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.
Files changed (32) hide show
  1. package/README.md +121 -6
  2. package/dist/{InMemoryAuthCacheAdapter-v5W-XB5M.mjs → InMemoryAuthCacheAdapter-Dr1sEd9y.mjs} +36 -16
  3. package/dist/InMemoryAuthCacheAdapter-Dr1sEd9y.mjs.map +1 -0
  4. package/dist/create-capxul-client-C7H5b68l.d.mts +2764 -0
  5. package/dist/create-capxul-client-C7H5b68l.d.mts.map +1 -0
  6. package/dist/create-capxul-client-DiqVIxsV.mjs +6980 -0
  7. package/dist/create-capxul-client-DiqVIxsV.mjs.map +1 -0
  8. package/dist/index.d.mts +119 -2020
  9. package/dist/index.d.mts.map +1 -1
  10. package/dist/index.mjs +2464 -6308
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/node/index.d.mts +3 -6
  13. package/dist/node/index.d.mts.map +1 -1
  14. package/dist/node/index.mjs +27 -27
  15. package/dist/node/index.mjs.map +1 -1
  16. package/dist/signer-CJT0pPiO.d.mts +301 -0
  17. package/dist/signer-CJT0pPiO.d.mts.map +1 -0
  18. package/dist/testing/index.d.mts +54 -0
  19. package/dist/testing/index.d.mts.map +1 -0
  20. package/dist/testing/index.mjs +1068 -0
  21. package/dist/testing/index.mjs.map +1 -0
  22. package/package.json +17 -18
  23. package/dist/InMemoryAuthCacheAdapter-v5W-XB5M.mjs.map +0 -1
  24. package/dist/index-CTXgQ_xR.d.mts +0 -158
  25. package/dist/index-CTXgQ_xR.d.mts.map +0 -1
  26. package/dist/ports/safe-deployment.d.mts +0 -2
  27. package/dist/ports/safe-deployment.mjs +0 -38
  28. package/dist/ports/safe-deployment.mjs.map +0 -1
  29. package/dist/safe-deployment-D3k9yndM.d.mts +0 -136
  30. package/dist/safe-deployment-D3k9yndM.d.mts.map +0 -1
  31. package/dist/signer-DqDtJU1l.d.mts +0 -145
  32. package/dist/signer-DqDtJU1l.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["_exhaustive","processLike","EVM_ADDRESS_HEX","ECDSA_SIGNATURE_HEX","SAFE_OP_DIGEST_HEX","recoverRawDigestSigner","withSignal","DEFAULT_JWT_LIFETIME_S","decodeJwtExp","authSessionFromBetterAuth","safeJson","isAbortError","mapFetchError","AppIdSchema","ChainIdSchema","CurrencyCodeSchema","DocumentHashSchema","EpochMsSchema","DurationMsSchema","AppIdSchema","ChainIdSchema","EpochMsSchema","DurationMsSchema","ChainIdSchema","CurrencyCodeSchema","DocumentHashSchema","EpochMsSchema","#client","#tokenProvider","#convex","catalog","parseEnvValue","parseCatalogEnvValue","#source","#convex","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#chainId","#runMutation","#runQuery","DEFAULT_FUNCTIONS","#convex","#fns","EVM_ADDRESS_RE","cloneProps","cloneTelemetryValue","#capture","#identify","#group","#reset","#runFireAndForget","#convex","#call","emailDomain","cryptoApi","processLike","processLike","sdkPackageJson.version","createCapxulClient","createCapxulClientFromProductionAdapters"],"sources":["../../config/src/tokens.ts","../../config/src/safe.ts","../../config/src/binding.ts","../../config/src/org-payments.ts","../../config/src/route.ts","../../config/src/role-dsl.ts","../../config/src/org-zodiac.ts","../src/telemetry/stack-frame-parser.ts","../src/telemetry/get-failure-mode.ts","../src/telemetry/capture-exception.ts","../src/client/_shared/effect-actor-bridge.ts","../src/client/_shared/provisioning-telemetry.ts","../src/client/account-deps.ts","../src/client/account-lane.ts","../src/client/account-lifecycle.ts","../src/client/to-capxul-result.ts","../src/client/account.ts","../src/client/account-providers.ts","../src/signer.ts","../src/dev-signer.ts","../src/adapters/openfort/embedded-wallet-port.ts","../src/openfort-embedded-signer.ts","../package.json","../src/ports/auth-client.ts","../src/adapters/auth-client/effect-port.ts","../src/adapters/auth-client/resolve-auth-url.ts","../src/adapters/auth-client/BetterAuthBrowserAdapter.ts","../src/adapters/auth-client/cookie-jar.ts","../src/adapters/auth-client/BetterAuthNodeAdapter.ts","../../wire/src/brands.ts","../../wire/src/bootstrap.ts","../../wire/src/financial-ops.ts","../../wire/src/document-render.ts","../src/ports/bootstrap.ts","../src/adapters/bootstrap/HttpBootstrapAdapter.ts","../src/ports/clock.ts","../src/adapters/clock/SystemClockAdapter.ts","../src/ports/convex-call.ts","../src/adapters/convex-call/ConvexCallAdapter.ts","../src/adapters/_shared/wire.ts","../src/ports/credentials.ts","../src/adapters/credentials/ConvexCredentialsAdapter.ts","../src/ports/env.ts","../src/env/catalog.json","../src/env/_internal.ts","../src/adapters/env/_shared.ts","../src/adapters/env/SystemEnvAdapter.ts","../src/ports/identity.ts","../src/adapters/convex-identity.ts","../src/money/to-wei.ts","../src/ports/account-read.ts","../src/money/from-wei.ts","../src/adapters/account-read/ConvexAccountAdapter.ts","../src/ports/sub-account.ts","../src/adapters/sub-account/ConvexSubAccountAdapter.ts","../src/ports/smart-account.ts","../src/adapters/smart-account/ConvexSmartAccountAdapter.ts","../src/testing/smart-account/smart-account-derivation.ts","../../observability/src/index.ts","../src/ports/telemetry.ts","../src/adapters/telemetry/PostHogTelemetryAdapter.ts","../src/ports/transport.ts","../src/adapters/transport/ConvexTransportAdapter.ts","../src/openfort/create-openfort-browser-signer.ts","../src/flows/auth.ts","../src/client/capxul-deps.ts","../src/client/auth.ts","../src/client/smart-account-deps.ts","../src/client/smart-account.ts","../src/client/identity-deps.ts","../src/client/identity.ts","../src/client/_shared/money-telemetry.ts","../src/client/accounts-deps.ts","../src/client/accounts.ts","../src/client/financial-ops.ts","../src/client/sub-accounts-deps.ts","../src/client/sub-accounts.ts","../src/client/_shared/org-telemetry.ts","../src/client/org-spend-gate.ts","../src/client/org-deps.ts","../src/client/org.ts","../src/flows/onboarding.ts","../src/client/onboarding.ts","../src/client/factory.ts","../src/client/create-capxul-client.ts","../src/production.ts","../src/client/create-capxul-client-from-production.ts"],"sourcesContent":["// Deployed test-token config for the Account/Balance domain (canon\n// `docs/canon/decisions/account-balance-model.md` §1). This domain is\n// TypeScript-only: it reuses the already-deployed `TestUSDC` (\"USDX\") token on\n// Base Sepolia rather than authoring or deploying a contract. Addresses live\n// here as plain string constants; the backend RPC helper encodes `balanceOf`\n// calldata from them.\n\n/** `TestUSDC` (\"USDX\") — Base Sepolia, 6 decimals, open `mint`. (Canon §1.) */\nexport const USDX_ADDRESS_BASE_SEPOLIA = \"0xf09fcbb6df9f8f918e58f9c8ab15a76ade862b77\";\n\n/** USDX on-chain precision. Drives the SDK-boundary `fromWei`/`toWei`. */\nexport const USDX_DECIMALS = 6;\n\n/**\n * The consumer-facing currency USDX represents. The Money surface is currency\n * USD/USDX only in v1 (canon §10); components stay currency-aware so a second\n * token (NGN) slots in later.\n */\nexport const USDX_CURRENCY = \"USD\";\n\n/**\n * ERC-20 `balanceOf(address)` 4-byte function selector\n * (`keccak256(\"balanceOf(address)\")[:4]`). Used to encode `eth_call` calldata\n * for the balance RPC pull (canon §2 — no indexer).\n */\nexport const ERC20_BALANCE_OF_SELECTOR = \"0x70a08231\";\n\n/**\n * Exact-transfer token allowlist (#536 / G2 HITL gate): the only ERC-20s the\n * `CapxulPayments` adapter may move via `send(token, …)`. v1 permits USDX on\n * Base Sepolia only. Enforced BEFORE any execute so a tainted or fuzzy token\n * address can never be transferred — the allowlist is the policy boundary, not\n * the caller's input. Lowercased for case-insensitive comparison.\n */\nexport const EXACT_TRANSFER_TOKEN_ALLOWLIST: readonly string[] = [\n USDX_ADDRESS_BASE_SEPOLIA.toLowerCase(),\n];\n\n/** True iff `tokenAddress` is on the exact-transfer allowlist (case-insensitive). */\nexport function isExactTransferTokenAllowed(tokenAddress: string): boolean {\n return EXACT_TRANSFER_TOKEN_ALLOWLIST.includes(tokenAddress.toLowerCase());\n}\n","import {\n concat,\n encodeAbiParameters,\n encodeFunctionData,\n encodePacked,\n getContractAddress,\n hashTypedData,\n keccak256,\n pad,\n toBytes,\n toHex,\n type Hex,\n} from \"viem\";\n\nimport { Errors } from \"@capxul/errors\";\n\nexport const BASE_SEPOLIA_CHAIN_ID = 84532;\n\nexport const SAFE_PROXY_FACTORY = \"0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67\";\nexport const SAFE_L2_SINGLETON = \"0x29fcB43b46531BcA003ddC8FCB67FFE91900C762\";\nexport const SAFE_MODULE_SETUP = \"0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47\";\nexport const SAFE_4337_MODULE = \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\";\nexport const MULTI_SEND = \"0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526\";\n\n/**\n * Canonical personal-Safe salt namespace — **v2** (PRD #462). v2 derives the\n * address from the email ONLY: the initializer's sole owner is the fixed\n * `CAPXUL_BOOTSTRAP_OWNER`, so the address exists before any user signer does\n * and can never rotate with one. The user's signer is installed at claim time\n * via `swapOwner` (see `capxulClaimOwnerCallData`).\n */\nexport const CAPXUL_SAFE_SALT_NAMESPACE = \"capxul:safe:email:v2\";\n\n/**\n * Retired v1 personal-Safe namespace (signer-in-derivation). Kept ONLY as the\n * pin for pre-v2 on-chain artifacts that must not move — today that is the\n * backend faucet Safe (`testUsdcMint.ts`), which stays owner=deployer,\n * namespace=v1 so its deployed address is unchanged. Never use for new lanes.\n */\nexport const CAPXUL_SAFE_SALT_NAMESPACE_V1 = \"capxul:safe:email:v1\";\n\n/**\n * The Capxul bootstrap owner — the sole `setup()` owner of every unclaimed\n * personal Safe under derivation v2. This address is part of the CREATE2\n * preimage of EVERY personal Safe address: treat it exactly like\n * `SAFE_PROXY_FACTORY` (changing it is a derivation-version event → v3).\n * The private key lives backend-only (`CAPXUL_BOOTSTRAP_OWNER_PRIVATE_KEY`)\n * and signs exactly one kind of operation: the claim userOp that deploys the\n * Safe and swaps this owner out for the user's signer (PRD #462). The earlier\n * ClaimGuard derivation-v3 placeholder (#461) is closed; future mainnet-scale\n * hardening should be filed against the current payments/claim architecture.\n */\nexport const CAPXUL_BOOTSTRAP_OWNER = \"0x425fca96f4a3e18fb80974e38096b5da460f2704\";\n\n/** Safe `OwnerManager` sentinel — `prevOwner` for the single-owner swap. */\nexport const SAFE_SENTINEL_OWNERS = \"0x0000000000000000000000000000000000000001\";\n\nconst UINT48_MAX = 281_474_976_710_655;\n\n// Captured 2026-05-17 via `eth_call SafeProxyFactory.proxyCreationCode()`\n// against Base mainnet (chainId 8453). Identical bytecode across every chain\n// the factory is deployed to because the factory is itself deterministically\n// deployed via CREATE2. 486 bytes / 972 hex chars after the `0x` prefix.\n//\n// Used by `deriveCapxulSafeAddress` below; previously duplicated in\n// `packages/backend/convex/_shared/counterfactual.ts:PROXY_CREATION_CODE`.\n// Both sites pin the same hex literal — keep them in sync if Safe ever\n// migrates the factory bytecode (no such migration through v1.4.1).\nexport const SAFE_PROXY_CREATION_CODE: Hex =\n \"0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea264697066735822122003d1488ee65e08fa41e58e888a9865554c535f2c77126a82cb4c0f917f31441364736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564\";\n\n/**\n * Normalize an email for use as a Capxul Safe salt input.\n *\n * Trims surrounding whitespace and lowercases the address so that\n * `\" User+Demo@Example.COM \"` and `\"user+demo@example.com\"` derive\n * the same `safeAddress`. This is the canonical normalization rule —\n * any future change here would shift every existing user's Safe\n * address, so the rule is pinned by the fixture matrix in\n * `packages/config/tests/safe-address-conformance.test.ts`.\n *\n * @param email - The raw email address to normalize\n * @returns The trimmed, lowercased email\n */\nexport function normalizeSafeSaltEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\n/**\n * Compute the deterministic Safe salt nonce for a `(namespace, email)`\n * pair. The salt nonce is the `bigint` reading of\n * `keccak256(namespace + \":\" + normalizeSafeSaltEmail(email))`.\n *\n * Namespace defaults to `CAPXUL_SAFE_SALT_NAMESPACE`\n * (`\"capxul:safe:email:v2\"`) — the per-version Capxul scheme. Pass a\n * different namespace only for pinned pre-v2 artifacts\n * (`CAPXUL_SAFE_SALT_NAMESPACE_V1`, faucet Safe) or when bumping the scheme.\n *\n * @param input.email - The email to derive the salt nonce from\n * @param input.namespace - Optional namespace override (defaults to `CAPXUL_SAFE_SALT_NAMESPACE`)\n * @returns The Capxul-namespaced salt nonce as a `bigint`\n */\nexport function computeCapxulSafeSaltNonce(input: {\n readonly email: string;\n readonly namespace?: string;\n}): bigint {\n const namespace = input.namespace ?? CAPXUL_SAFE_SALT_NAMESPACE;\n const normalizedEmail = normalizeSafeSaltEmail(input.email);\n return BigInt(keccak256(toBytes(`${namespace}:${normalizedEmail}`)));\n}\n\n// --- Safe v1.4.1 + 4337 module address derivation -----------------------------\n\nconst ZERO_ADDRESS: Hex = \"0x0000000000000000000000000000000000000000\";\n\nconst safeSetupAbi = [\n {\n type: \"function\",\n name: \"setup\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"_owners\", type: \"address[]\" },\n { name: \"_threshold\", type: \"uint256\" },\n { name: \"to\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"fallbackHandler\", type: \"address\" },\n { name: \"paymentToken\", type: \"address\" },\n { name: \"payment\", type: \"uint256\" },\n { name: \"paymentReceiver\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst enableModulesAbi = [\n {\n type: \"function\",\n name: \"enableModules\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"modules\", type: \"address[]\" }],\n outputs: [],\n },\n] as const;\n\nconst multiSendAbi = [\n {\n type: \"function\",\n name: \"multiSend\",\n stateMutability: \"payable\",\n inputs: [{ name: \"transactions\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst safeProxyFactoryAbi = [\n {\n type: \"function\",\n name: \"createProxyWithNonce\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"_singleton\", type: \"address\" },\n { name: \"initializer\", type: \"bytes\" },\n { name: \"saltNonce\", type: \"uint256\" },\n ],\n outputs: [{ name: \"proxy\", type: \"address\" }],\n },\n] as const;\n\n// Shared Safe `setup` initializer used by both `deriveCapxulSafeAddressForOwner`\n// (the CREATE2 address) and `safeDeploymentFactoryArgsForOwner` (the\n// `createProxyWithNonce` factory calldata). A single builder guarantees the\n// derived address and the factory data can never drift apart. Under\n// derivation v2 the sole owner is `CAPXUL_BOOTSTRAP_OWNER` for every personal\n// Safe; the faucet lane passes the deployer EOA (v1 pin).\nfunction buildCapxulSafeInitializer(owner: Hex): Hex {\n const enableModulesCall = encodeFunctionData({\n abi: enableModulesAbi,\n functionName: \"enableModules\",\n args: [[SAFE_4337_MODULE]],\n });\n\n // MultiSend payload per `permissionless/accounts/safe/encodeInternalTransaction`:\n // uint8 operation || address to || uint256 value || uint256 dataLen || bytes data\n // operation=1 (delegatecall) into SafeModuleSetup with the enableModules call.\n const enableModulesByteLen = BigInt((enableModulesCall.length - 2) / 2);\n const multiSendPayload: Hex = encodePacked(\n [\"uint8\", \"address\", \"uint256\", \"uint256\", \"bytes\"],\n [1, SAFE_MODULE_SETUP, 0n, enableModulesByteLen, enableModulesCall],\n );\n\n const setupData = encodeFunctionData({\n abi: multiSendAbi,\n functionName: \"multiSend\",\n args: [multiSendPayload],\n });\n\n return encodeFunctionData({\n abi: safeSetupAbi,\n functionName: \"setup\",\n args: [[owner], 1n, MULTI_SEND, setupData, SAFE_4337_MODULE, ZERO_ADDRESS, 0n, ZERO_ADDRESS],\n });\n}\n\nconst ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;\n\nfunction validateAndNormalizeAddress(field: string, value: string): Hex {\n const address = value.toLowerCase();\n if (!ADDRESS_REGEX.test(address)) {\n throw Errors.invalidInput(field, `must be 0x + 40 hex chars, got ${value}`);\n }\n return address as Hex;\n}\n\n/**\n * Pure derivation of the Capxul personal Safe address — **v2: email only**\n * (PRD #462). The Safe v1.4.1 (SafeL2) + 4337-module initializer's sole owner\n * is the fixed `CAPXUL_BOOTSTRAP_OWNER`, so the address is a pure function of\n * the (normalized) email and exists before any user signer does. The user's\n * signer is installed at claim time via `swapOwner` — signer rotation can\n * never move the address (org-domain rule D7, now system-wide).\n *\n * Returns the lowercased `0x` + 40 hex string (raw — no brand applied so this\n * function is callable from both `@capxul/config` consumers that don't have\n * `@capxul/types` available, and from packages that re-brand at their own\n * boundary).\n *\n * Algorithm: exactly mirrors `permissionless.toSafeSmartAccount({ version:\n * \"1.4.1\", safeSingletonAddress: SAFE_L2_SINGLETON, owners: [BOOTSTRAP] })`\n * + the Capxul-canonical module setup (delegatecall into\n * `SafeModuleSetup.enableModules([SAFE_4337_MODULE])` via the MultiSend lane\n * during proxy setup). The proxy creation code is pinned at\n * `SAFE_PROXY_CREATION_CODE`; the salt is Capxul-namespaced (v2) via\n * `computeCapxulSafeSaltNonce({ email })`.\n *\n * Canonical: SDK deployment adapters and\n * `packages/backend/convex/smartAccount/mutations.ts:provision` import this\n * function; the conformance test at\n * `packages/config/tests/safe-address-conformance.test.ts` pins the matrix.\n */\nexport function deriveCapxulSafeAddress(input: { readonly email: string }): string {\n return deriveCapxulSafeAddressForOwner({\n ownerAddress: CAPXUL_BOOTSTRAP_OWNER,\n email: input.email,\n });\n}\n\n/**\n * Owner-parametrized derivation core. Two callers only:\n * 1. `deriveCapxulSafeAddress` (canonical v2: owner = bootstrap, namespace v2);\n * 2. the backend faucet Safe (`testUsdcMint.ts`: owner = deployer EOA,\n * namespace pinned to `CAPXUL_SAFE_SALT_NAMESPACE_V1` so its deployed\n * address never moves).\n * Do NOT introduce new owner-parametrized lanes — per-user owners in the\n * derivation is exactly the v1 mistake v2 removes.\n */\nexport function deriveCapxulSafeAddressForOwner(input: {\n readonly ownerAddress: string;\n readonly email: string;\n readonly namespace?: string;\n}): string {\n const owner = validateAndNormalizeAddress(\"ownerAddress\", input.ownerAddress);\n const initializer = buildCapxulSafeInitializer(owner);\n\n const saltNonce = computeCapxulSafeSaltNonce(\n input.namespace === undefined\n ? { email: input.email }\n : { email: input.email, namespace: input.namespace },\n );\n const salt = keccak256(encodePacked([\"bytes32\", \"uint256\"], [keccak256(initializer), saltNonce]));\n\n const deploymentCode = concat([\n SAFE_PROXY_CREATION_CODE,\n encodeAbiParameters([{ type: \"uint256\" }], [BigInt(SAFE_L2_SINGLETON)]),\n ]);\n\n const address = getContractAddress({\n opcode: \"CREATE2\",\n from: SAFE_PROXY_FACTORY as Hex,\n salt,\n bytecodeHash: keccak256(deploymentCode),\n });\n\n return address.toLowerCase();\n}\n\n/** Factory address + `createProxyWithNonce` calldata for the deployment UserOp. */\nexport interface SafeDeploymentFactoryArgs {\n readonly factory: Hex;\n readonly factoryData: Hex;\n readonly safeAddress: string;\n}\n\n/**\n * Build the EntryPoint v0.7 `factory` + `factoryData` for deploying the Capxul\n * personal Safe for an email (derivation v2: owner = `CAPXUL_BOOTSTRAP_OWNER`).\n * `factoryData` is the\n * `SafeProxyFactory.createProxyWithNonce(singleton, initializer, saltNonce)`\n * calldata; the backend claim lane packs these into the UserOp `initCode`.\n * Byte-for-byte equal to permissionless's\n * `toSafeSmartAccount(...).getFactoryArgs()` — pinned in\n * `packages/sdk/src/__tests__/safe4337-split-sign.test.ts`.\n */\nexport function safeDeploymentFactoryArgs(input: {\n readonly email: string;\n}): SafeDeploymentFactoryArgs {\n return safeDeploymentFactoryArgsForOwner({\n ownerAddress: CAPXUL_BOOTSTRAP_OWNER,\n email: input.email,\n });\n}\n\n/** Owner-parametrized factory args — same two-caller rule as `deriveCapxulSafeAddressForOwner`. */\nexport function safeDeploymentFactoryArgsForOwner(input: {\n readonly ownerAddress: string;\n readonly email: string;\n readonly namespace?: string;\n}): SafeDeploymentFactoryArgs {\n const owner = validateAndNormalizeAddress(\"ownerAddress\", input.ownerAddress);\n const initializer = buildCapxulSafeInitializer(owner);\n const saltNonce = computeCapxulSafeSaltNonce(\n input.namespace === undefined\n ? { email: input.email }\n : { email: input.email, namespace: input.namespace },\n );\n const factoryData = encodeFunctionData({\n abi: safeProxyFactoryAbi,\n functionName: \"createProxyWithNonce\",\n args: [SAFE_L2_SINGLETON as Hex, initializer, saltNonce],\n });\n return {\n factory: SAFE_PROXY_FACTORY as Hex,\n factoryData,\n safeAddress: deriveCapxulSafeAddressForOwner(input),\n };\n}\n\n// --- Claim (PRD #462) ---------------------------------------------------------\n//\n// Claiming a personal Safe = the ONE sponsored userOp that (a) deploys the\n// proxy via `safeDeploymentFactoryArgs` initCode when undeployed and (b) swaps\n// the bootstrap owner for the user's signer. The swap executes FROM the Safe\n// on itself through the Safe4337Module's `executeUserOpWithErrorString`\n// (wrap this calldata with `safe4337ExecuteUserOpCallData({ to: safeAddress,\n// data })`). The SafeOp digest is signed server-side by the bootstrap key —\n// the user signs nothing at claim.\n\nconst ownerManagerSwapOwnerAbi = [\n {\n type: \"function\",\n name: \"swapOwner\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"prevOwner\", type: \"address\" },\n { name: \"oldOwner\", type: \"address\" },\n { name: \"newOwner\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\n/**\n * Encode the `OwnerManager.swapOwner` calldata that installs the user's signer\n * as the Safe's sole owner at claim. Single-owner Safe ⇒ `prevOwner` is the\n * `SAFE_SENTINEL_OWNERS` sentinel and `oldOwner` is `CAPXUL_BOOTSTRAP_OWNER`.\n */\nexport function capxulClaimOwnerCallData(input: { readonly newOwner: string }): Hex {\n const newOwner = validateAndNormalizeAddress(\"newOwner\", input.newOwner);\n if (newOwner === CAPXUL_BOOTSTRAP_OWNER) {\n throw Errors.invalidInput(\"newOwner\", \"must not be the bootstrap owner\");\n }\n if (newOwner === SAFE_SENTINEL_OWNERS || BigInt(newOwner) === 0n) {\n throw Errors.invalidInput(\"newOwner\", \"must not be the sentinel or zero address\");\n }\n return encodeFunctionData({\n abi: ownerManagerSwapOwnerAbi,\n functionName: \"swapOwner\",\n args: [SAFE_SENTINEL_OWNERS as Hex, CAPXUL_BOOTSTRAP_OWNER as Hex, newOwner],\n });\n}\n\n// --- Safe 4337 split-signing (backend builds + sponsors; client signs) --------\n//\n// The Safe4337Module validates the owner's signature over an EIP-712 `SafeOp`\n// typed-data digest — NOT the EntryPoint userOpHash. In the backend-orchestrated\n// deploy (backend-orchestrated-deploy.md) the backend builds + gas-fills +\n// paymaster-sponsors the deployment UserOperation and computes this digest; the\n// consumer's `CapxulSigner` signs it; the backend packs\n// `validAfter|validUntil|signature` and submits. These helpers MUST mirror\n// permissionless's `signUserOperation` byte-for-byte — verified hermetically in\n// `packages/sdk/src/__tests__/safe4337-split-sign.test.ts`.\n\n/** Canonical ERC-4337 EntryPoint v0.7 address (same on every chain). */\nexport const ENTRY_POINT_07_ADDRESS = \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\";\n\n/** EIP-712 `SafeOp` typed-data fields for EntryPoint v0.7 (Safe4337Module). */\nexport const EIP712_SAFE_OPERATION_TYPE_V07 = {\n SafeOp: [\n { type: \"address\", name: \"safe\" },\n { type: \"uint256\", name: \"nonce\" },\n { type: \"bytes\", name: \"initCode\" },\n { type: \"bytes\", name: \"callData\" },\n { type: \"uint128\", name: \"verificationGasLimit\" },\n { type: \"uint128\", name: \"callGasLimit\" },\n { type: \"uint256\", name: \"preVerificationGas\" },\n { type: \"uint128\", name: \"maxPriorityFeePerGas\" },\n { type: \"uint128\", name: \"maxFeePerGas\" },\n { type: \"bytes\", name: \"paymasterAndData\" },\n { type: \"uint48\", name: \"validAfter\" },\n { type: \"uint48\", name: \"validUntil\" },\n { type: \"address\", name: \"entryPoint\" },\n ],\n} as const;\n\n/** Prepared (gas + paymaster filled, unsigned) EntryPoint v0.7 UserOperation. */\nexport interface Safe4337PreparedUserOp {\n readonly sender: Hex;\n readonly nonce: bigint;\n readonly factory?: Hex | undefined;\n readonly factoryData?: Hex | undefined;\n readonly callData: Hex;\n readonly callGasLimit: bigint;\n readonly verificationGasLimit: bigint;\n readonly preVerificationGas: bigint;\n readonly maxFeePerGas: bigint;\n readonly maxPriorityFeePerGas: bigint;\n readonly paymaster?: Hex | undefined;\n readonly paymasterVerificationGasLimit?: bigint | undefined;\n readonly paymasterPostOpGasLimit?: bigint | undefined;\n readonly paymasterData?: Hex | undefined;\n}\n\n/** Pack EntryPoint v0.7 `factory` + `factoryData` into the SafeOp `initCode`. */\nexport function safe4337InitCode(userOp: Safe4337PreparedUserOp): Hex {\n if (userOp.factory === undefined || userOp.factory === \"0x\") return \"0x\";\n return concat([userOp.factory, userOp.factoryData ?? \"0x\"]);\n}\n\n/** Pack EntryPoint v0.7 unpacked paymaster fields into SafeOp `paymasterAndData`. */\nexport function safe4337PaymasterAndData(userOp: Safe4337PreparedUserOp): Hex {\n if (userOp.paymaster === undefined || userOp.paymaster === \"0x\") return \"0x\";\n return concat([\n userOp.paymaster,\n pad(toHex(userOp.paymasterVerificationGasLimit ?? 0n), { size: 16 }),\n pad(toHex(userOp.paymasterPostOpGasLimit ?? 0n), { size: 16 }),\n userOp.paymasterData ?? \"0x\",\n ]);\n}\n\n/**\n * Compute the EIP-712 `SafeOp` digest the Safe4337Module owner must sign for a\n * prepared deployment UserOperation. The `CapxulSigner` signs THIS digest.\n */\nexport function safe4337SafeOpDigest(input: {\n readonly userOp: Safe4337PreparedUserOp;\n readonly chainId: number;\n readonly validAfter?: number;\n readonly validUntil?: number;\n readonly safe4337ModuleAddress?: Hex;\n readonly entryPointAddress?: Hex;\n}): Hex {\n return hashTypedData({\n domain: {\n chainId: input.chainId,\n verifyingContract: input.safe4337ModuleAddress ?? (SAFE_4337_MODULE as Hex),\n },\n types: EIP712_SAFE_OPERATION_TYPE_V07,\n primaryType: \"SafeOp\",\n message: {\n safe: input.userOp.sender,\n nonce: input.userOp.nonce,\n initCode: safe4337InitCode(input.userOp),\n callData: input.userOp.callData,\n verificationGasLimit: input.userOp.verificationGasLimit,\n callGasLimit: input.userOp.callGasLimit,\n preVerificationGas: input.userOp.preVerificationGas,\n maxPriorityFeePerGas: input.userOp.maxPriorityFeePerGas,\n maxFeePerGas: input.userOp.maxFeePerGas,\n paymasterAndData: safe4337PaymasterAndData(input.userOp),\n validAfter: input.validAfter ?? 0,\n validUntil: input.validUntil ?? 0,\n entryPoint: input.entryPointAddress ?? ENTRY_POINT_07_ADDRESS,\n },\n });\n}\n\n/** Pack a single-owner ECDSA signature into the Safe4337 UserOp signature. */\nexport function packSafe4337OwnerSignature(input: {\n readonly signature: Hex;\n readonly validAfter?: number;\n readonly validUntil?: number;\n}): Hex {\n assertUint48(input.validAfter ?? 0, \"validAfter\");\n assertUint48(input.validUntil ?? 0, \"validUntil\");\n return encodePacked(\n [\"uint48\", \"uint48\", \"bytes\"],\n [input.validAfter ?? 0, input.validUntil ?? 0, input.signature],\n );\n}\n\nfunction assertUint48(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value < 0 || value > UINT48_MAX) {\n throw Errors.invalidInput(field, `must fit uint48 (0..${UINT48_MAX})`);\n }\n}\n\nconst executeUserOpWithErrorStringAbi = [\n {\n type: \"function\",\n name: \"executeUserOpWithErrorString\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\n/**\n * Encode the deployment UserOp `callData` — a single Safe4337Module\n * `executeUserOpWithErrorString(to, value, data, operation=0)` call. Byte-for-byte\n * equal to permissionless's `toSafeSmartAccount(...).encodeCalls([{ to, value, data }])`\n * for the single-call path (no ERC-7579 launchpad, no on-chain identifier) — the\n * same path the proven live deploy adapter uses.\n */\nexport function safe4337ExecuteUserOpCallData(input: {\n readonly to: Hex;\n readonly value?: bigint;\n readonly data?: Hex;\n}): Hex {\n return encodeFunctionData({\n abi: executeUserOpWithErrorStringAbi,\n functionName: \"executeUserOpWithErrorString\",\n args: [input.to, input.value ?? 0n, input.data ?? \"0x\", 0],\n });\n}\n\n// DO NOT USE IN PRODUCTION. SAFE4337_STUB_OWNER_ECDSA is an intentionally\n// insecure, deterministic, forgeable, and replayable gas-estimation stub.\n// safe4337StubSignature() must be replaced by a real owner signature before\n// submitting any transaction or deployment UserOp.\nconst SAFE4337_STUB_OWNER_ECDSA: Hex =\n \"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c\";\n\n/**\n * Packed Safe4337 stub signature (single static owner) for gas estimation —\n * byte-for-byte equal to permissionless's `getStubSignature()`.\n */\nexport function safe4337StubSignature(): Hex {\n return packSafe4337OwnerSignature({ signature: SAFE4337_STUB_OWNER_ECDSA });\n}\n","import { Errors } from \"@capxul/errors\";\nimport { normalizeSafeSaltEmail } from \"./safe.ts\";\n\n/** Openfort `thirdPartyUserId` namespace for email bindings (epic #331 / #332). */\nexport const CAPXUL_BINDING_EMAIL_NAMESPACE = \"capxul:binding:email:v1\";\n\nconst BINDING_EMAIL_PREFIX = `${CAPXUL_BINDING_EMAIL_NAMESPACE}:`;\n\n/**\n * Normalize a raw email for binding id + Safe salt derivation.\n * Delegates to {@link normalizeSafeSaltEmail} so binding resolution and\n * `deriveCapxulSafeAddress` never drift apart.\n */\nexport function normalizeBindingEmail(email: string): string {\n return normalizeSafeSaltEmail(email);\n}\n\n/**\n * Production Openfort player key for authenticated flows (#338).\n * Matches the BetterAuth ↔ Openfort browser bridge (`user._id`).\n * Hermetic smoke scripts may still pregen by normalized email directly.\n */\nexport function openfortThirdPartyUserIdForAuth(authUserId: string): string {\n return authUserId;\n}\n\n/**\n * Format the canonical Capxul email binding id (Convex + wire lookup key).\n *\n * `capxul:binding:email:v1:{normalizedEmail}` — pinned by the #332 conformance\n * matrix in `tests/binding.test.ts`. Openfort `thirdPartyUserId` for live SDK\n * flows uses {@link openfortThirdPartyUserIdForAuth}; unauthenticated smoke\n * scripts may still pass normalized email.\n */\nexport function formatEmailBindingId(email: string): string {\n return `${BINDING_EMAIL_PREFIX}${normalizeBindingEmail(email)}`;\n}\n\n/**\n * Parse a binding id back to the normalized email. Throws\n * {@link CapxulError} `INVALID_INPUT` when the id is not an email-binding\n * id for the v1 namespace.\n */\nexport function parseEmailBindingId(bindingId: string): string {\n if (!bindingId.startsWith(BINDING_EMAIL_PREFIX)) {\n throw Errors.invalidInput(\"bindingId\", `must start with \"${BINDING_EMAIL_PREFIX}\"`);\n }\n const suffix = bindingId.slice(BINDING_EMAIL_PREFIX.length);\n if (suffix.length === 0) {\n throw Errors.invalidInput(\"bindingId\", \"must include a normalized email suffix\");\n }\n if (normalizeBindingEmail(suffix) !== suffix) {\n throw Errors.invalidInput(\"bindingId\", \"email suffix must be canonical (normalized)\");\n }\n return suffix;\n}\n\n/** True when `bindingId` is a v1 email binding id with a canonical suffix. */\nexport function isEmailBindingId(bindingId: string): boolean {\n if (!bindingId.startsWith(BINDING_EMAIL_PREFIX)) {\n return false;\n }\n const suffix = bindingId.slice(BINDING_EMAIL_PREFIX.length);\n return suffix.length > 0 && normalizeBindingEmail(suffix) === suffix;\n}\n","import { concat, encodeFunctionData, encodePacked, isAddress, type Address, type Hex } from \"viem\";\n\n/** Zodiac MultiSendCallOnly module on Base Sepolia. */\nexport const MULTI_SEND_CALL_ONLY: Address = \"0x9641d764fc13c8b624c04430c7356c1c7c8102e2\";\n\n/** Zodiac Roles v2 mastercopy on Base Sepolia. */\nexport const ROLES_MASTERCOPY: Address = \"0x9646fdad06d3e24444381f44362a3b0eb343d337\";\n\n/** Zodiac ModuleProxyFactory on Base Sepolia. */\nexport const ZODIAC_MODULE_PROXY_FACTORY: Address = \"0x000000000000addb49795b0f9ba5bc298cdda236\";\n\n/** Zodiac MultiSend unwrapper on Base Sepolia. */\nexport const ZODIAC_MULTI_SEND_UNWRAPPER: Address = \"0x93b7fcbc63ed8a3a24b59e1c3e6649d50b7427c0\";\n\n/** CapxulPayments proxy on Base Sepolia. */\nexport const CAPXUL_PAYMENTS_ADDRESS: Address = \"0xe740ea65521edc9bef0ea75d30b5334711db99f4\";\n\nexport const CAPXUL_PAYMENTS_SEND_ABI = [\n {\n type: \"function\",\n name: \"send\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\nexport const ERC20_APPROVE_ABI = [\n {\n type: \"function\",\n name: \"approve\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n] as const;\n\nexport interface CapxulPaymentsSendCallInput {\n readonly tokenAddress: Address;\n readonly recipientAddress: Address;\n readonly amount: bigint;\n readonly documentHash?: Hex;\n readonly paymentType?: number;\n}\n\nexport interface CapxulPaymentsRoleSpendCallInput extends CapxulPaymentsSendCallInput {\n readonly rolesModuleAddress: Address;\n readonly roleKey: Hex;\n}\n\nexport interface EncodedOrgPaymentCall {\n readonly to: Address;\n readonly data: Hex;\n readonly value: bigint;\n}\n\nconst MULTI_SEND_CALL_ONLY_ABI = [\n {\n type: \"function\",\n name: \"multiSend\",\n stateMutability: \"payable\",\n inputs: [{ name: \"transactions\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI = [\n {\n type: \"function\",\n name: \"execTransactionWithRole\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n { name: \"roleKey\", type: \"bytes32\" },\n { name: \"shouldRevert\", type: \"bool\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n// Safe4337Module `executeUserOpWithErrorString(to, value, data, operation)` —\n// the single entry the module calls back into the Safe with. A personal Safe\n// batches approve+send by delegatecalling MultiSendCallOnly (operation=1).\nconst SAFE4337_EXECUTE_USEROP_ABI = [\n {\n type: \"function\",\n name: \"executeUserOpWithErrorString\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst OPERATION_CALL = 0;\nconst OPERATION_DELEGATECALL = 1;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\n\nfunction normalizeAddress(address: Address, field: string): Address {\n if (!isAddress(address)) {\n throw new RangeError(`${field} must be a valid EVM address`);\n }\n return address.toLowerCase() as Address;\n}\n\nfunction normalizeBytes32(value: Hex, field: string): Hex {\n if (!BYTES32_RE.test(value)) {\n throw new RangeError(`${field} must be a 32-byte 0x-prefixed hex string`);\n }\n return value.toLowerCase() as Hex;\n}\n\nfunction normalizeUint8(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 255) {\n throw new RangeError(`${field} must be an integer between 0 and 255`);\n }\n return value;\n}\n\nfunction normalizePositiveAmount(value: bigint, field: string): bigint {\n if (value <= 0n) {\n throw new RangeError(`${field} must be positive`);\n }\n return value;\n}\n\nexport function buildCapxulPaymentsSendCalls(\n input: CapxulPaymentsSendCallInput,\n): readonly [EncodedOrgPaymentCall, EncodedOrgPaymentCall] {\n const tokenAddress = normalizeAddress(input.tokenAddress, \"tokenAddress\");\n const recipientAddress = normalizeAddress(input.recipientAddress, \"recipientAddress\");\n const amount = normalizePositiveAmount(input.amount, \"amount\");\n const documentHash = normalizeBytes32(\n input.documentHash ?? (`0x${\"0\".repeat(64)}` as Hex),\n \"documentHash\",\n );\n const paymentType = normalizeUint8(input.paymentType ?? 0, \"paymentType\");\n\n return [\n {\n to: tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_APPROVE_ABI,\n functionName: \"approve\",\n args: [CAPXUL_PAYMENTS_ADDRESS, amount],\n }),\n value: 0n,\n },\n {\n to: CAPXUL_PAYMENTS_ADDRESS,\n data: encodeFunctionData({\n abi: CAPXUL_PAYMENTS_SEND_ABI,\n functionName: \"send\",\n args: [tokenAddress, recipientAddress, amount, documentHash, paymentType],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildCapxulPaymentsRoleSpendCall(\n input: CapxulPaymentsRoleSpendCallInput,\n): EncodedOrgPaymentCall {\n const paymentCalls = buildCapxulPaymentsSendCalls(input);\n const roleKey = normalizeBytes32(input.roleKey, \"roleKey\");\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(paymentCalls.map(encodeMultiSendCallTransaction))],\n });\n\n return {\n to: normalizeAddress(input.rolesModuleAddress, \"rolesModuleAddress\"),\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL, roleKey, true],\n }),\n value: 0n,\n };\n}\n\n/**\n * Wrap an org Roles `execTransactionWithRole` call (from `*RoleSpendCall` /\n * `*RoleBatchSpendCall`) into the member Safe's `executeUserOpWithErrorString`\n * (operation = CALL into the Roles module) — the full Safe callData a sponsored\n * UserOp from the member's personal Safe carries (G4 · #547).\n */\nexport function buildOrgRoleSpendPersonalCallData(roleSpendCall: EncodedOrgPaymentCall): Hex {\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [\n normalizeAddress(roleSpendCall.to, \"rolesModuleAddress\"),\n 0n,\n roleSpendCall.data,\n OPERATION_CALL,\n ],\n });\n}\n\n/**\n * Wrap an ARBITRARY batch of calls into a member Safe's\n * `executeUserOpWithErrorString` via a delegatecall into MultiSendCallOnly\n * (G4 · #547 dev seam). Used by the dev MCP proof to drive the org's Zodiac\n * Roles DEPLOY (deployModule + enableModule + setUpRoles) and role GRANT\n * (assignRoles) as ONE sponsored UserOp from the founder's personal Safe —\n * the same `buildSponsoredSafeUserOp` mechanism the spend path uses. A single\n * call is still wrapped (MultiSend of length 1) so the caller need not branch.\n */\nexport function buildOrgPersonalMultiCallData(calls: readonly EncodedOrgPaymentCall[]): Hex {\n if (calls.length === 0) {\n throw new RangeError(\"multi-call batch must include at least one call\");\n }\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(calls.map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\nexport interface CapxulPaymentsRoleBatchRun {\n readonly recipientAddress: Address;\n readonly amount: bigint;\n readonly documentHash?: Hex;\n}\n\nexport interface CapxulPaymentsRoleBatchSpendCallInput {\n readonly rolesModuleAddress: Address;\n readonly roleKey: Hex;\n readonly tokenAddress: Address;\n readonly runs: readonly CapxulPaymentsRoleBatchRun[];\n readonly paymentType?: number;\n}\n\n/**\n * Encode an org PAYROLL BATCH (G4 · #547): one `execTransactionWithRole`\n * (the member's role key) → MultiSendCallOnly → N × (approve + CapxulPayments.send),\n * one send per employee. Each send keeps its own recipient + amount, so each is\n * bounded independently by the role's on-chain Zodiac conditions (per-tx cap,\n * per-day allowance, allowed recipient). One sponsored UserOp settles the batch.\n */\nexport function buildCapxulPaymentsRoleBatchSpendCall(\n input: CapxulPaymentsRoleBatchSpendCallInput,\n): EncodedOrgPaymentCall {\n if (input.runs.length === 0) {\n throw new RangeError(\"payroll batch must include at least one run\");\n }\n const roleKey = normalizeBytes32(input.roleKey, \"roleKey\");\n const paymentType = input.paymentType ?? 0;\n const subCalls: EncodedOrgPaymentCall[] = input.runs.flatMap((run) => [\n ...buildCapxulPaymentsSendCalls({\n tokenAddress: input.tokenAddress,\n recipientAddress: run.recipientAddress,\n amount: run.amount,\n paymentType,\n ...(run.documentHash === undefined ? {} : { documentHash: run.documentHash }),\n }),\n ]);\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(subCalls.map(encodeMultiSendCallTransaction))],\n });\n return {\n to: normalizeAddress(input.rolesModuleAddress, \"rolesModuleAddress\"),\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL, roleKey, true],\n }),\n value: 0n,\n };\n}\n\nfunction encodeMultiSendCallTransaction(call: EncodedOrgPaymentCall): Hex {\n return encodePacked(\n [\"uint8\", \"address\", \"uint256\", \"uint256\", \"bytes\"],\n [OPERATION_CALL, call.to, call.value, BigInt((call.data.length - 2) / 2), call.data],\n );\n}\n\n/**\n * Encode a personal Safe's `executeUserOpWithErrorString` callData that pays via\n * CapxulPayments in one UserOp: approve + send batched through a delegatecall\n * into MultiSendCallOnly. The Safe4337Module invokes this on the Safe; the\n * MultiSend then CALLs each sub-transaction from the Safe's own context.\n */\nexport function buildCapxulPaymentsPersonalSendCallData(input: CapxulPaymentsSendCallInput): Hex {\n const calls = buildCapxulPaymentsSendCalls(input);\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(calls.map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\n// ── Commitments (G3 · #546) — CapxulPayments escrow-vest-claim ───────────────\n// The alpha Commitment engine is the deployed CapxulPayments contract\n// (commitment-engine-source.md). Times are uint48 epoch SECONDS. release maps:\n// scheduled → startTime == cliffTime == endTime == at\n// stream → linear [startTime, endTime], optional cliffTime\n\nexport const CAPXUL_PAYMENTS_COMMITMENT_ABI = [\n {\n type: \"function\",\n name: \"createCommitment\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"totalAmount\", type: \"uint256\" },\n { name: \"startTime\", type: \"uint48\" },\n { name: \"cliffTime\", type: \"uint48\" },\n { name: \"endTime\", type: \"uint48\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n ],\n outputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n },\n {\n type: \"function\",\n name: \"claim\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"cancel\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"commitmentId\", type: \"uint256\" },\n { name: \"documentHash\", type: \"bytes32\" },\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"redirect\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"commitmentId\", type: \"uint256\" },\n { name: \"newRecipient\", type: \"address\" },\n { name: \"newDocumentHash\", type: \"bytes32\" },\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"claimableAmount\",\n stateMutability: \"view\",\n inputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n // Public `commitments(uint256)` mapping getter — returns the full Commitment\n // struct. Used to bind lifecycle evidence to the on-chain STATE after a\n // claim/cancel/redirect op (G3 #546 — actions must not trust sender+success\n // alone). Mirrors the `Commitment` struct field order in CapxulPayments.sol.\n {\n type: \"function\",\n name: \"commitments\",\n stateMutability: \"view\",\n inputs: [{ name: \"\", type: \"uint256\" }],\n outputs: [\n { name: \"creator\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"totalAmount\", type: \"uint256\" },\n { name: \"claimed\", type: \"uint256\" },\n { name: \"startTime\", type: \"uint48\" },\n { name: \"cliffTime\", type: \"uint48\" },\n { name: \"endTime\", type: \"uint48\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n { name: \"cancelled\", type: \"bool\" },\n ],\n },\n] as const;\n\nexport interface CapxulCreateCommitmentInput {\n readonly tokenAddress: Address;\n readonly recipientAddress: Address;\n readonly totalAmount: bigint;\n readonly startTime: number;\n readonly cliffTime: number;\n readonly endTime: number;\n readonly documentHash?: Hex;\n readonly paymentType?: number;\n}\n\nfunction normalizeUint48(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff_ffff) {\n throw new RangeError(`${field} must be a uint48 (epoch seconds)`);\n }\n return value;\n}\n\n/**\n * Encode a personal Safe's `createCommitment` UserOp: approve + createCommitment\n * batched through a delegatecall into MultiSendCallOnly (one sponsored UserOp).\n * The creator (payer Safe) escrows `totalAmount` into CapxulPayments.\n */\nexport function buildCapxulCreateCommitmentPersonalCallData(\n input: CapxulCreateCommitmentInput,\n): Hex {\n const tokenAddress = normalizeAddress(input.tokenAddress, \"tokenAddress\");\n const recipientAddress = normalizeAddress(input.recipientAddress, \"recipientAddress\");\n const totalAmount = normalizePositiveAmount(input.totalAmount, \"totalAmount\");\n const startTime = normalizeUint48(input.startTime, \"startTime\");\n const cliffTime = normalizeUint48(input.cliffTime, \"cliffTime\");\n const endTime = normalizeUint48(input.endTime, \"endTime\");\n if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) {\n throw new RangeError(\"commitment times must satisfy start <= cliff <= end\");\n }\n const documentHash = normalizeBytes32(\n input.documentHash ?? (`0x${\"0\".repeat(64)}` as Hex),\n \"documentHash\",\n );\n const paymentType = normalizeUint8(input.paymentType ?? 0, \"paymentType\");\n\n const approveCall: EncodedOrgPaymentCall = {\n to: tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_APPROVE_ABI,\n functionName: \"approve\",\n args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount],\n }),\n value: 0n,\n };\n const createCall: EncodedOrgPaymentCall = {\n to: CAPXUL_PAYMENTS_ADDRESS,\n data: encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"createCommitment\",\n args: [\n tokenAddress,\n recipientAddress,\n totalAmount,\n startTime,\n cliffTime,\n endTime,\n documentHash,\n paymentType,\n ],\n }),\n value: 0n,\n };\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat([approveCall, createCall].map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\nfunction buildSingleCapxulPaymentsCallData(data: Hex): Hex {\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [CAPXUL_PAYMENTS_ADDRESS, 0n, data, OPERATION_CALL],\n });\n}\n\n/** Encode a recipient Safe's `claim(commitmentId)` UserOp callData. */\nexport function buildCapxulCommitmentClaimCallData(commitmentId: bigint): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"claim\",\n args: [commitmentId],\n }),\n );\n}\n\n/** Encode a creator Safe's `cancel(commitmentId, documentHash)` UserOp callData. */\nexport function buildCapxulCommitmentCancelCallData(commitmentId: bigint, documentHash?: Hex): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"cancel\",\n args: [\n commitmentId,\n normalizeBytes32(documentHash ?? (`0x${\"0\".repeat(64)}` as Hex), \"documentHash\"),\n ],\n }),\n );\n}\n\n/** Encode a creator Safe's `redirect(commitmentId, newRecipient, newDocumentHash)` UserOp callData. */\nexport function buildCapxulCommitmentRedirectCallData(\n commitmentId: bigint,\n newRecipient: Address,\n newDocumentHash?: Hex,\n): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"redirect\",\n args: [\n commitmentId,\n normalizeAddress(newRecipient, \"newRecipient\"),\n normalizeBytes32(newDocumentHash ?? (`0x${\"0\".repeat(64)}` as Hex), \"newDocumentHash\"),\n ],\n }),\n );\n}\n","// Settlement Route + Token value types (D1 · #563). The deepening move: chain /\n// token / decimals / verifying-contract knowledge was AMBIENT across the domain\n// — chainId re-defaulted in 7 executors, the token address known in 5 places,\n// the bare literal `84_532` hardcoded inside the chain-agnostic resolver, and\n// NO type binding `{chainId, token, decimals, verifyingContract}` so they could\n// drift apart. This module is the single binding.\n//\n// A `Token` is a settlement asset bound to its chain: `{chainId, address,\n// decimals}` travel together so a caller can never pair USDX's address with the\n// wrong chain or the wrong decimals. A `Route` is the settlement path: which\n// `Token` settles where, plus the `verifyingContract` (the CapxulPayments\n// contract the EIP-712 document hash + every send/commitment commit against).\n//\n// Only the `direct-base` route exists today (USDX on Base Sepolia through\n// CapxulPayments). `provider:blockradar` / `fiat-offramp` slot in later as new\n// `Route` values behind the UNCHANGED `SettlementPort` interface — the seam the\n// multi-route future requires.\n\nimport type { Address } from \"viem\";\n\nimport { BASE_SEPOLIA_CHAIN_ID } from \"./safe.ts\";\nimport { CAPXUL_PAYMENTS_ADDRESS } from \"./org-payments.ts\";\nimport { USDX_ADDRESS_BASE_SEPOLIA, USDX_DECIMALS } from \"./tokens.ts\";\n\n/**\n * The settlement-route identifiers. `direct-base` is the real USDX-on-Base\n * route; `provider:sandbox` (B3) is a HERMETIC mock route — a second route\n * behind the unchanged `SettlementPort` interface that returns deterministic\n * stub evidence with no chain access, so the withdraw lane can be proven\n * without a real provider. `provider:blockradar` / `fiat-offramp` remain\n * NOT_IMPLEMENTED until the real cash-out provider (Lightspark/UMA, BlockRadar)\n * lands in the R&D pass.\n */\nexport type SettlementRouteKind =\n | \"direct-base\"\n | \"provider:sandbox\"\n | \"provider:blockradar\"\n | \"fiat-offramp\";\n\n/**\n * A settlement asset bound to its chain. `{chainId, address, decimals}` travel\n * together — the binding that stops USDX's address being paired with the wrong\n * chain or the wrong decimals.\n */\nexport interface Token {\n readonly chainId: number;\n readonly address: Address;\n readonly decimals: number;\n}\n\n/**\n * A settlement path: which `Token` settles where, and the `verifyingContract`\n * (the CapxulPayments contract the EIP-712 document hash and every send /\n * commitment commits against). The deep `SettlementPort` owns one `Route`.\n */\nexport interface Route {\n readonly kind: SettlementRouteKind;\n readonly token: Token;\n /** Convenience mirror of `token.chainId` — the chain this route settles on. */\n readonly chainId: number;\n /** The CapxulPayments contract address (EIP-712 verifying contract). */\n readonly verifyingContract: Address;\n}\n\n/** USDX on Base Sepolia — the only settlement token in v1. */\nexport const USDX_BASE_SEPOLIA_TOKEN: Token = {\n chainId: BASE_SEPOLIA_CHAIN_ID,\n address: USDX_ADDRESS_BASE_SEPOLIA as Address,\n decimals: USDX_DECIMALS,\n};\n\n/**\n * The `direct-base` settlement route: USDX on Base Sepolia, settled directly\n * through the `CapxulPayments` contract. This is the ONLY route implemented in\n * D1; the `Route` shape is the seam future provider routes slot into.\n */\nexport const DIRECT_BASE_ROUTE: Route = {\n kind: \"direct-base\",\n token: USDX_BASE_SEPOLIA_TOKEN,\n chainId: USDX_BASE_SEPOLIA_TOKEN.chainId,\n verifyingContract: CAPXUL_PAYMENTS_ADDRESS,\n};\n\n/**\n * The `provider:sandbox` settlement route (B3): a HERMETIC mock cash-out route.\n * It binds the SAME token / chain / verifying contract as `direct-base` so the\n * value helpers (`moneyToRawUnits`, `normalizeRecipient`, …) behave identically;\n * only `submitAndConfirm` differs — the sandbox port returns deterministic stub\n * settlement evidence with no network access (see `sandboxSettlementPort`). The\n * real provider route (Lightspark/UMA, BlockRadar) replaces this behind the\n * unchanged `SettlementPort` interface in the R&D pass.\n */\nexport const SANDBOX_ROUTE: Route = {\n kind: \"provider:sandbox\",\n token: USDX_BASE_SEPOLIA_TOKEN,\n chainId: USDX_BASE_SEPOLIA_TOKEN.chainId,\n verifyingContract: CAPXUL_PAYMENTS_ADDRESS,\n};\n","import { keccak256, toBytes } from \"viem\";\n\nimport { Errors } from \"@capxul/errors\";\n\nexport type OrgRoleMoney = {\n readonly currency: \"USD\";\n /** Integer base units for USD with 6 decimals, e.g. $25,000 => \"25000000000\". */\n readonly value: string;\n readonly decimals: 6;\n};\n\nexport type OrgRoleSpendCap = {\n readonly perTx?: OrgRoleMoney;\n readonly perDay?: OrgRoleMoney;\n readonly toRecipients?: \"anyone\" | readonly string[];\n};\n\nexport type OrgRoleDefinition = {\n readonly label: string;\n readonly spend?: OrgRoleSpendCap;\n readonly subAccounts?: { readonly scope: \"all\" | readonly string[] };\n readonly canManageMembers?: boolean;\n readonly canManageRoles?: boolean;\n};\n\nexport type CompiledOrgRole = {\n readonly label: string;\n readonly roleKey: string;\n readonly definition: OrgRoleDefinition;\n readonly permissions: readonly string[];\n readonly allowance: OrgRoleSpendCap | null;\n};\n\nexport type CompiledOrgRoles = {\n readonly roles: readonly CompiledOrgRole[];\n readonly memberManagementRole: {\n readonly roleKey: string;\n readonly permission: \"zodiac.roles.assignRoles\";\n };\n};\n\nconst USD_DECIMALS = 6;\nconst USD_SCALE = 10n ** BigInt(USD_DECIMALS);\nconst USD_DISPLAY_RE = /^\\d+(?:\\.\\d{1,6})?$/;\nconst USD_BASE_UNIT_RE = /^\\d+$/;\nconst EXEC_TRANSACTION_WITH_ROLE = \"zodiac.roles.execTransactionWithRole\" as const;\nconst ASSIGN_ROLES = \"zodiac.roles.assignRoles\" as const;\nconst SCOPE_TARGET = \"zodiac.roles.scopeTarget\" as const;\nconst OWNER_ROLE_LABEL = \"Owner\";\nconst MARKETING_SUB_ACCOUNT_ID = \"subaccount_marketing\";\nconst PAYROLL_SUB_ACCOUNT_ID = \"subaccount_payroll\";\n\nfunction usd(value: string): OrgRoleMoney {\n return { currency: \"USD\", value: usdDisplayToBaseUnits(value), decimals: USD_DECIMALS };\n}\n\nfunction usdDisplayToBaseUnits(value: string): string {\n const trimmed = value.trim();\n if (trimmed !== value || !USD_DISPLAY_RE.test(value)) {\n throw Errors.invalidInput(\n \"role.spend\",\n \"USD caps must be unsigned decimal strings with at most 6 fractional digits\",\n );\n }\n const parts = value.split(\".\");\n const whole = parts[0] ?? \"0\";\n const fraction = parts[1] ?? \"\";\n return (BigInt(whole) * USD_SCALE + BigInt(fraction.padEnd(USD_DECIMALS, \"0\"))).toString();\n}\n\nfunction normalizeOrgRoleMoney(money: OrgRoleMoney, field: string): OrgRoleMoney {\n if (\n money.currency !== \"USD\" ||\n money.decimals !== USD_DECIMALS ||\n !USD_BASE_UNIT_RE.test(money.value)\n ) {\n throw Errors.invalidInput(field, `must be USD base units with ${USD_DECIMALS} decimals`);\n }\n return money;\n}\n\nfunction normalizeOrgRoleSpendCap(spend: OrgRoleSpendCap | undefined): OrgRoleSpendCap | undefined {\n if (spend === undefined) return undefined;\n return {\n ...(spend.perTx === undefined\n ? {}\n : { perTx: normalizeOrgRoleMoney(spend.perTx, \"roles.spend.perTx\") }),\n ...(spend.perDay === undefined\n ? {}\n : { perDay: normalizeOrgRoleMoney(spend.perDay, \"roles.spend.perDay\") }),\n ...(spend.toRecipients === undefined ? {} : { toRecipients: spend.toRecipients }),\n };\n}\n\nexport function normalizeOrgRoleLabel(label: string): string {\n const normalized = label.trim().replace(/\\s+/g, \" \");\n if (normalized.length === 0) {\n throw Errors.invalidInput(\"role.label\", \"must be a non-empty role label\");\n }\n return normalized;\n}\n\nexport function orgRoleKeyForLabel(label: string): string {\n return keccak256(toBytes(normalizeOrgRoleLabel(label).toLowerCase()));\n}\n\nexport function soloOrgRoleTemplate(): readonly OrgRoleDefinition[] {\n return [\n {\n label: \"Owner\",\n subAccounts: { scope: \"all\" },\n canManageMembers: true,\n canManageRoles: true,\n },\n ];\n}\n\nexport function startupOrgRoleTemplate(): readonly OrgRoleDefinition[] {\n return [\n ...soloOrgRoleTemplate(),\n {\n label: \"Finance Manager\",\n spend: {\n perTx: usd(\"25000\"),\n perDay: usd(\"100000\"),\n toRecipients: \"anyone\",\n },\n subAccounts: { scope: [MARKETING_SUB_ACCOUNT_ID] },\n },\n {\n label: \"Team Lead\",\n spend: {\n perTx: usd(\"5000\"),\n perDay: usd(\"15000\"),\n toRecipients: \"anyone\",\n },\n subAccounts: { scope: [PAYROLL_SUB_ACCOUNT_ID] },\n },\n ];\n}\n\nexport function orgRoleTemplateDefinitions(\n template: \"Solo\" | \"Startup\" | \"Custom\",\n customRoles: readonly OrgRoleDefinition[] = [],\n): readonly OrgRoleDefinition[] {\n switch (template) {\n case \"Solo\":\n return soloOrgRoleTemplate();\n case \"Startup\":\n return startupOrgRoleTemplate();\n case \"Custom\":\n return customRoles.length === 0 ? soloOrgRoleTemplate() : customRoles;\n default: {\n const _exhaustive: never = template;\n return _exhaustive;\n }\n }\n}\n\nexport function compileOrgRoleDefinitions(\n definitions: readonly OrgRoleDefinition[],\n): CompiledOrgRoles {\n if (definitions.length === 0) {\n throw Errors.invalidInput(\"roles\", \"must include at least one role\");\n }\n\n const seen = new Set<string>();\n const roles = definitions.map((definition): CompiledOrgRole => {\n const label = normalizeOrgRoleLabel(definition.label);\n const roleKey = orgRoleKeyForLabel(label);\n if (seen.has(roleKey)) {\n throw Errors.invalidInput(\"roles\", `duplicate role label: ${label}`);\n }\n seen.add(roleKey);\n const spend = normalizeOrgRoleSpendCap(definition.spend);\n\n const permissions: string[] = [];\n if (spend !== undefined || label === OWNER_ROLE_LABEL) {\n permissions.push(EXEC_TRANSACTION_WITH_ROLE);\n }\n if (definition.canManageMembers === true) {\n permissions.push(ASSIGN_ROLES);\n }\n if (definition.canManageRoles === true) {\n permissions.push(SCOPE_TARGET);\n }\n\n return {\n label,\n roleKey,\n definition: { ...definition, label, ...(spend === undefined ? {} : { spend }) },\n permissions,\n allowance: spend ?? null,\n };\n });\n\n const manager = roles.find((role) => role.definition.canManageMembers === true);\n if (manager === undefined) {\n throw Errors.invalidInput(\n \"roles.canManageMembers\",\n \"at least one role must compile to the on-chain member-management permission\",\n );\n }\n\n return {\n roles,\n memberManagementRole: {\n roleKey: manager.roleKey,\n permission: ASSIGN_ROLES,\n },\n };\n}\n","import {\n encodeAbiParameters,\n encodeFunctionData,\n getContractAddress,\n keccak256,\n padHex,\n parseAbiParameters,\n stringToHex,\n type Hex,\n} from \"viem\";\n\nimport {\n CAPXUL_PAYMENTS_ADDRESS,\n MULTI_SEND_CALL_ONLY,\n ROLES_MASTERCOPY,\n ZODIAC_MODULE_PROXY_FACTORY,\n ZODIAC_MULTI_SEND_UNWRAPPER,\n} from \"./org-payments.ts\";\nimport {\n compileOrgRoleDefinitions,\n normalizeOrgRoleLabel,\n startupOrgRoleTemplate,\n type CompiledOrgRole,\n type OrgRoleDefinition,\n type OrgRoleSpendCap,\n} from \"./role-dsl.ts\";\nimport { USDX_ADDRESS_BASE_SEPOLIA } from \"./tokens.ts\";\n\nexport interface EncodedOrgZodiacCall {\n readonly to: Hex;\n readonly data: Hex;\n readonly value: bigint;\n}\n\nexport interface BuildOrgRolesDeployCallsInput {\n readonly safeAddress: Hex;\n readonly ownerAddress: Hex;\n readonly roleDefinitions?: readonly OrgRoleDefinition[];\n readonly saltNonce?: bigint;\n}\n\nexport interface OrgRolesDeployCalls {\n readonly rolesModuleAddress: Hex;\n readonly calls: readonly EncodedOrgZodiacCall[];\n}\n\nexport interface BuildOrgRoleAssignmentCallInput {\n readonly rolesModuleAddress: Hex;\n readonly managerRoleKey: Hex;\n readonly memberAddress: Hex;\n readonly roleKey: Hex;\n readonly memberOf: boolean;\n}\n\ntype ZodiacCondition = {\n readonly paramType: number;\n readonly operator: number;\n readonly compValue?: Hex;\n readonly children?: readonly ZodiacCondition[];\n};\n\ntype ZodiacPermission = {\n readonly targetAddress: Hex;\n readonly signature: string;\n readonly condition?: ZodiacCondition;\n};\n\ntype ZodiacRoleConfig = {\n readonly key: Hex;\n readonly members: readonly Hex[];\n readonly permissions: readonly ZodiacPermission[];\n};\n\ntype ZodiacSdkCall = {\n readonly to: string;\n readonly data: string;\n readonly value: string | number | bigint;\n};\n\ntype ZodiacSdk = {\n readonly setUpRoles: (input: {\n readonly address: Hex;\n readonly roles: readonly ZodiacRoleConfig[];\n }) => readonly ZodiacSdkCall[];\n};\n\nconst MODULE_PROXY_FACTORY_ABI = [\n {\n type: \"function\",\n name: \"deployModule\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"masterCopy\", type: \"address\" },\n { name: \"initializer\", type: \"bytes\" },\n { name: \"saltNonce\", type: \"uint256\" },\n ],\n outputs: [{ name: \"proxy\", type: \"address\" }],\n },\n] as const;\n\nconst SAFE_ENABLE_MODULE_ABI = [\n {\n type: \"function\",\n name: \"enableModule\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"module\", type: \"address\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_UP_ABI = [\n {\n type: \"function\",\n name: \"setUp\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"initParams\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_ALLOWANCE_ABI = [\n {\n type: \"function\",\n name: \"setAllowance\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"key\", type: \"bytes32\" },\n { name: \"balance\", type: \"uint128\" },\n { name: \"maxRefill\", type: \"uint128\" },\n { name: \"refill\", type: \"uint128\" },\n { name: \"period\", type: \"uint64\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_TRANSACTION_UNWRAPPER_ABI = [\n {\n type: \"function\",\n name: \"setTransactionUnwrapper\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"target\", type: \"address\" },\n { name: \"selector\", type: \"bytes4\" },\n { name: \"adapter\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_ASSIGN_ROLES_ABI = [\n {\n type: \"function\",\n name: \"assignRoles\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"module\", type: \"address\" },\n { name: \"roleKeys\", type: \"bytes32[]\" },\n { name: \"memberOf\", type: \"bool[]\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI = [\n {\n type: \"function\",\n name: \"execTransactionWithRole\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n { name: \"roleKey\", type: \"bytes32\" },\n { name: \"shouldRevert\", type: \"bool\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\nexport const ORG_ROLE_ALLOWANCE_KEYS = {\n financeManagerDaily: padHex(stringToHex(\"FM_DAILY\"), { size: 32, dir: \"right\" }),\n teamLeadDaily: padHex(stringToHex(\"TL_DAILY\"), { size: 32, dir: \"right\" }),\n} as const;\n\nconst MULTI_SEND_SELECTOR = \"0x8d80ff0a\" as const;\nconst ONE_DAY_SECONDS = 86_400n;\nconst ZODIAC_OPERATION_CALL = 0;\nconst EXEC_TRANSACTION_WITH_ROLE = \"zodiac.roles.execTransactionWithRole\";\n\nconst PARAMETER_TYPE = {\n none: 0,\n static: 1,\n calldata: 5,\n} as const;\n\nconst OPERATOR = {\n pass: 0,\n and: 1,\n or: 2,\n matches: 5,\n equalTo: 16,\n lessThan: 18,\n withinAllowance: 28,\n} as const;\n\nfunction normalizeHexAddress(address: Hex): Hex {\n return address.toLowerCase() as Hex;\n}\n\nexport function orgRoleAllowanceKeyForLabel(label: string): Hex {\n const normalized = normalizeOrgRoleLabel(label);\n switch (normalized) {\n case \"Finance Manager\":\n return ORG_ROLE_ALLOWANCE_KEYS.financeManagerDaily;\n case \"Team Lead\":\n return ORG_ROLE_ALLOWANCE_KEYS.teamLeadDaily;\n default:\n return keccak256(stringToHex(`CAPXUL_ORG_DAILY_ALLOWANCE:${normalized.toLowerCase()}`));\n }\n}\n\nfunction passStatic(): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.static, operator: OPERATOR.pass };\n}\n\nfunction equalAddress(address: Hex): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.equalTo,\n compValue: encodeAbiParameters([{ type: \"address\" }], [address]),\n };\n}\n\nfunction lteUint256(value: string): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.lessThan,\n compValue: encodeAbiParameters([{ type: \"uint256\" }], [BigInt(value) + 1n]),\n };\n}\n\nfunction withinAllowance(allowanceKey: Hex): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.withinAllowance,\n compValue: encodeAbiParameters([{ type: \"bytes32\" }], [allowanceKey]),\n };\n}\n\nfunction and(...children: readonly ZodiacCondition[]): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.none, operator: OPERATOR.and, children };\n}\n\nfunction calldataMatches(children: readonly ZodiacCondition[]): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.calldata, operator: OPERATOR.matches, children };\n}\n\n/**\n * The on-chain recipient condition for a role's `toRecipients` scope. `\"anyone\"`\n * (or an empty/undefined set) leaves the recipient param unconstrained on-chain\n * (`passStatic` — recipient validation is the Level-2 off-chain guard). A FIXED\n * recipient set compiles to an `Or` over per-address equality so the on-chain\n * Roles modifier itself refuses any recipient outside the set — this is the\n * treasury-drain boundary for createCommitment / redirect, not just `send`.\n */\nfunction recipientCondition(toRecipients: OrgRoleSpendCap[\"toRecipients\"]): ZodiacCondition {\n if (toRecipients === undefined || toRecipients === \"anyone\" || toRecipients.length === 0) {\n return passStatic();\n }\n const equals = toRecipients.map((address) => equalAddress(normalizeHexAddress(address as Hex)));\n // A single allowed recipient is a bare equality; multiple are OR-combined.\n return equals.length === 1 ? (equals[0] as ZodiacCondition) : orMatch(equals);\n}\n\nfunction orMatch(children: readonly ZodiacCondition[]): ZodiacCondition {\n // A logical `Or` node addresses no concrete parameter slot of its own — it\n // combines child conditions that each address the SAME value. Zodiac's\n // on-chain `Integrity.sol` enforces `Operator.Or ⇒ ParameterType.None`; a\n // `Static` paramType makes `scopeFunction` REVERT on deploy, bricking any role\n // with a 2+ recipient set. The children keep their own (`Static`) param types.\n return { paramType: PARAMETER_TYPE.none, operator: OPERATOR.or, children };\n}\n\nfunction encodeRolesSetUpCall(input: {\n readonly owner: Hex;\n readonly avatar: Hex;\n readonly target: Hex;\n}): Hex {\n const innerInitParams = encodeAbiParameters(parseAbiParameters(\"address, address, address\"), [\n input.owner,\n input.avatar,\n input.target,\n ]);\n return encodeFunctionData({\n abi: ROLES_SET_UP_ABI,\n functionName: \"setUp\",\n args: [innerInitParams],\n });\n}\n\nexport function computeOrgRolesModuleAddress(input: {\n readonly owner: Hex;\n readonly avatar: Hex;\n readonly target: Hex;\n readonly saltNonce?: bigint;\n}): Hex {\n const saltNonce = input.saltNonce ?? 0n;\n const proxyInitCode = (\"0x602d8060093d393df3363d3d373d3d3d363d73\" +\n ROLES_MASTERCOPY.slice(2).toLowerCase() +\n \"5af43d82803e903d91602b57fd5bf3\") as Hex;\n const initializer = encodeRolesSetUpCall(input);\n const initializerHash = keccak256(initializer);\n const saltNonceEncoded = encodeAbiParameters(parseAbiParameters(\"uint256\"), [saltNonce]);\n const salt = keccak256((initializerHash + saltNonceEncoded.slice(2)) as Hex);\n\n return normalizeHexAddress(\n getContractAddress({\n opcode: \"CREATE2\",\n from: ZODIAC_MODULE_PROXY_FACTORY,\n salt,\n bytecodeHash: keccak256(proxyInitCode),\n }),\n );\n}\n\nfunction buildDeployModuleCall(input: {\n readonly safeAddress: Hex;\n readonly saltNonce: bigint;\n}): EncodedOrgZodiacCall {\n return {\n to: ZODIAC_MODULE_PROXY_FACTORY,\n data: encodeFunctionData({\n abi: MODULE_PROXY_FACTORY_ABI,\n functionName: \"deployModule\",\n args: [\n ROLES_MASTERCOPY,\n encodeRolesSetUpCall({\n owner: input.safeAddress,\n avatar: input.safeAddress,\n target: input.safeAddress,\n }),\n input.saltNonce,\n ],\n }),\n value: 0n,\n };\n}\n\nfunction buildEnableModuleCall(input: {\n readonly safeAddress: Hex;\n readonly rolesModuleAddress: Hex;\n}): EncodedOrgZodiacCall {\n return {\n to: input.safeAddress,\n data: encodeFunctionData({\n abi: SAFE_ENABLE_MODULE_ABI,\n functionName: \"enableModule\",\n args: [input.rolesModuleAddress],\n }),\n value: 0n,\n };\n}\n\nfunction buildSetUnwrapperCall(rolesModuleAddress: Hex): EncodedOrgZodiacCall {\n return {\n to: rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_SET_TRANSACTION_UNWRAPPER_ABI,\n functionName: \"setTransactionUnwrapper\",\n args: [MULTI_SEND_CALL_ONLY, MULTI_SEND_SELECTOR, ZODIAC_MULTI_SEND_UNWRAPPER],\n }),\n value: 0n,\n };\n}\n\nfunction buildSetAllowanceCall(input: {\n readonly rolesModuleAddress: Hex;\n readonly allowanceKey: Hex;\n readonly dailyCap: string;\n}): EncodedOrgZodiacCall {\n const dailyCap = BigInt(input.dailyCap);\n return {\n to: input.rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_SET_ALLOWANCE_ABI,\n functionName: \"setAllowance\",\n args: [input.allowanceKey, dailyCap, dailyCap, dailyCap, ONE_DAY_SECONDS, 0n],\n }),\n value: 0n,\n };\n}\n\nfunction buildTemplateAllowanceCalls(input: {\n readonly rolesModuleAddress: Hex;\n readonly roles: readonly CompiledOrgRole[];\n}): readonly EncodedOrgZodiacCall[] {\n return input.roles.flatMap((role) => {\n const dailyCap = role?.allowance?.perDay?.value;\n return dailyCap === undefined\n ? []\n : [\n buildSetAllowanceCall({\n rolesModuleAddress: input.rolesModuleAddress,\n allowanceKey: orgRoleAllowanceKeyForLabel(role.label),\n dailyCap,\n }),\n ];\n });\n}\n\n// Selector signatures the role compiler scopes on CapxulPayments. `claim` is\n// DELIBERATELY ABSENT: claim is recipient-side (a recipient pulling vested\n// funds), never org treasury authority — granting it would let a role drain\n// commitments addressed to others (#488, D10).\nconst CREATE_COMMITMENT_SIGNATURE =\n \"createCommitment(address,address,uint256,uint48,uint48,uint48,bytes32,uint8)\";\nconst CANCEL_SIGNATURE = \"cancel(uint256,bytes32)\";\nconst REDIRECT_SIGNATURE = \"redirect(uint256,address,bytes32)\";\n\nfunction approvePermission(): ZodiacPermission {\n return {\n targetAddress: USDX_ADDRESS_BASE_SEPOLIA,\n signature: \"approve(address,uint256)\",\n condition: calldataMatches([equalAddress(CAPXUL_PAYMENTS_ADDRESS), passStatic()]),\n };\n}\n\nfunction paymentPermissions(input: {\n readonly allowanceKey: Hex;\n readonly perTxCap: string;\n readonly recipient: ZodiacCondition;\n}): readonly [ZodiacPermission, ZodiacPermission] {\n return [\n approvePermission(),\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: \"send(address,address,uint256,bytes32,uint8)\",\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n input.recipient,\n and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),\n passStatic(),\n passStatic(),\n ]),\n },\n ];\n}\n\nfunction uncappedPaymentPermissions(): readonly [ZodiacPermission, ZodiacPermission] {\n return [\n approvePermission(),\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: \"send(address,address,uint256,bytes32,uint8)\",\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n ]),\n },\n ];\n}\n\n/**\n * Commitment-verb permissions for a CAPPED role (#488 / G4 #547). `createCommitment`\n * carries the SAME on-chain conditions as `send`: token == USDX, the recipient\n * is in the role's allowed set, and the escrowed `totalAmount` is `<= perTx cap`\n * AND `withinAllowance(perDay key)`. `redirect` re-pins `newRecipient` to the\n * same allowed set (it changes who receives, so it is a recipient-boundary op).\n * `cancel` only reclaims unvested funds from a commitment the role created and\n * carries no recipient/amount, so it is allow-listed by selector with no comp\n * value. `claim` is NEVER emitted — it is recipient-side, not treasury authority.\n */\nfunction commitmentPermissions(input: {\n readonly allowanceKey: Hex;\n readonly perTxCap: string;\n readonly recipient: ZodiacCondition;\n}): readonly ZodiacPermission[] {\n return [\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CREATE_COMMITMENT_SIGNATURE,\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n input.recipient,\n and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),\n passStatic(), // startTime\n passStatic(), // cliffTime\n passStatic(), // endTime\n passStatic(), // documentHash\n passStatic(), // paymentType\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: REDIRECT_SIGNATURE,\n condition: calldataMatches([\n passStatic(), // commitmentId\n input.recipient, // newRecipient — re-pinned to the role's allowed set\n passStatic(), // newDocumentHash\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CANCEL_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic()]),\n },\n ];\n}\n\n/** Uncapped commitment permissions for the Owner role (no per-tx/recipient cap). */\nfunction uncappedCommitmentPermissions(): readonly ZodiacPermission[] {\n return [\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CREATE_COMMITMENT_SIGNATURE,\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: REDIRECT_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic(), passStatic()]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CANCEL_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic()]),\n },\n ];\n}\n\nfunction rolePermissions(input: {\n readonly role: CompiledOrgRole;\n readonly rolesModuleAddress: Hex;\n}): readonly ZodiacPermission[] {\n const permissions: ZodiacPermission[] = [];\n if (input.role.definition.canManageMembers === true) {\n permissions.push({\n targetAddress: input.rolesModuleAddress,\n signature: \"assignRoles(address,bytes32[],bool[])\",\n });\n }\n if (\n input.role.allowance === null &&\n input.role.permissions.includes(EXEC_TRANSACTION_WITH_ROLE)\n ) {\n permissions.push(...uncappedPaymentPermissions(), ...uncappedCommitmentPermissions());\n }\n if (input.role.allowance?.perTx !== undefined && input.role.allowance.perDay !== undefined) {\n const allowanceKey = orgRoleAllowanceKeyForLabel(input.role.label);\n const perTxCap = input.role.allowance.perTx.value;\n const recipient = recipientCondition(input.role.allowance.toRecipients);\n permissions.push(\n ...paymentPermissions({ allowanceKey, perTxCap, recipient }),\n ...commitmentPermissions({ allowanceKey, perTxCap, recipient }),\n );\n }\n return permissions;\n}\n\nasync function getZodiacSdk(): Promise<ZodiacSdk> {\n return (await import(\"zodiac-roles-sdk\")) as unknown as ZodiacSdk;\n}\n\nasync function buildRoleSetupCalls(input: {\n readonly rolesModuleAddress: Hex;\n readonly ownerAddress: Hex;\n readonly roles: readonly CompiledOrgRole[];\n readonly managerRoleKey: string;\n}): Promise<readonly EncodedOrgZodiacCall[]> {\n const managerRoleKey = input.managerRoleKey.toLowerCase();\n const roles = input.roles.map(\n (role): ZodiacRoleConfig => ({\n key: role.roleKey as Hex,\n members: role.roleKey.toLowerCase() === managerRoleKey ? [input.ownerAddress] : [],\n permissions: rolePermissions({ role, rolesModuleAddress: input.rolesModuleAddress }),\n }),\n );\n const zodiacSdk = await getZodiacSdk();\n return zodiacSdk.setUpRoles({ address: input.rolesModuleAddress, roles }).map((call) => ({\n to: normalizeHexAddress(call.to as Hex),\n data: call.data as Hex,\n value: BigInt(call.value),\n }));\n}\n\nexport async function buildOrgRolesDeployCalls(\n input: BuildOrgRolesDeployCallsInput,\n): Promise<OrgRolesDeployCalls> {\n const safeAddress = normalizeHexAddress(input.safeAddress);\n const ownerAddress = normalizeHexAddress(input.ownerAddress);\n const saltNonce = input.saltNonce ?? 0n;\n const roleDefinitions = input.roleDefinitions ?? startupOrgRoleTemplate();\n const compiled = compileOrgRoleDefinitions(roleDefinitions);\n const rolesModuleAddress = computeOrgRolesModuleAddress({\n owner: safeAddress,\n avatar: safeAddress,\n target: safeAddress,\n saltNonce,\n });\n\n return {\n rolesModuleAddress,\n calls: [\n buildDeployModuleCall({ safeAddress, saltNonce }),\n buildEnableModuleCall({ safeAddress, rolesModuleAddress }),\n buildSetUnwrapperCall(rolesModuleAddress),\n ...buildTemplateAllowanceCalls({ rolesModuleAddress, roles: compiled.roles }),\n ...(await buildRoleSetupCalls({\n rolesModuleAddress,\n ownerAddress,\n roles: compiled.roles,\n managerRoleKey: compiled.memberManagementRole.roleKey,\n })),\n ],\n };\n}\n\nexport function buildOrgRoleAssignmentCall(\n input: BuildOrgRoleAssignmentCallInput,\n): EncodedOrgZodiacCall {\n const rolesModuleAddress = normalizeHexAddress(input.rolesModuleAddress);\n const memberAddress = normalizeHexAddress(input.memberAddress);\n const roleKey = input.roleKey.toLowerCase() as Hex;\n const managerRoleKey = input.managerRoleKey.toLowerCase() as Hex;\n const assignRolesData = encodeFunctionData({\n abi: ROLES_ASSIGN_ROLES_ABI,\n functionName: \"assignRoles\",\n args: [memberAddress, [roleKey], [input.memberOf]],\n });\n\n return {\n to: rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [rolesModuleAddress, 0n, assignRolesData, ZODIAC_OPERATION_CALL, managerRoleKey, true],\n }),\n value: 0n,\n };\n}\n","/**\n * A single frame in PostHog's `$exception_list` format.\n * Matches `[{ frames: [{ filename, function, lineno, colno }] }]`.\n */\nexport interface ExceptionFrame {\n readonly filename: string;\n readonly function: string;\n readonly lineno: number | null;\n readonly colno: number | null;\n}\n\n/**\n * Regex for V8/Chrome stack trace frame lines.\n * Matches:\n * `at functionName (url:line:col)`\n * `at url:line:col`\n * `at async functionName (url:line:col)`\n * `at new ClassName (url:line:col)`\n */\nconst V8_FRAME_RE = /^\\s*at\\s+(?:(.+?)\\s+\\()?(?:(.+?)(?::(\\d+):(\\d+))?|(.+?))\\)?\\s*$/;\n\nfunction isNonUrlName(name: string): boolean {\n return (\n name === \"<anonymous>\" ||\n name.startsWith(\"eval\") ||\n name.startsWith(\"new \") ||\n name.startsWith(\"async \")\n );\n}\n\n/**\n * Parse a V8/Chrome-style stack trace string into PostHog `ExceptionFrame` objects.\n * Returns an empty array when `error.stack` is absent or empty.\n *\n * Handles:\n * - Standard `at functionName (url:line:col)`\n * - Bare `at url:line:col` (no function name)\n * - `at async functionName (url:line:col)`\n * - `at new ClassName (url:line:col)`\n * - Native frames: `at Array.forEach (<anonymous>)`\n */\nexport function parseV8StackFrames(error: { readonly stack?: string }): readonly ExceptionFrame[] {\n const stack = error.stack;\n if (stack === undefined || stack === null || stack === \"\") {\n return [];\n }\n\n const lines = stack.split(\"\\n\");\n const frames: ExceptionFrame[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"at \")) continue;\n\n const match = V8_FRAME_RE.exec(trimmed);\n if (match === null) continue;\n\n if (match[1] !== undefined) {\n // Has function name: `at functionName (url:line:col)`\n frames.push({\n function: match[1],\n filename: match[2]!,\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n } else if (match[2] !== undefined && !isNonUrlName(match[2])) {\n // Bare URL: `at url:line:col`\n frames.push({\n function: \"<anonymous>\",\n filename: match[2],\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n } else {\n // Native or non-URL frame like `<anonymous>`\n frames.push({\n function: match[1] ?? match[2] ?? match[5] ?? \"<anonymous>\",\n filename: match[2] ?? match[5] ?? \"<anonymous>\",\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n }\n }\n\n return frames;\n}\n\n/**\n * Build PostHog's `$exception_list` format from a list of frames.\n * Returns `[{ frames: [...] }]` or `undefined` if the frames list is empty.\n */\nexport function buildExceptionList(\n frames: readonly ExceptionFrame[],\n): readonly [{ readonly frames: readonly ExceptionFrame[] }] | undefined {\n if (frames.length === 0) return undefined;\n return [{ frames } as { readonly frames: readonly ExceptionFrame[] }];\n}\n","import { isCapxulError, type FailureMode } from \"@capxul/config\";\n\n/**\n * The five canonical {@link FailureMode} members, for runtime membership checks.\n * Single source of truth — tests assert against this exact set so the taxonomy\n * and its guard can never drift apart.\n */\nexport const FAILURE_MODES: ReadonlySet<string> = new Set<FailureMode>([\n \"auth-origin-mismatch\",\n \"stale-openfort-cache\",\n \"app-env-allowlist\",\n \"no-secure-context\",\n \"unknown\",\n]);\n\nfunction isFailureMode(value: unknown): value is FailureMode {\n return typeof value === \"string\" && FAILURE_MODES.has(value);\n}\n\n/**\n * Extract the structured {@link FailureMode} from a CapxulError.\n *\n * Reads `details.failure_mode` and returns it only when it is one of the five\n * canonical members; any other value (a legacy free string, a typo, a\n * non-string) yields `undefined` so downstream telemetry never reports an\n * unrecognised cause.\n */\nexport function getFailureMode(error: unknown): FailureMode | undefined {\n if (!isCapxulError(error)) return undefined;\n const details = error.details;\n if (details === undefined) return undefined;\n return isFailureMode(details.failure_mode) ? details.failure_mode : undefined;\n}\n\n/**\n * Resolve the canonical {@link FailureMode} for a `$exception`, guaranteeing a\n * taxonomy member is always returned — never `undefined`, never a free string.\n *\n * Resolution order:\n * 1. the structured mode on the error's `details.failure_mode` (already guarded);\n * 2. a caller-supplied `contextFailureMode`, but ONLY when it passes the same\n * runtime membership check — the static `FailureMode` type is erased at\n * runtime, so an operation string (e.g. `\"signer-get-address\"`) injected via\n * a JS caller or `as` cast is rejected here rather than leaking to telemetry;\n * 3. `\"unknown\"` otherwise, so an unclassifiable error is still tagged with a\n * canonical value instead of being emitted with no `failure_mode` at all.\n */\nexport function resolveFailureMode(error: unknown, contextFailureMode?: unknown): FailureMode {\n return (\n getFailureMode(error) ?? (isFailureMode(contextFailureMode) ? contextFailureMode : \"unknown\")\n );\n}\n","import { Effect } from \"effect\";\n\nimport { isCapxulError, type FailureMode } from \"@capxul/config\";\n\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { parseV8StackFrames, buildExceptionList } from \"./stack-frame-parser\";\nimport { resolveFailureMode } from \"./get-failure-mode\";\n\nexport interface HandledErrorReportContext {\n readonly layer?: string;\n readonly operation?: string;\n readonly provider?: string;\n readonly capxul_error_code?: string;\n readonly failure_mode?: FailureMode;\n}\n\n/**\n * Capture an error as a `$exception` event through the telemetry port,\n * formatted for PostHog Error Tracking.\n *\n * Parses stack traces into `$exception_list` format, extracts structured\n * metadata from CapxulError objects, and supplements with context props.\n * Fire-and-forget: telemetry defects are silently swallowed.\n * Returns `Effect<void, never>` for use in Effect pipelines; the underlying\n * adapter work is synchronous, so callers outside Effect contexts can\n * use `Effect.runSync`.\n */\nexport function captureException(\n telemetry: TelemetryPort,\n error: unknown,\n context?: HandledErrorReportContext,\n): Effect.Effect<void, never> {\n return Effect.catchAllDefect(\n Effect.sync(() => {\n const frames = error instanceof Error ? parseV8StackFrames(error) : [];\n const exceptionList = buildExceptionList(frames);\n\n const capxulError = isCapxulError(error) ? error : null;\n const errorCode = capxulError?.code ?? context?.capxul_error_code ?? \"UNKNOWN\";\n\n const props: Record<string, unknown> = {\n capxul_error_code: errorCode,\n layer: capxulError?.layer ?? context?.layer,\n operation: context?.operation,\n provider: context?.provider,\n // Always a canonical FailureMode member (defaults to \"unknown\"); the\n // resolver rejects non-taxonomy context values so an operation string\n // can never reach PostHog, and the key is never pruned as undefined.\n failure_mode: resolveFailureMode(error, context?.failure_mode),\n };\n\n if (exceptionList !== undefined) {\n props.$exception_list = exceptionList;\n }\n\n if (capxulError?.details !== undefined) {\n props.details = JSON.stringify(capxulError.details);\n }\n\n // Remove undefined values\n for (const key of Object.keys(props)) {\n if (props[key] === undefined) {\n // oxlint-disable-next-line no-dynamic-delete -- prune absent props before emit\n delete props[key];\n }\n }\n\n return telemetry.emit({ name: \"$exception\" as never, props });\n }).pipe(Effect.flatten),\n () => Effect.void,\n );\n}\n\n/**\n * Synchronous fire-and-forget capture. Runs the Effect inline with\n * `Effect.runSync` so callers outside an Effect context (e.g. React\n * hooks before throwing) can report errors without awaiting.\n */\nexport function captureExceptionSync(\n telemetry: TelemetryPort,\n error: unknown,\n context?: HandledErrorReportContext,\n): void {\n try {\n Effect.runSync(captureException(telemetry, error, context));\n } catch {\n // Fire-and-forget: telemetry failures never propagate\n }\n}\n","// Shared substrate for the consumer-facing method bundles in\n// `packages/sdk/src/client/*`. Two pieces of boilerplate were duplicated\n// across `account.ts` and `smart-account.ts` (and will be needed by the\n// `_internal.account` provision/deploy slot landing with #161):\n//\n// 1. The Effect→`Promise<CapxulResult<T>>` bridge for ports whose typed\n// failure channel carries `{ publicError: CapxulError }`.\n// 2. Reading the live AuthFlow actor snapshot. The actor's `getSnapshot`\n// is already fully typed (`AuthFlowObserver.getSnapshot` in\n// `../../flows/auth`), so the previous inline `as { context: { session } }`\n// cast in `account.ts` was redundant — this module replaces it with a\n// typed accessor derived from the actor's own return type.\n\nimport type { CapxulError } from \"@capxul/config\";\nimport type { AuthSession } from \"@capxul/types\";\nimport { Effect, Either } from \"effect\";\n\nimport type { AuthFlowActor } from \"../../flows/auth\";\nimport type { CapxulResult } from \"../types\";\n\n/**\n * Bridge an Effect whose typed failure carries `{ publicError: CapxulError }`\n * into the `Promise<CapxulResult<T>>` shape the consumer-facing method\n * bundles return. Applies to every port that surfaces a `publicError`\n * (smart-account, identity, auth-cache, and — post-#161 — account\n * provision/deploy).\n */\nexport async function runPortEffect<T>(\n effect: Effect.Effect<T, { readonly publicError: CapxulError }>,\n): Promise<CapxulResult<T>> {\n const result = await Effect.runPromise(Effect.either(effect));\n if (Either.isRight(result)) return { ok: true, value: result.right };\n return { ok: false, error: result.left.publicError };\n}\n\n/** The session carried by the actor's current snapshot, or `null`. */\nexport function sessionFromActor(actor: AuthFlowActor): AuthSession | null {\n return actor.getSnapshot().context.session;\n}\n","import { Effect } from \"effect\";\n\nimport type { SmartAccount } from \"@capxul/types\";\n\nimport type { TelemetryPort } from \"../../ports/telemetry\";\n\nexport async function emitProvisioningTelemetry(\n telemetry: TelemetryPort | undefined,\n smartAccount: SmartAccount,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry\n .emit({\n name: \"provisioning_safe_created\",\n props: { safe_address: smartAccount.smartAccountAddress },\n })\n .pipe(\n Effect.catchAll((cause) =>\n Effect.sync(() => reportProvisioningTelemetryFailure(\"error\", smartAccount, cause)),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.sync(() => reportProvisioningTelemetryFailure(\"defect\", smartAccount, cause)),\n ),\n ),\n );\n}\n\nfunction reportProvisioningTelemetryFailure(\n kind: \"error\" | \"defect\",\n smartAccount: SmartAccount,\n cause: unknown,\n): void {\n if (!isProvisioningTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] provisioning telemetry dropped\", {\n kind,\n safeAddress: smartAccount.smartAccountAddress,\n cause,\n });\n}\n\nfunction isProvisioningTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","// Account-readiness substrate — the `client.account.getStatus` readiness\n// ladder expressed as an Effect program that resolves a single Context tag\n// (PRD #209 hourglass collapse, slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape:\n//\n// 1. `AccountDeps` — the dependency bundle one Context tag carries.\n// A structural subset of `MakeAccountMethodsDeps`\n// (`account.ts`) — exactly the deps the\n// `getStatus` ladder reads.\n// 2. `AccountDepsTag` — the single tag the account atom + the public\n// `getStatus` method (via `toCapxulResult`)\n// resolve.\n// 3. `accountDepsLayer` — wraps a bundle as `Layer<AccountDepsTag>`.\n// 4. `accountStatusProgram` — `account.getStatus` as a single\n// `Effect<AccountStatus, CapxulError,\n// AccountDepsTag>`.\n//\n// `statusFromAccount` + `currentSession` live here (the `getStatus` helpers);\n// `account.ts` imports them back so `account-deps.ts` depends on `account.ts`\n// for the `AccountStatus` TYPE only (erased at runtime → no value cycle).\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — reachable only via the\n// `@capxul/sdk/react-substrate` subpath. See\n// `.claude/rules/flow-internal-substrate.md`.\n\nimport { Context, Effect, Either, Layer } from \"effect\";\n\nimport { Errors, isCapxulError, type CapxulError } from \"@capxul/config\";\nimport type { AuthSession, SmartAccount } from \"@capxul/types\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { IdentityPort } from \"../ports/identity\";\nimport { sessionFromActor } from \"./_shared/effect-actor-bridge\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { AccountRequirement } from \"./account-providers\";\nimport type { CapxulSigner } from \"../signer\";\nimport type { AccountStatus } from \"./account\";\n\n/**\n * The dependency bundle a single `Context.Tag` carries (PRD #209). A\n * structural subset of `MakeAccountMethodsDeps` — exactly the deps the\n * `getStatus` ladder reads — so a `MakeAccountMethodsDeps` value is assignable\n * wherever an `AccountDeps` is expected.\n */\nexport interface AccountDeps {\n readonly actor: AuthFlowActor;\n readonly authCache?: AuthCachePort;\n readonly identityPort: IdentityPort;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: number;\n readonly requirement: AccountRequirement;\n readonly signer?: CapxulSigner;\n}\n\n/** The single Context tag the account atom + `account.getStatus` resolve. */\nexport class AccountDepsTag extends Context.Tag(\"@capxul/sdk/AccountDeps\")<\n AccountDepsTag,\n AccountDeps\n>() {}\n\n/** Wrap a bundle as the `Layer<AccountDepsTag>` the React provider consumes. */\nexport function accountDepsLayer(deps: AccountDeps): Layer.Layer<AccountDepsTag> {\n return Layer.succeed(AccountDepsTag, deps);\n}\n\n/**\n * `account.getStatus` as a single Effect requiring ONLY `AccountDepsTag`.\n * Faithful transcription of the current public method body (`account.ts`):\n * resolve the session (actor first, then the resume-path `authCache`), then\n * walk the readiness ladder. The `SmartAccountPort` failure narrows to its\n * `publicError`; a consumer `AccountProvider.getAddress` rejection becomes a\n * `providerError` (defending the public `CapxulResult` contract).\n */\nexport const accountStatusProgram: Effect.Effect<AccountStatus, CapxulError, AccountDepsTag> =\n Effect.gen(function* () {\n const deps = yield* AccountDepsTag;\n const session = yield* Effect.promise(() => currentSession(deps.actor, deps.authCache));\n if (session === null) {\n return { status: \"notAuthenticated\" };\n }\n\n const current = yield* deps.smartAccountPort\n .loadByAuthUserId(session.authUserId)\n .pipe(Effect.mapError((failure) => failure.publicError));\n if (current !== null) {\n return statusFromAccount(current, deps.requirement);\n }\n\n if (deps.requirement === \"none\") {\n return {\n status: \"accountReady\",\n requirement: deps.requirement,\n account: null,\n deployment: { status: \"counterfactual\" },\n };\n }\n\n const signer = deps.signer;\n if (signer === undefined) {\n return { status: \"accountRequired\", requirement: deps.requirement, chainId: deps.chainId };\n }\n // Defend the public `CapxulResult` contract — a consumer-supplied signer\n // could throw. A rejection here would otherwise propagate up through\n // `client.account.getStatus()` and break it. Preserve an already-classified\n // CapxulError (e.g. the signer's `no-secure-context` probe) so its\n // `failure_mode` survives instead of being flattened into a bare\n // `getAddress` provider error.\n const signerAddress = yield* Effect.tryPromise({\n try: () => signer.getAddress(),\n catch: (cause) =>\n isCapxulError(cause) ? cause : Errors.providerError(\"signer\", \"getAddress\", cause),\n });\n return {\n status: \"accountProviderReady\",\n requirement: deps.requirement,\n chainId: deps.chainId,\n source: signer.source,\n signerAddress,\n };\n });\n\n/**\n * Resume-path session resolution. Consults the actor first; if the actor has\n * no session (e.g. page refresh before any sign-in event), reads\n * `authCache.getSession`. `AuthCacheError` is non-fatal at this read point —\n * treat as \"no session\" and let the consumer's `auth.signIn` path resolve.\n */\nexport async function currentSession(\n actor: AuthFlowActor,\n authCache: AuthCachePort | undefined,\n): Promise<AuthSession | null> {\n const fromActor = sessionFromActor(actor);\n if (fromActor !== null) return fromActor;\n if (authCache === undefined) return null;\n const cached = await Effect.runPromise(Effect.either(authCache.getSession));\n if (Either.isRight(cached)) return cached.right;\n return null;\n}\n\n/** Map a backend `SmartAccount` row onto the readiness `AccountStatus`. */\nfunction statusFromAccount(account: SmartAccount, requirement: AccountRequirement): AccountStatus {\n if (requirement === \"deployed\") {\n if (account.deployedAt === null) {\n return {\n status: \"accountPrepared\",\n requirement,\n account,\n deployment: { status: \"counterfactual\" },\n };\n }\n return {\n status: \"accountReady\",\n requirement,\n account,\n deployment: { status: \"deployed\", deployedAt: account.deployedAt },\n };\n }\n return {\n status: \"accountReady\",\n requirement,\n account,\n deployment:\n account.deployedAt === null\n ? { status: \"counterfactual\" }\n : { status: \"deployed\", deployedAt: account.deployedAt },\n };\n}\n","import type { CapxulError } from \"@capxul/config\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { AccountRequirement } from \"./account-providers\";\nimport type { AccountStatus } from \"./account\";\nimport type { CapxulResult } from \"./types\";\n\n// PRD #462 (derivation v2): the binding step is GONE — the Safe address is a\n// pure function of the authenticated email, so the lane is wallet → identity\n// → provision (counterfactual), plus the claim (\"deploy\") step when the\n// requirement is `deployed` and a signer is present to claim with.\nexport type ProvisioningFailureStep = \"wallet\" | \"identity\" | \"provision\" | \"deploy\";\n\nexport type ProvisioningPhase =\n | { readonly status: \"idle\" }\n | { readonly status: \"wallet\" }\n | { readonly status: \"identity\" }\n | { readonly status: \"provision\" }\n | { readonly status: \"deploy\" }\n | { readonly status: \"ready\" }\n | {\n readonly status: \"failed\";\n readonly at: ProvisioningFailureStep;\n readonly error: CapxulError;\n };\n\nexport function isActiveProvisioningPhase(phase: ProvisioningPhase): boolean {\n return (\n phase.status === \"wallet\" ||\n phase.status === \"identity\" ||\n phase.status === \"provision\" ||\n phase.status === \"deploy\"\n );\n}\n\nexport function isRequirementMet(status: AccountStatus, requirement: AccountRequirement): boolean {\n if (requirement === \"none\") {\n return status.status !== \"notAuthenticated\";\n }\n if (status.status !== \"accountReady\") {\n return false;\n }\n if (requirement === \"deployed\") {\n return status.deployment.status === \"deployed\";\n }\n return true;\n}\n\nexport interface AccountLaneSteps {\n readonly requirement: AccountRequirement;\n /**\n * Whether the client holds a `CapxulSigner` — i.e. whether THIS client can\n * claim. Counterfactual provisioning is naturally signerless under\n * derivation v2 (PRD #462). A `deployed` requirement without a signer\n * parks at `accountPrepared` (counterfactual): the dedicated approval\n * surface owns the claim (pending + approvalUrl pattern). Omitted = signer\n * present (browser default).\n */\n readonly hasSigner?: boolean;\n readonly getStatus: () => Promise<CapxulResult<AccountStatus>>;\n readonly getSession: () => Promise<AuthSession | null>;\n readonly runWallet: () => Promise<CapxulResult<void>>;\n readonly runIdentity: (session: AuthSession) => Promise<CapxulResult<void>>;\n readonly runProvision: () => Promise<CapxulResult<unknown>>;\n readonly runDeploy: () => Promise<CapxulResult<unknown>>;\n}\n\nexport interface AccountLane {\n getProvisioningPhase(): ProvisioningPhase;\n kickProvisioning(): void;\n resolveProvisioningPhase(): Promise<ProvisioningPhase>;\n retryProvisioning(): Promise<ProvisioningPhase>;\n runLane(): Promise<ProvisioningPhase>;\n}\n\nexport function createAccountLane(steps: AccountLaneSteps): AccountLane {\n let phase: ProvisioningPhase = { status: \"idle\" };\n let inFlight: Promise<ProvisioningPhase> | null = null;\n\n const setPhase = (next: ProvisioningPhase): void => {\n phase = next;\n };\n\n const failAt = (at: ProvisioningFailureStep, error: CapxulError): ProvisioningPhase => {\n const failed: ProvisioningPhase = { status: \"failed\", at, error };\n setPhase(failed);\n return failed;\n };\n\n const shouldAutoStart = async (): Promise<boolean> => {\n if (steps.requirement === \"none\") return false;\n if (phase.status === \"failed\") return false;\n if (isActiveProvisioningPhase(phase)) return false;\n if (phase.status === \"ready\") return false;\n const session = await steps.getSession();\n if (session === null) return false;\n const status = await steps.getStatus();\n if (!status.ok) return false;\n return !isRequirementMet(status.value, steps.requirement);\n };\n\n const runLane = async (): Promise<ProvisioningPhase> => {\n if (steps.requirement === \"none\") {\n setPhase({ status: \"idle\" });\n return phase;\n }\n\n const session = await steps.getSession();\n if (session === null) {\n setPhase({ status: \"idle\" });\n return phase;\n }\n\n let status = await steps.getStatus();\n if (!status.ok) {\n return failAt(\"wallet\", status.error);\n }\n if (isRequirementMet(status.value, steps.requirement)) {\n setPhase({ status: \"ready\" });\n return phase;\n }\n\n if (\n status.value.status === \"accountRequired\" ||\n status.value.status === \"accountProviderReady\" ||\n status.value.status === \"notAuthenticated\"\n ) {\n setPhase({ status: \"wallet\" });\n const wallet = await steps.runWallet();\n if (!wallet.ok) return failAt(\"wallet\", wallet.error);\n status = await steps.getStatus();\n if (!status.ok) return failAt(\"wallet\", status.error);\n if (isRequirementMet(status.value, steps.requirement)) {\n setPhase({ status: \"ready\" });\n return phase;\n }\n }\n\n // Counterfactual provisioning is signerless by construction (PRD #462):\n // identity → provision derives the Safe from the authenticated email\n // alone — no binding, no pregeneration, no vendor call.\n if (\n status.value.status === \"accountRequired\" ||\n status.value.status === \"accountProviderReady\"\n ) {\n setPhase({ status: \"identity\" });\n const identity = await steps.runIdentity(session);\n if (!identity.ok) return failAt(\"identity\", identity.error);\n\n setPhase({ status: \"provision\" });\n const provisioned = await steps.runProvision();\n if (!provisioned.ok) return failAt(\"provision\", provisioned.error);\n\n status = await steps.getStatus();\n if (!status.ok) return failAt(\"provision\", status.error);\n if (isRequirementMet(status.value, steps.requirement)) {\n setPhase({ status: \"ready\" });\n return phase;\n }\n }\n\n // Claim (\"deploy\") step: only when this client can claim (signer present).\n // Signerless deployed-requirement clients park at counterfactual — the\n // dedicated approval surface owns the claim.\n if (\n status.value.status === \"accountPrepared\" &&\n steps.requirement === \"deployed\" &&\n steps.hasSigner !== false\n ) {\n setPhase({ status: \"deploy\" });\n const deployed = await steps.runDeploy();\n if (!deployed.ok) return failAt(\"deploy\", deployed.error);\n status = await steps.getStatus();\n if (!status.ok) return failAt(\"deploy\", status.error);\n }\n\n if (status.ok && isRequirementMet(status.value, steps.requirement)) {\n setPhase({ status: \"ready\" });\n return phase;\n }\n\n setPhase({ status: \"idle\" });\n return phase;\n };\n\n const startLane = (): Promise<ProvisioningPhase> => {\n if (inFlight !== null) return inFlight;\n inFlight = runLane().finally(() => {\n inFlight = null;\n });\n return inFlight;\n };\n\n return {\n getProvisioningPhase(): ProvisioningPhase {\n return phase;\n },\n\n kickProvisioning(): void {\n void (async () => {\n if (await shouldAutoStart()) {\n await startLane();\n }\n })();\n },\n\n async resolveProvisioningPhase(): Promise<ProvisioningPhase> {\n // Snapshot reads must not await the full lane — `getLifecycle` polls this\n // every 2s and the UI maps `loading` to \"Checking account…\". Kick the\n // lane in the background and return the current phase instead.\n if (await shouldAutoStart()) {\n void startLane();\n return phase;\n }\n if (inFlight !== null) {\n return phase;\n }\n return phase;\n },\n\n async retryProvisioning(): Promise<ProvisioningPhase> {\n if (inFlight !== null) {\n return inFlight;\n }\n if (phase.status === \"failed\" || phase.status === \"idle\") {\n setPhase({ status: \"idle\" });\n inFlight = runLane().finally(() => {\n inFlight = null;\n });\n return inFlight;\n }\n return phase;\n },\n\n async runLane(): Promise<ProvisioningPhase> {\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = runLane().finally(() => {\n inFlight = null;\n });\n return inFlight;\n },\n };\n}\n","import type { CapxulError } from \"@capxul/config\";\n\nimport {\n isActiveProvisioningPhase,\n isRequirementMet,\n type ProvisioningFailureStep,\n type ProvisioningPhase,\n} from \"./account-lane\";\nimport type { AccountStatus } from \"./account\";\nimport type { AccountRequirement } from \"./account-providers\";\n\nexport type AccountSetupStep = \"connecting\" | \"confirmingIdentity\" | \"registering\" | \"activating\";\n\nexport type AccountLifecycle =\n | { readonly status: \"loading\" }\n | { readonly status: \"settingUp\"; readonly step: AccountSetupStep }\n | { readonly status: \"ready\"; readonly accountId: string; readonly canTransact: boolean }\n | { readonly status: \"failed\"; readonly at: AccountSetupStep; readonly error: CapxulError };\n\nexport interface MapAccountLifecycleInput {\n readonly status: AccountStatus;\n readonly phase: ProvisioningPhase;\n readonly requirement: AccountRequirement;\n readonly accountId?: string;\n}\n\n// PRD #462: the \"binding\" provisioning step no longer exists — the address\n// derives from the email alone. \"confirmingIdentity\" stays in the public\n// `AccountSetupStep` vocabulary (contract-stable) but is no longer produced.\nexport function mapProvisioningFailureStep(step: ProvisioningFailureStep): AccountSetupStep {\n switch (step) {\n case \"wallet\":\n return \"connecting\";\n case \"identity\":\n return \"registering\";\n case \"provision\":\n case \"deploy\":\n return \"activating\";\n }\n}\n\nexport function mapProvisioningPhaseToSetupStep(phase: ProvisioningPhase): AccountSetupStep {\n switch (phase.status) {\n case \"idle\":\n case \"wallet\":\n return \"connecting\";\n case \"identity\":\n return \"registering\";\n case \"provision\":\n case \"deploy\":\n return \"activating\";\n case \"ready\":\n case \"failed\":\n return \"connecting\";\n }\n}\n\nexport function isSettingUpLifecycle(lifecycle: AccountLifecycle): boolean {\n return lifecycle.status === \"settingUp\";\n}\n\nfunction readyLifecycle(status: AccountStatus, accountId: string): AccountLifecycle {\n const canTransact = status.status === \"accountReady\" && status.deployment.status === \"deployed\";\n return { status: \"ready\", accountId, canTransact };\n}\n\nexport function mapAccountLifecycle(input: MapAccountLifecycleInput): AccountLifecycle {\n const { status, phase, requirement, accountId } = input;\n\n if (status.status === \"notAuthenticated\") {\n return { status: \"loading\" };\n }\n\n if (phase.status === \"failed\") {\n return {\n status: \"failed\",\n at: mapProvisioningFailureStep(phase.at),\n error: phase.error,\n };\n }\n\n if (isRequirementMet(status, requirement) || phase.status === \"ready\") {\n if (accountId === undefined) {\n return { status: \"loading\" };\n }\n return readyLifecycle(status, accountId);\n }\n\n if (isActiveProvisioningPhase(phase) || phase.status === \"idle\") {\n return {\n status: \"settingUp\",\n step: mapProvisioningPhaseToSetupStep(phase),\n };\n }\n\n return { status: \"loading\" };\n}\n","// toCapxulResult — the single Effect→`CapxulResult` bridge (PRD #209).\n//\n// The hourglass collapse routes every public method through ONE bridge instead\n// of the per-method `Effect.either` runners scattered across the method\n// bundles. Given a program whose typed failure channel is `CapxulError` and the\n// `Layer` that satisfies its requirement, it:\n//\n// 1. provides the layer,\n// 2. catches any non-`CapxulError` DEFECT and converts it to\n// `Errors.unknown(...)` so the error channel stays typed `CapxulError`\n// end-to-end, and\n// 3. runs `Effect.either` to split success/failure into the `CapxulResult`\n// shape consumers expect.\n\nimport { Effect, Either, type Layer } from \"effect\";\n\nimport { Errors, type CapxulError } from \"@capxul/config\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport async function toCapxulResult<T, R>(\n program: Effect.Effect<T, CapxulError, R>,\n layer: Layer.Layer<R>,\n): Promise<CapxulResult<T>> {\n const result = await Effect.runPromise(\n program.pipe(\n Effect.provide(layer),\n Effect.catchAllDefect((defect) => Effect.fail(Errors.unknown(defect))),\n Effect.either,\n ),\n );\n if (Either.isLeft(result)) return { ok: false, error: result.left };\n return { ok: true, value: result.right };\n}\n","// Public consumer-facing `client.account` surface for the Effect-native\n// rebuild trunk. Ports the public-surface narrowing + readiness-ladder\n// shape from master (`packages/sdk/src/client/account.ts:42-77`) for\n// issue #159, sub-epic child 003b of #120.\n//\n// Diverges from master in two intentional ways for this slice:\n//\n// 1. `SmartAccountPort` is Effect-based on this trunk\n// (`Effect.Effect<SmartAccount | null, SmartAccountError, never>`),\n// so the public methods bridge via the shared `runPortEffect`\n// helper rather than awaiting a `Promise<CapxulResult<...>>`.\n// Mirrors the pattern already used by `makeSmartAccountMethods`.\n//\n// 2. The provision-action path (driving `accountProviderReady →\n// accountReady`) and the deploy path (`SafeDeploymentPort`,\n// `(authUserId, safeAddress)` deploy mutex, `accountPrepared`\n// upgrade) are deferred to sibling issue #161. `ensureReady` is a\n// fixed point relative to `getStatus` in this slice — every\n// readiness state returns the same value `getStatus` would.\n//\n// The `AccountStatus` discriminated union is the SHAPE the future\n// provision + deploy slices will fill; the `accountPrepared` variant is\n// reachable through `getStatus` (deployed-requirement + not-yet-deployed\n// backend record) but the upward `ensureReady → deploySafe` transition\n// lands in #161 with the deploy port.\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport {\n toAddress,\n toChainId,\n type Address,\n type AuthSession,\n type SmartAccount,\n} from \"@capxul/types\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { IdentityPort } from \"../ports/identity\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport type { CapxulSigner } from \"../signer\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport { runPortEffect } from \"./_shared/effect-actor-bridge\";\nimport { emitProvisioningTelemetry } from \"./_shared/provisioning-telemetry\";\nimport { accountDepsLayer, accountStatusProgram, currentSession } from \"./account-deps\";\nimport { createAccountLane, isRequirementMet, type ProvisioningPhase } from \"./account-lane\";\nimport { mapAccountLifecycle, type AccountLifecycle } from \"./account-lifecycle\";\nimport type { AccountProviderSource, AccountRequirement } from \"./account-providers\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport type { AccountLifecycle, AccountSetupStep } from \"./account-lifecycle\";\nexport {\n isSettingUpLifecycle,\n mapAccountLifecycle,\n mapProvisioningFailureStep,\n mapProvisioningPhaseToSetupStep,\n} from \"./account-lifecycle\";\nexport type { ProvisioningFailureStep, ProvisioningPhase } from \"./account-lane\";\nexport { isActiveProvisioningPhase, isRequirementMet } from \"./account-lane\";\n\nexport type AccountStatus =\n | { readonly status: \"notAuthenticated\" }\n | {\n readonly status: \"accountRequired\";\n readonly requirement: AccountRequirement;\n readonly chainId: number;\n }\n | {\n readonly status: \"accountProviderReady\";\n readonly requirement: AccountRequirement;\n readonly chainId: number;\n readonly source: AccountProviderSource;\n readonly signerAddress: Address;\n }\n | {\n readonly status: \"accountPrepared\";\n readonly requirement: AccountRequirement;\n readonly account: SmartAccount;\n readonly deployment: { readonly status: \"counterfactual\" };\n }\n | {\n readonly status: \"accountReady\";\n readonly requirement: AccountRequirement;\n readonly account: SmartAccount | null;\n readonly deployment:\n | { readonly status: \"counterfactual\" }\n | {\n readonly status: \"deployed\";\n readonly deployedAt: SmartAccount[\"deployedAt\"];\n };\n };\n\n/**\n * Public consumer-facing surface (issue #159 · AC1+AC3). Exactly two\n * methods. `provision` and `deploySafe` are intentionally NOT here —\n * they are advanced/testing-only and will live on\n * `client._internal.account` when sibling issue #161 lands. Per\n * `docs/canon/rules/public-surface.md`, the narrowing is enforced at\n * both the type level (the `keyof AccountMethods` extract is exactly\n * `\"getStatus\" | \"ensureReady\"`) and at runtime (the bundle returned\n * here has those two own-keys and nothing else).\n *\n * Per `docs/canon/conventions/flow-internal-substrate.md`, the\n * `AccountStatus` discriminant — including the variants this slice can\n * only reach via `getStatus` (e.g. `accountPrepared`) — is the durable\n * shape consumers depend on. Sibling #161 will extend `ensureReady` to\n * advance the ladder past `accountProviderReady` and from\n * `accountPrepared` to `accountReady(deployed)`; until then, the type\n * surface is stable and the runtime fixed-point is documented.\n */\nexport interface AccountMethods {\n /**\n * Post-auth account setup lifecycle — domain vocabulary over the internal\n * readiness ladder + provisioning lane (#356).\n */\n getLifecycle(): Promise<CapxulResult<AccountLifecycle>>;\n /** Resume setup after `failed` and return the updated lifecycle snapshot. */\n retrySetup(): Promise<CapxulResult<AccountLifecycle>>;\n /**\n * Internal advanced surface (#161 · AC1). Reserved for the rebuild's\n * own `ensureReady` upward transitions and for testing harnesses;\n * consumers MUST NOT depend on this in production. Tagged\n * `@internal-use` per `.claude/rules/flow-internal-substrate.md`.\n *\n * @internal-use\n */\n readonly _internal: AccountInternalSurface;\n}\n\n/**\n * Internal `provision` + `deploySafe` arms exposed at\n * `client._internal.account` (#161). Each returns `Promise<CapxulResult<T>>`\n * with the same error catalog the public methods use.\n *\n * @internal-use\n */\nexport interface AccountInternalSurface {\n provision(): Promise<CapxulResult<SmartAccount>>;\n deploySafe(): Promise<CapxulResult<SmartAccount>>;\n /** @internal-use Substrate readiness ladder — tests and e2e only. */\n getStatus(): Promise<CapxulResult<AccountStatus>>;\n /** @internal-use Lane runner — tests and e2e only. */\n ensureReady(): Promise<CapxulResult<AccountStatus>>;\n /** @internal-use Provisioning lane phase — tests and e2e only. */\n getProvisioningPhase(): Promise<CapxulResult<ProvisioningPhase>>;\n /** @internal-use Lane retry — tests and e2e only. */\n retryProvisioning(): Promise<CapxulResult<ProvisioningPhase>>;\n}\n\nexport interface MakeAccountMethodsDeps {\n readonly actor: AuthFlowActor;\n /**\n * Resume-path fallback. `currentSession` consults the actor first; if\n * the actor has no session (e.g. page refresh before any sign-in\n * event), it then reads `authCache.getSession`. Without this,\n * `getStatus` returns `notAuthenticated` on resume even when the cache\n * holds a valid session.\n */\n readonly authCache?: AuthCachePort;\n readonly identityPort: IdentityPort;\n readonly smartAccountPort: SmartAccountPort;\n readonly telemetry?: TelemetryPort;\n readonly chainId: number;\n /**\n * Init-time readiness target. The factory closes over this so the\n * public methods don't need to take a per-call requirement arg.\n * REQUIRED at every boundary — `assembleCapxulClient` always sets it\n * (see `CreateCapxulClientInput`), and hermetic tests that exercise\n * `makeAccountMethods` directly must pass an explicit value (no hidden\n * default; issue #159 · AC4 \"no backwards-compat shims\").\n */\n readonly requirement: AccountRequirement;\n /**\n * Consumer-held signer (PRD #462). The claim path reads `getAddress()` —\n * the ONLY signer interaction at claim time: the backend builds and\n * bootstrap-signs the claim userOp; the user's key signs nothing until\n * their first real transaction. The client never holds an RPC URL, a gas\n * policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n /** Resolves logical `Account.id` when mapping lifecycle to `ready`. */\n readonly accountReadPort?: AccountReadPort;\n}\n\nexport interface MakeAccountMethodsResult {\n readonly methods: AccountMethods;\n readonly kickProvisioning: () => void;\n}\n\nexport function makeAccountMethods(deps: MakeAccountMethodsDeps): MakeAccountMethodsResult {\n // Brand the chain id eagerly at construction so hermetic tests surface\n // bad values now rather than on the first call. The branded value is\n // unused in this slice; sibling #161 (provision + deploy) reads it from\n // `deps` directly.\n toChainId(deps.chainId);\n const requirement: AccountRequirement = deps.requirement;\n\n // Hourglass seam (PRD #209, slice 5): the readiness ladder now lives in\n // `accountStatusProgram` (resolving `AccountDepsTag`), run through the\n // shared `toCapxulResult` bridge. `ensureReady` + the `_internal` arms below\n // still call `getStatus()` and the ports directly.\n const getStatus: AccountInternalSurface[\"getStatus\"] = () =>\n toCapxulResult(accountStatusProgram, accountDepsLayer(deps));\n\n const runWallet = async (): Promise<CapxulResult<void>> => {\n const signer = deps.signer;\n if (signer === undefined) {\n return { ok: true, value: undefined };\n }\n try {\n await signer.getAddress();\n return { ok: true, value: undefined };\n } catch (cause) {\n if (cause instanceof CapxulError) {\n return { ok: false, error: cause };\n }\n return { ok: false, error: Errors.providerError(\"signer\", \"getAddress\", cause) };\n }\n };\n\n const ensureIdentityProfile = async (session: AuthSession): Promise<CapxulResult<void>> => {\n const existing = await runPortEffect(deps.identityPort.loadByAuthUserId(session.authUserId));\n if (!existing.ok) return { ok: false, error: existing.error };\n if (existing.value !== null) return { ok: true, value: undefined };\n const created = await runPortEffect(\n deps.identityPort.create({\n authUserId: session.authUserId,\n email: session.email,\n }),\n );\n if (!created.ok) return { ok: false, error: created.error };\n return { ok: true, value: undefined };\n };\n\n // --- _internal.account.provision (#161 · AC1) ---\n const provisionImpl = async (): Promise<CapxulResult<SmartAccount>> => {\n const session = await currentSession(deps.actor, deps.authCache);\n if (session === null) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n const profileReady = await ensureIdentityProfile(session);\n if (!profileReady.ok) return { ok: false, error: profileReady.error };\n const provisioned = await runPortEffect(\n deps.smartAccountPort.provision({\n authUserId: session.authUserId,\n chainId: toChainId(deps.chainId),\n }),\n );\n if (!provisioned.ok) return provisioned;\n await emitProvisioningTelemetry(deps.telemetry, provisioned.value);\n return { ok: true, value: provisioned.value };\n };\n\n // --- _internal.account.deploySafe → CLAIM (PRD #462) ---\n //\n // The \"deploy\" step is now the claim: ONE backend-built, bootstrap-signed\n // sponsored userOp (deploy + swapOwner). The signer contributes ONLY its\n // address. AC3 mutex: shared in-process Map<key, in-flight promise>;\n // the backend claim mutex is the authoritative dedup.\n const deployMutex = new Map<string, Promise<CapxulResult<SmartAccount>>>();\n\n const deploySafeImpl = async (): Promise<CapxulResult<SmartAccount>> => {\n const session = await currentSession(deps.actor, deps.authCache);\n if (session === null) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n const signer = deps.signer;\n if (signer === undefined) {\n return { ok: false, error: Errors.smartAccountMissing(\"deploySafe\") };\n }\n\n // Idempotency: a confirmed claim is final.\n const existing = await runPortEffect(\n deps.smartAccountPort.loadByAuthUserId(session.authUserId),\n );\n if (!existing.ok) return existing;\n if (existing.value !== null && existing.value.claimedAt !== null) {\n return { ok: true, value: existing.value };\n }\n // The smart-account row must exist before the backend can build the claim\n // op. If another caller provisions after loadByAuthUserId but before this\n // provisionImpl call, backend idempotency safely returns the existing row.\n if (existing.value === null) {\n const provisioned = await provisionImpl();\n if (!provisioned.ok) return provisioned;\n }\n\n // AC3 mutex collapse — one in-flight claim per (authUserId, chainId).\n const mutexKey = `${String(session.authUserId)}:${deps.chainId}`;\n const inFlight = deployMutex.get(mutexKey);\n if (inFlight !== undefined) return inFlight;\n\n const work = runBackendClaim({\n authUserId: session.authUserId,\n chainId: deps.chainId,\n signer,\n smartAccountPort: deps.smartAccountPort,\n }).finally(() => {\n deployMutex.delete(mutexKey);\n });\n deployMutex.set(mutexKey, work);\n return work;\n };\n\n const lane = createAccountLane({\n requirement,\n hasSigner: deps.signer !== undefined,\n getStatus,\n getSession: () => currentSession(deps.actor, deps.authCache),\n runWallet,\n runIdentity: ensureIdentityProfile,\n runProvision: provisionImpl,\n runDeploy: deploySafeImpl,\n });\n\n // ensureReady advances the ladder by delegating to the lane runner.\n const ensureReady: AccountInternalSurface[\"ensureReady\"] = async () => {\n const ran = await lane.runLane();\n if (ran.status === \"failed\") {\n return { ok: false, error: ran.error };\n }\n return getStatus();\n };\n\n const getProvisioningPhase: AccountInternalSurface[\"getProvisioningPhase\"] = async () => {\n const value = await lane.resolveProvisioningPhase();\n return { ok: true, value };\n };\n\n const retryProvisioning: AccountInternalSurface[\"retryProvisioning\"] = async () => {\n const next = await lane.retryProvisioning();\n return { ok: true, value: next };\n };\n\n const reportAndReturn = (error: CapxulError): { ok: false; error: CapxulError } => {\n if (deps.telemetry) {\n captureExceptionSync(deps.telemetry, error, {\n layer: \"account\",\n operation: \"getLifecycle\",\n });\n }\n return { ok: false, error };\n };\n\n const resolveLifecycle = async (): Promise<CapxulResult<AccountLifecycle>> => {\n const phase = await lane.resolveProvisioningPhase();\n const status = await getStatus();\n if (!status.ok) {\n return reportAndReturn(status.error);\n }\n let accountId: string | undefined;\n if (\n status.value.status !== \"notAuthenticated\" &&\n (phase.status === \"ready\" || isRequirementMet(status.value, requirement))\n ) {\n const accountReadPort = deps.accountReadPort;\n if (accountReadPort === undefined) {\n return reportAndReturn(\n Errors.invalidInput(\"account\", \"accountReadPort is required to resolve ready lifecycle\"),\n );\n }\n const account = await runPortEffect(\n accountReadPort.readBalance({ chainId: toChainId(deps.chainId) }),\n );\n if (!account.ok) {\n return reportAndReturn(account.error);\n }\n accountId = String(account.value.id);\n }\n\n return {\n ok: true,\n value: mapAccountLifecycle({\n status: status.value,\n phase,\n requirement,\n ...(accountId === undefined ? {} : { accountId }),\n }),\n };\n };\n\n const getLifecycle: AccountMethods[\"getLifecycle\"] = () => resolveLifecycle();\n\n const retrySetup: AccountMethods[\"retrySetup\"] = async () => {\n await lane.retryProvisioning();\n return resolveLifecycle();\n };\n\n return {\n methods: {\n getLifecycle,\n retrySetup,\n _internal: {\n provision: provisionImpl,\n deploySafe: deploySafeImpl,\n getStatus,\n ensureReady,\n getProvisioningPhase,\n retryProvisioning,\n },\n },\n kickProvisioning: () => {\n lane.kickProvisioning();\n },\n };\n}\n\ninterface BackendClaimInput {\n readonly authUserId: AuthSession[\"authUserId\"];\n readonly chainId: number;\n readonly signer: CapxulSigner;\n readonly smartAccountPort: SmartAccountPort;\n}\n\n/**\n * Backend-orchestrated claim (PRD #462):\n * 1. `signer.getAddress()` — the ONLY signer interaction at claim time.\n * 2. `claim` — the backend builds, bootstrap-signs, and submits the ONE\n * sponsored userOp (deploy when undeployed + swapOwner to the signer),\n * then confirms on-chain. The user's key signs nothing until their\n * first real transaction.\n * A row returned with `claimedAt: null` means another claim is in flight —\n * the lane re-checks status and lifecycle polling retries.\n */\nasync function runBackendClaim(input: BackendClaimInput): Promise<CapxulResult<SmartAccount>> {\n const chainId = toChainId(input.chainId);\n\n let signerAddress: Address;\n try {\n signerAddress = toAddress(await input.signer.getAddress());\n } catch (cause) {\n return { ok: false, error: Errors.providerError(\"signer\", \"getAddress\", cause) };\n }\n\n const claimed = await runPortEffect(\n input.smartAccountPort.claim({\n authUserId: input.authUserId,\n chainId,\n signerAddress,\n }),\n );\n if (!claimed.ok) return claimed;\n return { ok: true, value: claimed.value };\n}\n// Re-export the AccountProvider lane types so consumers depending on\n// `import { AccountProvider } from \"./account\"` (mirroring master)\n// continue to work. The runtime factories stay in\n// `./account-providers` (the canonical home; #158 landed them there).\nexport type {\n AccountProvider,\n AccountProviderSource,\n AccountRequirement,\n} from \"./account-providers\";\n","import { Errors } from \"@capxul/config\";\nimport { toAddress, type Address } from \"@capxul/types\";\nimport type { Account as ViemAccount, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport type AccountProviderSource = \"local-private-key\" | \"openfort-embedded\" | \"injected-eip1193\";\n\nexport type AccountRequirement = \"none\" | \"counterfactual\" | \"deployed\";\n\nexport interface AccountProvider {\n readonly source: AccountProviderSource;\n /**\n * Resolve the signer's EVM address.\n *\n * @determinism MUST return the same `Address` across calls for the\n * lifetime of a single provider instance — the SDK-level deploy mutex\n * keys on `(authUserId, safeAddress)` where `safeAddress` is computed\n * from `getAddress()`'s result before the port's `prepare()` round-trip.\n * If two successive calls returned different addresses, concurrent\n * `deploySafe` invocations would compute different mutex keys and\n * bypass dedup, defeating the mutex.\n *\n * The two sanctioned providers both satisfy this invariant:\n * - `localPrivateKeyAccountProvider` — derives once from the key\n * - `eip1193AccountProvider` — reads `eth_accounts` (idempotent once\n * the wallet is connected; consumer is responsible for connection)\n *\n * The Openfort embedded path no longer needs a provider: the\n * `openfortEmbeddedSigner` `CapxulSigner` caches its own address and the\n * deploy is backend-orchestrated (backend-orchestrated-deploy.md).\n *\n * Custom providers MUST honor this contract.\n */\n getAddress(): Promise<CapxulResult<Address>>;\n getDeployAccount(): Promise<CapxulResult<ViemAccount>>;\n}\n\nexport interface Eip1193Provider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\nexport function localPrivateKeyAccountProvider(input: {\n readonly privateKey: Hex;\n}): AccountProvider {\n const account = privateKeyToAccount(input.privateKey);\n const address = toAddress(account.address);\n return {\n source: \"local-private-key\",\n async getAddress() {\n return { ok: true, value: address };\n },\n async getDeployAccount() {\n return { ok: true, value: account };\n },\n };\n}\n\nexport function eip1193AccountProvider(input: {\n readonly provider: Eip1193Provider;\n}): AccountProvider {\n // Cache the first successful address to honor the determinism contract on\n // `AccountProvider.getAddress` (see JSDoc above). Without this cache, a user\n // switching accounts in their browser wallet mid-flow would produce a\n // different `Address` on successive calls, defeating the deploy mutex.\n // Errors are intentionally NOT cached — transient wallet-not-connected or\n // RPC failures must remain retryable.\n //\n // `inFlight` memoizes the in-progress request so that concurrent first\n // callers (e.g. two `await provider.getAddress()` issued in parallel before\n // either resolves) share the same `eth_accounts` round-trip and the same\n // resolved Address. Without it, both calls would race, both would hit the\n // wallet, and the second resolver could overwrite `cachedAddress` with a\n // stale-vs-fresh wallet read — defeating determinism even with the resolved\n // cache. Cleared in `finally` so the lane stays retryable after errors.\n let cachedAddress: Address | null = null;\n let inFlight: Promise<CapxulResult<Address>> | null = null;\n\n const getAddress = async (): Promise<CapxulResult<Address>> => {\n if (cachedAddress !== null) {\n return { ok: true, value: cachedAddress };\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const accounts = await input.provider.request({ method: \"eth_accounts\" });\n const first = firstAccount(accounts);\n if (first === null) {\n return { ok: false, error: Errors.smartAccountMissing(\"eip1193-account\") };\n }\n const address = toAddress(first);\n cachedAddress = address;\n return { ok: true, value: address };\n } catch (err) {\n return {\n ok: false,\n error: Errors.providerError(\"eip1193\", \"eth_accounts\", err),\n };\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n return {\n source: \"injected-eip1193\",\n getAddress,\n async getDeployAccount() {\n return {\n ok: false,\n error: Errors.notImplemented(\"Eip1193AccountProvider\", \"getDeployAccount\"),\n };\n },\n };\n}\n\nfunction firstAccount(value: unknown): string | null {\n if (!Array.isArray(value)) return null;\n const first = value[0];\n return typeof first === \"string\" ? first : null;\n}\n","// CapxulSigner — the consumer-held key boundary (backend-orchestrated-deploy.md).\n//\n// The backend orchestrates the Safe deployment (build + gas + paymaster + submit)\n// but never holds the user's key. The consumer supplies a `CapxulSigner` that\n// signs exactly one thing: the EIP-712 `SafeOp` digest the backend returns for\n// the prepared deployment UserOperation. `safe4337SafeOpDigest` (@capxul/config)\n// computes that digest; this signer produces the owner signature; the backend\n// packs + submits. Verified equivalent to permissionless's inline signing in\n// `src/__tests__/safe4337-split-sign.test.ts`.\n//\n// Security note: the browser signer uses `eth_sign`, which can sign arbitrary\n// bytes. In the backend-orchestrated flow, `CapxulSigner` signs only the\n// backend-provided SafeOp digest, so consumers must trust the backend that\n// constructs the UserOperation and computes that digest. A malicious backend\n// could ask the wallet to sign a harmful digest; prefer typed structured\n// signing when that flow exists, and only enable raw-hash signing for trusted\n// Capxul deployments.\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport type { AccountProviderSource } from \"./client/account-providers\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface CapxulSigner {\n /**\n * Signer kind — surfaced on the `accountProviderReady` status so the\n * readiness ladder reports which signer the consumer wired.\n */\n readonly source: AccountProviderSource;\n /** Owner EOA address — the Safe's single owner. */\n getAddress(): Promise<Address>;\n /**\n * Sign the EIP-712 `SafeOp` digest the backend returns for the prepared\n * deployment UserOperation. Returns the raw 65-byte ECDSA signature; the\n * backend packs `validAfter|validUntil|signature`.\n */\n signUserOpHash(hash: Hex): Promise<Hex>;\n}\n\n/** Minimal EIP-1193 surface an injected browser wallet exposes. */\nexport interface Eip1193RequestProvider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\n/**\n * Browser `CapxulSigner` backed by an injected EIP-1193 wallet (MetaMask, etc.).\n * Signs the SafeOp digest via `eth_sign`, then verifies the returned signature\n * recovers the selected account against that raw digest. Wallets that prefix\n * `eth_sign` payloads are rejected before the backend submits an invalid SafeOp.\n * The node key signer lives in `@capxul/sdk/node` (`localPrivateKeySigner`).\n */\nexport function injectedWalletSigner(provider: Eip1193RequestProvider): CapxulSigner {\n const resolveAddress = async (): Promise<Address> => {\n const accounts = await provider.request({ method: \"eth_requestAccounts\" });\n const first = Array.isArray(accounts) ? accounts[0] : undefined;\n if (typeof first !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned no accounts\");\n }\n if (!EVM_ADDRESS_HEX.test(first)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid address format\");\n }\n return toAddress(first);\n };\n return {\n source: \"injected-eip1193\",\n getAddress: resolveAddress,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"injectedWalletSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: unknown;\n try {\n signature = await provider.request({ method: \"eth_sign\", params: [address, hash] });\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: eth_sign failed; enable raw-hash signing for deployment (${detail})`,\n );\n }\n if (typeof signature !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned a non-string signature\");\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid signature format\");\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"injectedWalletSigner: wallet signature did not recover the selected account for the raw SafeOp digest; use a raw-hash-capable wallet or @capxul/sdk/node localPrivateKeySigner for deployed flows\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: could not verify raw SafeOp digest signature (${detail})`,\n );\n }\n}\n","// devPrivateKeySigner — browser-safe dev-mode `CapxulSigner` (dogfood only).\n//\n// Derives a deterministic throwaway EOA per email: privateKey =\n// keccak256(utf8(seed + normalizedEmail)). Re-login with the same email\n// reproduces the same signer, so binding resolution (signerAddress-hint\n// path) and the account lane stay coherent without Openfort. The seed is a\n// dev-only secret for unfunded keys; never fund these accounts.\n//\n// The signer is constructed before login, so the email is resolved lazily:\n// at first use it reads the cached `AuthSession` the SDK wrote to browser\n// localStorage (`capxul.session`, BrowserAuthCacheAdapter) — or uses the\n// explicit `email` override (tests / non-browser harnesses).\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { keccak256, stringToHex, type Hex } from \"viem\";\nimport { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\n\nimport { normalizeBindingEmail } from \"@capxul/config\";\n\nimport type { BrowserStorageShape } from \"./adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst SESSION_KEY = \"capxul.session\";\n\nexport interface DevPrivateKeySignerInput {\n /** Dev-only derivation seed (e.g. `VITE_CAPXUL_DEV_SIGNER_SEED`). Throwaway keys only. */\n readonly seed: string;\n /** Explicit email — skips the auth-cache lookup (tests, node harnesses). */\n readonly email?: string;\n /** Storage holding the cached session. Defaults to browser `localStorage`. */\n readonly storage?: BrowserStorageShape;\n}\n\n/** Deterministic dev private key for an email under a seed. Exported for probes. */\nexport function deriveDevPrivateKey(seed: string, email: string): Hex {\n return keccak256(stringToHex(seed + normalizeBindingEmail(email)));\n}\n\nfunction readSessionEmail(storage: BrowserStorageShape | undefined): string {\n const resolved =\n storage ??\n (globalThis as unknown as { window?: { localStorage?: BrowserStorageShape } }).window\n ?.localStorage;\n if (resolved === undefined) {\n throw new Error(\n \"devPrivateKeySigner: no browser localStorage available and no explicit email supplied\",\n );\n }\n const raw = resolved.getItem(SESSION_KEY);\n if (raw === null) {\n throw new Error(\n \"devPrivateKeySigner: no cached session yet — sign in before the account lane uses the signer\",\n );\n }\n let email: unknown;\n try {\n email = (JSON.parse(raw) as { email?: unknown }).email;\n } catch {\n throw new Error(\"devPrivateKeySigner: cached session is not valid JSON\");\n }\n if (typeof email !== \"string\" || email.length === 0) {\n throw new Error(\"devPrivateKeySigner: cached session has no email\");\n }\n return email;\n}\n\n/**\n * Browser-safe dev signer. Lazy: the email (and so the key) is resolved at\n * each `getAddress()` / `signUserOpHash()` from the cached session, so the\n * same signer instance follows whichever user is signed in.\n */\nexport function devPrivateKeySigner(input: DevPrivateKeySignerInput): CapxulSigner {\n if (input.seed.trim().length === 0) {\n throw new Error(\"devPrivateKeySigner: seed must be non-empty\");\n }\n const accounts = new Map<string, PrivateKeyAccount>();\n const resolveAccount = (): PrivateKeyAccount => {\n const email = normalizeBindingEmail(input.email ?? readSessionEmail(input.storage));\n const cached = accounts.get(email);\n if (cached !== undefined) return cached;\n const account = privateKeyToAccount(deriveDevPrivateKey(input.seed, email));\n accounts.set(email, account);\n return account;\n };\n return {\n source: \"local-private-key\",\n async getAddress(): Promise<Address> {\n return toAddress(resolveAccount().address);\n },\n async signUserOpHash(hash: Hex): Promise<Hex> {\n // Raw digest signing — same semantics as `localPrivateKeySigner` in\n // `@capxul/sdk/node`: no EIP-191 prefix on the SafeOp digest.\n return resolveAccount().sign({ hash });\n },\n };\n}\n","import type { Hex } from \"viem\";\n\n/**\n * Minimal Openfort embedded-wallet surface for hermetic tests and\n * `openfortEmbeddedSigner`. Keeps Convex / Shield secrets out of the SDK.\n */\nexport interface OpenfortEmbeddedWalletPort {\n /** Owner EOA address — must stay stable for the lifetime of this port. */\n getAddress(): Promise<string>;\n /**\n * Sign a 32-byte SafeOp digest without EIP-191 prefixing (backend-orchestrated\n * deploy contract).\n */\n signRawDigest(hash: Hex): Promise<Hex>;\n}\n\n/** Openfort `embeddedWallet` subset used by `openfortEmbeddedWalletPort`. */\nexport interface OpenfortEmbeddedWalletApi {\n get(): Promise<{ readonly address: string }>;\n signMessage(\n message: string | Uint8Array,\n options?: { readonly hashMessage?: boolean; readonly arrayifyMessage?: boolean },\n ): Promise<string>;\n}\n\nexport function openfortEmbeddedWalletPort(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureReady?: () => Promise<void>;\n}): OpenfortEmbeddedWalletPort {\n return {\n async getAddress() {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n const account = await input.embeddedWallet.get();\n return account.address;\n },\n async signRawDigest(hash) {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n // The digest must cross the Openfort iframe RPC as the 0x-hex STRING\n // with BOTH flags off — openfort-js's own raw-hash path\n // (walletHelpers: `signer.sign(hash, false, false)`) is the canon.\n // A Uint8Array mangles to UTF-8 across the RPC, and arrayifyMessage\n // triggers a double-arrayify inside the iframe; either way signing\n // dies with \"invalid arrayify value\" (first live signing proof,\n // mcp-stretch S4). hashMessage stays off: raw SafeOp digest, no\n // EIP-191 prefix.\n return (await input.embeddedWallet.signMessage(hash, {\n hashMessage: false,\n arrayifyMessage: false,\n })) as Hex;\n },\n };\n}\n","import { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport {\n openfortEmbeddedWalletPort,\n type OpenfortEmbeddedWalletApi,\n type OpenfortEmbeddedWalletPort,\n} from \"./adapters/openfort/embedded-wallet-port\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface OpenfortEmbeddedSignerInput {\n readonly wallet: OpenfortEmbeddedWalletPort;\n}\n\n/** Browser helper: wrap an initialized Openfort `embeddedWallet` API. */\nexport function openfortEmbeddedSignerFromWallet(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureWalletReady?: () => Promise<void>;\n}): OpenfortEmbeddedSigner {\n return openfortEmbeddedSigner({\n wallet: openfortEmbeddedWalletPort({\n embeddedWallet: input.embeddedWallet,\n ...(input.ensureWalletReady === undefined ? {} : { ensureReady: input.ensureWalletReady }),\n }),\n });\n}\n\n/**\n * Browser `CapxulSigner` backed by an Openfort embedded wallet (#335).\n * Signs the backend's SafeOp digest via raw `signMessage` (no EIP-191 prefix)\n * and verifies recovery before the backend submits.\n */\nexport type OpenfortEmbeddedSigner = CapxulSigner & {\n /** Drop cached `getAddress()` so the next read hits the embedded wallet again. */\n readonly resetAddressCache: () => void;\n};\n\nexport function openfortEmbeddedSigner(input: OpenfortEmbeddedSignerInput): OpenfortEmbeddedSigner {\n let cachedAddress: Address | null = null;\n let addressInFlight: Promise<Address> | null = null;\n // Bumped on every reset so a resolve that started before the reset cannot\n // win the race and repopulate the cache with the now-stale session address.\n let cacheEpoch = 0;\n\n const resetAddressCache = (): void => {\n cacheEpoch += 1;\n cachedAddress = null;\n addressInFlight = null;\n };\n\n const resolveAddress = async (): Promise<Address> => {\n if (cachedAddress !== null) {\n return cachedAddress;\n }\n if (addressInFlight !== null) {\n return addressInFlight;\n }\n const epoch = cacheEpoch;\n addressInFlight = (async () => {\n try {\n const raw = await input.wallet.getAddress();\n if (!EVM_ADDRESS_HEX.test(raw)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid address format\",\n );\n }\n const address = toAddress(raw);\n // A reset during this resolve invalidates the result — don't cache it.\n if (epoch === cacheEpoch) {\n cachedAddress = address;\n }\n return address;\n } finally {\n if (epoch === cacheEpoch) {\n addressInFlight = null;\n }\n }\n })();\n return addressInFlight;\n };\n\n return {\n source: \"openfort-embedded\",\n getAddress: resolveAddress,\n resetAddressCache,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"openfortEmbeddedSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: string;\n try {\n signature = await input.wallet.signRawDigest(hash);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: raw digest signing failed; ensure the embedded wallet is configured (${detail})`,\n { cause },\n );\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid signature format\",\n );\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"openfortEmbeddedSigner: signature did not recover the embedded wallet address for the raw SafeOp digest\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\n/**\n * Canonical name for the embedded-wallet `CapxulSigner` constructor\n * (backend-orchestrated-deploy.md). The embedded-wallet (passkey / Openfort)\n * member of the named constructor trio `localPrivateKeySigner` /\n * `injectedWalletSigner` / `embeddedSigner`. Takes the provider-agnostic\n * `OpenfortEmbeddedWalletPort` (getAddress + signRawDigest); the Openfort-API\n * convenience wrapper is `openfortEmbeddedSignerFromWallet`.\n */\nexport const embeddedSigner = openfortEmbeddedSigner;\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError } from \"@capxul/config\";\nimport type { AuthSession, DurationMs, Email } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"./auth-cache\";\n\nexport type AuthClientResult<A> =\n | { readonly ok: true; readonly value: A }\n | { readonly ok: false; readonly error: CapxulError };\n\nexport type AuthClientOperationOptions = {\n readonly signal?: AbortSignal;\n};\n\nexport type SendOtpInput = {\n readonly email: Email;\n};\n\nexport type CanSendOtpInput = {\n readonly email: Email;\n};\n\nexport type CanSendOtpStatus = {\n readonly allowed: boolean;\n readonly cooldownMs: DurationMs;\n};\n\nexport type VerifyOtpInput = {\n readonly email: Email;\n readonly otp: string;\n};\n\nexport type GetConvexJwtOptions = AuthClientOperationOptions & {\n readonly forceRefresh?: boolean;\n};\n\nexport class AuthClientError extends Data.TaggedError(\"AuthClientError\")<{\n readonly operation: string;\n readonly kind: string;\n readonly cause: unknown;\n}> {}\n\n// Platform port for authentication operations. Cancellation lives only on the\n// options bag; input objects do not carry `signal`.\nexport interface AuthClientPort {\n canSendOtp(\n input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<CanSendOtpStatus, AuthClientError>;\n sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<void, AuthClientError>;\n verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<AuthSession, AuthClientError>;\n getSession(\n options?: AuthClientOperationOptions,\n ): Effect.Effect<AuthSession | null, AuthClientError>;\n signOut(options?: AuthClientOperationOptions): Effect.Effect<void, AuthClientError>;\n /**\n * Fetches a Convex-aud JWT from `/api/auth/convex/token` (W7). Server mints\n * a fresh JWT on every call per Probe A's 2026-05-19 finding (RS256, 900 s\n * lifetime, `iss = <site-url>`, `aud = convex`). The caller (the SDK's\n * `tokenProvider` wired into ConvexCallPort) is responsible for the\n * `exp - 30s` proactive cache + `forceRefresh` callback handshake.\n */\n getConvexJwt(options?: GetConvexJwtOptions): Effect.Effect<CachedJwt, AuthClientError>;\n}\n\nexport class AuthClientPortTag extends Context.Tag(\"@capxul/sdk/ports/AuthClientPort\")<\n AuthClientPortTag,\n AuthClientPort\n>() {}\n","import type { CapxulError } from \"@capxul/config\";\nimport { Effect } from \"effect\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport {\n AuthClientError,\n type CanSendOtpInput,\n type CanSendOtpStatus,\n type AuthClientOperationOptions,\n type AuthClientPort,\n type AuthClientResult,\n type GetConvexJwtOptions,\n type SendOtpInput,\n type VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport type { AuthSession } from \"@capxul/types\";\n\nexport interface PromiseAuthClientAdapter {\n readonly canSendOtp: (\n input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<CanSendOtpStatus>>;\n readonly sendOtp: (\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<void>>;\n readonly verifyOtp: (\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<AuthSession>>;\n readonly getSession: (\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<AuthSession | null>>;\n readonly signOut: (options?: AuthClientOperationOptions) => Promise<AuthClientResult<void>>;\n readonly getConvexJwt: (options?: GetConvexJwtOptions) => Promise<AuthClientResult<CachedJwt>>;\n}\n\nexport function authClientPortFromPromiseAdapter(\n adapter: PromiseAuthClientAdapter,\n): AuthClientPort {\n return {\n canSendOtp: (input, options) =>\n fromResult(\"canSendOtp\", () => adapter.canSendOtp(input, options)),\n sendOtp: (input, options) => fromResult(\"sendOtp\", () => adapter.sendOtp(input, options)),\n verifyOtp: (input, options) => fromResult(\"verifyOtp\", () => adapter.verifyOtp(input, options)),\n getSession: (options) => fromResult(\"getSession\", () => adapter.getSession(options)),\n signOut: (options) => fromResult(\"signOut\", () => adapter.signOut(options)),\n getConvexJwt: (options) => fromResult(\"getConvexJwt\", () => adapter.getConvexJwt(options)),\n };\n}\n\nfunction fromResult<A>(\n operation: string,\n run: () => Promise<AuthClientResult<A>>,\n): Effect.Effect<A, AuthClientError> {\n return Effect.tryPromise({\n try: run,\n catch: (cause) => new AuthClientError({ operation, kind: \"thrown\", cause }),\n }).pipe(\n Effect.flatMap((result) =>\n result.ok\n ? Effect.succeed(result.value)\n : Effect.fail(\n new AuthClientError({\n operation,\n kind: errorKind(result.error),\n cause: result.error,\n }),\n ),\n ),\n );\n}\n\nfunction errorKind(error: CapxulError): string {\n if (error.code === \"CANCELLED\") return \"cancelled\";\n if (error.code === \"NETWORK_ERROR\") return \"network\";\n if (error.code === \"INVALID_INPUT\" || error.code === \"OTP_EXPIRED\") return \"validation\";\n return \"provider\";\n}\n","/** Join bootstrap `authBaseUrl` with a BetterAuth route without duplicating `/api/auth`. */\nexport function resolveAuthClientUrl(authBaseUrl: string, path: string): string {\n const base = authBaseUrl.replace(/\\/$/, \"\");\n if (base.endsWith(\"/api/auth\") && path.startsWith(\"/api/auth\")) {\n return `${base}${path.slice(\"/api/auth\".length)}`;\n }\n return `${base}${path}`;\n}\n","// BetterAuthBrowserAdapter — TA3 production adapter for browser runtimes.\n// Aligned with W1/W2/W3/W6/W7 wire reality verified against\n// incredible-possum-990 (2026-05-19) using @convex-dev/better-auth@0.10.13.\n//\n// - W1 sendOtp POST /api/auth/email-otp/send-verification-otp\n// body `{email, type: \"sign-in\"}`\n// 200 `{success: true}` | 400 `{code, message}`\n// - W2 verifyOtp POST /api/auth/sign-in/email-otp\n// 200 `{token, user}` + Set-Cookie headers |\n// 400 `{code, message}` (OTP_EXPIRED, INVALID_OTP)\n// - W3 getSession GET /api/auth/get-session\n// 200 literal `null` body OR `{session, user}`\n// - W6 signOut POST /api/auth/sign-out body `\"{}\"`\n// (without body the server returns 500 — F11)\n// - W7 getConvexJwt GET /api/auth/convex/token\n// 200 `{token: <JWT>}`; decode `exp` for cache\n// eviction (Probe A: fresh JWT per call)\n//\n// Browser-runtime semantics: the browser fetch automatically attaches +\n// stores cookies for the same-origin domain. We send `credentials: \"include\"`\n// on requests that need cookies, but never read/write Set-Cookie ourselves —\n// that's the browser's job. The Node adapter takes a different path via\n// CookieJar (see BetterAuthNodeAdapter).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\n\nexport interface BetterAuthBrowserAdapterDeps {\n readonly authBaseUrl: string;\n readonly fetch?: typeof fetch;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n readonly emailVerified?: boolean;\n readonly name?: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface GetSessionBody {\n readonly session: { readonly id?: string; readonly token?: string; readonly expiresAt?: string };\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\n// Sentinel — a 15-min JWT lifetime per Probe A. Used when we can't decode\n// the `exp` claim from a malformed/opaque token (fixtures, defensive depth).\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n // Strip whitespace defensively (real JWTs don't have it; the fixture\n // builder's line-wrap can introduce some).\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = atob(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad);\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction mapBetterAuthError(\n operation: string,\n body: unknown,\n): ReturnType<typeof Errors.invalidInput | typeof Errors.providerError | typeof Errors.otpExpired> {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n const code = typeof errBody.code === \"string\" ? errBody.code : \"\";\n if (code === \"OTP_EXPIRED\") {\n return Errors.otpExpired();\n }\n if (code === \"INVALID_OTP\") {\n return Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\");\n }\n if (code === \"VALIDATION_ERROR\" || code === \"INVALID_EMAIL\") {\n return Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\");\n }\n }\n return Errors.providerError(\"better-auth\", operation, new Error(String(body)));\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthBrowserAdapter {\n private readonly authBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(deps: BetterAuthBrowserAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n if (res.status === 429) {\n return { ok: false, error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }) };\n }\n const body = await safeJson(res);\n // W1 errors: 400 with { code, message } shape — OTP_EXPIRED can't\n // appear on send; INVALID_EMAIL / VALIDATION_ERROR can.\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n const body = await safeJson(res);\n if (res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(\"unexpected 200 body\")),\n };\n }\n // W2 errors: structured 400 with `{ code, message }`.\n return { ok: false, error: mapBetterAuthError(\"verifyOtp\", body) };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n // W3 body is literal `null` OR a `{session, user}` object.\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<GetSessionBody>;\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n // Build a session synthetically — get-session doesn't return a\n // bearer token in the body (cookies carry it). For ports that\n // want a non-null AuthSession on success, we set token to the\n // session id if available.\n const token = okBody.session?.token ?? okBody.session?.id ?? \"session\";\n return { ok: true, value: authSessionFromBetterAuth(token, okBody.user) };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n // F11: BetterAuth REQUIRES a non-empty body + Content-Type:\n // application/json. Without it the route returns HTTP 500.\n headers: { \"Content-Type\": \"application/json\" },\n body: \"{}\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n // forceRefresh is observed by the caller (ConvexCallAdapter); the\n // bridge mints fresh on every call regardless (Probe A).\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthBrowserLayer(\n deps: BetterAuthBrowserAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthBrowserAdapter(deps)),\n );\n}\n","// Minimal in-tree cookie jar for the Node auth-client adapter (tactical\n// placeholder 4 resolution). Scope is tiny: set + replay via `Cookie`\n// header on subsequent requests, expiry tracking, scope-by-host.\n//\n// No `tough-cookie` dependency.\n\nexport interface ParsedCookie {\n readonly name: string;\n readonly value: string;\n readonly maxAgeSeconds: number | null;\n readonly expiresEpochMs: number | null;\n readonly path: string | null;\n readonly httpOnly: boolean;\n readonly secure: boolean;\n readonly sameSite: \"strict\" | \"lax\" | \"none\" | null;\n}\n\ninterface StoredCookie extends ParsedCookie {\n readonly storedAtEpochMs: number;\n}\n\nfunction parseSetCookie(raw: string): ParsedCookie | null {\n // Set-Cookie header format: `name=value; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax`\n const parts = raw.split(\";\").map((p) => p.trim());\n if (parts.length === 0 || parts[0] === undefined) return null;\n const nameValue = parts[0];\n const eq = nameValue.indexOf(\"=\");\n if (eq < 0) return null;\n const name = nameValue.slice(0, eq).trim();\n const value = nameValue.slice(eq + 1).trim();\n if (name.length === 0) return null;\n\n let maxAgeSeconds: number | null = null;\n let expiresEpochMs: number | null = null;\n let path: string | null = null;\n let httpOnly = false;\n let secure = false;\n let sameSite: \"strict\" | \"lax\" | \"none\" | null = null;\n\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (part === undefined) continue;\n const partEq = part.indexOf(\"=\");\n const key = (partEq < 0 ? part : part.slice(0, partEq)).trim().toLowerCase();\n const val = partEq < 0 ? \"\" : part.slice(partEq + 1).trim();\n if (key === \"max-age\") {\n const n = Number(val);\n if (Number.isFinite(n)) maxAgeSeconds = n;\n } else if (key === \"expires\") {\n const t = Date.parse(val);\n if (Number.isFinite(t)) expiresEpochMs = t;\n } else if (key === \"path\") {\n path = val;\n } else if (key === \"httponly\") {\n httpOnly = true;\n } else if (key === \"secure\") {\n secure = true;\n } else if (key === \"samesite\") {\n const lc = val.toLowerCase();\n if (lc === \"strict\" || lc === \"lax\" || lc === \"none\") sameSite = lc;\n }\n }\n\n return { name, value, maxAgeSeconds, expiresEpochMs, path, httpOnly, secure, sameSite };\n}\n\nfunction isExpired(cookie: StoredCookie, nowEpochMs: number): boolean {\n if (cookie.maxAgeSeconds !== null) {\n if (cookie.maxAgeSeconds <= 0) return true;\n return nowEpochMs >= cookie.storedAtEpochMs + cookie.maxAgeSeconds * 1000;\n }\n if (cookie.expiresEpochMs !== null) {\n return nowEpochMs >= cookie.expiresEpochMs;\n }\n // Session cookie — never expires in this process. The Node adapter does\n // not preserve the jar across processes; this is fine.\n return false;\n}\n\nexport class CookieJar {\n // host → name → cookie. Map preserves insertion order, which keeps the\n // serialized Cookie header deterministic for tests.\n private readonly store = new Map<string, Map<string, StoredCookie>>();\n\n set(host: string, setCookieHeaders: readonly string[]): void {\n let perHost = this.store.get(host);\n const now = Date.now();\n for (const raw of setCookieHeaders) {\n const parsed = parseSetCookie(raw);\n if (parsed === null) continue;\n if (perHost === undefined) {\n perHost = new Map();\n this.store.set(host, perHost);\n }\n // Max-Age=0 (or negative) immediately deletes; treat as a clear.\n if (parsed.maxAgeSeconds !== null && parsed.maxAgeSeconds <= 0) {\n perHost.delete(parsed.name);\n continue;\n }\n perHost.set(parsed.name, { ...parsed, storedAtEpochMs: now });\n }\n if (perHost !== undefined && perHost.size === 0) {\n this.store.delete(host);\n }\n }\n\n getCookieHeader(host: string): string | null {\n const perHost = this.store.get(host);\n if (perHost === undefined || perHost.size === 0) return null;\n const now = Date.now();\n const live: string[] = [];\n for (const [name, cookie] of perHost.entries()) {\n if (isExpired(cookie, now)) {\n perHost.delete(name);\n continue;\n }\n live.push(`${name}=${cookie.value}`);\n }\n if (live.length === 0) {\n this.store.delete(host);\n return null;\n }\n return live.join(\"; \");\n }\n}\n","// BetterAuthNodeAdapter — TA3 production adapter for Node + Ink runtimes.\n// Same surface as the browser adapter; cookies round-trip via the in-tree\n// CookieJar instead of being managed by the browser.\n//\n// Wire shapes are identical to BetterAuthBrowserAdapter (W1/W2/W3/W6/W7).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\n\nimport { CookieJar } from \"./cookie-jar\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\n\nexport interface BetterAuthNodeAdapterDeps {\n readonly authBaseUrl: string;\n /**\n * Some BetterAuth routes (notably sign-out) enforce an Origin check and will\n * return 403 if absent. For Node clients, pass the same origin a browser\n * would send (e.g. SITE_URL).\n */\n readonly origin?: string;\n readonly cookieJar?: CookieJar;\n readonly fetch?: typeof fetch;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = Buffer.from(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\").toString(\n \"utf-8\",\n );\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n try {\n return new URL(baseUrl).host;\n } catch {\n return baseUrl;\n }\n}\n\nfunction originFromBaseUrl(baseUrl: string): string | undefined {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction setCookiesFromResponse(jar: CookieJar, host: string, res: Response): void {\n // Headers.getSetCookie() is the Node 19.7+ way; falls back to single header\n // splitting if unavailable.\n type HeadersExt = Headers & { getSetCookie?: () => string[] };\n const ext = res.headers as HeadersExt;\n let setCookies: string[] = [];\n if (typeof ext.getSetCookie === \"function\") {\n setCookies = ext.getSetCookie();\n } else {\n res.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\") setCookies.push(value);\n });\n }\n if (setCookies.length > 0) jar.set(host, setCookies);\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthNodeAdapter {\n private readonly authBaseUrl: string;\n private readonly host: string;\n private readonly origin: string | undefined;\n private readonly cookieJar: CookieJar;\n private readonly fetchImpl: typeof fetch;\n\n constructor(deps: BetterAuthNodeAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.host = hostFromBaseUrl(this.authBaseUrl);\n this.origin = deps.origin?.replace(/\\/$/, \"\");\n this.cookieJar = deps.cookieJar ?? new CookieJar();\n this.fetchImpl = deps.fetch ?? fetch;\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n private headersWithCookie(extra: Record<string, string> = {}): Record<string, string> {\n const cookie = this.cookieJar.getCookieHeader(this.host);\n return cookie !== null ? { ...extra, cookie } : { ...extra };\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) return { ok: true, value: undefined };\n if (res.status === 429) {\n return {\n ok: false,\n error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n setCookiesFromResponse(this.cookieJar, this.host, res);\n const body = await safeJson(res);\n if (res.ok && typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n if (!res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"OTP_EXPIRED\") {\n return { ok: false, error: Errors.otpExpired() };\n }\n if (errBody.code === \"INVALID_OTP\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\"),\n };\n }\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as {\n readonly session?: { readonly id?: string; readonly token?: string };\n readonly user?: BetterAuthUser;\n };\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n return {\n ok: true,\n value: authSessionFromBetterAuth(\n okBody.session?.token ?? okBody.session?.id ?? \"session\",\n okBody.user,\n ),\n };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const signOutOrigin = originFromBaseUrl(this.authBaseUrl) ?? this.origin;\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n headers: this.headersWithCookie({\n \"content-type\": \"application/json\",\n ...(signOutOrigin ? { origin: signOutOrigin } : {}),\n }),\n body: \"{}\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // The sign-out response sets Max-Age=0 cookies — the jar treats those\n // as immediate deletions.\n setCookiesFromResponse(this.cookieJar, this.host, res);\n if (res.ok) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthNodeLayer(\n deps: BetterAuthNodeAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthNodeAdapter(deps)),\n );\n}\n","// Brand schemas for `@capxul/wire` envelopes. Per Decision 2 of issue #119\n// (2b parity required), each schema MUST validate as strictly as its `to*`\n// counterpart in `@capxul/types`. We achieve mechanical parity by importing\n// the regex/range constants from `@capxul/types` and reusing them inside\n// `Schema.filter(...)` refinements that narrow to the local `Brand<T, B>`\n// types — so decoded values are typed as `AppId` / `ChainId` / etc. directly,\n// no cast at the consumer site.\n\nimport { Schema } from \"@effect/schema\";\n\nimport {\n APP_ID_RE,\n type AppId,\n type ChainId,\n type CurrencyCode,\n BYTES32_RE,\n SUPPORTED_CURRENCY_CODES,\n type DocumentHash,\n type DurationMs,\n type EpochMs,\n type SessionToken,\n} from \"@capxul/types\";\n\n/**\n * `AppId` schema. Mirrors `toAppId` from `@capxul/types`:\n * `app_` + Crockford-base32 ULID (26 chars, first char in `[0-7]`).\n */\nexport const AppIdSchema: Schema.Schema<AppId, string> = Schema.String.pipe(\n Schema.filter((s): s is AppId => APP_ID_RE.test(s), {\n message: () => \"must be app_ plus a ULID\",\n }),\n);\n\n/**\n * `ChainId` schema. Mirrors `toChainId`: positive safe integer.\n */\nexport const ChainIdSchema: Schema.Schema<ChainId, number> = Schema.Number.pipe(\n Schema.filter((n): n is ChainId => Number.isSafeInteger(n) && n > 0, {\n message: () => \"must be a positive safe integer\",\n }),\n);\n\n/**\n * `CurrencyCode` schema. Mirrors `toCurrencyCode`: currently supported\n * consumer-facing ISO-ish currency code set.\n */\nexport const CurrencyCodeSchema: Schema.Schema<CurrencyCode, string> = Schema.String.pipe(\n Schema.filter(\n (s): s is CurrencyCode =>\n SUPPORTED_CURRENCY_CODES.includes(s as (typeof SUPPORTED_CURRENCY_CODES)[number]),\n {\n message: () => \"must be a supported currency code\",\n },\n ),\n);\n\nconst DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;\n\n/**\n * `DocumentHash` schema. Mirrors `toDocumentHash`: bare or 0x-prefixed bytes32,\n * normalized to lowercase 0x-prefixed form.\n */\nexport const DocumentHashSchema: Schema.Schema<DocumentHash, string> = Schema.String.pipe(\n Schema.transform(Schema.String, {\n decode: (s) => {\n const stripped = s.startsWith(\"0x\") || s.startsWith(\"0X\") ? s.slice(2) : s;\n return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;\n },\n encode: (s) => s,\n }),\n Schema.filter((s): s is DocumentHash => BYTES32_RE.test(s), {\n message: () => \"must be 32 bytes of hex\",\n }),\n);\n\n/**\n * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.\n * Issuance source distinguishes SDK-handshake tokens from auth-session\n * tokens; the brand itself is opaque.\n */\nexport const SessionTokenSchema: Schema.Schema<SessionToken, string> = Schema.String.pipe(\n Schema.filter((s): s is SessionToken => s.length > 0, {\n message: () => \"must be a non-empty string\",\n }),\n);\n\n/**\n * `EpochMs` schema. Mirrors `toEpochMs`: non-negative safe integer.\n */\nexport const EpochMsSchema: Schema.Schema<EpochMs, number> = Schema.Number.pipe(\n Schema.filter((n): n is EpochMs => Number.isSafeInteger(n) && n >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\n\n/**\n * `DurationMs` schema. Mirrors `toDurationMs`: non-negative safe integer.\n */\nexport const DurationMsSchema: Schema.Schema<DurationMs, number> = Schema.Number.pipe(\n Schema.filter((n): n is DurationMs => Number.isSafeInteger(n) && n >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\n","// `BootstrapEnvelope` — the JSON body returned by\n// `POST /v1/client/bootstrap`. Producer: `@capxul/backend`\n// (`packages/backend/convex/credentials/http.ts`). Consumer:\n// `@capxul/sdk` (`packages/sdk/src/adapters/bootstrap/HttpBootstrapAdapter.ts`).\n//\n// Per Decision 1 of issue #119, the envelope wraps the existing\n// `BootstrapResolution`-shaped payload in `{ protocol, version, state }`\n// so version negotiation is explicit on the wire. `state` matches the\n// `BootstrapResolution` port shape at\n// `packages/sdk/src/ports/bootstrap.ts:18-31` field-for-field — no new\n// fields. Forward-compatible additions (e.g. `deployment`) belong to\n// later slices that change the port surface.\n//\n// Per Decision 2 (2b parity required), every branded field uses the\n// matching schema from `./brands.ts`, which reuses the regex/range\n// constants exported from `@capxul/types`.\n\nimport { Schema } from \"@effect/schema\";\n\nimport {\n AppIdSchema,\n ChainIdSchema,\n DurationMsSchema,\n EpochMsSchema,\n SessionTokenSchema,\n} from \"./brands\";\n\n/**\n * `BootstrapEnvelope` v1.\n *\n * - `protocol`: discriminator that lets future protocols coexist on the\n * same endpoint without a wire-shape conflict.\n * - `version`: numeric version inside the protocol. Unknown versions MUST\n * fail decode with an INVALID_INPUT-class `CapxulError` at the SDK seam.\n * - `state`: the resolved bootstrap payload. Field shape matches the\n * `BootstrapResolution` port; the SDK consumer can pass `state`\n * directly (after `normalizeRuntimeUrl` on the two URL fields) into\n * the port without re-branding.\n */\nexport const BootstrapEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.bootstrap\"),\n version: Schema.Literal(1),\n state: Schema.Struct({\n applicationId: AppIdSchema,\n chainId: ChainIdSchema,\n sessionToken: SessionTokenSchema,\n issuedAt: EpochMsSchema,\n expiresIn: DurationMsSchema,\n authBaseUrl: Schema.String,\n convexUrl: Schema.String,\n siteBaseUrl: Schema.String,\n openfortPublishableKey: Schema.String,\n shieldPublishableKey: Schema.String,\n }),\n});\n\nexport type BootstrapEnvelopeV1 = Schema.Schema.Type<typeof BootstrapEnvelope>;\nexport type BootstrapEnvelopeEncoded = Schema.Schema.Encoded<typeof BootstrapEnvelope>;\n","import { Schema } from \"@effect/schema\";\n\nimport { ChainIdSchema, CurrencyCodeSchema, DocumentHashSchema, EpochMsSchema } from \"./brands\";\n\nconst MINOR_UNIT_STRING_RE = /^[0-9]+$/;\nconst DECIMAL_STRING_RE = /^[0-9]+(?:\\.[0-9]+)?$/;\nconst EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;\n/**\n * The canonical on-chain domain anchor for the v1 payment-document EIP-712\n * `domain` (payment-document-spec.md v1). The `PaymentDocumentDomain` schema\n * validates against this exact literal, and the backend's receipt builder mints\n * envelopes carrying it — so it MUST stay byte-identical across both. Exported\n * once here to remove the drift risk of a mirrored declaration.\n */\nexport const PAYMENT_DOCUMENT_VERIFYING_CONTRACT = \"0xe740ea65521edc9bef0ea75d30b5334711db99f4\";\nconst PAYMENT_ID_RE = /^payment_[0-9A-Za-z]+$/;\nconst PAYEE_ID_RE = /^payee_[0-9A-Za-z]+$/;\nconst ORG_ID_RE = /^org_[0-9A-Za-z]+$/;\nconst USER_ID_RE = /^user_[0-9A-Za-z]+$/;\nconst HANDLE_RE = /^@[0-9A-Za-z][0-9A-Za-z_.-]{0,63}$/;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst MinorUnitStringSchema = Schema.String.pipe(\n Schema.filter((value): value is string => MINOR_UNIT_STRING_RE.test(value), {\n message: () => \"must be a non-negative integer minor-unit string\",\n }),\n);\nconst PaymentIdSchema = Schema.String.pipe(\n Schema.filter((value): value is string => PAYMENT_ID_RE.test(value), {\n message: () => \"must be payment_ plus an alphanumeric id\",\n }),\n);\nconst PayeeIdSchema = Schema.String.pipe(\n Schema.filter((value): value is string => PAYEE_ID_RE.test(value), {\n message: () => \"must be payee_ plus an alphanumeric id\",\n }),\n);\nconst OrgIdSchema = Schema.String.pipe(\n Schema.filter((value): value is string => ORG_ID_RE.test(value), {\n message: () => \"must be org_ plus an alphanumeric id\",\n }),\n);\nconst DecimalStringSchema = Schema.String.pipe(\n Schema.filter((value): value is string => DECIMAL_STRING_RE.test(value), {\n message: () => \"must be a non-negative decimal string\",\n }),\n);\nconst PaymentRecipientRefSchema = Schema.String.pipe(\n Schema.filter(\n (value): value is string =>\n !EVM_ADDRESS_RE.test(value) &&\n (PAYEE_ID_RE.test(value) ||\n ORG_ID_RE.test(value) ||\n USER_ID_RE.test(value) ||\n HANDLE_RE.test(value) ||\n EMAIL_RE.test(value)),\n {\n message: () =>\n \"must be a handle, email, user id, org id, or payee id; raw addresses are not accepted\",\n },\n ),\n);\nconst Uint8Schema = Schema.Number.pipe(\n Schema.filter(\n (value): value is number => Number.isSafeInteger(value) && value >= 0 && value <= 255,\n {\n message: () => \"must be a uint8\",\n },\n ),\n);\nconst Uint64Schema = Schema.Number.pipe(\n Schema.filter((value): value is number => Number.isSafeInteger(value) && value >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\nconst PaymentDocumentDomain = Schema.Struct({\n name: Schema.Literal(\"CapxulPayments\"),\n version: Schema.Literal(\"1\"),\n chainId: ChainIdSchema,\n verifyingContract: Schema.Literal(PAYMENT_DOCUMENT_VERIFYING_CONTRACT),\n});\nconst MemoDocument = Schema.Struct({\n kind: Schema.Literal(0),\n reference: Schema.String,\n note: Schema.String,\n issuedAt: Uint64Schema,\n});\nconst InvoiceDocument = Schema.Struct({\n kind: Schema.Literal(1),\n invoiceNumber: Schema.String,\n payerRef: Schema.String,\n payeeRef: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n issuedAt: Uint64Schema,\n dueAt: Uint64Schema,\n lineItemsHash: DocumentHashSchema,\n});\nconst PayslipDocument = Schema.Struct({\n kind: Schema.Literal(2),\n employerRef: Schema.String,\n employeeRef: Schema.String,\n period: Schema.String,\n gross: MinorUnitStringSchema,\n net: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n issuedAt: Uint64Schema,\n});\nconst ReceiptDocument = Schema.Struct({\n kind: Schema.Literal(3),\n reference: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n paidAt: Uint64Schema,\n note: Schema.String,\n});\nconst WithdrawalDestAddressSchema = Schema.String.pipe(\n Schema.filter((value): value is string => EVM_ADDRESS_RE.test(value), {\n message: () => \"must be a 0x EVM address\",\n }),\n);\n// Withdrawal / cash-out document (kind 4, payment-document-spec.md). Minted by\n// the B3 withdraw lane when value leaves the custody Safe to an external wallet.\n// `destAddress` lives ON the document (user-visible / consent-gated, audit-only)\n// — it is NEVER model-visible; only the documentHash crosses the model wire.\n// `provider`/`note` are required strings (\"\" when absent) so the EIP-712 hash is\n// deterministic (an absent field cannot be hashed) — mirrors Receipt.note.\nconst WithdrawalDocument = Schema.Struct({\n kind: Schema.Literal(4),\n reference: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n destChain: ChainIdSchema,\n destAddress: WithdrawalDestAddressSchema,\n settledAt: Uint64Schema,\n provider: Schema.String,\n note: Schema.String,\n});\n\nexport const FinancialOpsMoney = Schema.Struct({\n currency: CurrencyCodeSchema,\n value: DecimalStringSchema,\n decimals: Schema.Number.pipe(\n Schema.filter((value): value is number => Number.isSafeInteger(value) && value >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n ),\n});\n\nexport const PaymentDocument = Schema.Struct({\n documentHash: DocumentHashSchema,\n // `withdrawal` (B3): the kind:4 cash-out document attached to a withdraw\n // Payment. It maps to paymentType \"unspecified\" (see paymentTypeForDocumentKind).\n kind: Schema.Literal(\"invoice\", \"receipt\", \"payslip\", \"memo\", \"withdrawal\"),\n title: Schema.optional(Schema.String),\n uri: Schema.optional(Schema.String),\n issuedAt: Schema.optional(EpochMsSchema),\n});\ntype PaymentDocumentKind = Schema.Schema.Type<typeof PaymentDocument>[\"kind\"];\n\nconst PaymentType = Schema.Literal(\"unspecified\", \"invoice\", \"payroll\", \"reimbursement\");\ntype PaymentTypeV1 = Schema.Schema.Type<typeof PaymentType>;\n\nfunction paymentTypeForDocumentKind(kind: PaymentDocumentKind): PaymentTypeV1 {\n switch (kind) {\n case \"memo\":\n return \"unspecified\";\n case \"invoice\":\n return \"invoice\";\n case \"payslip\":\n return \"payroll\";\n case \"receipt\":\n return \"reimbursement\";\n // B3: a withdrawal/cash-out document maps to the unspecified payment type.\n case \"withdrawal\":\n return \"unspecified\";\n }\n}\n\nexport const PaymentDocumentEnvelope = Schema.Union(\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Memo\"),\n message: MemoDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Invoice\"),\n message: InvoiceDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Payslip\"),\n message: PayslipDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Receipt\"),\n message: ReceiptDocument,\n }),\n // Withdrawal (kind 4) is added at spec v1: EIP-712 hashStruct is per\n // primaryType, so a disjoint new struct provably cannot change how any\n // existing v1 document (Memo/Invoice/Payslip/Receipt) hashes. The spec's\n // version-bump rule guards MUTATING a shipped struct, not adding a new one\n // (see payment-document-spec.md § Versioning rules).\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Withdrawal\"),\n message: WithdrawalDocument,\n }),\n);\n\nexport const PayeeSummary = Schema.Struct({\n payeeId: PayeeIdSchema,\n label: Schema.String,\n trustState: Schema.Literal(\"unverified\", \"trusted\", \"blocked\"),\n destinationKind: Schema.Literal(\"handle\", \"email\", \"saved-payee\", \"org\"),\n});\n\nexport const PaymentRecipient = Schema.Struct({\n // `external_address` (B3 withdraw/cash-out): the recipient is an EXTERNAL 0x\n // wallet outside Capxul custody. The full address lives ONLY on the kind:4\n // Withdrawal document (user-visible / audit); here the `label` is a REDACTED\n // form (\"0x1234…abcd\") so a withdraw Payment renders leak-safe on the model\n // wire (assertWireSafe still bans `destAddress`). NOT added to the pay\n // resolver / PaymentRecipientRefSchema — withdraw takes the raw 0x on its own\n // path, the pay lane keeps rejecting bare addresses.\n kind: Schema.Literal(\"handle\", \"email\", \"payee\", \"me\", \"org\", \"external_address\"),\n label: Schema.String,\n payeeId: Schema.optional(PayeeIdSchema),\n});\n\n/**\n * A raw external EVM address for the B3 withdraw lane — the cash-out\n * destination. This is the ONE schema that ACCEPTS a bare 0x (the withdraw\n * mutation args use it), as opposed to `PaymentRecipientRefSchema` which\n * REJECTS bare addresses to protect the pay lane. The full address never\n * crosses the model wire; it lives on the kind:4 Withdrawal document only.\n */\nexport const ExternalAddressSchema = Schema.String.pipe(\n Schema.filter((value): value is string => EVM_ADDRESS_RE.test(value), {\n message: () => \"must be a 0x EVM address (40 hex chars)\",\n }),\n);\n\n/**\n * Redact a full external 0x address to a short, model-safe label\n * (\"0x1234…abcd\"): first 6 + last 4 chars. The withdraw lane stores this as\n * the wire recipient `label` so the model can reference the destination\n * without the full address ever crossing the wire.\n */\nexport function redactExternalAddress(address: string): string {\n const lower = address.toLowerCase();\n if (!EVM_ADDRESS_RE.test(lower)) {\n throw new Error(\"redactExternalAddress requires a 0x EVM address\");\n }\n return `${lower.slice(0, 6)}…${lower.slice(-4)}`;\n}\n\nexport const PaymentRelease = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal(\"instant\"),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"scheduled\"),\n at: EpochMsSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"stream\"),\n startsAt: EpochMsSchema,\n endsAt: EpochMsSchema,\n cliffAt: Schema.optional(EpochMsSchema),\n }),\n);\n\nexport const Payment = Schema.Struct({\n id: PaymentIdSchema,\n status: Schema.Literal(\n \"pending\",\n \"submitted\",\n \"pending_claim\",\n \"scheduled\",\n \"streaming\",\n \"settled\",\n \"cancelled\",\n \"redirected\",\n \"expired\",\n \"failed\",\n ),\n amount: FinancialOpsMoney,\n paymentType: PaymentType,\n recipient: PaymentRecipient,\n documents: Schema.Array(PaymentDocument),\n release: PaymentRelease,\n released: FinancialOpsMoney,\n availableToClaim: FinancialOpsMoney,\n createdAt: EpochMsSchema,\n updatedAt: EpochMsSchema,\n}).pipe(\n Schema.filter(\n (payment) =>\n payment.documents.every(\n (document) => paymentTypeForDocumentKind(document.kind) === payment.paymentType,\n ),\n {\n message: () => \"document kind must map to paymentType\",\n },\n ),\n);\n\nconst PaymentSource = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal(\"me\"),\n orgId: Schema.optional(Schema.Undefined),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"org\"),\n orgId: OrgIdSchema,\n }),\n);\n\n/**\n * #592 invoice line item. `quantity` is a positive integer; `unitMinor` is the\n * per-unit price in integer minor units. The list is canonically hashed by\n * `hashLineItems` (payment-document-hash.ts) into the Invoice `lineItemsHash`,\n * and Σ(quantity × unitMinor) MUST equal the invoice `amount`. The hash binds\n * the documentHash to the exact items; the sum-check makes the items add up to\n * the amount due. See the payment-document spec (canon/mcp/financial-ops.md).\n */\nexport const LineItem = Schema.Struct({\n description: Schema.String,\n quantity: Schema.Number.pipe(\n Schema.filter((value): value is number => Number.isSafeInteger(value) && value > 0, {\n message: () => \"quantity must be a positive integer\",\n }),\n ),\n unitMinor: MinorUnitStringSchema,\n});\n\nexport const PaymentsPayInput = Schema.Struct({\n from: Schema.optional(PaymentSource),\n to: Schema.Union(PaymentRecipientRefSchema, Schema.Array(PaymentRecipientRefSchema)),\n amount: FinancialOpsMoney,\n release: Schema.optional(PaymentRelease),\n document: Schema.optional(PaymentDocument),\n // #592: the itemized line-item list backing an Invoice document. When present\n // the backend asserts hashLineItems(lineItems) === document.lineItemsHash AND\n // Σ(quantity × unitMinor) === document.amount, then persists the list so the\n // render path can re-verify + itemize.\n lineItems: Schema.optional(Schema.Array(LineItem)),\n});\n\n// B3 (withdraw / cash-out): send USDX from the user's custody Safe to an\n// EXTERNAL 0x wallet. `to` is the raw external address (validated by\n// `ExternalAddressSchema` — the ONE schema that accepts a bare 0x), `document`\n// is the REQUIRED kind:4 Withdrawal envelope (the only doc kind allowed; it\n// carries the audit-visible destAddress). Stripe-shaped: no chain / Safe /\n// token / hash custody substrate on the input.\nexport const PaymentsWithdrawInput = Schema.Struct({\n to: ExternalAddressSchema,\n amount: FinancialOpsMoney,\n document: PaymentDocumentEnvelope,\n});\n\nexport const MeEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.me\"),\n version: Schema.Literal(1),\n me: Schema.Struct({\n displayName: Schema.NullOr(Schema.String),\n handle: Schema.NullOr(Schema.String),\n defaultCurrency: CurrencyCodeSchema,\n depositInstructions: Schema.Array(\n Schema.Struct({\n network: Schema.String,\n asset: CurrencyCodeSchema,\n depositTarget: Schema.String,\n memo: Schema.optional(Schema.String),\n }),\n ),\n }),\n});\n\nexport const PaymentListEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.payments\"),\n version: Schema.Literal(1),\n payments: Schema.Array(Payment),\n});\n\nexport type FinancialOpsMoneyV1 = Schema.Schema.Type<typeof FinancialOpsMoney>;\nexport type PaymentDocumentV1 = Schema.Schema.Type<typeof PaymentDocument>;\nexport type PaymentDocumentEnvelopeV1 = Schema.Schema.Type<typeof PaymentDocumentEnvelope>;\nexport type PayeeSummaryV1 = Schema.Schema.Type<typeof PayeeSummary>;\nexport type PaymentRecipientV1 = Schema.Schema.Type<typeof PaymentRecipient>;\nexport type PaymentReleaseV1 = Schema.Schema.Type<typeof PaymentRelease>;\nexport type PaymentV1 = Schema.Schema.Type<typeof Payment>;\nexport type LineItemV1 = Schema.Schema.Type<typeof LineItem>;\nexport type PaymentsPayInputV1 = Schema.Schema.Type<typeof PaymentsPayInput>;\nexport type PaymentsWithdrawInputV1 = Schema.Schema.Type<typeof PaymentsWithdrawInput>;\nexport type MeEnvelopeV1 = Schema.Schema.Type<typeof MeEnvelope>;\nexport type PaymentListEnvelopeV1 = Schema.Schema.Type<typeof PaymentListEnvelope>;\n","// Payment-document HTML rendering (ADR-4, payment-document-spec.md).\n//\n// Each template is a function of the verified EIP-712 envelope PLUS optional\n// verified product CONTEXT the rendering surface holds — the `from`/`to` party\n// labels (sourced from the Payment, not the hashed struct) and the invoice\n// line-item list (the one the committed `lineItemsHash` commits to). The hash\n// still anchors the envelope; the context is never invented — a caller passes\n// only data it has verified. Money is always integer minor units + currency +\n// decimals (BigInt-safe string math, never a float). Free-text is HTML-escaped.\n// Output is framework-free semantic HTML with stable class hooks.\n\nimport type { PaymentDocumentEnvelopeV1 } from \"./financial-ops\";\nimport { hashLineItems } from \"./payment-document-hash\";\n\n/** A single invoice line item — committed (as an ordered list) by the envelope's `lineItemsHash`. */\nexport interface DocumentLineItem {\n readonly description: string;\n readonly quantity: number;\n /** Unit price in integer minor units (same currency/decimals as the document). */\n readonly unitMinor: string;\n}\n\n/**\n * Verified product context the rendering surface supplies alongside the envelope.\n * NONE of it is invented by the renderer: `from`/`to` are the Payment's party\n * labels; `lineItems` are the list the `lineItemsHash` commits to.\n */\nexport interface DocumentRenderContext {\n readonly from?: string;\n readonly to?: string;\n readonly lineItems?: readonly DocumentLineItem[];\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction esc(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char] ?? char);\n}\n\nconst CURRENCY_SYMBOLS: Record<string, string> = {\n USD: \"$\",\n NGN: \"₦\",\n GHS: \"₵\",\n KES: \"KSh \",\n UGX: \"USh \",\n};\n\n/** Group the integer part with thousands separators (BigInt-safe, no float). */\nfunction groupThousands(digits: string): string {\n return digits.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Format integer minor units as a fixed-decimal display string (no float). */\nfunction formatMinorUnits(amount: string, decimals: number): string {\n const digits = amount.replace(/^0+(?=\\d)/, \"\");\n if (decimals === 0) return groupThousands(digits);\n const padded = digits.padStart(decimals + 1, \"0\");\n const whole = padded.slice(0, padded.length - decimals);\n const fraction = padded.slice(padded.length - decimals);\n return `${groupThousands(whole)}.${fraction}`;\n}\n\n/** A money amount with its currency symbol, e.g. `$1,250.00`. */\nfunction money(amount: string, currency: string, decimals: number): string {\n const symbol = CURRENCY_SYMBOLS[currency] ?? \"\";\n const formatted = `${symbol}${formatMinorUnits(amount, decimals)}`;\n const suffix = symbol === \"\" ? ` ${currency}` : \"\";\n return `${formatted}${suffix}`;\n}\n\nfunction moneyEl(amount: string, currency: string, decimals: number): string {\n return `<span class=\"doc-amount\"><span class=\"doc-amount-value\">${esc(\n money(amount, currency, decimals),\n )}</span></span>`;\n}\n\nconst MONTHS = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\n/** Deterministic UTC date, e.g. `28 June 2026` (stable golden output, no locale). */\nfunction formatDate(epochMs: number): string {\n const d = new Date(epochMs);\n return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;\n}\n\nfunction isoDate(epochMs: number): string {\n return new Date(epochMs).toISOString();\n}\n\nfunction truncateAddress(address: string): string {\n return address.length <= 14 ? address : `${address.slice(0, 8)}…${address.slice(-6)}`;\n}\n\n/** A party block (label + name). Omitted entirely when no name is available. */\nfunction party(role: string, name: string | undefined): string {\n if (name === undefined || name === \"\") return \"\";\n return `<div class=\"doc-party\"><span class=\"doc-party-label\">${esc(\n role,\n )}</span><span class=\"doc-party-name\">${esc(name)}</span></div>`;\n}\n\nfunction brand(): string {\n return `<div class=\"doc-brand\"><span class=\"doc-brand-mark\">◆</span><span class=\"doc-brand-name\">Capxul</span></div>`;\n}\n\nfunction shell(kind: number, modifier: string, title: string, badge: string, body: string): string {\n return [\n `<article class=\"capxul-doc capxul-doc--${modifier}\" data-kind=\"${kind}\">`,\n `<header class=\"doc-header\">${brand()}`,\n `<div class=\"doc-headline\"><h1 class=\"doc-title\">${esc(title)}</h1>`,\n badge === \"\" ? \"\" : `<span class=\"doc-badge\">${esc(badge)}</span>`,\n `</div></header>`,\n body,\n `</article>`,\n ].join(\"\");\n}\n\nfunction metaRow(label: string, value: string): string {\n return `<div class=\"doc-meta-row\"><span class=\"doc-meta-label\">${esc(\n label,\n )}</span><span class=\"doc-meta-value\">${value}</span></div>`;\n}\n\nfunction dateEl(label: string, cls: string, epochMs: number): string {\n return `<div class=\"doc-meta-row\"><span class=\"doc-meta-label\">${esc(\n label,\n )}</span><time class=\"${cls}\" datetime=\"${esc(isoDate(epochMs))}\">${esc(\n formatDate(epochMs),\n )}</time></div>`;\n}\n\nfunction renderMemo(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 0 }>,\n ctx: DocumentRenderContext,\n): string {\n return shell(\n 0,\n \"memo\",\n \"Memo\",\n m.reference,\n [\n `<section class=\"doc-parties\">${party(\"From\", ctx.from)}${party(\"To\", ctx.to)}</section>`,\n `<section class=\"doc-body\"><p class=\"doc-note\">${esc(m.note)}</p></section>`,\n `<footer class=\"doc-footer\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}</footer>`,\n ].join(\"\"),\n );\n}\n\nfunction lineItemsTable(\n items: readonly DocumentLineItem[],\n currency: string,\n decimals: number,\n): { rows: string; computedTotalMinor: bigint } {\n let total = 0n;\n const rows = items\n .map((item) => {\n const lineTotal = BigInt(item.unitMinor) * BigInt(item.quantity);\n total += lineTotal;\n return [\n `<tr><td class=\"doc-li-desc\">${esc(item.description)}</td>`,\n `<td class=\"doc-li-qty\">${esc(String(item.quantity))}</td>`,\n `<td class=\"doc-li-unit\">${esc(money(item.unitMinor, currency, decimals))}</td>`,\n `<td class=\"doc-li-total\">${esc(\n money(lineTotal.toString(), currency, decimals),\n )}</td></tr>`,\n ].join(\"\");\n })\n .join(\"\");\n return { rows, computedTotalMinor: total };\n}\n\nfunction renderInvoice(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 1 }>,\n ctx: DocumentRenderContext,\n): string {\n const fromName = ctx.from ?? m.payeeRef; // the issuer/biller of an invoice is the payee\n const toName = ctx.to ?? m.payerRef;\n // #592: the line-item LIST is committed by `lineItemsHash`. Before itemizing,\n // RE-VERIFY that the supplied list actually hashes to the committed hash —\n // otherwise a tampered/mismatched list could be rendered as if authentic.\n // On mismatch (or no list), fall back to honestly showing the committed hash.\n const suppliedItems = ctx.lineItems;\n const itemsVerified =\n suppliedItems !== undefined &&\n suppliedItems.length > 0 &&\n hashLineItems(suppliedItems).toLowerCase() === m.lineItemsHash.toLowerCase();\n const itemsBlock = itemsVerified\n ? (() => {\n const { rows } = lineItemsTable(suppliedItems, m.currency, m.decimals);\n return `<table class=\"doc-line-items\"><thead><tr><th>Description</th><th class=\"doc-li-qty\">Qty</th><th class=\"doc-li-unit\">Unit</th><th class=\"doc-li-total\">Amount</th></tr></thead><tbody>${rows}</tbody></table>`;\n })()\n : `<p class=\"doc-line-items-hash\" data-line-items-hash=\"${esc(\n m.lineItemsHash,\n )}\">Line items committed by <code>${esc(m.lineItemsHash)}</code></p>`;\n return shell(\n 1,\n \"invoice\",\n \"Invoice\",\n m.invoiceNumber,\n [\n `<section class=\"doc-parties\">${party(\"From\", fromName)}${party(\"Bill to\", toName)}</section>`,\n `<section class=\"doc-meta\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}${dateEl(\n \"Due\",\n \"doc-due\",\n m.dueAt,\n )}</section>`,\n `<section class=\"doc-items\">${itemsBlock}</section>`,\n `<section class=\"doc-totals\"><div class=\"doc-total-line doc-total-grand\"><span class=\"doc-total-label\">Amount due</span>${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n ].join(\"\"),\n );\n}\n\nfunction renderPayslip(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 2 }>,\n ctx: DocumentRenderContext,\n): string {\n const deductions = (BigInt(m.gross) - BigInt(m.net)).toString();\n return shell(\n 2,\n \"payslip\",\n \"Payslip\",\n m.period,\n [\n `<section class=\"doc-parties\">${party(\"Employer\", ctx.from ?? m.employerRef)}${party(\n \"Employee\",\n ctx.to ?? m.employeeRef,\n )}</section>`,\n `<section class=\"doc-totals\">`,\n `<div class=\"doc-total-line\"><span class=\"doc-total-label\">Gross</span>${moneyEl(\n m.gross,\n m.currency,\n m.decimals,\n )}</div>`,\n `<div class=\"doc-total-line doc-total-deduction\"><span class=\"doc-total-label\">Deductions</span><span class=\"doc-amount\"><span class=\"doc-amount-value\">−${esc(\n money(deductions, m.currency, m.decimals),\n )}</span></span></div>`,\n `<div class=\"doc-total-line doc-total-grand\"><span class=\"doc-total-label\">Net pay</span>${moneyEl(\n m.net,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<footer class=\"doc-footer\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}</footer>`,\n ].join(\"\"),\n );\n}\n\nfunction renderReceipt(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 3 }>,\n ctx: DocumentRenderContext,\n): string {\n return shell(\n 3,\n \"receipt\",\n \"Receipt\",\n \"Paid\",\n [\n `<section class=\"doc-hero\"><span class=\"doc-hero-label\">Amount paid</span><div class=\"doc-hero-amount\">${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<section class=\"doc-parties\">${party(\"From\", ctx.from)}${party(\"To\", ctx.to)}</section>`,\n `<section class=\"doc-meta\">${metaRow(\"Reference\", esc(m.reference))}${dateEl(\n \"Paid\",\n \"doc-paid\",\n m.paidAt,\n )}</section>`,\n m.note === \"\"\n ? \"\"\n : `<footer class=\"doc-footer\"><p class=\"doc-note\">${esc(m.note)}</p></footer>`,\n ].join(\"\"),\n );\n}\n\nfunction renderWithdrawal(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 4 }>,\n _ctx: DocumentRenderContext,\n): string {\n const providerRow =\n m.provider === \"\"\n ? \"\"\n : metaRow(\"Provider\", `<span class=\"doc-provider\">${esc(m.provider)}</span>`);\n return shell(\n 4,\n \"withdrawal\",\n \"Withdrawal\",\n m.reference,\n [\n `<section class=\"doc-hero\"><span class=\"doc-hero-label\">Amount sent</span><div class=\"doc-hero-amount\">${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<section class=\"doc-meta\">`,\n metaRow(\n \"To wallet\",\n `<span class=\"doc-dest-address\" data-chain=\"${esc(String(m.destChain))}\" data-address=\"${esc(\n m.destAddress,\n )}\" title=\"${esc(m.destAddress)}\">${esc(truncateAddress(m.destAddress))}</span>`,\n ),\n metaRow(\"Chain\", `chain ${esc(String(m.destChain))}`),\n providerRow,\n dateEl(\"Settled\", \"doc-settled\", m.settledAt),\n `</section>`,\n m.note === \"\"\n ? \"\"\n : `<footer class=\"doc-footer\"><p class=\"doc-note\">${esc(m.note)}</p></footer>`,\n ].join(\"\"),\n );\n}\n\n/**\n * Render a verified Payment-document envelope to framework-free semantic HTML.\n * Output depends on the envelope's own fields plus the optional verified\n * `context` (party labels from the Payment; the committed line-item list).\n * The template is selected by `primaryType` (equivalently the `kind`).\n */\nexport function renderPaymentDocument(\n envelope: PaymentDocumentEnvelopeV1,\n context: DocumentRenderContext = {},\n): string {\n switch (envelope.primaryType) {\n case \"Memo\":\n return renderMemo(envelope.message, context);\n case \"Invoice\":\n return renderInvoice(envelope.message, context);\n case \"Payslip\":\n return renderPayslip(envelope.message, context);\n case \"Receipt\":\n return renderReceipt(envelope.message, context);\n case \"Withdrawal\":\n return renderWithdrawal(envelope.message, context);\n }\n}\n\n/** A professional, swappable default stylesheet for the `.capxul-doc` class hooks. */\nexport const DOCUMENT_STYLESHEET = `\n.capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;\n font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Inter,system-ui,sans-serif;\n color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;\n border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);\n line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}\n.capxul-doc *{box-sizing:border-box;min-width:0}\n.capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}\n.capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}\n.capxul-doc .doc-brand-mark{font-size:1.1rem}\n.capxul-doc .doc-brand-name{letter-spacing:.02em}\n.capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}\n.capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}\n.capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;\n color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}\n.capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}\n.capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}\n.capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}\n.capxul-doc .doc-party-name{font-weight:600}\n.capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}\n.capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}\n.capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}\n.capxul-doc .doc-meta-value{font-weight:500;text-align:right}\n.capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}\n.capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}\n.capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;\n color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}\n.capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}\n.capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}\n.capxul-doc .doc-li-desc{width:100%}\n.capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}\n.capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}\n.capxul-doc .doc-total-label{color:var(--muted)}\n.capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}\n.capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}\n.capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}\n.capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}\n.capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}\n.capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}\n.capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}\n.capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}\n.capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}\n.capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}\n.capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}\n@media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}\n`.trim();\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type {\n AllowedOrigin,\n AppId,\n ChainId,\n DurationMs,\n EpochMs,\n PublishableKey,\n SessionToken,\n} from \"@capxul/types\";\n\nexport type BootstrapInput = {\n readonly publishableKey: PublishableKey;\n /**\n * Browser callers send the App origin so bootstrap can enforce the\n * publishable-key allowlist. Node/server callers may omit it; the backend\n * only applies the origin allowlist when an origin is present.\n */\n readonly origin?: AllowedOrigin;\n};\n\nexport type BootstrapResolution = {\n readonly applicationId: AppId;\n readonly chainId: ChainId;\n /**\n * SDK-handshake session token — distinct from the user-auth `AuthSession`\n * token issued by `AuthClientPort`. Both use the `SessionToken` brand for\n * opaque-string discipline; the issuance source distinguishes them.\n */\n readonly sessionToken: SessionToken;\n readonly issuedAt: EpochMs;\n readonly expiresIn: DurationMs;\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n readonly siteBaseUrl: string;\n readonly openfortPublishableKey: string;\n readonly shieldPublishableKey: string;\n};\n\nexport type BootstrapErrorKind =\n | \"notAuthenticated\"\n | \"network\"\n | \"provider\"\n | \"malformedBody\"\n | \"invalidInput\"\n | \"rateLimited\";\n\nexport class BootstrapError extends Data.TaggedError(\"BootstrapError\")<{\n readonly operation: \"resolve\";\n readonly kind: BootstrapErrorKind;\n readonly publicCode: CapxulErrorCode;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function bootstrapErrorFromCapxul(\n kind: BootstrapErrorKind,\n error: CapxulError,\n): BootstrapError {\n return new BootstrapError({\n operation: \"resolve\",\n kind,\n publicCode: error.code,\n cause: error,\n ...(kind === \"notAuthenticated\" || error.details === undefined\n ? {}\n : { details: error.details }),\n });\n}\n\nexport interface BootstrapPort {\n readonly resolve: (input: BootstrapInput) => Effect.Effect<BootstrapResolution, BootstrapError>;\n}\n\nexport class BootstrapPortTag extends Context.Tag(\"@capxul/sdk/ports/BootstrapPort\")<\n BootstrapPortTag,\n BootstrapPort\n>() {}\n","// HttpBootstrapAdapter — TA3 production adapter. Calls\n// POST `/v1/client/bootstrap` on the backend. Per W4 + issue #119\n// (audit row B3), the 200 body is a versioned `BootstrapEnvelope`\n// shared with the producer via `@capxul/wire` — backend encodes,\n// SDK decodes, same schema both sides.\n//\n// Error mapping:\n// HTTP 401 and explicit NOT_AUTHENTICATED bodies map to NOT_AUTHENTICATED.\n// Schema-decode failures on a 200 body map to INVALID_INPUT per #119 AC1.\n// Provider 500s stay PROVIDER_ERROR so infrastructure faults are not collapsed\n// into auth failures.\n\nimport { Effect, Either, Layer } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { BootstrapEnvelope } from \"@capxul/wire\";\n\nimport type { BootstrapInput, BootstrapPort, BootstrapResolution } from \"../../ports/bootstrap\";\nimport { BootstrapError, BootstrapPortTag, bootstrapErrorFromCapxul } from \"../../ports/bootstrap\";\n\nexport interface HttpBootstrapAdapterDeps {\n readonly bootstrapBaseUrl: string;\n readonly fetch?: typeof fetch;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text();\n } catch {\n return \"\";\n }\n}\n\nexport class HttpBootstrapAdapter implements BootstrapPort {\n private readonly bootstrapBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(deps: HttpBootstrapAdapterDeps) {\n this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\\/$/, \"\");\n // Bind through an arrow — assigning `fetch` to `this.fetchImpl` and calling it\n // as a method throws \"Illegal invocation\" in browsers.\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n resolve(input: BootstrapInput): Effect.Effect<BootstrapResolution, BootstrapError> {\n return Effect.tryPromise({\n try: () => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n };\n return this.fetchImpl(`${this.bootstrapBaseUrl}/v1/client/bootstrap`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ publishableKey: input.publishableKey }),\n });\n },\n catch: (cause) =>\n bootstrapErrorFromCapxul(\"network\", Errors.networkError(\"bootstrap\", cause)),\n }).pipe(Effect.flatMap((res) => this.mapResponse(res)));\n }\n\n private mapResponse(res: Response): Effect.Effect<BootstrapResolution, BootstrapError> {\n if (res.ok) {\n return Effect.tryPromise({\n try: async () => {\n const body: unknown = await res.json();\n // `BootstrapEnvelope` lives in `@capxul/wire` so the producer\n // (`packages/backend/convex/credentials/http.ts`) and this\n // consumer share one schema. Branded fields (`applicationId`,\n // `chainId`, `sessionToken`, `issuedAt`, `expiresIn`) come out\n // of decode already branded — no `to*` chain afterwards.\n const decoded = Schema.decodeUnknownEither(BootstrapEnvelope)(body);\n if (Either.isLeft(decoded)) {\n // Schema validation failure → INVALID_INPUT per #119 AC1.\n // Unknown `version` literals, missing fields, and brand-rule\n // failures (e.g. `applicationId` not matching `APP_ID_RE`)\n // all land here.\n throw Errors.invalidInput(\"bootstrapEnvelope\", decoded.left.message);\n }\n const { state } = decoded.right;\n return {\n applicationId: state.applicationId,\n chainId: state.chainId,\n sessionToken: state.sessionToken,\n issuedAt: state.issuedAt,\n expiresIn: state.expiresIn,\n authBaseUrl: normalizeRuntimeUrl(\"authBaseUrl\", state.authBaseUrl),\n convexUrl: normalizeRuntimeUrl(\"convexUrl\", state.convexUrl),\n siteBaseUrl: normalizeRuntimeUrl(\"siteBaseUrl\", state.siteBaseUrl),\n openfortPublishableKey: state.openfortPublishableKey,\n shieldPublishableKey: state.shieldPublishableKey,\n };\n },\n catch: (cause) => {\n if (cause instanceof CapxulError && cause.code === \"INVALID_INPUT\") {\n return bootstrapErrorFromCapxul(\"invalidInput\", cause);\n }\n return bootstrapErrorFromCapxul(\n \"malformedBody\",\n Errors.providerError(\n \"convex\",\n \"bootstrap\",\n cause instanceof Error ? cause : new Error(String(cause)),\n ),\n );\n },\n });\n }\n\n return Effect.promise(() => safeText(res)).pipe(\n Effect.flatMap((body) => {\n if (res.status === 401 || body.startsWith(\"NOT_AUTHENTICATED\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\"notAuthenticated\", Errors.notAuthenticated()),\n );\n }\n if (res.status === 400 || body.startsWith(\"INVALID_INPUT\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"invalidInput\",\n Errors.invalidInput(\"publishableKey\", \"rejected by bootstrap\"),\n ),\n );\n }\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"provider\",\n Errors.providerError(\"convex\", \"bootstrap\", new Error(`HTTP ${res.status}`)),\n ),\n );\n }),\n );\n }\n}\n\nexport function HttpBootstrapLayer(deps: HttpBootstrapAdapterDeps): Layer.Layer<BootstrapPortTag> {\n return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));\n}\n\nfunction normalizeRuntimeUrl(\n field: \"authBaseUrl\" | \"convexUrl\" | \"siteBaseUrl\",\n raw: string,\n): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n","import { Context, Data, Effect } from \"effect\";\n\nimport type { DurationMs, EpochMs } from \"@capxul/types\";\n\nexport interface ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError>;\n readonly sleep: (duration: DurationMs) => Effect.Effect<void, ClockError>;\n}\n\nexport class ClockError extends Data.TaggedError(\"ClockError\")<{\n readonly operation: \"now\" | \"sleep\" | \"initialize\";\n readonly cause: unknown;\n}> {}\n\nexport class ClockPortTag extends Context.Tag(\"@capxul/sdk/ports/ClockPort\")<\n ClockPortTag,\n ClockPort\n>() {}\n","import type { DurationMs, EpochMs } from \"@capxul/types\";\nimport { toEpochMs } from \"@capxul/types\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ClockError, ClockPortTag, type ClockPort } from \"../../ports/clock\";\n\nexport class SystemClockAdapter implements ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError, never> = Effect.try({\n try: () => toEpochMs(Date.now()),\n catch: (cause) => new ClockError({ operation: \"now\", cause }),\n });\n\n sleep(duration: DurationMs): Effect.Effect<void, ClockError, never> {\n return Effect.async<void, ClockError>((resume) => {\n const timeout = setTimeout(() => resume(Effect.void), duration as number);\n return Effect.sync(() => clearTimeout(timeout));\n });\n }\n}\n\nexport function SystemClockLayer(): Layer.Layer<ClockPortTag, ClockError, never> {\n return Layer.succeed(ClockPortTag, new SystemClockAdapter());\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { FunctionReference } from \"convex/server\";\n\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Snapshot, Unsubscribe } from \"./subscription\";\n\nexport type { Snapshot, Unsubscribe } from \"./subscription\";\n\nexport class ConvexCallError extends Data.TaggedError(\"ConvexCallError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function convexCallErrorFromCapxul(operation: string, error: CapxulError): ConvexCallError {\n return new ConvexCallError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause: error,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\nexport interface ConvexCallPort {\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n /**\n * Substrate-level reactive transport over Convex's `onUpdate`.\n *\n * @internal-use — substrate only; see `ports/subscription.ts`. Domain\n * ports do not expose reactive callback methods to consumers (ARCH-LOCK-1).\n */\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError>;\n}\n\nexport class ConvexCallPortTag extends Context.Tag(\"@capxul/sdk/ports/ConvexCallPort\")<\n ConvexCallPortTag,\n ConvexCallPort\n>() {}\n","import { CapxulError, Errors, decodeConvexError } from \"@capxul/config\";\nimport { ConvexClient } from \"convex/browser\";\nimport { getFunctionName, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport {\n ConvexCallPortTag,\n convexCallErrorFromCapxul,\n type ConvexCallError,\n type ConvexCallPort,\n type Snapshot,\n type Unsubscribe,\n} from \"../../ports/convex-call\";\n\nexport type ConvexCallAuthFetcher = (args: {\n readonly forceRefreshToken: boolean;\n}) => Promise<string | null>;\n\nexport interface ConvexClientShape {\n setAuth(fetchToken: ConvexCallAuthFetcher): void;\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n onUpdate<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n onValue: (value: TOutput) => void,\n onError: (err: Error) => void,\n ): () => void;\n close(): Promise<void>;\n}\n\nexport type ConvexCallLayerDeps = {\n readonly convexUrl: string;\n readonly tokenProvider?: ConvexCallAuthFetcher;\n readonly client?: ConvexClientShape;\n};\n\nexport class ConvexCallAdapter implements ConvexCallPort {\n readonly #client: ConvexClientShape;\n readonly #tokenProvider: ConvexCallAuthFetcher | undefined;\n\n constructor(deps: ConvexCallLayerDeps) {\n this.#client = deps.client ?? (new ConvexClient(deps.convexUrl) as ConvexClientShape);\n this.#tokenProvider = deps.tokenProvider;\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n refreshAuth(): void {\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n return Effect.tryPromise({\n try: () => this.#client.query(fn, args),\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n });\n }\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n return Effect.tryPromise({\n try: () => this.#client.mutation(fn, args),\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n });\n }\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n return Effect.tryPromise({\n try: () => this.#client.action(fn, args),\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n });\n }\n\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError> {\n return Effect.try({\n try: () => {\n const path = getFunctionName(fn);\n const unsubscribe = this.#client.onUpdate(\n fn,\n args,\n (value) => callback({ status: \"ok\", value }),\n (err) => callback({ status: \"error\", error: mapToCapxulError(path, err) }),\n );\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n unsubscribe();\n };\n },\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n }).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n callback({ status: \"loading\" });\n }),\n ),\n );\n }\n\n async close(): Promise<void> {\n await this.#client.close();\n }\n}\n\nexport function ConvexCallLayer(deps: ConvexCallLayerDeps): Layer.Layer<ConvexCallPortTag> {\n return Layer.scoped(\n ConvexCallPortTag,\n Effect.acquireRelease(\n Effect.sync(() => new ConvexCallAdapter(deps)),\n (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie),\n ),\n );\n}\n\nfunction mapToCapxulError(operation: string, err: unknown): CapxulError {\n const decoded = decodeConvexError(err);\n if (decoded !== null) return decoded;\n if (err instanceof CapxulError) return err;\n if (err instanceof Error) {\n if (isTransportError(err)) return Errors.networkError(operation, err);\n return Errors.providerError(\"convex\", operation, err);\n }\n return Errors.providerError(\"convex\", operation, new Error(String(err)));\n}\n\nfunction mapToConvexCallError(operation: string, err: unknown): ConvexCallError {\n return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err));\n}\n\nfunction isTransportError(err: Error): boolean {\n const message = err.message.toLowerCase();\n return (\n message.includes(\"failed to fetch\") ||\n message.includes(\"network\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"enotfound\") ||\n message.includes(\"etimedout\") ||\n message.includes(\"socket\")\n );\n}\n","import type { Address, ChainId, DurationMs } from \"@capxul/types\";\n\n/**\n * Documented brand-erasure helpers for the wire boundary.\n *\n * Branded primitives (`Address`, `ChainId`) carry compile-time tags that\n * vanish at runtime. When sending values across a wire — Convex function\n * args, viem's template-literal-typed parameters, raw JSON — we have to\n * remove the brand at the type level so the wire-side type system accepts\n * the value.\n *\n * Using these helpers (rather than ad-hoc `as number` / `as \\`0x${string}\\``\n * casts) localizes every de-branding site. If we ever need to centralize\n * validation (e.g. \"must not de-brand a placeholder address\"), the change\n * lands here once instead of grep-and-replace across every adapter.\n */\n\n/**\n * De-brand a `ChainId` for the wire. The runtime representation is already\n * `number` — the cast removes the compile-time brand only.\n */\nexport function wireChainId(chainId: ChainId): number {\n return chainId;\n}\n\n/**\n * De-brand a `DurationMs` for the wire. The runtime representation is\n * already `number` — the cast removes the compile-time brand only.\n *\n * Used at Convex mutation call sites where the backend's schema expects\n * a plain `number` for `graceMs` (and similar duration fields). The\n * branded `DurationMs` type is the SDK's discipline; the wire format is\n * agnostic.\n */\nexport function wireDurationMs(duration: DurationMs): number {\n return duration;\n}\n\n/**\n * De-brand an `Address` for viem's `\\`0x${string}\\`` template-literal type.\n * Our `Address` brand is structurally `\\`0x${string}\\`` (lowercased hex)\n * but TypeScript needs an explicit cast to satisfy viem's type signature.\n */\nexport function addressForViem(address: Address): `0x${string}` {\n return address as `0x${string}`;\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type {\n AllowedOrigin,\n AppId,\n AuthUserId,\n DeveloperApplication,\n DurationMs,\n PublishableKeyId,\n PublishableKeyRecord,\n} from \"@capxul/types\";\n\nexport type CreateApplicationInput = {\n readonly authUserId: AuthUserId;\n readonly name: string;\n readonly allowedOrigins: readonly AllowedOrigin[];\n};\n\nexport type MintKeyInput = {\n readonly applicationId: AppId;\n readonly authUserId: AuthUserId;\n};\n\nexport type RotateKeyInput = {\n readonly keyId: PublishableKeyId;\n readonly authUserId: AuthUserId;\n readonly graceMs: DurationMs;\n};\n\nexport type RevokeKeyInput = {\n readonly keyId: PublishableKeyId;\n readonly authUserId: AuthUserId;\n};\n\nexport type RotateKeyResult = {\n readonly active: PublishableKeyRecord;\n readonly retired: PublishableKeyRecord;\n};\n\nexport class CredentialsError extends Data.TaggedError(\"CredentialsError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function credentialsErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): CredentialsError {\n return new CredentialsError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n// Domain port. Sibling to the platform-ports bundle; deliberately NOT a\n// member of `PlatformPorts` — domain ports are composed by consumers per the\n// hexagonal Option C decision. See `docs/canon/ports/credentials.md`.\nexport interface CredentialsPort {\n listApplications(\n authUserId: AuthUserId,\n ): Effect.Effect<readonly DeveloperApplication[], CredentialsError>;\n createApplication(\n input: CreateApplicationInput,\n ): Effect.Effect<DeveloperApplication, CredentialsError>;\n mintPublishableKey(input: MintKeyInput): Effect.Effect<PublishableKeyRecord, CredentialsError>;\n rotatePublishableKey(input: RotateKeyInput): Effect.Effect<RotateKeyResult, CredentialsError>;\n revokePublishableKey(input: RevokeKeyInput): Effect.Effect<void, CredentialsError>;\n}\n\nexport class CredentialsPortTag extends Context.Tag(\"@capxul/sdk/ports/CredentialsPort\")<\n CredentialsPortTag,\n CredentialsPort\n>() {}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type {\n AllowedOrigin,\n AuthUserId,\n DeveloperApplication,\n PublishableKeyRecord,\n} from \"@capxul/types\";\nimport {\n toAllowedOrigin,\n toAppId,\n toAuthUserId,\n toEpochMs,\n toPublishableKeyId,\n} from \"@capxul/types\";\nimport { makeFunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireDurationMs } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateApplicationInput,\n CredentialsPort,\n MintKeyInput,\n RevokeKeyInput,\n RotateKeyInput,\n RotateKeyResult,\n} from \"../../ports/credentials\";\nimport {\n credentialsErrorFromCapxul,\n CredentialsPortTag,\n type CredentialsError,\n} from \"../../ports/credentials\";\n\ntype RawDeveloperApplication = {\n readonly id: string;\n readonly authUserId: string;\n readonly name: string;\n readonly allowedOrigins: readonly string[];\n readonly createdAt: number;\n readonly archivedAt: number | null;\n};\n\ntype RawPublishableKey = {\n readonly id: string;\n readonly applicationId: string;\n readonly activeFromMs: number;\n readonly gracePeriodEndsMs: number | null;\n readonly revokedAt: number | null;\n};\n\nexport class ConvexCredentialsAdapter implements CredentialsPort {\n readonly #convex: ConvexCallPort;\n\n constructor(deps: { readonly convex: ConvexCallPort }) {\n this.#convex = deps.convex;\n }\n\n listApplications(\n authUserId: AuthUserId,\n ): Effect.Effect<readonly DeveloperApplication[], CredentialsError> {\n return this.#convex\n .query(applicationsListFn, {\n authUserId: String(authUserId),\n })\n .pipe(\n Effect.mapError((error) =>\n credentialsErrorFromCapxul(\"listApplications\", error.publicError, error),\n ),\n Effect.flatMap((rows) =>\n Effect.try({\n try: () => rows.map(brandDeveloperApplication),\n catch: (cause) => credentialsErrorFromUnknown(\"listApplications\", cause),\n }),\n ),\n );\n }\n\n createApplication(\n input: CreateApplicationInput,\n ): Effect.Effect<DeveloperApplication, CredentialsError> {\n return this.#convex\n .mutation(applicationsCreateFn, {\n authUserId: String(input.authUserId),\n name: input.name,\n allowedOrigins: input.allowedOrigins.map(String),\n })\n .pipe(\n Effect.mapError((error) =>\n credentialsErrorFromCapxul(\"createApplication\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandDeveloperApplication(row),\n catch: (cause) => credentialsErrorFromUnknown(\"createApplication\", cause),\n }),\n ),\n );\n }\n\n mintPublishableKey(input: MintKeyInput): Effect.Effect<PublishableKeyRecord, CredentialsError> {\n return this.#convex\n .mutation(publishableKeysMintFn, {\n applicationId: String(input.applicationId),\n authUserId: String(input.authUserId),\n })\n .pipe(\n Effect.mapError((error) =>\n credentialsErrorFromCapxul(\"mintPublishableKey\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandPublishableKeyRecord(row),\n catch: (cause) => credentialsErrorFromUnknown(\"mintPublishableKey\", cause),\n }),\n ),\n );\n }\n\n rotatePublishableKey(input: RotateKeyInput): Effect.Effect<RotateKeyResult, CredentialsError> {\n return this.#convex\n .mutation(publishableKeysRotateFn, {\n keyId: String(input.keyId),\n authUserId: String(input.authUserId),\n graceMs: wireDurationMs(input.graceMs),\n })\n .pipe(\n Effect.mapError((error) =>\n credentialsErrorFromCapxul(\"rotatePublishableKey\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => ({\n active: brandPublishableKeyRecord(row.active),\n retired: brandPublishableKeyRecord(row.retired),\n }),\n catch: (cause) => credentialsErrorFromUnknown(\"rotatePublishableKey\", cause),\n }),\n ),\n );\n }\n\n revokePublishableKey(input: RevokeKeyInput): Effect.Effect<void, CredentialsError> {\n return this.#convex\n .mutation(publishableKeysRevokeFn, {\n keyId: String(input.keyId),\n authUserId: String(input.authUserId),\n })\n .pipe(\n Effect.mapError((error) =>\n credentialsErrorFromCapxul(\"revokePublishableKey\", error.publicError, error),\n ),\n Effect.asVoid,\n );\n }\n}\n\nexport function ConvexCredentialsLayer(): Layer.Layer<\n CredentialsPortTag,\n CredentialsError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n CredentialsPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexCredentialsAdapter({ convex })),\n );\n}\n\nconst applicationsListFn = makeFunctionReference<\n \"query\",\n { readonly authUserId: string },\n readonly RawDeveloperApplication[]\n>(\"credentials/applications:list\");\n\nconst applicationsCreateFn = makeFunctionReference<\n \"mutation\",\n {\n readonly authUserId: string;\n readonly name: string;\n readonly allowedOrigins: readonly string[];\n },\n RawDeveloperApplication\n>(\"credentials/applications:create\");\n\nconst publishableKeysMintFn = makeFunctionReference<\n \"mutation\",\n { readonly applicationId: string; readonly authUserId: string },\n RawPublishableKey\n>(\"credentials/publishableKeys:mint\");\n\nconst publishableKeysRotateFn = makeFunctionReference<\n \"mutation\",\n {\n readonly keyId: string;\n readonly authUserId: string;\n readonly graceMs: number;\n },\n { readonly active: RawPublishableKey; readonly retired: RawPublishableKey }\n>(\"credentials/publishableKeys:rotate\");\n\nconst publishableKeysRevokeFn = makeFunctionReference<\n \"mutation\",\n { readonly keyId: string; readonly authUserId: string },\n null\n>(\"credentials/publishableKeys:revoke\");\n\nfunction brandDeveloperApplication(row: RawDeveloperApplication): DeveloperApplication {\n return {\n id: toAppId(row.id),\n authUserId: toAuthUserId(row.authUserId),\n name: row.name,\n allowedOrigins: row.allowedOrigins.map((o) => toAllowedOrigin(o)) as readonly AllowedOrigin[],\n createdAt: toEpochMs(row.createdAt),\n archivedAt: row.archivedAt === null ? null : toEpochMs(row.archivedAt),\n };\n}\n\nfunction brandPublishableKeyRecord(row: RawPublishableKey): PublishableKeyRecord {\n return {\n id: toPublishableKeyId(row.id),\n applicationId: toAppId(row.applicationId),\n activeFromMs: toEpochMs(row.activeFromMs),\n gracePeriodEndsMs: row.gracePeriodEndsMs === null ? null : toEpochMs(row.gracePeriodEndsMs),\n revokedAt: row.revokedAt === null ? null : toEpochMs(row.revokedAt),\n };\n}\n\nfunction credentialsErrorFromUnknown(operation: string, cause: unknown): CredentialsError {\n if (cause instanceof CapxulError) {\n return credentialsErrorFromCapxul(operation, cause);\n }\n const publicError = Errors.providerError(\n \"credentials\",\n operation,\n cause instanceof Error ? cause : new Error(String(cause)),\n );\n return credentialsErrorFromCapxul(operation, publicError, cause);\n}\n","import { Context, Data, Effect } from \"effect\";\n\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { EnvKey, EnvShape, OptionalEnvKey, RequiredEnvKey } from \"../env\";\n\nexport type { EnvKey, EnvShape, OptionalEnvKey, RequiredEnvKey } from \"../env\";\n\nexport class EnvError extends Data.TaggedError(\"EnvError\")<{\n readonly publicError: CapxulError;\n readonly publicCode?: CapxulErrorCode;\n readonly key?: string;\n readonly details?: CapxulErrorDetails;\n readonly cause?: unknown;\n}> {}\n\nexport function envErrorFromCapxul(\n key: string,\n error: CapxulError,\n cause: unknown = error,\n): EnvError {\n return new EnvError({\n publicError: error,\n publicCode: error.code,\n key,\n ...(error.details === undefined ? {} : { details: error.details }),\n cause,\n });\n}\n\nexport interface EnvPort {\n readonly require: <K extends RequiredEnvKey>(\n key: K,\n ) => Effect.Effect<EnvShape[K], EnvError, never>;\n readonly optional: <K extends OptionalEnvKey>(\n key: K,\n ) => Effect.Effect<EnvShape[K] | undefined, EnvError, never>;\n readonly has: (key: EnvKey) => Effect.Effect<boolean, EnvError, never>;\n}\n\nexport class EnvPortTag extends Context.Tag(\"@capxul/sdk/ports/EnvPort\")<EnvPortTag, EnvPort>() {}\n","","import { Schema, TreeFormatter } from \"@effect/schema\";\nimport { Either } from \"effect\";\n\nimport { Errors } from \"@capxul/config\";\n\nimport catalog from \"./catalog.json\" with { type: \"json\" };\n\ntype EnvFieldKind = \"authMode\" | \"email\" | \"nonempty\" | \"privateKey\" | \"url\";\n\nexport type EnvRuntime = \"client\" | \"server\";\n\nexport type EnvField = {\n readonly runtime: EnvRuntime;\n readonly kind: EnvFieldKind;\n readonly required: boolean;\n readonly example: string;\n};\n\nexport const envFields = catalog as Record<string, EnvField>;\n\nconst PARSE_OPTIONS = { onExcessProperty: \"error\" } as const;\n\nexport function schemaFor(kind: EnvFieldKind): Schema.Schema<string, string, never> {\n switch (kind) {\n case \"authMode\":\n return Schema.String.pipe(\n Schema.filter(\n (value): value is string =>\n value === \"development\" || value === \"production\" || value === \"test\",\n {\n message: () => \"Invalid enum value\",\n },\n ),\n );\n case \"email\":\n return Schema.String.pipe(\n Schema.filter((value) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value), {\n message: () => \"Invalid email\",\n }),\n );\n case \"nonempty\":\n return Schema.String.pipe(Schema.minLength(1));\n case \"privateKey\":\n return Schema.String.pipe(\n Schema.filter((value) => /^0x[0-9a-fA-F]{64}$/.test(value), {\n message: () => \"Must be a 0x-prefixed 32-byte hex private key\",\n }),\n );\n case \"url\":\n return Schema.String.pipe(\n Schema.filter(\n (value) => {\n try {\n const parsed = new URL(value);\n return parsed.href.length > 0;\n } catch {\n return false;\n }\n },\n {\n message: () => \"Invalid url\",\n },\n ),\n );\n default: {\n const unsupported: never = kind;\n throw Errors.invalidInput(String(unsupported), \"unsupported environment field kind\");\n }\n }\n}\n\nconst envShapeFields = Object.fromEntries(\n Object.entries(envFields).map(([key, field]) => [\n key,\n field.required ? schemaFor(field.kind) : Schema.optional(schemaFor(field.kind)),\n ]),\n);\n\nconst envShapeSchema = Schema.Struct(envShapeFields);\nconst envShapePartialSchema = Schema.partial(envShapeSchema);\n\nexport type EnvShape = Schema.Schema.Type<typeof envShapeSchema>;\nexport type EnvKey = keyof EnvShape & string;\n\ntype EnvShapeParser = {\n parse(input: unknown): EnvShape;\n partial(): {\n parse(input: unknown): Partial<EnvShape>;\n };\n};\n\nfunction decodeEnvShape<A, I>(schema: Schema.Schema<A, I, never>, input: unknown): A {\n return Schema.decodeUnknownSync(schema)(input, PARSE_OPTIONS);\n}\n\nexport const envShape: EnvShapeParser = {\n parse(input: unknown): EnvShape {\n return decodeEnvShape(envShapeSchema, input);\n },\n partial() {\n return {\n parse(input: unknown): Partial<EnvShape> {\n return decodeEnvShape(envShapePartialSchema, input);\n },\n };\n },\n};\n\nexport function parseEnvValue(key: EnvKey, raw: string | undefined, required: boolean): unknown {\n const field = envFields[key];\n if (field === undefined) {\n throw Errors.invalidInput(key, \"unknown environment key\");\n }\n\n const normalized = normalizeEnvRaw(raw);\n if (normalized === undefined) {\n if (required) {\n throw Errors.envMissing(key);\n }\n return undefined;\n }\n\n const result = Schema.decodeUnknownEither(schemaFor(field.kind))(normalized);\n if (Either.isLeft(result)) {\n throw Errors.invalidInput(key, TreeFormatter.formatErrorSync(result.left));\n }\n\n return result.right;\n}\n\nexport function normalizeEnvRaw(raw: string | undefined): string | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n\n return raw;\n}\n\nexport function runtimeEnv(): Record<string, string | undefined> {\n const maybeProcess = (\n globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n }\n ).process;\n return maybeProcess?.env ?? {};\n}\n","import { Errors, isCapxulError } from \"@capxul/config\";\nimport type { EnvKey, EnvShape } from \"@capxul/sdk/env\";\nimport { envFields } from \"@capxul/sdk/env\";\n\nimport { EnvError, envErrorFromCapxul } from \"../../ports/env\";\nimport {\n normalizeEnvRaw,\n parseEnvValue as parseCatalogEnvValue,\n runtimeEnv,\n} from \"../../env/_internal\";\n\nexport type EnvSource = Readonly<Record<string, string | undefined>>;\n\nexport { runtimeEnv };\n\nexport function parseEnvValue<K extends EnvKey>(\n key: K,\n raw: string | undefined,\n required: boolean,\n): EnvShape[K] | undefined {\n return parseCatalogEnvValue(key, raw, required) as EnvShape[K] | undefined;\n}\n\nexport function hasEnvValue(key: EnvKey, raw: string | undefined): boolean {\n if (envFields[key] === undefined) {\n throw envErrorFromCapxul(key, Errors.invalidInput(key, \"unknown environment key\"));\n }\n return normalizeEnvRaw(raw) !== undefined;\n}\n\nexport function catchEnvError(key: string, cause: unknown): EnvError {\n if (cause instanceof EnvError) {\n return cause;\n }\n if (isCapxulError(cause)) {\n return envErrorFromCapxul(key, cause, cause);\n }\n const redactedCause = new Error(`env ${key} read failed`);\n return envErrorFromCapxul(key, Errors.providerError(\"env\", key, redactedCause), redactedCause);\n}\n","import type { EnvKey, EnvShape } from \"@capxul/sdk/env\";\nimport { Effect, Layer } from \"effect\";\n\nimport { EnvPortTag, type EnvError, type EnvPort } from \"../../ports/env\";\nimport { catchEnvError, hasEnvValue, parseEnvValue, runtimeEnv, type EnvSource } from \"./_shared\";\n\nexport type SystemEnvLayerDeps = {\n readonly source?: EnvSource;\n};\n\nexport class SystemEnvAdapter implements EnvPort {\n readonly #source: EnvSource;\n\n constructor(deps: SystemEnvLayerDeps = {}) {\n this.#source = deps.source ?? runtimeEnv();\n }\n\n readonly require = <K extends EnvKey>(key: K): Effect.Effect<EnvShape[K], EnvError, never> =>\n Effect.try({\n try: () => parseEnvValue(key, this.#source[key], true) as EnvShape[K],\n catch: (cause) => catchEnvError(key, cause),\n });\n\n readonly optional = <K extends EnvKey>(\n key: K,\n ): Effect.Effect<EnvShape[K] | undefined, EnvError, never> =>\n Effect.try({\n try: () => parseEnvValue(key, this.#source[key], false),\n catch: (cause) => catchEnvError(key, cause),\n });\n\n readonly has = (key: EnvKey): Effect.Effect<boolean, EnvError, never> =>\n Effect.try({\n try: () => hasEnvValue(key, this.#source[key]),\n catch: (cause) => catchEnvError(key, cause),\n });\n}\n\nexport function SystemEnvLayer(\n deps: SystemEnvLayerDeps = {},\n): Layer.Layer<EnvPortTag, EnvError, never> {\n return Layer.succeed(EnvPortTag, new SystemEnvAdapter(deps));\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Address, AuthUserId, CountryCode, Email, Profile } from \"@capxul/types\";\n\nexport type CreateIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName?: string;\n readonly country?: CountryCode;\n};\n\nexport type UpdateIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly displayName?: string;\n readonly country?: CountryCode;\n};\n\n/**\n * D-ONBOARD (#669) — the onboarding-complete identity write. Composes the\n * existing create/update write into one idempotent upsert that ALSO sets the\n * `onboarded` flag and persists the optional `withdrawalAddress` (the one\n * allowed raw-0x class). `displayName` + `country` are required at onboarding\n * time. The returned `Profile` is the existing branded shape — the onboarding\n * flags live on the wire row and are not projected onto the read surface.\n */\nexport type CompleteOnboardingIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string;\n readonly country: CountryCode;\n readonly withdrawalAddress?: Address;\n};\n\nexport class IdentityError extends Data.TaggedError(\"IdentityError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function identityErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): IdentityError {\n return new IdentityError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n// First domain port. Sibling to the platform-ports bundle; deliberately NOT a\n// member of `PlatformPorts` — domain ports are composed by consumers per the\n// hexagonal Option C decision. See `docs/canon/ports/identity.md`.\nexport interface IdentityPort {\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError, never>;\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError, never>;\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError, never>;\n /** D-ONBOARD (#669): idempotent upsert that marks the identity onboarded. */\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError, never>;\n}\n\nexport class IdentityPortTag extends Context.Tag(\"@capxul/sdk/ports/IdentityPort\")<\n IdentityPortTag,\n IdentityPort\n>() {}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, Profile } from \"@capxul/types\";\nimport { toAuthUserId, toCountryCode, toEmail, toEpochMs, toKycTier } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../ports/convex-call\";\nimport type {\n CompleteOnboardingIdentityInput,\n CreateIdentityInput,\n IdentityError,\n IdentityPort,\n UpdateIdentityInput,\n} from \"../ports/identity\";\nimport { identityErrorFromCapxul, IdentityPortTag } from \"../ports/identity\";\n\ntype RawProfile = {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly country: string | null;\n readonly kycTier: 0 | 1 | 2 | 3;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nconst identityLoadByAuthUserIdQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: AuthUserId },\n RawProfile | null\n> = makeFunctionReference<\"query\", { readonly authUserId: AuthUserId }, RawProfile | null>(\n \"identity/queries:loadByAuthUserId\",\n);\n\nconst identityCreateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CreateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CreateIdentityInput, RawProfile>(\"identity/mutations:create\");\n\nconst identityUpdateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n UpdateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", UpdateIdentityInput, RawProfile>(\"identity/mutations:update\");\n\nconst identityCompleteOnboardingMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CompleteOnboardingIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CompleteOnboardingIdentityInput, RawProfile>(\n \"identity/mutations:completeOnboarding\",\n);\n\nexport class ConvexIdentityAdapter implements IdentityPort {\n readonly #convex: ConvexCallPort;\n\n constructor(deps: { readonly convex: ConvexCallPort }) {\n this.#convex = deps.convex;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError> {\n return this.#convex.query(identityLoadByAuthUserIdQuery, { authUserId }).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => (row === null ? null : brandProfile(row)),\n catch: (cause) => identityErrorFromUnknown(\"loadByAuthUserId\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCreateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"create\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"create\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown(\"create\", cause))),\n );\n }\n\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityUpdateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"update\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"update\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown(\"update\", cause))),\n );\n }\n\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"completeOnboarding\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"completeOnboarding\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"completeOnboarding\", cause)),\n ),\n );\n }\n}\n\nexport function ConvexIdentityLayer(): Layer.Layer<\n IdentityPortTag,\n IdentityError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n IdentityPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })),\n );\n}\n\nfunction brandProfile(raw: RawProfile): Profile {\n return {\n authUserId: toAuthUserId(raw.authUserId),\n email: toEmail(raw.email),\n displayName: raw.displayName,\n country: raw.country === null ? null : toCountryCode(raw.country),\n kycTier: toKycTier(raw.kycTier),\n createdAt: toEpochMs(raw.createdAt),\n updatedAt: toEpochMs(raw.updatedAt),\n };\n}\n\nfunction identityErrorFromUnknown(operation: string, cause: unknown): IdentityError {\n if (cause instanceof CapxulError) return identityErrorFromCapxul(operation, cause);\n return identityErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { parseUnits } from \"viem\";\n\n/**\n * Lower consumer `Money` into an on-chain integer string for guarded writes.\n * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.\n */\nexport function toWei(money: { readonly value: string; readonly decimals: number }): string {\n return parseUnits(money.value, money.decimals).toString();\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Account, ChainId, Money } from \"@capxul/types\";\n\nexport type ReadAccountBalanceInput = {\n readonly chainId: ChainId;\n};\n\nexport type FundFromFaucetInput = {\n readonly chainId: ChainId;\n readonly amount: Money;\n};\n\nexport type FundFromFaucetResult = {\n readonly txHash: string;\n};\n\nexport class AccountReadError extends Data.TaggedError(\"AccountReadError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function accountReadErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): AccountReadError {\n return new AccountReadError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n/**\n * Logical Account money read (M2 Slice S1a). Joins the `accounts` row with a\n * live RPC `balanceOf` pull; the adapter lifts wire integers to `Money`.\n */\nexport interface AccountReadPort {\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError, never>;\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError, never>;\n}\n\nexport class AccountReadPortTag extends Context.Tag(\"@capxul/sdk/ports/AccountReadPort\")<\n AccountReadPortTag,\n AccountReadPort\n>() {}\n","import { formatUnits } from \"viem\";\n\nimport { toCurrencyCode, type Money } from \"@capxul/types\";\n\n/**\n * Lift an on-chain integer (e.g. USDX 6-decimal) into consumer `Money`.\n * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.\n */\nexport function fromWei(rawBalance: string, decimals: number, currency: string): Money {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new Error(`fromWei: decimals must be a non-negative integer, got ${String(decimals)}`);\n }\n const normalized = rawBalance.trim();\n if (!/^\\d+$/.test(normalized)) {\n // Show the exact (trimmed) value that failed the regex, truncated to keep\n // logs bounded for a pathologically long input.\n const truncated = normalized.length > 80 ? `${normalized.slice(0, 80)}…` : normalized;\n throw new Error(`fromWei: rawBalance must be a base-10 integer string, got ${truncated}`);\n }\n return {\n currency: toCurrencyCode(currency),\n value: formatUnits(BigInt(normalized), decimals),\n decimals,\n };\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Account } from \"@capxul/types\";\nimport { toAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n AccountReadError,\n AccountReadPort,\n FundFromFaucetInput,\n FundFromFaucetResult,\n ReadAccountBalanceInput,\n} from \"../../ports/account-read\";\nimport { toWei } from \"../../money/to-wei\";\nimport { accountReadErrorFromCapxul, AccountReadPortTag } from \"../../ports/account-read\";\nimport { fromWei } from \"../../money/from-wei\";\n\nexport type WireAccountBalance = {\n readonly accountId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\nexport type WireFaucetMintResult = {\n readonly txHash: string;\n};\n\nexport type ConvexAccountFunctions = {\n readonly readBalance: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number },\n WireAccountBalance\n >;\n readonly faucetMint: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number; readonly rawAmount: string },\n WireFaucetMintResult\n >;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexAccountFunctions = {\n readBalance: makeFunctionReference<\"action\", { chainId: number }, WireAccountBalance>(\n \"account/actions:readBalance\",\n ),\n faucetMint: makeFunctionReference<\n \"action\",\n { chainId: number; rawAmount: string },\n WireFaucetMintResult\n >(\"account/actions:faucetMint\"),\n};\n\nexport class ConvexAccountAdapter implements AccountReadPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError> {\n return this.#convex.action(this.#fns.readBalance, { chainId: wireChainId(input.chainId) }).pipe(\n Effect.mapError((error) =>\n accountReadErrorFromCapxul(\"readBalance\", error.publicError, error),\n ),\n Effect.flatMap((wire) => brandAccountEffect(\"readBalance\", wire)),\n Effect.catchAllDefect((cause) =>\n Effect.fail(accountReadErrorFromUnknown(\"readBalance\", cause)),\n ),\n );\n }\n\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError> {\n const operation = \"fundFromFaucet\";\n // `toWei`/`parseUnits` throws on a malformed money string; suspend so the\n // throw surfaces as a defect below and maps to an AccountReadError, never an\n // escaped throw out of `fundFromFaucet` (mirrors ConvexSubAccountAdapter.transfer).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(this.#fns.faucetMint, {\n chainId: wireChainId(input.chainId),\n rawAmount,\n });\n }).pipe(\n Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => ({ txHash: wire.txHash })),\n Effect.catchAllDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexAccountLayer(): Layer.Layer<\n AccountReadPortTag,\n AccountReadError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n AccountReadPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })),\n );\n}\n\nfunction brandAccountEffect(\n operation: string,\n wire: WireAccountBalance,\n): Effect.Effect<Account, AccountReadError> {\n return Effect.try({\n try: () => brandAccount(wire),\n catch: (cause) => accountReadErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandAccount(wire: WireAccountBalance): Account {\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(\n wire.rawAvailableBalance ?? wire.rawBalance,\n wire.decimals,\n wire.currency,\n );\n return {\n id: toAccountId(wire.accountId),\n balance,\n available,\n };\n}\n\nfunction accountReadErrorFromUnknown(operation: string, cause: unknown): AccountReadError {\n if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);\n return accountReadErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { AccountId, Money, SubAccount, SubAccountId } from \"@capxul/types\";\n\nexport class SubAccountError extends Data.TaggedError(\"SubAccountError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function subAccountErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): SubAccountError {\n return new SubAccountError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\nexport type CreateSubAccountInput = {\n readonly accountId: AccountId;\n readonly name: string;\n};\n\nexport type SubAccountIdInput = {\n readonly subAccountId: SubAccountId;\n};\n\nexport type RenameSubAccountInput = {\n readonly subAccountId: SubAccountId;\n readonly name: string;\n};\n\n/**\n * A `transfer` endpoint is either the Account's MAIN balance (the remainder\n * left over after every sub-account is funded — never a stored row) or a\n * specific sub-account, addressed by its `SubAccountId` (canon\n * `account-balance-model.md` §5, §12).\n */\nexport type TransferEndpoint = \"main\" | SubAccountId;\n\n/**\n * Move money between two of the SAME Account's balances (canon §12). The\n * backend resolves the Account from auth (v1 = one Account per user), so the\n * input carries no `accountId` — only the from/to endpoints and the `Money`\n * amount. One verb covers money in (`main → sub`), money out (`sub → main`),\n * and `sub → sub`.\n */\nexport type TransferInput = {\n readonly from: TransferEndpoint;\n readonly to: TransferEndpoint;\n readonly amount: Money;\n};\n\n/**\n * Result of a `transfer`: the recomputed `available` (`balanceOf − Σ`), plus\n * the updated source/destination sub-account rows. An endpoint that is `\"main\"`\n * has no stored row, so its slot is `null`.\n */\nexport type TransferResult = {\n readonly available: Money;\n readonly from: SubAccount | null;\n readonly to: SubAccount | null;\n};\n\nexport interface SubAccountPort {\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError, never>;\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError, never>;\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError, never>;\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError, never>;\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError, never>;\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError, never>;\n}\n\nexport class SubAccountPortTag extends Context.Tag(\"@capxul/sdk/ports/SubAccountPort\")<\n SubAccountPortTag,\n SubAccountPort\n>() {}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount } from \"@capxul/types\";\nimport { toAccountId, toEpochMs, toSubAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { fromWei } from \"../../money/from-wei\";\nimport { toWei } from \"../../money/to-wei\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateSubAccountInput,\n RenameSubAccountInput,\n SubAccountError,\n SubAccountIdInput,\n SubAccountPort,\n TransferInput,\n TransferResult,\n} from \"../../ports/sub-account\";\nimport { subAccountErrorFromCapxul, SubAccountPortTag } from \"../../ports/sub-account\";\n\nexport type WireSubAccount = {\n readonly subAccountId: string;\n readonly accountId: string;\n readonly name: string;\n readonly rawBalance: string;\n readonly decimals: number;\n readonly currency: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\n/**\n * Wire result of `subAccount/actions:transfer`. `availableRaw` is the\n * recomputed `balanceOf − Σ` on-chain integer; the SDK lifts it to `Money`\n * via `fromWei`. `from`/`to` are the updated sub-account rows, or `null` when\n * that endpoint is the Account's MAIN balance (never a stored row).\n */\nexport type WireTransferResult = {\n readonly availableRaw: string;\n readonly decimals: number;\n readonly currency: string;\n readonly from: WireSubAccount | null;\n readonly to: WireSubAccount | null;\n};\n\nexport type WireTransferArgs = {\n readonly chainId: number;\n readonly from: string;\n readonly to: string;\n readonly rawAmount: string;\n};\n\nexport type ConvexSubAccountFunctions = {\n readonly create: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly accountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly get: FunctionReference<\n \"query\",\n \"public\",\n { readonly subAccountId: string },\n WireSubAccount | null\n >;\n readonly list: FunctionReference<\n \"query\",\n \"public\",\n { readonly accountId: string },\n readonly WireSubAccount[]\n >;\n readonly rename: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly remove: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string },\n { readonly ok: true }\n >;\n readonly transfer: FunctionReference<\"action\", \"public\", WireTransferArgs, WireTransferResult>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSubAccountFunctions = {\n create: makeFunctionReference<\"mutation\", { accountId: string; name: string }, WireSubAccount>(\n \"subAccount/mutations:create\",\n ),\n get: makeFunctionReference<\"query\", { subAccountId: string }, WireSubAccount | null>(\n \"subAccount/queries:get\",\n ),\n list: makeFunctionReference<\"query\", { accountId: string }, readonly WireSubAccount[]>(\n \"subAccount/queries:list\",\n ),\n rename: makeFunctionReference<\"mutation\", { subAccountId: string; name: string }, WireSubAccount>(\n \"subAccount/mutations:rename\",\n ),\n remove: makeFunctionReference<\"mutation\", { subAccountId: string }, { ok: true }>(\n \"subAccount/mutations:remove\",\n ),\n transfer: makeFunctionReference<\"action\", WireTransferArgs, WireTransferResult>(\n \"subAccount/actions:transfer\",\n ),\n};\n\nexport class ConvexSubAccountAdapter implements SubAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSubAccountFunctions;\n readonly #chainId: number;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly chainId: number;\n readonly functions?: ConvexSubAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#chainId = deps.chainId;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"create\", this.#fns.create, {\n accountId: input.accountId as string,\n name: input.name,\n });\n }\n\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError> {\n return this.#runQuery(\n \"get\",\n this.#fns.get,\n { subAccountId: input.subAccountId as string },\n (wire) => (wire === null ? null : brandSubAccount(wire)),\n );\n }\n\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError> {\n return this.#runQuery(\n \"list\",\n this.#fns.list,\n { accountId: input.accountId as string },\n (wires) => wires.map((wire) => brandSubAccount(wire)),\n );\n }\n\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"rename\", this.#fns.rename, {\n subAccountId: input.subAccountId as string,\n name: input.name,\n });\n }\n\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError> {\n const operation = \"delete\";\n return this.#convex\n .mutation(this.#fns.remove, { subAccountId: input.subAccountId as string })\n .pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.asVoid,\n Effect.catchAllDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError> {\n const operation = \"transfer\";\n // `toWei`/`parseUnits` throws on a malformed money string; that surfaces as\n // a defect below and is mapped to a SubAccountError (INVALID_INPUT-ish).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(this.#fns.transfer, {\n chainId: this.#chainId,\n from: input.from as string,\n to: input.to as string,\n rawAmount,\n });\n }).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n // Branding (`fromWei` / `brandSubAccount`) runs INSIDE the guarded pipe so\n // a throw surfaces as a SubAccountError defect, never an escaped defect.\n Effect.map((wire) => brandTransferResult(wire)),\n Effect.catchAllDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runMutation(\n operation: string,\n ref: FunctionReference<\"mutation\", \"public\", Record<string, string>, WireSubAccount>,\n args: Record<string, string>,\n ): Effect.Effect<SubAccount, SubAccountError> {\n return this.#convex.mutation(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => brandSubAccount(wire)),\n Effect.catchAllDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runQuery<TWire, TOut>(\n operation: string,\n ref: FunctionReference<\"query\", \"public\", Record<string, string>, TWire>,\n args: Record<string, string>,\n map: (wire: TWire) => TOut,\n ): Effect.Effect<TOut, SubAccountError> {\n // Branding (`map`) runs INSIDE the guarded pipe so a throw from\n // toAccountId/toSubAccountId/fromWei surfaces as a SubAccountError defect,\n // never an unhandled defect that escapes the typed channel.\n return this.#convex.query(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map(map),\n Effect.catchAllDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexSubAccountLayer(\n chainId: number,\n): Layer.Layer<SubAccountPortTag, SubAccountError, ConvexCallPortTag> {\n return Layer.effect(\n SubAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSubAccountAdapter({ convex, chainId })),\n );\n}\n\nfunction brandTransferResult(wire: WireTransferResult): TransferResult {\n return {\n available: fromWei(wire.availableRaw, wire.decimals, wire.currency),\n from: wire.from === null ? null : brandSubAccount(wire.from),\n to: wire.to === null ? null : brandSubAccount(wire.to),\n };\n}\n\nfunction brandSubAccount(wire: WireSubAccount): SubAccount {\n return {\n id: toSubAccountId(wire.subAccountId),\n accountId: toAccountId(wire.accountId),\n name: wire.name,\n balance: fromWei(wire.rawBalance, wire.decimals, wire.currency),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction subAccountErrorFromUnknown(operation: string, cause: unknown): SubAccountError {\n if (cause instanceof CapxulError) return subAccountErrorFromCapxul(operation, cause);\n return subAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Address, AuthUserId, ChainId, RunId, SmartAccount } from \"@capxul/types\";\n\nimport type { SafeDeploymentEvidence } from \"./safe-deployment\";\n\nexport type ProvisionInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n};\n\n/**\n * Input to `SmartAccountPort.confirmDeployment` (#161 · γ-B).\n *\n * The SDK provides evidence pointers; the backend is the oracle for\n * `deployedAt`. `evidence.deployedAt` does NOT exist by schema (see\n * `SafeDeploymentEvidence`) — the backend derives `deployedAt` from\n * the on-chain receipt block via `eth_getBlockByNumber`.\n *\n * Precheck path: `evidence.userOpHash` omitted; backend scans\n * `SafeProxyFactory.ProxyCreation(safeAddress, _)` via `eth_getLogs`.\n *\n * Real-userOp path: `evidence.userOpHash` populated; backend calls\n * `eth_getUserOperationReceipt(userOpHash)` to re-verify and derive.\n */\nexport type ConfirmDeploymentInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n readonly safeAddress: Address;\n readonly evidence: SafeDeploymentEvidence;\n /**\n * Optional live-E2E correlation id. This does not prove deployment; the\n * backend still re-verifies chain evidence and only mirrors this branded\n * id onto telemetry for PostHog run joins.\n */\n readonly telemetryRunId?: RunId;\n};\n\n/**\n * Input to `SmartAccountPort.claim` (PRD #462). The authenticated session\n * reports the browser-created signer address; the BACKEND builds and\n * bootstrap-signs the claim userOp (deploy + swapOwner) — the consumer signs\n * nothing at claim.\n */\nexport type ClaimInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n readonly signerAddress: Address;\n readonly telemetryRunId?: RunId;\n};\n\nexport class SmartAccountError extends Data.TaggedError(\"SmartAccountError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function smartAccountErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): SmartAccountError {\n return new SmartAccountError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n// Domain port. Sibling to the platform-ports bundle; deliberately NOT a\n// member of `PlatformPorts` — domain ports are composed by consumers per the\n// hexagonal Option C decision. See `docs/canon/ports/smart-account.md`.\nexport interface SmartAccountPort {\n loadByAuthUserId(\n authUserId: AuthUserId,\n ): Effect.Effect<SmartAccount | null, SmartAccountError, never>;\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError, never>;\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError, never>;\n /**\n * Persist on-chain Safe-deployment evidence. The backend re-verifies\n * the evidence against chain state and derives `deployedAt` from the\n * receipt block's timestamp. Returns the updated `SmartAccount` row.\n *\n * γ-B trust model: the SDK supplies evidence pointers only. The\n * backend is the SOLE oracle for `deployedAt` — see\n * `docs/canon/ports/smart-account.md`.\n */\n confirmDeployment(\n input: ConfirmDeploymentInput,\n ): Effect.Effect<SmartAccount, SmartAccountError, never>;\n /**\n * Claim the account (PRD #462): the backend builds, bootstrap-signs, and\n * submits ONE sponsored userOp — deploy (when undeployed) + swapOwner\n * (bootstrap → `signerAddress`). Idempotent; returns the updated row. When\n * another claim is in flight the row comes back with `claimedAt: null` —\n * callers poll lifecycle until the claim lands.\n */\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError, never>;\n}\n\nexport class SmartAccountPortTag extends Context.Tag(\"@capxul/sdk/ports/SmartAccountPort\")<\n SmartAccountPortTag,\n SmartAccountPort\n>() {}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Address, AuthUserId, SmartAccount } from \"@capxul/types\";\nimport { toAddress, toAuthUserId, toChainId, toEpochMs } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n ClaimInput,\n ConfirmDeploymentInput,\n ProvisionInput,\n SmartAccountError,\n SmartAccountPort,\n} from \"../../ports/smart-account\";\nimport { smartAccountErrorFromCapxul, SmartAccountPortTag } from \"../../ports/smart-account\";\n\nexport type WireSmartAccount = {\n readonly authUserId: string;\n readonly signerAddress: string | null;\n readonly smartAccountAddress: string;\n readonly chainId: number;\n readonly deployedAt: number | null;\n readonly claimedAt: number | null;\n readonly createdAt: number;\n};\n\nexport type WireConfirmDeploymentArgs = {\n readonly chainId: number;\n readonly safeAddress: string;\n readonly telemetryRunId?: string;\n readonly evidence: {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly safeAddress: string;\n readonly userOpHash?: string;\n readonly txHash?: string;\n readonly blockNumber?: number;\n };\n};\n\nexport type WireClaimArgs = {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly telemetryRunId?: string;\n};\n\nexport type ConvexSmartAccountFunctions = {\n readonly loadByAuthUserId: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: string },\n WireSmartAccount | null\n >;\n readonly loadBySmartAccountAddress: FunctionReference<\n \"query\",\n \"public\",\n { readonly address: string },\n WireSmartAccount | null\n >;\n readonly provision: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly chainId: number;\n },\n WireSmartAccount\n >;\n // `confirmDeployment` is an ACTION, not a mutation, because the\n // backend handler must perform outbound `fetch` calls to Alchemy\n // (eth_getCode / eth_getUserOperationReceipt / eth_getLogs /\n // eth_getBlockByNumber) — Convex mutations are transactional and\n // cannot do fetch. See `packages/backend/convex/smartAccount/actions.ts`.\n readonly confirmDeployment: FunctionReference<\n \"action\",\n \"public\",\n WireConfirmDeploymentArgs,\n WireSmartAccount\n >;\n // `claim` is an ACTION: the backend builds, bootstrap-signs, and submits\n // the claim userOp (deploy + swapOwner) via outbound bundler RPC (PRD #462).\n readonly claim: FunctionReference<\"action\", \"public\", WireClaimArgs, WireSmartAccount>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSmartAccountFunctions = {\n loadByAuthUserId: makeFunctionReference<\"query\", { authUserId: string }, WireSmartAccount | null>(\n \"smartAccount/queries:loadByAuthUserId\",\n ),\n loadBySmartAccountAddress: makeFunctionReference<\n \"query\",\n { address: string },\n WireSmartAccount | null\n >(\"smartAccount/queries:loadBySmartAccountAddress\"),\n provision: makeFunctionReference<\"mutation\", { chainId: number }, WireSmartAccount>(\n \"smartAccount/mutations:provision\",\n ),\n confirmDeployment: makeFunctionReference<\"action\", WireConfirmDeploymentArgs, WireSmartAccount>(\n \"smartAccount/actions:confirmDeployment\",\n ),\n claim: makeFunctionReference<\"action\", WireClaimArgs, WireSmartAccount>(\n \"smartAccount/actions:claim\",\n ),\n};\n\nexport class ConvexSmartAccountAdapter implements SmartAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSmartAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexSmartAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadByAuthUserId\", row)),\n Effect.catchAllDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadBySmartAccountAddress\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadBySmartAccountAddress\", row)),\n Effect.catchAllDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadBySmartAccountAddress\", cause)),\n ),\n );\n }\n\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .mutation(this.#fns.provision, {\n chainId: wireChainId(input.chainId),\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"provision\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"provision\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"provision\", cause)),\n ),\n );\n }\n\n confirmDeployment(input: ConfirmDeploymentInput): Effect.Effect<SmartAccount, SmartAccountError> {\n const evidence: WireConfirmDeploymentArgs[\"evidence\"] = {\n chainId: wireChainId(input.evidence.chainId),\n signerAddress: input.evidence.signerAddress,\n safeAddress: input.evidence.safeAddress,\n ...(input.evidence.userOpHash === undefined ? {} : { userOpHash: input.evidence.userOpHash }),\n ...(input.evidence.txHash === undefined ? {} : { txHash: input.evidence.txHash }),\n ...(input.evidence.blockNumber === undefined\n ? {}\n : { blockNumber: input.evidence.blockNumber }),\n };\n return this.#convex\n .action(this.#fns.confirmDeployment, {\n chainId: wireChainId(input.chainId),\n safeAddress: input.safeAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n evidence,\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"confirmDeployment\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"confirmDeployment\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"confirmDeployment\", cause)),\n ),\n );\n }\n\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .action(this.#fns.claim, {\n chainId: wireChainId(input.chainId),\n signerAddress: input.signerAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n })\n .pipe(\n Effect.mapError((error) => smartAccountErrorFromCapxul(\"claim\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"claim\", cause),\n }),\n ),\n Effect.catchAllDefect((cause) => Effect.fail(smartAccountErrorFromUnknown(\"claim\", cause))),\n );\n }\n}\n\nexport function ConvexSmartAccountLayer(): Layer.Layer<\n SmartAccountPortTag,\n SmartAccountError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n SmartAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })),\n );\n}\n\nfunction brandSmartAccountEffect(\n operation: string,\n wire: WireSmartAccount | null,\n): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return Effect.try({\n try: () => (wire === null ? null : brandNonNullSmartAccount(wire)),\n catch: (cause) => smartAccountErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandNonNullSmartAccount(wire: WireSmartAccount): SmartAccount {\n return {\n authUserId: toAuthUserId(wire.authUserId),\n signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),\n smartAccountAddress: toAddress(wire.smartAccountAddress),\n chainId: toChainId(wire.chainId),\n deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),\n claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction brandProvisionedSmartAccount(\n requestedAuthUserId: AuthUserId,\n wire: WireSmartAccount,\n): SmartAccount {\n if (wire.authUserId !== String(requestedAuthUserId)) {\n throw Errors.notAuthenticated();\n }\n return brandNonNullSmartAccount(wire);\n}\n\nfunction smartAccountErrorFromUnknown(operation: string, cause: unknown): SmartAccountError {\n if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);\n return smartAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import type { Address, ChainId } from \"@capxul/types\";\nimport { toAddress } from \"@capxul/types\";\nimport { encodePacked, getCreate2Address, keccak256 } from \"viem\";\n\nimport { addressForViem, wireChainId } from \"../../adapters/_shared/wire\";\n\nconst SUPPORTED_CHAIN_IDS = new Set<number>([84532, 8453]);\nconst SAFE_DEPLOYER_ADDRESS: Address = toAddress(\"0xa6b71e26c5e0845f74c812102ca7114b6a896ab2\");\nconst SAFE_INITCODE_HASH = keccak256(\"0x\");\n\nexport function isSupportedSmartAccountChain(chainId: ChainId): boolean {\n return SUPPORTED_CHAIN_IDS.has(wireChainId(chainId));\n}\n\nexport function deriveSmartAccountAddress(signerAddress: Address, chainId: ChainId): Address {\n const normalizedSigner = toAddress(signerAddress);\n const salt = keccak256(\n encodePacked([\"address\", \"uint256\"], [addressForViem(normalizedSigner), BigInt(chainId)]),\n );\n return toAddress(\n getCreate2Address({\n from: addressForViem(SAFE_DEPLOYER_ADDRESS),\n salt,\n bytecodeHash: SAFE_INITCODE_HASH,\n }),\n );\n}\n","import { Effect } from \"effect\";\n\nimport { Schema } from \"@effect/schema\";\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 \"provisioning_safe_created\",\n \"provisioning_safe_confirmed\",\n \"bootstrap_resolved\",\n \"bootstrap_failed\",\n // Money domain (M2). Producer split documented in\n // docs/canon/conventions/telemetry-spine.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_confirmed\",\n \"transfer_failed\",\n // Organization domain — creation funnel (canon org-domain-model.md §C5, J1).\n // Producer split documented in docs/canon/conventions/telemetry-spine.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 FunnelJourney = {\n readonly type: \"funnel\";\n readonly steps: NonEmptyTelemetryEventNames;\n readonly drops_on?: NonEmptyTelemetryEventNames;\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 // 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.Schema<Address, string> = Schema.String.pipe(\n Schema.transform(Schema.String, {\n decode: (value) => value.toLowerCase(),\n encode: (value) => value,\n }),\n Schema.filter((value): value is Address => EVM_ADDRESS_RE.test(value), {\n message: () => \"must be 0x + 40 hex chars\",\n }),\n);\nconst AppIdSchema: Schema.Schema<AppId, string> = Schema.String.pipe(\n Schema.filter((value): value is AppId => APP_ID_RE.test(value), {\n message: () => \"must be app_ plus a ULID\",\n }),\n);\nconst BlockNumberSchema: Schema.Schema<BlockNumber, number> = Schema.Number.pipe(\n Schema.filter((value): value is BlockNumber => Number.isSafeInteger(value) && value >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\nconst ChainIdSchema: Schema.Schema<ChainId, number> = Schema.Number.pipe(\n Schema.filter((value): value is ChainId => Number.isSafeInteger(value) && value > 0, {\n message: () => \"must be a positive safe integer\",\n }),\n);\nconst DurationMsSchema: Schema.Schema<DurationMs, number> = Schema.Number.pipe(\n Schema.filter((value): value is DurationMs => Number.isSafeInteger(value) && value >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\nconst EpochMsSchema: Schema.Schema<EpochMs, number> = Schema.Number.pipe(\n Schema.filter((value): value is EpochMs => Number.isSafeInteger(value) && value >= 0, {\n message: () => \"must be a non-negative safe integer\",\n }),\n);\nconst PublishableKeyIdSchema: Schema.Schema<PublishableKeyId, string> = Schema.String.pipe(\n Schema.filter((value): value is PublishableKeyId => value.length > 0, {\n message: () => \"must be a non-empty string\",\n }),\n);\nconst TxHashSchema: Schema.Schema<TxHash, string> = Schema.String.pipe(\n Schema.filter((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.Schema<AccountId, string> = Schema.String.pipe(\n Schema.filter((value): value is AccountId => ACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: () => \"must be account_ plus an alphanumeric id\",\n }),\n);\nconst SubAccountIdSchema: Schema.Schema<SubAccountId, string> = Schema.String.pipe(\n Schema.filter((value): value is SubAccountId => SUBACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: () => \"must be subaccount_ plus an alphanumeric id\",\n }),\n);\nconst WeiAmountSchema: Schema.Schema<WeiAmount, string> = Schema.String.pipe(\n Schema.filter((value): value is WeiAmount => WEI_AMOUNT_TELEMETRY_RE.test(value), {\n message: () => \"must be a non-negative integer string\",\n }),\n);\nconst CurrencyCodeSchema: Schema.Schema<CurrencyCode, string> = Schema.String.pipe(\n Schema.filter((value): value is CurrencyCode => value.length > 0, {\n message: () => \"must be a non-empty currency code\",\n }),\n);\nconst BalanceBucketSchema = Schema.Literal(\"zero\", \"nonzero\");\nconst TransferDirectionSchema = Schema.Literal(\"add\", \"out\", \"between\");\nconst SubAccountOpSchema = Schema.Literal(\"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.filter((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.filter((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.filter((value): value is string => BYTES32_RE.test(value), {\n message: () => \"must be 0x + 64 hex chars\",\n }),\n);\nconst TelemetryEnvelopeProps = {\n capxul_e2e_run_id: OptionalString,\n correlationId: OptionalString,\n capxulEnv: OptionalString,\n sdkVersion: OptionalString,\n producer: OptionalString,\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// docs/canon/conventions/telemetry-spine.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 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// docs/canon/conventions/telemetry-spine.md \"Organization domain\".\nconst ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;\nconst OrgIdTelemetrySchema: Schema.Schema<string, string> = Schema.String.pipe(\n Schema.filter((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 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: Schema.optional(AuthOtpRequestedProps),\n});\nexport const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_delivered\"),\n props: Schema.optional(AuthOtpDeliveredProps),\n});\nexport const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_expired\"),\n props: Schema.optional(AuthOtpExpiredProps),\n});\nexport const AuthVerifiedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_verified\"),\n props: Schema.optional(AuthVerifiedProps),\n});\nexport const AuthFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_failed\"),\n props: Schema.optional(AuthFailedProps),\n});\nexport const AuthSignedOutTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_signed_out\"),\n props: Schema.optional(AuthSignedOutProps),\n});\nexport const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_created\"),\n props: Schema.optional(ProvisioningSafeCreatedProps),\n});\nexport const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_confirmed\"),\n props: Schema.optional(ProvisioningSafeConfirmedProps),\n});\nexport const BootstrapResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_resolved\"),\n props: Schema.optional(BootstrapResolvedProps),\n});\nexport const BootstrapFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_failed\"),\n props: Schema.optional(BootstrapFailedProps),\n});\nexport const AccountBalanceReadTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_read\"),\n props: Schema.optional(AccountBalanceReadProps),\n});\nexport const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_failed\"),\n props: Schema.optional(AccountBalanceFailedProps),\n});\nexport const FaucetRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_requested\"),\n props: Schema.optional(FaucetRequestedProps),\n});\nexport const FaucetConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_confirmed\"),\n props: Schema.optional(FaucetConfirmedProps),\n});\nexport const FaucetFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_failed\"),\n props: Schema.optional(FaucetFailedProps),\n});\nexport const SubaccountCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_created\"),\n props: Schema.optional(SubaccountCreatedProps),\n});\nexport const SubaccountRenamedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_renamed\"),\n props: Schema.optional(SubaccountRenamedProps),\n});\nexport const SubaccountDeletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_deleted\"),\n props: Schema.optional(SubaccountDeletedProps),\n});\nexport const SubaccountOpFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_op_failed\"),\n props: Schema.optional(SubaccountOpFailedProps),\n});\nexport const TransferRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_requested\"),\n props: Schema.optional(TransferRequestedProps),\n});\nexport const TransferConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_confirmed\"),\n props: Schema.optional(TransferConfirmedProps),\n});\nexport const TransferFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_failed\"),\n props: Schema.optional(TransferFailedProps),\n});\nexport const OrgCreateStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_started\"),\n props: Schema.optional(OrgCreateStartedProps),\n});\nexport const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_created\"),\n props: Schema.optional(OrgSafeCreatedProps),\n});\nexport const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_confirmed\"),\n props: Schema.optional(OrgSafeConfirmedProps),\n});\nexport const OrgRolesSeededTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_roles_seeded\"),\n props: Schema.optional(OrgRolesSeededProps),\n});\nexport const OrgCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_created\"),\n props: Schema.optional(OrgCreatedProps),\n});\nexport const OrgCreateFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_failed\"),\n props: Schema.optional(OrgCreateFailedProps),\n});\nexport const OrgInviteSentTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_sent\"),\n props: Schema.optional(OrgInviteSentProps),\n});\nexport const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_accepted\"),\n props: Schema.optional(OrgInviteAcceptedProps),\n});\nexport const OrgRoleGrantedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_granted\"),\n props: Schema.optional(OrgRoleGrantedProps),\n});\nexport const OrgMemberActiveTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_active\"),\n props: Schema.optional(OrgMemberActiveProps),\n});\nexport const OrgMemberRemovedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_removed\"),\n props: Schema.optional(OrgMemberRemovedProps),\n});\nexport const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_expired\"),\n props: Schema.optional(OrgInviteExpiredProps),\n});\nexport const OrgRoleGrantFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_grant_failed\"),\n props: Schema.optional(OrgRoleGrantFailedProps),\n});\nexport const PaymentRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_requested\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_resolved\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentDocumentAttachedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_document_attached\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_submitted\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_settled\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_claimed\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_cancelled\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentRedirectedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_redirected\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const PaymentFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_failed\"),\n props: Schema.optional(PaymentTargetTelemetryProps),\n});\nexport const StreamCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_created\"),\n props: Schema.optional(StreamTargetTelemetryProps),\n});\nexport const StreamClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_claimed\"),\n props: Schema.optional(StreamTargetTelemetryProps),\n});\nexport const StreamCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_cancelled\"),\n props: Schema.optional(StreamTargetTelemetryProps),\n});\nexport const StreamCompletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_completed\"),\n props: Schema.optional(StreamTargetTelemetryProps),\n});\nexport const StreamFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_failed\"),\n props: Schema.optional(StreamTargetTelemetryProps),\n});\nexport const WithdrawalRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_requested\"),\n props: Schema.optional(WithdrawalTargetTelemetryProps),\n});\nexport const WithdrawalSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_submitted\"),\n props: Schema.optional(WithdrawalTargetTelemetryProps),\n});\nexport const WithdrawalSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_settled\"),\n props: Schema.optional(WithdrawalTargetTelemetryProps),\n});\nexport const WithdrawalFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_failed\"),\n props: Schema.optional(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 provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,\n provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,\n bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,\n bootstrap_failed: BootstrapFailedTelemetryEventSchema,\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_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 // all FOUR settle lanes: direct pay (markPaymentSettled) + workbench execute\n // (executePayment) via the awaited emitSettledTelemetry, and org spend/payroll\n // (applyOrgPaymentRecord) + receivable collect (receivablesMutations.collect) via\n // the scheduled emitScheduledSettledTelemetry. The ADR-0007 rule was relaxed from\n // exactly-one to ≥1 for this reason. Absent 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\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\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: import(\"@capxul/config\").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: import(\"@capxul/config\").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: import(\"@capxul/config\").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","import { Context } from \"effect\";\nexport {\n TELEMETRY_EVENT_NAMES,\n redactTelemetryEvent,\n redactTelemetryProps,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEvent,\n type TelemetryEventName,\n type TelemetryProps,\n type TelemetryRedactionOptions,\n} from \"@capxul/observability\";\nexport type { TelemetryPort, HandledErrorReportContext } from \"@capxul/observability\";\nimport type { TelemetryPort } from \"@capxul/observability\";\n\nexport class TelemetryPortTag extends Context.Tag(\"@capxul/sdk/ports/TelemetryPort\")<\n TelemetryPortTag,\n TelemetryPort\n>() {}\n","import { Effect, Layer } from \"effect\";\n\nimport {\n redactTelemetryProps,\n TelemetryPortTag,\n type TelemetryEvent,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEventName,\n type TelemetryPort,\n type TelemetryProps,\n} from \"../../ports/telemetry\";\n\nexport type PostHogCapture = (\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n) => void | Promise<void>;\nexport type PostHogIdentify = (input: TelemetryIdentifyInput) => void | Promise<void>;\nexport type PostHogGroup = (input: TelemetryGroupInput) => void | Promise<void>;\nexport type PostHogReset = () => void | Promise<void>;\n\nexport type PostHogTelemetryLayerDeps = {\n readonly capture: PostHogCapture;\n readonly identify?: PostHogIdentify;\n readonly group?: PostHogGroup;\n readonly reset?: PostHogReset;\n};\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: PostHogCapture;\n readonly #identify: PostHogIdentify;\n readonly #group: PostHogGroup;\n readonly #reset: PostHogReset;\n\n constructor(deps: PostHogTelemetryLayerDeps) {\n this.#capture = deps.capture;\n this.#identify = deps.identify ?? (() => undefined);\n this.#group = deps.group ?? (() => undefined);\n this.#reset = deps.reset ?? (() => undefined);\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never, never> {\n return Effect.sync(() => {\n this.#runFireAndForget(() =>\n this.#capture(event.name, redactTelemetryProps(event.name, cloneProps(event.props))),\n );\n });\n }\n\n identify(input: TelemetryIdentifyInput): Effect.Effect<void, never, never> {\n return Effect.sync(() => {\n this.#runFireAndForget(() => this.#identify(cloneIdentifyInput(input)));\n });\n }\n\n group(input: TelemetryGroupInput): Effect.Effect<void, never, never> {\n return Effect.sync(() => {\n this.#runFireAndForget(() => this.#group(cloneGroupInput(input)));\n });\n }\n\n reset(): Effect.Effect<void, never, never> {\n return Effect.sync(() => {\n this.#runFireAndForget(() => this.#reset());\n });\n }\n\n #runFireAndForget(operation: () => void | Promise<void>): void {\n try {\n void Promise.resolve(operation()).catch(() => {\n // Telemetry is fire-and-forget: transport failures never fail flows.\n });\n } catch {\n // Telemetry is fire-and-forget: synchronous transport failures are ignored.\n }\n }\n}\n\nexport function PostHogTelemetryLayer(\n deps: PostHogTelemetryLayerDeps,\n): Layer.Layer<TelemetryPortTag, never, never> {\n return Layer.succeed(TelemetryPortTag, new PostHogTelemetryAdapter(deps));\n}\n\nfunction cloneIdentifyInput(input: TelemetryIdentifyInput): TelemetryIdentifyInput {\n const traits = input.traits === undefined ? undefined : cloneProps(input.traits);\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return {\n distinctId: input.distinctId,\n ...(input.anonDistinctId === undefined ? {} : { anonDistinctId: input.anonDistinctId }),\n ...(traits === undefined ? {} : { traits }),\n ...(properties === undefined ? {} : { properties }),\n };\n}\n\nfunction cloneGroupInput(input: TelemetryGroupInput): TelemetryGroupInput {\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return properties === undefined\n ? { groupType: input.groupType, groupKey: input.groupKey }\n : {\n groupType: input.groupType,\n groupKey: input.groupKey,\n properties,\n };\n}\n\nfunction cloneProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\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","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\n\nexport type TransportOperationKind = \"query\" | \"mutation\" | \"action\";\n\nexport type TransportRequest<TArgs = unknown> = {\n readonly name: string;\n readonly args: TArgs;\n readonly correlationId?: string;\n};\n\nexport class TransportError extends Data.TaggedError(\"TransportError\")<{\n readonly operation: TransportOperationKind;\n readonly name: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly correlationId?: string;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function transportErrorFromCapxul(\n operation: TransportOperationKind,\n request: TransportRequest<unknown>,\n error: CapxulError,\n cause: unknown = error,\n): TransportError {\n return new TransportError({\n operation,\n name: request.name,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(request.correlationId === undefined ? {} : { correlationId: request.correlationId }),\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\nexport interface TransportPort {\n readonly runQuery: <TOutput = unknown, TArgs = unknown>(\n request: TransportRequest<TArgs>,\n ) => Effect.Effect<TOutput, TransportError>;\n readonly runMutation: <TOutput = unknown, TArgs = unknown>(\n request: TransportRequest<TArgs>,\n ) => Effect.Effect<TOutput, TransportError>;\n readonly runAction: <TOutput = unknown, TArgs = unknown>(\n request: TransportRequest<TArgs>,\n ) => Effect.Effect<TOutput, TransportError>;\n}\n\nexport class TransportPortTag extends Context.Tag(\"@capxul/sdk/ports/TransportPort\")<\n TransportPortTag,\n TransportPort\n>() {}\n","import { Errors } from \"@capxul/config\";\nimport { makeFunctionReference } from \"convex/server\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConvexCallPortTag, type ConvexCallError } from \"../../ports/convex-call\";\nimport {\n TransportPortTag,\n transportErrorFromCapxul,\n type TransportError,\n type TransportOperationKind,\n type TransportPort,\n type TransportRequest,\n} from \"../../ports/transport\";\n\nexport type TransportRouteName = string;\nexport type TransportHandlerMap = Readonly<Record<string, (args: unknown) => unknown>>;\ntype ConvexTransportLayerDeps = Record<string, never>;\n\nexport class ConvexTransportAdapter implements TransportPort {\n readonly #convex: typeof ConvexCallPortTag.Service;\n\n constructor(convex: typeof ConvexCallPortTag.Service) {\n this.#convex = convex;\n }\n\n runQuery<TOutput, TArgs>(\n request: TransportRequest<TArgs>,\n ): Effect.Effect<TOutput, TransportError> {\n return this.#call(\"query\", request, () => {\n const fn = makeFunctionReference<\"query\", Record<string, unknown>, TOutput>(request.name);\n return this.#convex.query(fn, asRecordArgs(request.args));\n });\n }\n\n runMutation<TOutput, TArgs>(\n request: TransportRequest<TArgs>,\n ): Effect.Effect<TOutput, TransportError> {\n return this.#call(\"mutation\", request, () => {\n const fn = makeFunctionReference<\"mutation\", Record<string, unknown>, TOutput>(request.name);\n return this.#convex.mutation(fn, asRecordArgs(request.args));\n });\n }\n\n runAction<TOutput, TArgs>(\n request: TransportRequest<TArgs>,\n ): Effect.Effect<TOutput, TransportError> {\n return this.#call(\"action\", request, () => {\n const fn = makeFunctionReference<\"action\", Record<string, unknown>, TOutput>(request.name);\n return this.#convex.action(fn, asRecordArgs(request.args));\n });\n }\n\n #call<TOutput, TArgs>(\n operation: TransportOperationKind,\n request: TransportRequest<TArgs>,\n run: () => Effect.Effect<TOutput, ConvexCallError>,\n ): Effect.Effect<TOutput, TransportError> {\n return Effect.try({\n try: run,\n catch: (cause) => transportErrorFromThrown(operation, request, cause),\n }).pipe(\n Effect.flatMap((effect) =>\n effect.pipe(\n Effect.mapError((error) => transportErrorFromConvex(operation, request, error)),\n Effect.catchAllDefect((cause) =>\n Effect.fail(transportErrorFromThrown(operation, request, cause)),\n ),\n ),\n ),\n );\n }\n}\n\nexport function ConvexTransportLayer(\n _deps: ConvexTransportLayerDeps = {},\n): Layer.Layer<TransportPortTag, never, ConvexCallPortTag> {\n return Layer.effect(\n TransportPortTag,\n Effect.gen(function* () {\n const convex = yield* ConvexCallPortTag;\n return new ConvexTransportAdapter(convex);\n }),\n );\n}\n\nfunction transportErrorFromConvex<TArgs>(\n operation: TransportOperationKind,\n request: TransportRequest<TArgs>,\n error: ConvexCallError,\n): TransportError {\n return transportErrorFromCapxul(\n operation,\n request as TransportRequest<unknown>,\n error.publicError,\n error.cause,\n );\n}\n\nfunction asRecordArgs(args: unknown): Record<string, unknown> {\n if (args !== null && typeof args === \"object\" && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n return { value: args };\n}\n\nfunction transportErrorFromThrown<TArgs>(\n operation: TransportOperationKind,\n request: TransportRequest<TArgs>,\n cause: unknown,\n): TransportError {\n const error =\n cause instanceof Error\n ? Errors.providerError(\"transport\", request.name, cause)\n : Errors.providerError(\"transport\", request.name, new Error(String(cause)));\n return transportErrorFromCapxul(operation, request as TransportRequest<unknown>, error, cause);\n}\n","import {\n AccountTypeEnum,\n ChainTypeEnum,\n EmbeddedState,\n Openfort,\n RecoveryMethod,\n ThirdPartyOAuthProvider,\n} from \"@openfort/openfort-js\";\n\nimport { Errors } from \"@capxul/config\";\n\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { DiagnosticPort } from \"../ports/diagnostic\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport type { CapxulSigner } from \"../signer\";\nimport { openfortEmbeddedSignerFromWallet } from \"../openfort-embedded-signer\";\n\nexport interface OpenfortBrowserSigner extends CapxulSigner {\n readonly resetSession: () => void;\n}\n\nexport interface OpenfortBrowserSignerOptions {\n readonly diagnostic?: DiagnosticPort;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * True when the browser cannot perform Web Crypto — sandboxed iframes, headless\n * agent browsers, or non-HTTPS origins. OpenFort's embedded-wallet `configure`\n * silently produces no address in this state, so we detect it up front and name\n * it `no-secure-context` instead of letting it decay into `unknown`.\n */\nfunction isInsecureBrowserContext(): boolean {\n return globalThis.isSecureContext === false || globalThis.crypto?.subtle === undefined;\n}\n\n/** Openfort SDK storage keys (`@openfort/openfort-js` StorageKeys). */\nconst OPENFORT_BROWSER_STORAGE_KEYS = [\n \"openfort.authentication\",\n \"openfort.account\",\n \"openfort.session\",\n \"openfort.configuration\",\n] as const;\n\n/**\n * Matches `@openfort/openfort-js` ScopedStorage.createScope — chars 8–15 of the\n * publishable key, prefixed onto each StorageKeys entry in localStorage.\n */\nexport function openfortBrowserStorageScope(publishableKey: string): string | undefined {\n const trimmed = publishableKey.trim();\n if (trimmed.length < 16) {\n return undefined;\n }\n return trimmed.substring(8, 16);\n}\n\n/**\n * Drop cached Openfort auth/account state so third-party login re-runs for the\n * current Better Auth session. The SDK skips `authenticateThirdParty` when a\n * stale `userId` is already in storage, which yields 401 on `v2/accounts`.\n */\nfunction clearStaleOpenfortBrowserStorage(publishableKey: string): void {\n if (typeof localStorage === \"undefined\") {\n return;\n }\n const scope = openfortBrowserStorageScope(publishableKey);\n if (scope === undefined) {\n return;\n }\n for (const key of OPENFORT_BROWSER_STORAGE_KEYS) {\n localStorage.removeItem(`${scope}.${key}`);\n }\n}\n\nexport function createOpenfortBrowserSignerFromBootstrap(\n bootstrap: BootstrapResolution,\n options: OpenfortBrowserSignerOptions = {},\n): OpenfortBrowserSigner {\n const diagnostic = options.diagnostic;\n const telemetry = options.telemetry;\n const authBaseUrl = normalizeBetterAuthBaseUrl(bootstrap.authBaseUrl);\n\n /**\n * Closes the black hole: when the browser has no Web Crypto, OpenFort's\n * `configure` would resolve to no address and the failure would be reported\n * as `unknown`. Detect it before any network/wallet work, tag it\n * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`, breadcrumb\n * it via DiagnosticPort, and self-report via TelemetryPort.\n */\n function failNoSecureContext(): never {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"no-secure-context\",\n });\n const error = Errors.providerError(\n \"openfort\",\n \"configure\",\n new Error(\"Web Crypto unavailable: browser is not a secure context\"),\n { failure_mode: \"no-secure-context\" },\n );\n if (telemetry) {\n captureExceptionSync(telemetry, error, {\n layer: \"openfort\",\n operation: \"configure\",\n provider: \"openfort\",\n failure_mode: \"no-secure-context\",\n });\n }\n throw error;\n }\n\n function betterAuthSessionUrl(): string {\n return `${authBaseUrl}/get-session`;\n }\n\n function encryptionSessionUrl(): string {\n return `${authBaseUrl}/encryption-session`;\n }\n\n async function fetchBetterAuthAccessToken(): Promise<string | null> {\n const response = await fetch(betterAuthSessionUrl(), { credentials: \"include\" });\n if (!response.ok) {\n diagnostic?.trace(\"openfort.token\", { tokenPresent: false, httpStatus: response.status });\n return null;\n }\n const body = (await response.json()) as { session?: { token?: string } };\n const token = body.session?.token?.trim();\n if (token === undefined || token.length === 0) {\n diagnostic?.trace(\"openfort.token\", { tokenPresent: false });\n return null;\n }\n diagnostic?.trace(\"openfort.token\", { tokenPresent: true });\n return token;\n }\n\n const openfort = new Openfort({\n baseConfiguration: {\n publishableKey: bootstrap.openfortPublishableKey,\n },\n shieldConfiguration: {\n shieldPublishableKey: bootstrap.shieldPublishableKey,\n },\n thirdPartyAuth: {\n provider: ThirdPartyOAuthProvider.BETTER_AUTH,\n getAccessToken: fetchBetterAuthAccessToken,\n },\n });\n\n let walletReadyPromise: Promise<void> | null = null;\n\n function startWalletReady(): Promise<void> {\n return (async () => {\n if (isInsecureBrowserContext()) {\n failNoSecureContext();\n }\n await openfort.waitForInitialization();\n\n const accessToken = await fetchBetterAuthAccessToken();\n if (accessToken === null) {\n throw Errors.notAuthenticated();\n }\n\n const encryptionResponse = await fetch(encryptionSessionUrl(), {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n });\n diagnostic?.trace(\"openfort.encryptionSession\", { httpStatus: encryptionResponse.status });\n if (!encryptionResponse.ok) {\n const detail = await encryptionResponse.text();\n throw Errors.providerError(\n \"openfort\",\n \"encryptionSession\",\n new Error(\n `Openfort encryption session failed (${encryptionResponse.status}): ${detail.slice(0, 200)}`,\n ),\n );\n }\n const encryptionBody = (await encryptionResponse.json()) as { sessionId?: string };\n if (typeof encryptionBody.sessionId !== \"string\" || encryptionBody.sessionId.length === 0) {\n throw Errors.providerError(\n \"openfort\",\n \"encryptionSession\",\n new Error(\"Openfort encryption session response missing sessionId\"),\n );\n }\n\n const embeddedState = await openfort.embeddedWallet.getEmbeddedState();\n diagnostic?.trace(\"openfort.embeddedState\", { state: embeddedState });\n if (embeddedState !== EmbeddedState.READY) {\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n diagnostic?.trace(\"openfort.storageCleared\", { beforeConfigure: true });\n try {\n await openfort.embeddedWallet.configure({\n accountType: AccountTypeEnum.EOA,\n chainType: ChainTypeEnum.EVM,\n recoveryParams: {\n recoveryMethod: RecoveryMethod.AUTOMATIC,\n encryptionSession: encryptionBody.sessionId,\n },\n });\n diagnostic?.trace(\"openfort.configure\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n message: cause instanceof Error ? cause.message : String(cause),\n });\n throw cause;\n }\n }\n\n try {\n await openfort.embeddedWallet.get();\n diagnostic?.trace(\"openfort.get\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.get\", {\n ok: false,\n message: cause instanceof Error ? cause.message : String(cause),\n });\n throw cause;\n }\n })();\n }\n\n async function ensureOpenfortWalletReady(): Promise<void> {\n walletReadyPromise ??= startWalletReady();\n try {\n await walletReadyPromise;\n } catch (cause) {\n walletReadyPromise = null;\n throw cause;\n }\n }\n\n const signer = openfortEmbeddedSignerFromWallet({\n embeddedWallet: openfort.embeddedWallet,\n ensureWalletReady: ensureOpenfortWalletReady,\n });\n\n return {\n ...signer,\n resetSession: () => {\n walletReadyPromise = null;\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n signer.resetAddressCache();\n },\n };\n}\n\nfunction normalizeBetterAuthBaseUrl(raw: string): string {\n const trimmed = raw.replace(/\\/$/, \"\");\n return trimmed.endsWith(\"/api/auth\") ? trimmed : `${trimmed}/api/auth`;\n}\n","import { Machine } from \"@effect/experimental\";\nimport { CapxulError, Errors, type CapxulErrorCode } from \"@capxul/config\";\nimport {\n toAnonymousDistinctId,\n toEmail,\n type AnonymousDistinctId,\n type AuthSession,\n type Email,\n type EpochMs,\n} from \"@capxul/types\";\nimport { Data, Deferred, Duration, Effect, Exit, Ref, Request, Scope } from \"effect\";\n\nimport { AuthClientError, AuthClientPortTag } from \"../ports/auth-client\";\nimport type { AuthClientOperationOptions } from \"../ports/auth-client\";\nimport { ClockPortTag } from \"../ports/clock\";\nimport {\n TelemetryPortTag,\n type TelemetryEvent,\n type TelemetryIdentifyInput,\n} from \"../ports/telemetry\";\n\nexport interface AuthFlowInput {\n readonly otpTtlMs?: number;\n}\n\nexport type CreateAuthFlowMachineInput = AuthFlowInput;\n\nexport type AuthFlowState =\n | \"idle\"\n | \"sending_otp\"\n | \"otp_requested\"\n | \"verifying\"\n | \"authenticated\"\n | \"signing_out\"\n | \"error\";\n\nexport interface AuthFlowContext {\n readonly state: AuthFlowState;\n readonly email: Email | null;\n readonly session: AuthSession | null;\n readonly otpRequestedAt: EpochMs | null;\n readonly anonDistinctId?: AnonymousDistinctId;\n readonly error: CapxulError | null;\n}\n\nexport type AuthFlowSnapshot = readonly [input: AuthFlowInput, state: AuthFlowContext];\n\nexport interface AuthFlowOperationOptions extends AuthClientOperationOptions {\n readonly timeoutMs?: number;\n}\n\nexport type AuthFlowRequestInput =\n | {\n readonly _tag: \"RequestOtp\";\n readonly email: Email;\n readonly options?: AuthFlowOperationOptions;\n }\n | {\n readonly _tag: \"VerifyOtp\";\n readonly email: Email;\n readonly otp: string;\n readonly options?: AuthFlowOperationOptions;\n }\n | { readonly _tag: \"GetSession\"; readonly options?: AuthFlowOperationOptions }\n | { readonly _tag: \"SignOut\"; readonly options?: AuthFlowOperationOptions }\n | { readonly _tag: \"RestoreCachedSession\"; readonly session: AuthSession }\n | { readonly _tag: \"ResumeOtpEntry\" }\n | { readonly _tag: \"ResetAuthFlow\" };\n\nexport class AuthFlowError extends Data.TaggedError(\"AuthFlowError\")<{\n readonly operation: \"requestOtp\" | \"verifyOtp\" | \"getSession\" | \"signOut\" | \"transition\";\n readonly state: AuthFlowState;\n readonly publicError: CapxulError;\n readonly publicCode: CapxulErrorCode;\n readonly cause?: unknown;\n}> {}\n\nexport class RequestOtpRequest extends Request.TaggedClass(\"RequestOtp\")<\n AuthFlowSnapshot,\n AuthFlowError,\n { readonly email: Email; readonly options?: AuthFlowOperationOptions }\n> {}\n\nexport class VerifyOtpRequest extends Request.TaggedClass(\"VerifyOtp\")<\n AuthFlowSnapshot,\n AuthFlowError,\n { readonly email: Email; readonly otp: string; readonly options?: AuthFlowOperationOptions }\n> {}\n\nexport class GetSessionRequest extends Request.TaggedClass(\"GetSession\")<\n AuthFlowSnapshot,\n AuthFlowError,\n { readonly options?: AuthFlowOperationOptions }\n> {}\n\nexport class SignOutRequest extends Request.TaggedClass(\"SignOut\")<\n AuthFlowSnapshot,\n AuthFlowError,\n { readonly options?: AuthFlowOperationOptions }\n> {}\n\nexport class RestoreCachedSessionRequest extends Request.TaggedClass(\"RestoreCachedSession\")<\n AuthFlowSnapshot,\n AuthFlowError,\n { readonly session: AuthSession }\n> {}\n\nexport class ResumeOtpEntryRequest extends Request.TaggedClass(\"ResumeOtpEntry\")<\n AuthFlowSnapshot,\n AuthFlowError,\n object\n> {}\n\nexport class ResetAuthFlowRequest extends Request.TaggedClass(\"ResetAuthFlow\")<\n AuthFlowSnapshot,\n AuthFlowError,\n object\n> {}\n\nclass CommitAuthFlowRequest extends Request.TaggedClass(\"CommitAuthFlow\")<\n AuthFlowSnapshot,\n never,\n {\n readonly input: AuthFlowInput;\n readonly context: AuthFlowContext;\n readonly policy?: AuthFlowCommitPolicy;\n }\n> {}\n\nexport type AuthFlowPublicRequest =\n | RequestOtpRequest\n | VerifyOtpRequest\n | GetSessionRequest\n | SignOutRequest\n | RestoreCachedSessionRequest\n | ResumeOtpEntryRequest\n | ResetAuthFlowRequest;\n\ntype AuthFlowPrivateRequest = CommitAuthFlowRequest;\ntype AuthFlowCommitPolicy = {\n readonly _tag: \"sessionRefresh\" | \"mutation\";\n readonly startedRevision: number;\n};\n\nexport type AuthFlowMachine = Machine.Machine<\n AuthFlowContext,\n AuthFlowPublicRequest,\n AuthFlowPrivateRequest,\n AuthFlowInput,\n never,\n AuthClientPortTag | ClockPortTag | TelemetryPortTag\n>;\n\ntype AuthFlowMachineActor = Machine.Actor<AuthFlowMachine>;\ninterface AuthFlowRuntimeControl {\n stopped: boolean;\n}\n\nconst AUTH_FLOW_CONTEXT_REVISIONS = new WeakMap<AuthFlowContext, number>();\n\nexport interface AuthFlowObserver {\n readonly input: AuthFlowInput;\n readonly getSnapshot: () => {\n readonly value: AuthFlowState;\n readonly context: AuthFlowContext;\n readonly status: \"active\" | \"stopped\";\n };\n readonly stop: () => void;\n}\n\nexport interface AuthFlowActor extends AuthFlowObserver {\n readonly send: (\n request: AuthFlowRequestInput,\n ) => Effect.Effect<\n AuthFlowSnapshot,\n AuthFlowError,\n AuthClientPortTag | ClockPortTag | TelemetryPortTag\n >;\n}\n\nconst DEFAULT_OTP_TTL_MS = 300_000;\nconst ACTOR_MACHINE = new WeakMap<AuthFlowActor, AuthFlowMachineActor>();\nconst RUNTIME_CONTROLS = new WeakMap<AuthFlowInput, AuthFlowRuntimeControl>();\n\nconst AUTH_FLOW_TRANSITION_TABLE: Record<\n AuthFlowState,\n {\n readonly valid: readonly AuthFlowRequestInput[\"_tag\"][];\n readonly invalid: readonly string[];\n }\n> = {\n idle: {\n valid: [\"RequestOtp\", \"GetSession\", \"RestoreCachedSession\", \"ResetAuthFlow\"],\n invalid: [\"VerifyOtp WRONG_STATE\", \"SignOut WRONG_STATE\"],\n },\n sending_otp: {\n valid: [\"ResetAuthFlow\", \"SignOut\"],\n invalid: [\"RequestOtp WRONG_STATE\", \"VerifyOtp WRONG_STATE\", \"GetSession WRONG_STATE\"],\n },\n otp_requested: {\n valid: [\"RequestOtp\", \"VerifyOtp\", \"GetSession\", \"SignOut\", \"ResetAuthFlow\"],\n invalid: [],\n },\n verifying: {\n valid: [\"ResetAuthFlow\", \"SignOut\"],\n invalid: [\"RequestOtp WRONG_STATE\", \"VerifyOtp WRONG_STATE\", \"GetSession WRONG_STATE\"],\n },\n authenticated: {\n valid: [\"GetSession\", \"SignOut\", \"ResetAuthFlow\"],\n invalid: [\"RequestOtp WRONG_STATE\", \"VerifyOtp WRONG_STATE\"],\n },\n signing_out: {\n valid: [\"ResetAuthFlow\"],\n invalid: [\n \"RequestOtp WRONG_STATE\",\n \"VerifyOtp WRONG_STATE\",\n \"GetSession WRONG_STATE\",\n \"SignOut WRONG_STATE\",\n ],\n },\n error: {\n valid: [\"ResetAuthFlow\", \"RequestOtp\", \"GetSession\", \"ResumeOtpEntry\"],\n invalid: [\"VerifyOtp WRONG_STATE\", \"SignOut WRONG_STATE\"],\n },\n};\n\nfunction tuple<A, B>(first: A, second: B): readonly [A, B] {\n return [first, second];\n}\n\nfunction normalizeInput(input: AuthFlowInput): Required<AuthFlowInput> {\n return { otpTtlMs: input.otpTtlMs ?? DEFAULT_OTP_TTL_MS };\n}\n\nfunction publicInput(input: Required<AuthFlowInput>): AuthFlowInput {\n return { otpTtlMs: input.otpTtlMs };\n}\n\nfunction initialContext(): AuthFlowContext {\n return withContextRevision(\n {\n state: \"idle\",\n email: null,\n session: null,\n otpRequestedAt: null,\n error: null,\n },\n 0,\n );\n}\n\nexport function createAuthFlowMachine(): AuthFlowMachine {\n return Machine.makeWith<AuthFlowContext, AuthFlowInput>()((input) => {\n const normalized = normalizeInput(input);\n const bootInput = publicInput(normalized);\n const control = runtimeControl(input);\n\n return Machine.procedures\n .make<AuthFlowContext>(initialContext(), {\n identifier: `AuthFlow:${normalized.otpTtlMs}`,\n })\n .pipe(\n Machine.procedures.addPrivate<CommitAuthFlowRequest>()(\n \"CommitAuthFlow\",\n ({ request, state }) => {\n const next = mergeCommittedContext(state, request.context, request.policy);\n return Effect.succeed(tuple(tuple(request.input, next), next));\n },\n ),\n Machine.procedures.add<RequestOtpRequest>()(\"RequestOtp\", (context) =>\n Effect.gen(function* () {\n const email = assertEmailWellFormed(context.request.email);\n if (!canTransition(context.state.state, \"RequestOtp\")) {\n return yield* Effect.fail(wrongState(\"RequestOtp\", context.state.state));\n }\n const anonDistinctId = context.state.anonDistinctId ?? makeAnonymousDistinctId();\n const transient = mutationContext(context.state, {\n state: \"sending_otp\",\n email,\n session: null,\n otpRequestedAt: null,\n anonDistinctId,\n error: null,\n });\n const complete = completeRequest(\n context.unsafeSendAwait,\n context.deferred,\n bootInput,\n control,\n requestOtpCompletion(email, anonDistinctId, context.request.options),\n (failure) =>\n failureContext(failure, {\n email: null,\n session: null,\n otpRequestedAt: null,\n anonDistinctId,\n }),\n mutationCommitPolicy(transient),\n );\n return yield* complete.pipe(\n context.forkReplaceWith(\"auth-flow:mutation\", transient),\n Effect.as(tuple(Machine.NoReply, transient)),\n );\n }),\n ),\n Machine.procedures.add<VerifyOtpRequest>()(\"VerifyOtp\", (context) =>\n Effect.gen(function* () {\n const email = assertEmailWellFormed(context.request.email);\n if (!/^\\d{6}$/.test(context.request.otp)) {\n return yield* Effect.fail(\n new AuthFlowError({\n operation: \"verifyOtp\",\n state: context.state.state,\n publicError: Errors.invalidInput(\"otp\", \"must be a six digit code\"),\n publicCode: \"INVALID_INPUT\",\n }),\n );\n }\n if (!canTransition(context.state.state, \"VerifyOtp\")) {\n return yield* Effect.fail(wrongState(\"VerifyOtp\", context.state.state));\n }\n const current = context.state;\n const anonDistinctId = current.anonDistinctId ?? makeAnonymousDistinctId();\n const clock = yield* ClockPortTag;\n const now = yield* clock.now.pipe(\n Effect.mapError(\n (cause) =>\n new AuthFlowError({\n operation: \"verifyOtp\",\n state: current.state,\n publicError: Errors.providerError(\"clock\", \"now\", cause),\n publicCode: \"PROVIDER_ERROR\",\n cause,\n }),\n ),\n );\n if (Number(now) - Number(current.otpRequestedAt) > normalized.otpTtlMs) {\n const failure = new AuthFlowError({\n operation: \"verifyOtp\",\n state: \"otp_requested\",\n publicError: Errors.otpExpired({\n expiredAt: Number(current.otpRequestedAt) + normalized.otpTtlMs,\n }),\n publicCode: \"OTP_EXPIRED\",\n });\n yield* emitTelemetry({\n name: \"auth_otp_expired\",\n props: { email_domain: emailDomain(current.email ?? email) },\n });\n return yield* Effect.fail(failure);\n }\n const transient = mutationContext(context.state, {\n state: \"verifying\",\n email,\n session: null,\n otpRequestedAt: current.otpRequestedAt,\n anonDistinctId,\n error: null,\n });\n const complete = completeRequest(\n context.unsafeSendAwait,\n context.deferred,\n bootInput,\n control,\n verifyOtpCompletion(\n email,\n context.request.otp,\n anonDistinctId,\n context.request.options,\n ),\n (failure) =>\n failureContext(failure, {\n email,\n session: null,\n otpRequestedAt: current.otpRequestedAt,\n anonDistinctId,\n }),\n mutationCommitPolicy(transient),\n );\n return yield* complete.pipe(\n context.forkReplaceWith(\"auth-flow:mutation\", transient),\n Effect.as(tuple(Machine.NoReply, transient)),\n );\n }),\n ),\n Machine.procedures.add<GetSessionRequest>()(\"GetSession\", (context) =>\n Effect.gen(function* () {\n if (!canTransition(context.state.state, \"GetSession\")) {\n return yield* Effect.fail(wrongState(\"GetSession\", context.state.state));\n }\n const complete = completeRequest(\n context.unsafeSendAwait,\n context.deferred,\n bootInput,\n control,\n getSessionCompletion(context.request.options, context.state),\n (failure) =>\n failureContext(failure, {\n email: context.state.email,\n session: context.state.session,\n otpRequestedAt: context.state.otpRequestedAt,\n ...(context.state.anonDistinctId === undefined\n ? {}\n : { anonDistinctId: context.state.anonDistinctId }),\n }),\n { _tag: \"sessionRefresh\", startedRevision: contextRevision(context.state) },\n );\n return yield* complete.pipe(\n context.forkReplaceWith(\"auth-flow:session\", context.state),\n Effect.as(tuple(Machine.NoReply, context.state)),\n );\n }),\n ),\n Machine.procedures.add<SignOutRequest>()(\"SignOut\", (context) =>\n Effect.gen(function* () {\n if (!canTransition(context.state.state, \"SignOut\")) {\n return yield* Effect.fail(wrongState(\"SignOut\", context.state.state));\n }\n const transient = mutationContext(context.state, {\n state: \"signing_out\",\n email: context.state.email,\n session: context.state.session,\n otpRequestedAt: null,\n error: null,\n });\n const complete = completeRequest(\n context.unsafeSendAwait,\n context.deferred,\n bootInput,\n control,\n signOutCompletion(context.request.options),\n () => initialContext(),\n mutationCommitPolicy(transient),\n );\n return yield* complete.pipe(\n context.forkReplaceWith(\"auth-flow:mutation\", transient),\n Effect.as(tuple(Machine.NoReply, transient)),\n );\n }),\n ),\n Machine.procedures.add<RestoreCachedSessionRequest>()(\"RestoreCachedSession\", (context) =>\n Effect.gen(function* () {\n if (!canTransition(context.state.state, \"RestoreCachedSession\")) {\n return yield* Effect.fail(wrongState(\"RestoreCachedSession\", context.state.state));\n }\n const restored = mutationContext(context.state, {\n state: \"authenticated\",\n email: context.request.session.email,\n session: context.request.session,\n otpRequestedAt: null,\n error: null,\n });\n return tuple(tuple(bootInput, restored), restored);\n }),\n ),\n Machine.procedures.add<ResumeOtpEntryRequest>()(\"ResumeOtpEntry\", (context) =>\n Effect.gen(function* () {\n if (!canTransition(context.state.state, \"ResumeOtpEntry\")) {\n return yield* Effect.fail(wrongState(\"ResumeOtpEntry\", context.state.state));\n }\n const current = context.state;\n if (current.email === null || current.otpRequestedAt === null) {\n return yield* Effect.fail(wrongState(\"ResumeOtpEntry\", context.state.state));\n }\n const clock = yield* ClockPortTag;\n const now = yield* clock.now.pipe(\n Effect.mapError(\n (cause) =>\n new AuthFlowError({\n operation: \"verifyOtp\",\n state: current.state,\n publicError: Errors.providerError(\"clock\", \"now\", cause),\n publicCode: \"PROVIDER_ERROR\",\n cause,\n }),\n ),\n );\n if (Number(now) - Number(current.otpRequestedAt) > normalized.otpTtlMs) {\n const failure = new AuthFlowError({\n operation: \"verifyOtp\",\n state: \"error\",\n publicError: Errors.otpExpired({\n expiredAt: Number(current.otpRequestedAt) + normalized.otpTtlMs,\n }),\n publicCode: \"OTP_EXPIRED\",\n });\n yield* emitTelemetry({\n name: \"auth_otp_expired\",\n props: { email_domain: emailDomain(current.email) },\n });\n return yield* Effect.fail(failure);\n }\n const restored = mutationContext(context.state, {\n state: \"otp_requested\",\n email: current.email,\n session: null,\n otpRequestedAt: current.otpRequestedAt,\n ...(current.anonDistinctId === undefined\n ? {}\n : { anonDistinctId: current.anonDistinctId }),\n error: null,\n });\n return tuple(tuple(bootInput, restored), restored);\n }),\n ),\n Machine.procedures.add<ResetAuthFlowRequest>()(\"ResetAuthFlow\", (context) => {\n const reset = mutationContext(context.state, initialContext());\n return Effect.succeed(tuple(tuple(bootInput, reset), reset));\n }),\n );\n });\n}\n\nexport function bootAuthFlow(\n machine: AuthFlowMachine,\n input: AuthFlowInput,\n): Effect.Effect<AuthFlowActor, never, AuthClientPortTag | ClockPortTag | TelemetryPortTag> {\n return Effect.gen(function* () {\n const normalized = normalizeInput(input);\n const bootInput = publicInput(normalized);\n const scope = yield* Scope.make();\n const control: AuthFlowRuntimeControl = { stopped: false };\n const actor = yield* Machine.boot(machine, withRuntimeControl(bootInput, control)).pipe(\n Scope.extend(scope),\n );\n const statusRef = yield* Ref.make<\"active\" | \"stopped\">(\"active\");\n const stopDeferred = yield* Deferred.make<void>();\n\n const flowActor: AuthFlowActor = {\n input: bootInput,\n getSnapshot() {\n const context = Effect.runSync(actor.get);\n const status = Effect.runSync(Ref.get(statusRef));\n return {\n value: context.state,\n context,\n status,\n };\n },\n stop() {\n control.stopped = true;\n Effect.runSync(Ref.set(statusRef, \"stopped\"));\n Effect.runSync(Deferred.succeed(stopDeferred, void 0));\n Effect.runFork(Scope.close(scope, Exit.void));\n },\n send(request) {\n return Ref.get(statusRef).pipe(\n Effect.flatMap((status) =>\n status === \"active\"\n ? actor.send(toMachineRequest(request)).pipe(\n Effect.raceFirst(\n Deferred.await(stopDeferred).pipe(\n Effect.flatMap(() =>\n Effect.fail(\n new AuthFlowError({\n operation: \"transition\",\n state: Effect.runSync(actor.get).state,\n publicError: Errors.cancelled({ operation: \"authFlow.send\" }),\n publicCode: \"CANCELLED\",\n }),\n ),\n ),\n ),\n ),\n )\n : Effect.fail(\n new AuthFlowError({\n operation: \"transition\",\n state: Effect.runSync(actor.get).state,\n publicError: Errors.cancelled({ operation: \"authFlow.send\" }),\n publicCode: \"CANCELLED\",\n }),\n ),\n ),\n Effect.tapError((failure) =>\n failure.publicCode === \"OTP_EXPIRED\"\n ? Effect.void\n : emitTelemetry({\n name: \"auth_failed\",\n props: { auth_type: \"otp\", reason: failure.publicCode },\n }),\n ),\n );\n },\n };\n ACTOR_MACHINE.set(flowActor, actor);\n return flowActor;\n });\n}\n\nexport function snapshotAuthFlow(actor: AuthFlowActor): Effect.Effect<AuthFlowSnapshot, never> {\n return actorMachine(actor).get.pipe(Effect.map((state) => tuple(actor.input, state)));\n}\n\nexport function sendAuthFlowRequest(\n actor: AuthFlowActor,\n request: AuthFlowRequestInput,\n): Effect.Effect<\n AuthFlowSnapshot,\n AuthFlowError,\n AuthClientPortTag | ClockPortTag | TelemetryPortTag\n> {\n return actor.send(request);\n}\n\nexport function assertEmailWellFormed(email: Email): Email {\n return toEmail(email);\n}\n\nfunction toMachineRequest(request: AuthFlowRequestInput): AuthFlowPublicRequest {\n switch (request._tag) {\n case \"RequestOtp\":\n return new RequestOtpRequest(optionalOptions({ email: request.email }, request.options));\n case \"VerifyOtp\":\n return new VerifyOtpRequest(\n optionalOptions({ email: request.email, otp: request.otp }, request.options),\n );\n case \"GetSession\":\n return new GetSessionRequest(optionalOptions({}, request.options));\n case \"SignOut\":\n return new SignOutRequest(optionalOptions({}, request.options));\n case \"RestoreCachedSession\":\n return new RestoreCachedSessionRequest({ session: request.session });\n case \"ResumeOtpEntry\":\n return new ResumeOtpEntryRequest();\n case \"ResetAuthFlow\":\n return new ResetAuthFlowRequest();\n }\n}\n\nfunction optionalOptions<T extends object>(\n base: T,\n options: AuthFlowOperationOptions | undefined,\n): T | (T & { readonly options: AuthFlowOperationOptions }) {\n return options === undefined ? base : { ...base, options };\n}\n\nfunction requestOtpCompletion(\n email: Email,\n anonDistinctId: AnonymousDistinctId,\n options?: AuthFlowOperationOptions,\n): Effect.Effect<\n AuthFlowContext,\n AuthFlowError,\n AuthClientPortTag | ClockPortTag | TelemetryPortTag\n> {\n return Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n yield* withAuthFlowTimeout(\n authClient.sendOtp({ email }, authClientOptions(options)),\n \"requestOtp\",\n \"sending_otp\",\n options,\n ).pipe(Effect.mapError((error) => authClientFailure(\"requestOtp\", \"sending_otp\", error)));\n const clock = yield* ClockPortTag;\n const now = yield* clock.now.pipe(\n Effect.mapError(\n (cause) =>\n new AuthFlowError({\n operation: \"requestOtp\",\n state: \"sending_otp\",\n publicError: Errors.providerError(\"clock\", \"now\", cause),\n publicCode: \"PROVIDER_ERROR\",\n cause,\n }),\n ),\n );\n yield* emitTelemetry({\n name: \"auth_otp_requested\",\n props: { email_domain: emailDomain(email) },\n });\n return {\n state: \"otp_requested\",\n email,\n session: null,\n otpRequestedAt: now,\n anonDistinctId,\n error: null,\n };\n });\n}\n\nfunction verifyOtpCompletion(\n email: Email,\n otp: string,\n anonDistinctId: AnonymousDistinctId,\n options?: AuthFlowOperationOptions,\n): Effect.Effect<AuthFlowContext, AuthFlowError, AuthClientPortTag | TelemetryPortTag> {\n return Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const session = yield* withAuthFlowTimeout(\n authClient.verifyOtp({ email, otp }, authClientOptions(options)),\n \"verifyOtp\",\n \"verifying\",\n options,\n ).pipe(Effect.mapError((error) => authClientFailure(\"verifyOtp\", \"verifying\", error)));\n yield* emitTelemetry({ name: \"auth_verified\", props: { auth_type: \"otp\" } });\n yield* identifyTelemetry({\n distinctId: session.authUserId,\n anonDistinctId,\n traits: { email_domain: emailDomain(session.email) },\n });\n return {\n state: \"authenticated\",\n email: session.email,\n session,\n otpRequestedAt: null,\n error: null,\n };\n });\n}\n\nfunction isInFlightOtpAuthState(state: AuthFlowState): boolean {\n return state === \"otp_requested\" || state === \"sending_otp\" || state === \"verifying\";\n}\n\nfunction getSessionCompletion(\n options: AuthFlowOperationOptions | undefined,\n current: AuthFlowContext,\n): Effect.Effect<AuthFlowContext, AuthFlowError, AuthClientPortTag> {\n return Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const session = yield* withAuthFlowTimeout(\n authClient.getSession(authClientOptions(options)),\n \"getSession\",\n current.state,\n options,\n ).pipe(Effect.mapError((error) => authClientFailure(\"getSession\", current.state, error)));\n if (session === null) {\n // Wire session absent during OTP entry is normal — do not reset the flow.\n if (isInFlightOtpAuthState(current.state)) return current;\n return initialContext();\n }\n return {\n state: \"authenticated\",\n email: session.email,\n session,\n otpRequestedAt: null,\n error: null,\n };\n });\n}\n\nfunction signOutCompletion(\n options?: AuthFlowOperationOptions,\n): Effect.Effect<AuthFlowContext, AuthFlowError, AuthClientPortTag | TelemetryPortTag> {\n return Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n yield* withAuthFlowTimeout(\n authClient.signOut(authClientOptions(options)),\n \"signOut\",\n \"signing_out\",\n options,\n ).pipe(Effect.mapError((error) => authClientFailure(\"signOut\", \"signing_out\", error)));\n yield* emitTelemetry({ name: \"auth_signed_out\" });\n yield* resetTelemetry();\n return initialContext();\n });\n}\n\nfunction withAuthFlowTimeout<A, E>(\n effect: Effect.Effect<A, E>,\n operation: Exclude<AuthFlowError[\"operation\"], \"transition\">,\n state: AuthFlowState,\n options: AuthFlowOperationOptions | undefined,\n): Effect.Effect<A, E | AuthFlowError> {\n const timeoutMs = options?.timeoutMs;\n if (timeoutMs === undefined) return effect;\n return effect.pipe(\n Effect.timeoutFail({\n duration: Duration.millis(timeoutMs),\n onTimeout: () =>\n new AuthFlowError({\n operation,\n state,\n publicError: Errors.providerTimeout(\"auth-flow\", operation, timeoutMs),\n publicCode: \"PROVIDER_ERROR\",\n }),\n }),\n );\n}\n\nfunction authClientOptions(\n options: AuthFlowOperationOptions | undefined,\n): AuthClientOperationOptions | undefined {\n if (options?.signal === undefined) return undefined;\n return { signal: options.signal };\n}\n\nfunction authClientFailure(\n operation: Exclude<AuthFlowError[\"operation\"], \"transition\">,\n state: AuthFlowState,\n error: AuthClientError | AuthFlowError,\n): AuthFlowError {\n if (error instanceof AuthFlowError) return error;\n return toAuthFlowError(operation, state, error);\n}\n\nfunction completeRequest(\n commit: (request: CommitAuthFlowRequest) => Effect.Effect<AuthFlowSnapshot, never>,\n deferred: Deferred.Deferred<AuthFlowSnapshot, AuthFlowError>,\n input: AuthFlowInput,\n control: AuthFlowRuntimeControl,\n effect: Effect.Effect<\n AuthFlowContext,\n AuthFlowError,\n AuthClientPortTag | ClockPortTag | TelemetryPortTag\n >,\n toFailureContext: (failure: AuthFlowError) => AuthFlowContext,\n policy?: AuthFlowCommitPolicy,\n): Effect.Effect<void, never, AuthClientPortTag | ClockPortTag | TelemetryPortTag> {\n return effect.pipe(\n Effect.either,\n Effect.flatMap((result) => {\n const stopped = stoppedFailure();\n const resolution = control.stopped\n ? commit(commitAuthFlowRequest(input, toFailureContext(stopped), policy)).pipe(\n Effect.zipRight(Deferred.fail(deferred, stopped)),\n )\n : result._tag === \"Right\"\n ? commit(commitAuthFlowRequest(input, result.right, policy)).pipe(\n Effect.flatMap((snapshot) => Deferred.succeed(deferred, snapshot)),\n )\n : commit(commitAuthFlowRequest(input, toFailureContext(result.left), policy)).pipe(\n Effect.zipRight(Deferred.fail(deferred, result.left)),\n );\n\n // Once port work has produced a result, the actor commit + caller response is\n // one handoff. Refetches may interrupt long port work, but not this resolution.\n return Effect.uninterruptible(resolution);\n }),\n Effect.catchAllDefect((cause) => {\n const failure = new AuthFlowError({\n operation: \"transition\",\n state: \"error\",\n publicError: Errors.unknown(cause),\n publicCode: \"UNKNOWN\",\n cause,\n });\n return Effect.uninterruptible(\n commit(commitAuthFlowRequest(input, toFailureContext(failure), policy)).pipe(\n Effect.zipRight(Deferred.fail(deferred, failure)),\n ),\n );\n }),\n Effect.onInterrupt(() =>\n Effect.uninterruptible(\n commit(commitAuthFlowRequest(input, toFailureContext(stoppedFailure()), policy)).pipe(\n Effect.zipRight(Deferred.fail(deferred, stoppedFailure())),\n ),\n ),\n ),\n );\n}\n\nfunction commitAuthFlowRequest(\n input: AuthFlowInput,\n context: AuthFlowContext,\n policy: AuthFlowCommitPolicy | undefined,\n): CommitAuthFlowRequest {\n if (policy === undefined) return new CommitAuthFlowRequest({ input, context });\n return new CommitAuthFlowRequest({ input, context, policy });\n}\n\n// Auth requests may overlap with background session refreshes. Mutations commit\n// only if no reset/sign-out advanced the WeakMap-backed revision since their\n// transient context started; session refreshes use the same stale-commit check.\nfunction mergeCommittedContext(\n current: AuthFlowContext,\n next: AuthFlowContext,\n policy: AuthFlowCommitPolicy | undefined,\n): AuthFlowContext {\n const currentRevision = contextRevision(current);\n if (policy === undefined) return withContextRevision(next, currentRevision);\n if (currentRevision !== policy.startedRevision) return current;\n return withContextRevision(next, currentRevision);\n}\n\nfunction mutationCommitPolicy(context: AuthFlowContext): AuthFlowCommitPolicy {\n return { _tag: \"mutation\", startedRevision: contextRevision(context) };\n}\n\nfunction mutationContext(context: AuthFlowContext, next: AuthFlowContext): AuthFlowContext {\n return withContextRevision(next, contextRevision(context) + 1);\n}\n\nfunction contextRevision(context: AuthFlowContext): number {\n return AUTH_FLOW_CONTEXT_REVISIONS.get(context) ?? 0;\n}\n\nfunction withContextRevision(context: AuthFlowContext, revision: number): AuthFlowContext {\n AUTH_FLOW_CONTEXT_REVISIONS.set(context, revision);\n return context;\n}\n\nfunction stoppedFailure(): AuthFlowError {\n return new AuthFlowError({\n operation: \"transition\",\n state: \"error\",\n publicError: Errors.cancelled({ operation: \"authFlow.request\" }),\n publicCode: \"CANCELLED\",\n });\n}\n\nfunction withRuntimeControl(input: AuthFlowInput, control: AuthFlowRuntimeControl): AuthFlowInput {\n const runtimeInput = { ...input };\n RUNTIME_CONTROLS.set(runtimeInput, control);\n return runtimeInput;\n}\n\nfunction runtimeControl(input: AuthFlowInput): AuthFlowRuntimeControl {\n return RUNTIME_CONTROLS.get(input) ?? { stopped: false };\n}\n\nfunction failureContext(\n failure: AuthFlowError,\n preserved: Pick<AuthFlowContext, \"email\" | \"session\" | \"otpRequestedAt\" | \"anonDistinctId\">,\n): AuthFlowContext {\n return {\n state: \"error\",\n email: preserved.email,\n session: preserved.session,\n otpRequestedAt: preserved.otpRequestedAt,\n ...(preserved.anonDistinctId === undefined ? {} : { anonDistinctId: preserved.anonDistinctId }),\n error: failure.publicError,\n };\n}\n\nfunction canTransition(state: AuthFlowState, request: AuthFlowRequestInput[\"_tag\"]): boolean {\n return AUTH_FLOW_TRANSITION_TABLE[state].valid.includes(request);\n}\n\nfunction wrongState(request: AuthFlowRequestInput[\"_tag\"], state: AuthFlowState): AuthFlowError {\n return new AuthFlowError({\n operation: \"transition\",\n state,\n publicError: Errors.wrongState({\n method: request,\n currentState: state,\n validStates: AUTH_FLOW_TRANSITION_TABLE[state].valid,\n }),\n publicCode: \"WRONG_STATE\",\n });\n}\n\nfunction toAuthFlowError(\n operation: Exclude<AuthFlowError[\"operation\"], \"transition\">,\n state: AuthFlowState,\n error: AuthClientError,\n): AuthFlowError {\n const publicError = toCapxulError(operation, error);\n return new AuthFlowError({\n operation,\n state,\n publicError,\n publicCode: publicError.code,\n cause: error,\n });\n}\n\nfunction toCapxulError(operation: string, error: AuthClientError): CapxulError {\n if (error.cause instanceof CapxulError) {\n return error.cause;\n }\n if (operation === \"requestOtp\" && error.kind === \"provider\") {\n return Errors.emailDeliveryFailed(\"provider rejected OTP request\");\n }\n return Errors.providerError(\"auth-client\", operation, new Error(\"auth-client provider failure\"));\n}\n\nfunction emitTelemetry(event: TelemetryEvent): Effect.Effect<void, never, TelemetryPortTag> {\n return Effect.gen(function* () {\n const telemetry = yield* TelemetryPortTag;\n yield* telemetry.emit(event).pipe(\n Effect.catchAllDefect(() => Effect.void),\n Effect.catchAll(() => Effect.void),\n );\n });\n}\n\nfunction identifyTelemetry(\n input: TelemetryIdentifyInput,\n): Effect.Effect<void, never, TelemetryPortTag> {\n return Effect.gen(function* () {\n const telemetry = yield* TelemetryPortTag;\n yield* telemetry.identify(input).pipe(\n Effect.catchAllDefect(() => Effect.void),\n Effect.catchAll(() => Effect.void),\n );\n });\n}\n\nfunction resetTelemetry(): Effect.Effect<void, never, TelemetryPortTag> {\n return Effect.gen(function* () {\n const telemetry = yield* TelemetryPortTag;\n yield* telemetry.reset().pipe(\n Effect.catchAllDefect(() => Effect.void),\n Effect.catchAll(() => Effect.void),\n );\n });\n}\n\nfunction makeAnonymousDistinctId(): AnonymousDistinctId {\n const cryptoApi = globalThis as {\n readonly crypto?: { readonly randomUUID?: () => string };\n };\n const id =\n cryptoApi.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n return toAnonymousDistinctId(`anon_${id}`);\n}\n\nfunction emailDomain(email: Email): string {\n const [, domain = \"unknown\"] = email.split(\"@\");\n return domain;\n}\n\nfunction actorMachine(actor: AuthFlowActor): AuthFlowMachineActor {\n const machine = ACTOR_MACHINE.get(actor);\n if (machine === undefined) {\n throw new Error(\"AuthFlowActor was not created by bootAuthFlow\");\n }\n return machine;\n}\n","// CapxulDeps — the single dependency bundle the new Effect seam resolves\n// (PRD #209; shape validated by SPIKE #210 \"shape works\").\n//\n// The hourglass collapse replaces the per-method Effect→Result plumbing in\n// `auth.ts` (and, in slices 3–6, the sibling method bundles) with:\n//\n// 1. `CapxulDeps` — the dependency bundle carried by ONE Context tag.\n// Verbatim mirror of `MakeAuthMethodsDeps`\n// (auth.ts:56-64), incl. the optional `otpTtlMs?`\n// / `invokeTimeoutMs?` knobs.\n// 2. `CapxulDepsTag` — the single Context tag both the public methods\n// (via `toCapxulResult`) and internal reactive\n// atoms resolve.\n// 3. `authFlowLayer` — builds the 3-port AuthFlow layer FROM a bundle.\n// Discharged INSIDE each program so the program's\n// external requirement narrows to exactly\n// `CapxulDepsTag`.\n// 4. `getSessionProgram` — the getSession operation as a single\n// `Effect<Session | null, CapxulError, CapxulDepsTag>`.\n// 5. `verifyOtpProgram` — the verifyOtp operation (slice 3) as a single\n// `Effect<Session, CapxulError, CapxulDepsTag>`.\n//\n// This module is NOT re-exported from the `@capxul/sdk` main barrel — it is\n// reachable only via the `@capxul/sdk/react-substrate` subpath (consumed by\n// the React reactive surface). See `.claude/rules/flow-internal-substrate.md`.\n\nimport { Context, Effect, Either, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toEmail, type Email } from \"@capxul/types\";\n\nimport {\n sendAuthFlowRequest,\n type AuthFlowActor,\n type AuthFlowOperationOptions,\n type AuthFlowState,\n} from \"../flows/auth\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport {\n AuthClientPortTag,\n type AuthClientPort,\n type CanSendOtpStatus,\n} from \"../ports/auth-client\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport { ClockPortTag, type ClockPort } from \"../ports/clock\";\nimport { TelemetryPortTag, type TelemetryPort } from \"../ports/telemetry\";\n\nimport type { Session } from \"./types\";\n\n/**\n * The dependency bundle a single `Context.Tag` carries (PRD #209). Verbatim\n * mirror of `MakeAuthMethodsDeps` (auth.ts:56-64) — kept structurally identical\n * so a `MakeAuthMethodsDeps` value is assignable wherever a `CapxulDeps` is\n * expected (and vice versa).\n */\nexport interface CapxulDeps {\n readonly actor: AuthFlowActor;\n readonly authClient: AuthClientPort;\n readonly authCache: AuthCachePort;\n readonly clock: ClockPort;\n readonly telemetry?: TelemetryPort;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n readonly afterVerifyOtp?: () => Promise<void>;\n}\n\n/** The single Context tag the atoms + public methods both resolve. */\nexport class CapxulDepsTag extends Context.Tag(\"@capxul/sdk/CapxulDeps\")<\n CapxulDepsTag,\n CapxulDeps\n>() {}\n\n/** Wrap a bundle as the `Layer<CapxulDepsTag>` the React provider consumes. */\nexport function capxulDepsLayer(deps: CapxulDeps): Layer.Layer<CapxulDepsTag> {\n return Layer.succeed(CapxulDepsTag, deps);\n}\n\n/**\n * Build the 3-port AuthFlow layer FROM the bundle. The single home for this\n * construction — `auth.ts` imports it for its per-method Effect runners, and\n * each program (`getSessionProgram`, …) provides it internally so the actor\n * send's `AuthClientPortTag | ClockPortTag | TelemetryPortTag` requirement is\n * discharged and the program's external requirement stays `CapxulDepsTag`.\n */\nexport function authFlowLayer(\n deps: CapxulDeps,\n): Layer.Layer<AuthClientPortTag | ClockPortTag | TelemetryPortTag> {\n return Layer.mergeAll(\n Layer.succeed(AuthClientPortTag, deps.authClient),\n Layer.succeed(ClockPortTag, deps.clock),\n Layer.succeed(TelemetryPortTag, deps.telemetry ?? noopTelemetryPort()),\n );\n}\n\nfunction noopTelemetryPort(): TelemetryPort {\n return {\n emit: () => Effect.void,\n identify: () => Effect.void,\n group: () => Effect.void,\n reset: () => Effect.void,\n };\n}\n\nfunction hasMachineActor(actor: AuthFlowActor): boolean {\n return typeof (actor as { readonly send?: unknown }).send === \"function\";\n}\n\n/**\n * getSession as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the current public method body (auth.ts:250-281): the\n * leading `signal.aborted` pre-check stays in the thin method wrapper, while a\n * non-aborted signal is forwarded through the actor request options. The\n * `Effect.provide(authFlowLayer(deps))` on the inner actor send\n * is what narrows R from\n * `CapxulDepsTag | AuthClientPortTag | ClockPortTag | TelemetryPortTag` down to\n * `CapxulDepsTag` — the load-bearing structural property the explicit\n * annotation asserts.\n */\nexport const getSessionProgramWithOptions = (\n options?: AuthProgramOptions,\n): Effect.Effect<Session | null, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // Cache-first (auth.ts:255-258).\n const cached = yield* deps.authCache.getSession.pipe(\n Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"getSession\", e)),\n );\n const actorState = String(deps.actor.getSnapshot().value) as AuthFlowState;\n if (\n cached === null &&\n (actorState === \"otp_requested\" || actorState === \"sending_otp\" || actorState === \"verifying\")\n ) {\n return null;\n }\n if (cached !== null && actorState !== \"idle\") return cached;\n if (cached !== null && actorState === \"idle\") {\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"RestoreCachedSession\",\n session: cached,\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n return cached;\n }\n\n // Non-machine actor stub carrying an error context (auth.ts:259-262).\n if (!hasMachineActor(deps.actor)) {\n const existingError = deps.actor.getSnapshot().context.error;\n if (existingError !== null) return yield* Effect.fail(existingError);\n }\n\n // Drive the actor's GetSession (auth.ts:263-270).\n const refreshed = yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"GetSession\",\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n if (refreshed[1].session !== null) return refreshed[1].session;\n\n // Cache miss: snapshot the machine context (auth.ts:276-280).\n const session = deps.actor.getSnapshot().context.session;\n if (session !== null) return session;\n\n // Cache may hold a session while the actor is still idle (browser reload).\n if (cached !== null) return cached;\n\n // No session known locally (auth.ts:280).\n return null;\n });\n\nexport const getSessionProgram: Effect.Effect<Session | null, CapxulError, CapxulDepsTag> =\n getSessionProgramWithOptions();\n\n/** Consumer input for {@link verifyOtpProgram}. Mirrors the public method arg. */\nexport interface VerifyOtpProgramInput {\n readonly email: string;\n readonly code: string;\n readonly signer?: ExternalSigner;\n}\n\n/**\n * verifyOtp as a single Effect requiring ONLY `CapxulDepsTag` (PRD #209, slice\n * 3 — parallels {@link getSessionProgram}). Faithful transcription of the\n * current public method body (auth.ts:145-201): the leading `signal.aborted`\n * pre-check stays in the thin method wrapper, while non-aborted per-request\n * signals and the dep-level `invokeTimeoutMs` knob are forwarded. The\n * `Effect.provide(authFlowLayer(\n * deps))` on the inner actor send narrows R from\n * `CapxulDepsTag | AuthClientPortTag | ClockPortTag | TelemetryPortTag` down to\n * `CapxulDepsTag`.\n */\nexport function verifyOtpProgram(\n input: VerifyOtpProgramInput,\n options?: AuthProgramOptions,\n): Effect.Effect<Session, CapxulError, CapxulDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // 1. Validate code shape — 6 digits (auth.ts:150-152).\n if (!/^\\d{6}$/.test(input.code)) {\n return yield* Effect.fail(Errors.invalidInput(\"otp\", \"must be 6 digits\"));\n }\n\n // 2. Brand email (already branded inside the machine; consumer-friendly\n // here — auth.ts:154-161).\n let email: Email;\n try {\n email = toEmail(input.email);\n } catch (err) {\n return yield* Effect.fail(\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n );\n }\n\n // 3. Precondition: otp_requested, or error after a failed verify (Back → retry).\n let value = String(deps.actor.getSnapshot().value) as AuthFlowState;\n if (value === \"error\") {\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"ResumeOtpEntry\",\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n value = \"otp_requested\";\n } else if (value !== \"otp_requested\") {\n return yield* Effect.fail(\n Errors.wrongState({\n method: \"verifyOtp\",\n currentState: value,\n validStates: [\"otp_requested\"],\n }),\n );\n }\n\n // Legacy non-machine actor error snapshot (auth.ts:175-183).\n if (!hasMachineActor(deps.actor)) {\n const next = deps.actor.getSnapshot();\n if (String(next.value) === \"error\") {\n return yield* Effect.fail(next.context.error ?? Errors.unknown({ method: \"verifyOtp\" }));\n }\n }\n\n // 4. Drive VERIFY with the externalSigner payload (no SET_SIGNER event —\n // auth.ts:184-197). The `signer` arg is accepted for parity with the\n // public method but, as today, not forwarded into the VerifyOtp event.\n const session = yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"VerifyOtp\",\n email,\n otp: input.code,\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.map((snapshot) => snapshot[1].session),\n Effect.mapError((failure) => failure.publicError),\n );\n if (session === null) return yield* Effect.fail(Errors.notAuthenticated());\n\n // 5. Persist the verified session (auth.ts:198-199).\n yield* deps.authCache\n .setSession(session)\n .pipe(Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"setSession\", e)));\n\n return session;\n });\n}\n\n/** The `signIn` Result payload (mirrors the `AuthMethods[\"signIn\"]` value). */\nexport interface SignInSuccess {\n readonly sessionId: string;\n readonly expiresAt: number;\n}\n\n/**\n * Deps-only request-option builder. The verbatim deps half of `auth.ts`'s\n * former `authRequestOptions(deps, signal)` — the bundle-level\n * `invokeTimeoutMs` and per-request `signal` are forwarded into the actor\n * request options when present.\n */\nfunction depsRequestOptions(\n deps: CapxulDeps,\n signal?: AbortSignal,\n): { readonly options: AuthFlowOperationOptions } | object {\n if (deps.invokeTimeoutMs === undefined && signal === undefined) return {};\n return {\n options: {\n ...(deps.invokeTimeoutMs === undefined ? {} : { timeoutMs: deps.invokeTimeoutMs }),\n ...(signal === undefined ? {} : { signal }),\n },\n };\n}\n\n/**\n * Clear the local auth cache (session then JWT), mapping each failure into a\n * typed `CapxulError`. Effect transcription of `auth.ts`'s former\n * `clearAuthCache` helper: `clearSession` runs first and short-circuits the\n * JWT clear on failure, matching the original's sequential `if (!ok) return`.\n */\nfunction clearAuthCacheEffect(authCache: AuthCachePort): Effect.Effect<void, CapxulError> {\n return authCache.clearSession.pipe(\n Effect.mapError((cause) => Errors.providerError(\"auth-cache\", \"clearSession\", cause)),\n Effect.zipRight(\n authCache.clearJwt.pipe(\n Effect.mapError((cause) => Errors.providerError(\"auth-cache\", \"clearJwt\", cause)),\n ),\n ),\n );\n}\n\nfunction cryptoRandomId(): string {\n // Best-effort 16-char hex id. Used only as a tracking value for the\n // `signIn` Result; not auth-critical. Moved here verbatim from `auth.ts`\n // when `signIn` collapsed onto `signInProgram`.\n const bytes = new Uint8Array(8);\n if (\n typeof globalThis.crypto !== \"undefined\" &&\n typeof globalThis.crypto.getRandomValues === \"function\"\n ) {\n globalThis.crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * `canSendOtp` as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the former public method body minus the leading\n * `signal.aborted` pre-check (stays in the thin method wrapper). The auth-port\n * failure mapping mirrors the former `runAuthClientEffect`: a `CapxulError`\n * cause passes through verbatim, anything else becomes a typed `providerError`.\n */\ninterface AuthProgramOptions {\n readonly signal?: AbortSignal;\n}\n\nexport const canSendOtpProgram = (\n input: {\n readonly email: string;\n },\n options?: AuthProgramOptions,\n): Effect.Effect<CanSendOtpStatus, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n const email = yield* Effect.try({\n try: () => toEmail(input.email),\n catch: (err) =>\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n });\n return yield* deps.authClient\n .canSendOtp({ email }, options?.signal === undefined ? undefined : { signal: options.signal })\n .pipe(\n Effect.mapError((failure) =>\n failure.cause instanceof CapxulError\n ? failure.cause\n : Errors.providerError(\"auth-client\", \"canSendOtp\", failure.cause),\n ),\n );\n });\n\n/**\n * `signIn` as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the former public method body: brand the email, enforce the\n * idle/otp_requested/error precondition, auto-RESET out of error, drive\n * `RequestOtp`, then mint the tracking Result from the clock. Each actor send\n * provides `authFlowLayer(deps)` INTERNALLY so external R stays `CapxulDepsTag`.\n */\nexport const signInProgram = (\n input: {\n readonly email: string;\n },\n options?: AuthProgramOptions,\n): Effect.Effect<SignInSuccess, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // 1. Brand at entry — consumer passes raw string.\n const email = yield* Effect.try({\n try: () => toEmail(input.email),\n catch: (err) =>\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n });\n\n // 2. Precondition: idle, otp_requested (re-send), or error (auto-RESET first).\n const value = String(deps.actor.getSnapshot().value) as AuthFlowState;\n if (value !== \"idle\" && value !== \"otp_requested\" && value !== \"error\") {\n return yield* Effect.fail(\n Errors.wrongState({\n method: \"signIn\",\n currentState: value,\n validStates: [\"idle\", \"otp_requested\", \"error\"],\n }),\n );\n }\n if (value === \"error\") {\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"ResetAuthFlow\",\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n }\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"RequestOtp\",\n email,\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n const now = yield* deps.clock.now.pipe(\n Effect.mapError((cause) => Errors.providerError(\"clock\", \"now\", cause)),\n );\n return {\n sessionId: cryptoRandomId(),\n expiresAt: now + (deps.otpTtlMs ?? 300_000),\n };\n });\n\n/**\n * `signOut` as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the former public method body: WRONG_STATE from idle,\n * reset-and-clear from error, otherwise drive `SignOut` and clear the local\n * cache REGARDLESS of the wire outcome. `Effect.either` captures the `SignOut`\n * result without short-circuiting so the cache clear always runs — a cache\n * clear failure then takes precedence over the wire error, matching the former\n * `if (!cacheClear.ok) return cacheClear; return result`.\n */\nexport const signOutProgramWithOptions = (\n options?: AuthProgramOptions,\n): Effect.Effect<void, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n let value = String(deps.actor.getSnapshot().value) as AuthFlowState;\n\n if (value === \"idle\") {\n const cached = yield* deps.authCache.getSession.pipe(\n Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"getSession\", e)),\n );\n if (cached !== null) {\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"RestoreCachedSession\",\n session: cached,\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n value = String(deps.actor.getSnapshot().value) as AuthFlowState;\n }\n if (value === \"idle\") {\n return yield* Effect.fail(\n Errors.wrongState({\n method: \"signOut\",\n currentState: value,\n validStates: [\"authenticated\", \"otp_requested\", \"verifying\", \"sending_otp\", \"error\"],\n }),\n );\n }\n }\n\n if (value === \"error\") {\n yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"ResetAuthFlow\",\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n );\n yield* clearAuthCacheEffect(deps.authCache);\n return;\n }\n\n const signOutResult = yield* sendAuthFlowRequest(deps.actor, {\n _tag: \"SignOut\",\n ...depsRequestOptions(deps, options?.signal),\n }).pipe(\n Effect.provide(authFlowLayer(deps)),\n Effect.mapError((failure) => failure.publicError),\n Effect.either,\n );\n // Clear local cache regardless of server outcome.\n yield* clearAuthCacheEffect(deps.authCache);\n if (Either.isLeft(signOutResult)) {\n return yield* Effect.fail(signOutResult.left);\n }\n });\n\nexport const signOutProgram: Effect.Effect<void, CapxulError, CapxulDepsTag> =\n signOutProgramWithOptions();\n","// makeAuthMethods — TA12 imperative methods. Returns the `auth` bundle of\n// the CapxulClient surface.\n//\n// All five operations now collapse onto the hourglass `CapxulDeps` seam\n// (PRD #209): each method is a thin wrapper that runs its program\n// (`canSendOtpProgram` / `signInProgram` / `verifyOtpProgram` /\n// `signOutProgram` / `getSessionProgram`) through the shared `toCapxulResult`\n// bridge. The wrapper keeps the leading `signal.aborted` pre-check and threads\n// non-aborted signals into the programs; validate → precondition → actor-drive\n// → cache logic lives in the programs, which require ONLY `CapxulDepsTag`.\n\nimport { CapxulError, Errors } from \"@capxul/config\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport type { AuthClientPort, CanSendOtpStatus } from \"../ports/auth-client\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { ClockPort } from \"../ports/clock\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport {\n canSendOtpProgram,\n capxulDepsLayer,\n getSessionProgramWithOptions,\n signInProgram,\n signOutProgramWithOptions,\n verifyOtpProgram,\n} from \"./capxul-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, Session } from \"./types\";\n\nexport interface SignInOptions {\n readonly signal?: AbortSignal;\n}\n\nexport type AuthMethodOptions = SignInOptions;\n\nexport interface AuthMethods {\n canSendOtp(\n input: { readonly email: string },\n options?: AuthMethodOptions,\n ): Promise<CapxulResult<CanSendOtpStatus>>;\n signIn(\n input: { readonly email: string },\n options?: SignInOptions,\n ): Promise<CapxulResult<{ readonly sessionId: string; readonly expiresAt: number }>>;\n verifyOtp(\n input: {\n readonly email: string;\n readonly code: string;\n readonly signer?: ExternalSigner;\n },\n options?: AuthMethodOptions,\n ): Promise<CapxulResult<Session>>;\n signOut(options?: AuthMethodOptions): Promise<CapxulResult<void>>;\n getSession(options?: AuthMethodOptions): Promise<CapxulResult<Session | null>>;\n}\n\nexport interface MakeAuthMethodsDeps {\n readonly actor: AuthFlowActor;\n readonly authClient: AuthClientPort;\n readonly authCache: AuthCachePort;\n readonly clock: ClockPort;\n readonly telemetry?: TelemetryPort;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n readonly afterVerifyOtp?: () => Promise<void>;\n}\n\nexport function makeAuthMethods(deps: MakeAuthMethodsDeps): AuthMethods {\n return {\n async canSendOtp(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n // Hourglass seam (PRD #209): brand + auth-port call now live in\n // `canSendOtpProgram`, run through the shared bridge.\n return toCapxulResult(canSendOtpProgram(input, options), capxulDepsLayer(deps));\n },\n\n async signIn(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signIn\" }) };\n }\n // Hourglass seam (PRD #209): brand → precondition → RequestOtp → clock\n // logic now lives in `signInProgram`, run through the shared bridge.\n return toCapxulResult(signInProgram(input, options), capxulDepsLayer(deps));\n },\n\n async verifyOtp(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n // Hourglass seam (PRD #209, slice 3): the validate → precondition →\n // actor-drive → cache-write logic now lives in `verifyOtpProgram`, run\n // through the shared bridge.\n const result = await toCapxulResult(verifyOtpProgram(input, options), capxulDepsLayer(deps));\n if (!result.ok) {\n return result;\n }\n const afterVerifyOtp = deps.afterVerifyOtp;\n if (afterVerifyOtp === undefined) {\n return result;\n }\n try {\n await afterVerifyOtp();\n } catch (cause) {\n if (cause instanceof CapxulError) {\n return { ok: false, error: cause };\n }\n return {\n ok: false,\n error: Errors.providerError(\"sdk\", \"afterVerifyOtp\", cause),\n };\n }\n return result;\n },\n\n async signOut(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // Hourglass seam (PRD #209): the WRONG_STATE guard, error-reset, SignOut\n // drive, and cache-clear-regardless logic now live in `signOutProgram`,\n // run through the shared bridge.\n return toCapxulResult(signOutProgramWithOptions(options), capxulDepsLayer(deps));\n },\n\n async getSession(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n // Hourglass seam (PRD #209): the cache-first → actor-drive → snapshot\n // logic now lives in `getSessionProgram`, run through the shared bridge.\n return toCapxulResult(getSessionProgramWithOptions(options), capxulDepsLayer(deps));\n },\n };\n}\n","// Smart-account substrate — the `SmartAccountMethods` operations expressed as\n// Effect programs that resolve a single Context tag (PRD #209 hourglass\n// collapse, slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape:\n//\n// 1. `SmartAccountDeps` — the dependency bundle one Context tag\n// carries. Verbatim mirror of\n// `MakeSmartAccountMethodsDeps`\n// (`smart-account.ts`).\n// 2. `SmartAccountDepsTag` — the single tag the public methods\n// resolve via `toCapxulResult`.\n// 3. `smartAccountDepsLayer` — wraps a bundle as\n// `Layer<SmartAccountDepsTag>`.\n// 4. `loadSmartAccountProgram` — `smartAccount.loadCurrent` as a single\n// `Effect<SmartAccount | null,\n// CapxulError, SmartAccountDepsTag>`.\n// 5. `provisionSmartAccountProgram`— `smartAccount.provision` as an\n// input-parameterised program returning\n// `Effect<SmartAccount, CapxulError,\n// SmartAccountDepsTag>`.\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — reachable only via the\n// `@capxul/sdk/react-substrate` subpath. See\n// `.claude/rules/flow-internal-substrate.md`.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, ChainId } from \"@capxul/types\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { SmartAccount } from \"@capxul/types\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { emitProvisioningTelemetry } from \"./_shared/provisioning-telemetry\";\n\n/**\n * The dependency bundle a single `Context.Tag` carries (PRD #209). Verbatim\n * mirror of `MakeSmartAccountMethodsDeps` — kept structurally identical so a\n * `MakeSmartAccountMethodsDeps` value is assignable wherever a\n * `SmartAccountDeps` is expected.\n */\nexport interface SmartAccountDeps {\n readonly actor: AuthFlowActor;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: ChainId;\n readonly sessionAuthUserIdFallback?: AuthUserId | null;\n readonly telemetry?: TelemetryPort;\n}\n\n/** The single Context tag the `smartAccount.*` methods resolve. */\nexport class SmartAccountDepsTag extends Context.Tag(\"@capxul/sdk/SmartAccountDeps\")<\n SmartAccountDepsTag,\n SmartAccountDeps\n>() {}\n\n/** Wrap a bundle as the `Layer<SmartAccountDepsTag>` the React provider consumes. */\nexport function smartAccountDepsLayer(deps: SmartAccountDeps): Layer.Layer<SmartAccountDepsTag> {\n return Layer.succeed(SmartAccountDepsTag, deps);\n}\n\n/**\n * `smartAccount.loadCurrent` as a single Effect requiring ONLY\n * `SmartAccountDepsTag`. Faithful transcription of the current public method\n * body (`smart-account.ts`): snapshot the actor for the session authUserId,\n * append the optional sentinel fallback, and return the first non-null\n * `SmartAccountPort` row. The leading `signal.aborted` pre-check stays in the\n * thin method wrapper. Port failures narrow to their `publicError`.\n */\nexport const loadSmartAccountProgram: Effect.Effect<\n SmartAccount | null,\n CapxulError,\n SmartAccountDepsTag\n> = Effect.gen(function* () {\n const deps = yield* SmartAccountDepsTag;\n const snap = deps.actor.getSnapshot();\n const fallback = deps.sessionAuthUserIdFallback ?? null;\n const candidates: AuthUserId[] = [];\n if (snap.context.session?.authUserId !== undefined) {\n candidates.push(snap.context.session.authUserId);\n }\n if (fallback !== null) candidates.push(fallback);\n for (const candidate of candidates) {\n const row = yield* deps.smartAccountPort\n .loadByAuthUserId(candidate)\n .pipe(Effect.mapError((failure) => failure.publicError));\n if (row !== null) return row;\n }\n return null;\n});\n\n/**\n * `smartAccount.provision` as an input-parameterised program requiring ONLY\n * `SmartAccountDepsTag`. Faithful transcription of the current public method\n * body (`smart-account.ts`): precondition the actor on `authenticated`, brand\n * the external signer at entry, then drive the `SmartAccountPort.provision`\n * port. The leading `signal.aborted` pre-check stays in the thin method\n * wrapper (provision currently takes no signal, so there is none).\n */\nexport function provisionSmartAccountProgram(): Effect.Effect<\n SmartAccount,\n CapxulError,\n SmartAccountDepsTag\n> {\n return Effect.gen(function* () {\n const deps = yield* SmartAccountDepsTag;\n const snap = deps.actor.getSnapshot();\n const value = snap.value;\n if (value !== \"authenticated\") {\n return yield* Effect.fail(\n Errors.wrongState({\n method: \"smartAccount.provision\",\n currentState: value,\n validStates: [\"authenticated\"],\n }),\n );\n }\n const session = snap.context.session;\n if (session === null) {\n return yield* Effect.fail(Errors.notAuthenticated());\n }\n const provisioned = yield* deps.smartAccountPort\n .provision({ authUserId: session.authUserId, chainId: deps.chainId })\n .pipe(Effect.mapError((failure) => failure.publicError));\n yield* Effect.promise(() => emitProvisioningTelemetry(deps.telemetry, provisioned));\n return provisioned;\n });\n}\n","// makeSmartAccountMethods — TA12 imperative bundle. Read paths snapshot\n// from SmartAccountPort; provision drives ProvisioningFlow via the AuthFlow\n// actor's chainId closure (TA8 — chainId never crosses the consumer\n// boundary).\n//\n// Hourglass seam (PRD #209, slice 5): the snapshot/precondition/port logic now\n// lives in `loadSmartAccountProgram` + `provisionSmartAccountProgram`\n// (resolving `SmartAccountDepsTag`), run through the shared `toCapxulResult`\n// bridge. The `signal.aborted` pre-check stays here in the thin method wrapper.\n\nimport { Errors } from \"@capxul/config\";\nimport type { AuthUserId, ChainId } from \"@capxul/types\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport {\n loadSmartAccountProgram,\n provisionSmartAccountProgram,\n smartAccountDepsLayer,\n} from \"./smart-account-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, SmartAccount } from \"./types\";\n\nexport interface SmartAccountMethods {\n loadCurrent(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<SmartAccount | null>>;\n provision(input?: {\n readonly externalSigner?: ExternalSigner;\n }): Promise<CapxulResult<SmartAccount>>;\n}\n\nexport interface MakeSmartAccountMethodsDeps {\n readonly actor: AuthFlowActor;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: ChainId;\n readonly sessionAuthUserIdFallback?: AuthUserId | null;\n readonly telemetry?: TelemetryPort;\n}\n\nexport function makeSmartAccountMethods(deps: MakeSmartAccountMethodsDeps): SmartAccountMethods {\n return {\n async loadCurrent(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"smartAccount.loadCurrent\" }),\n };\n }\n return toCapxulResult(loadSmartAccountProgram, smartAccountDepsLayer(deps));\n },\n\n async provision(_input) {\n return toCapxulResult(provisionSmartAccountProgram(), smartAccountDepsLayer(deps));\n },\n };\n}\n","// Identity substrate — the `IdentityMethods` operations expressed as Effect\n// programs that resolve a single Context tag (PRD #209 hourglass collapse,\n// slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape for the auth surface:\n//\n// 1. `IdentityDeps` — the dependency bundle one Context tag\n// carries. Verbatim mirror of\n// `MakeIdentityMethodsDeps`\n// (`identity.ts`) so a method-deps value is\n// assignable wherever an `IdentityDeps` is\n// expected (and vice versa).\n// 2. `IdentityDepsTag` — the single tag both the public method (via\n// `toCapxulResult`) and the\n// profile resolution in reactive consumers.\n// 3. `identityDepsLayer` — wraps a bundle as `Layer<IdentityDepsTag>`.\n// 4. `loadIdentityProgram` — `identity.loadCurrent` as a single\n// `Effect<Profile | null, CapxulError,\n// IdentityDepsTag>`.\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — reachable only via the\n// `@capxul/sdk/react-substrate` subpath. See\n// `.claude/rules/flow-internal-substrate.md`.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport type { Profile } from \"@capxul/types\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport { identityErrorFromCapxul, type IdentityPort } from \"../ports/identity\";\n\n/**\n * The dependency bundle a single `Context.Tag` carries (PRD #209). Verbatim\n * mirror of `MakeIdentityMethodsDeps` — kept structurally identical so a\n * `MakeIdentityMethodsDeps` value is assignable wherever an `IdentityDeps` is\n * expected.\n */\nexport interface IdentityDeps {\n readonly identityPort: IdentityPort;\n readonly actor?: AuthFlowActor;\n}\n\n/** The single Context tag the profile atom + `identity.loadCurrent` resolve. */\nexport class IdentityDepsTag extends Context.Tag(\"@capxul/sdk/IdentityDeps\")<\n IdentityDepsTag,\n IdentityDeps\n>() {}\n\n/** Wrap a bundle as the `Layer<IdentityDepsTag>` the React provider consumes. */\nexport function identityDepsLayer(deps: IdentityDeps): Layer.Layer<IdentityDepsTag> {\n return Layer.succeed(IdentityDepsTag, deps);\n}\n\n/**\n * `identity.loadCurrent` as a single Effect requiring ONLY `IdentityDepsTag`.\n * Faithful transcription of the current public method body (`identity.ts`):\n * the leading `signal.aborted` pre-check stays in the thin method wrapper;\n * the program snapshots the actor session, then narrows the `IdentityPort`\n * failure to its `publicError`. Defects/sync-throws surface as `UNKNOWN`\n * through `toCapxulResult`'s `catchAllDefect` (and the atom's runtime), which\n * replaces the old outer `try/catch`.\n */\nexport const loadIdentityProgram: Effect.Effect<Profile | null, CapxulError, IdentityDepsTag> =\n Effect.gen(function* () {\n const deps = yield* IdentityDepsTag;\n\n if (deps.actor === undefined) {\n return yield* Effect.fail(Errors.notAuthenticated());\n }\n const snapshot = deps.actor.getSnapshot();\n const existingError = snapshot.context.error;\n if (existingError instanceof CapxulError) {\n return yield* Effect.fail(existingError);\n }\n const authUserId = snapshot.context.session?.authUserId;\n if (authUserId === undefined) {\n return null;\n }\n return yield* deps.identityPort.loadByAuthUserId(authUserId).pipe(\n Effect.catchAllDefect((cause) =>\n Effect.fail(\n identityErrorFromCapxul(\n \"loadByAuthUserId\",\n cause instanceof CapxulError ? cause : Errors.unknown(cause),\n cause,\n ),\n ),\n ),\n Effect.mapError((failure) => failure.publicError),\n );\n });\n","// makeIdentityMethods — TA12 imperative bundle. `loadCurrent` snapshots\n// from IdentityPort.\n//\n// Hourglass seam (PRD #209, slice 5): the snapshot-then-port logic now lives\n// in `loadIdentityProgram` (resolving `IdentityDepsTag`), run through the\n// shared `toCapxulResult` bridge. The `signal.aborted` pre-check stays here in\n// the thin method wrapper.\n\nimport { Errors } from \"@capxul/config\";\n\nimport type { AuthFlowActor } from \"../flows/auth\";\nimport type { IdentityPort } from \"../ports/identity\";\n\nimport { identityDepsLayer, loadIdentityProgram } from \"./identity-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, Profile } from \"./types\";\n\nexport interface IdentityMethods {\n loadCurrent(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Profile | null>>;\n}\n\nexport interface MakeIdentityMethodsDeps {\n readonly identityPort: IdentityPort;\n readonly actor?: AuthFlowActor;\n}\n\nexport function makeIdentityMethods(deps: MakeIdentityMethodsDeps): IdentityMethods {\n return {\n async loadCurrent(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"identity.loadCurrent\" }) };\n }\n return toCapxulResult(loadIdentityProgram, identityDepsLayer(deps));\n },\n };\n}\n","// Money-domain telemetry helpers for the SDK method bundles (M2).\n//\n// Mirrors `provisioning-telemetry.ts`: a thin, fire-and-forget bridge that\n// emits a catalogued `TelemetryEvent` through an optional `TelemetryPort`,\n// swallowing all failures (telemetry must never fail a money flow). The\n// producer split (which names the SDK emits vs which the backend emits) is\n// documented in `docs/canon/conventions/telemetry-spine.md` \"Money domain\".\n//\n// PII discipline (Aaron's locked decisions): sub-account NAMES never enter\n// telemetry. Props carry only branded ids (`sub_account_id`), WeiAmount\n// strings (never floats — `.claude/rules/numeric-parsing.md`), buckets, and\n// directions. Helpers here construct exactly those shapes.\n\nimport { Effect } from \"effect\";\n\nimport type { Money, SubAccountId } from \"@capxul/types\";\n\nimport { toWei } from \"../../money/to-wei\";\nimport type { TelemetryEvent, TelemetryPort } from \"../../ports/telemetry\";\n\n/**\n * Lower a consumer `Money` into a non-negative integer WeiAmount string for\n * telemetry props. Reuses the SDK boundary `toWei` (viem `parseUnits`, string\n * math only — never a float multiply per `.claude/rules/numeric-parsing.md`).\n */\nfunction moneyToWeiAmount(money: Money): string {\n return toWei(money);\n}\n\n/** \"out\" = sub → main, \"add\" = main → sub, \"between\" = sub → sub. */\ntype TransferDirection = \"add\" | \"out\" | \"between\";\n\nfunction transferDirection(from: string, to: string): TransferDirection {\n if (from === \"main\") return \"add\";\n if (to === \"main\") return \"out\";\n return \"between\";\n}\n\nexport type SubAccountOp = \"create\" | \"rename\" | \"delete\";\n\n/** Fire-and-forget emit through an optional port; never throws. */\nasync function emitMoneyTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry.emit(event).pipe(\n Effect.catchAll((cause) =>\n Effect.sync(() => reportMoneyTelemetryFailure(\"error\", event.name, cause)),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.sync(() => reportMoneyTelemetryFailure(\"defect\", event.name, cause)),\n ),\n ),\n );\n}\n\nexport function emitFaucetRequested(\n telemetry: TelemetryPort | undefined,\n input: { readonly amount: Money; readonly chainId: number },\n): Promise<void> {\n // Convert BEFORE the fire-and-forget emit, but guard it: a malformed amount\n // (parseUnits throw) must never escape into the money flow. Report + drop.\n let amount: string;\n try {\n amount = moneyToWeiAmount(input.amount);\n } catch (cause) {\n reportMoneyTelemetryFailure(\"defect\", \"faucet_requested\", cause);\n return Promise.resolve();\n }\n return emitMoneyTelemetry(telemetry, {\n name: \"faucet_requested\",\n props: { amount, chainId: input.chainId },\n });\n}\n\nexport function emitFaucetFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"faucet_failed\", props: { reason } });\n}\n\nexport function emitAccountBalanceFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"account_balance_failed\", props: { reason } });\n}\n\nexport function emitTransferRequested(\n telemetry: TelemetryPort | undefined,\n input: { readonly amount: Money; readonly from: string; readonly to: string },\n): Promise<void> {\n let amount: string;\n try {\n amount = moneyToWeiAmount(input.amount);\n } catch (cause) {\n reportMoneyTelemetryFailure(\"defect\", \"transfer_requested\", cause);\n return Promise.resolve();\n }\n return emitMoneyTelemetry(telemetry, {\n name: \"transfer_requested\",\n props: { amount, direction: transferDirection(input.from, input.to) },\n });\n}\n\nexport function emitTransferFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"transfer_failed\", props: { reason } });\n}\n\nexport function emitSubAccountCreated(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_created\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountRenamed(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_renamed\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountDeleted(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_deleted\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountOpFailed(\n telemetry: TelemetryPort | undefined,\n op: SubAccountOp,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_op_failed\",\n props: { op, reason },\n });\n}\n\nfunction reportMoneyTelemetryFailure(kind: \"error\" | \"defect\", name: string, cause: unknown): void {\n if (!isMoneyTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] money telemetry dropped\", { kind, name, cause });\n}\n\nfunction isMoneyTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError } from \"@capxul/config\";\nimport type { Account, ChainId, Money } from \"@capxul/types\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n emitAccountBalanceFailed,\n emitFaucetFailed,\n emitFaucetRequested,\n} from \"./_shared/money-telemetry\";\n\nexport interface AccountsDeps {\n readonly accountReadPort: AccountReadPort;\n readonly chainId: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class AccountsDepsTag extends Context.Tag(\"@capxul/sdk/AccountsDeps\")<\n AccountsDepsTag,\n AccountsDeps\n>() {}\n\nexport function accountsDepsLayer(deps: AccountsDeps): Layer.Layer<AccountsDepsTag> {\n return Layer.succeed(AccountsDepsTag, deps);\n}\n\nexport const readAccountProgram: Effect.Effect<Account, CapxulError, AccountsDepsTag> = Effect.gen(\n function* () {\n const deps = yield* AccountsDepsTag;\n // The server-confirmed `account_balance_read` is emitted backend-side\n // (`account/actions:readBalance`) — the balance is a server fact. The SDK\n // owns only the client-side `account_balance_failed` on a rejected read.\n const account = yield* deps.accountReadPort.readBalance({ chainId: deps.chainId }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitAccountBalanceFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n return account;\n },\n);\n\nexport function fundFromFaucetProgram(\n amount: Money,\n): Effect.Effect<{ readonly txHash: string }, CapxulError, AccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* AccountsDepsTag;\n // SDK producer for `faucet_requested` (before the backend mint). The\n // server-confirmed `faucet_confirmed` is emitted backend-side\n // (`account/actions:faucetMint`) after the mint receipt. Awaited (not\n // forked) on purpose: the SDK pins client-side telemetry causal ordering\n // (`faucet_requested` strictly before `faucet_failed`), asserted in\n // `money-telemetry-wiring.test.ts`, and mirrors the transfer flow's awaited\n // `emitTransferRequested`. \"Fire-and-forget\" here means the emit can never\n // THROW into the money flow (`emitMoneyTelemetry` swallows all failures),\n // not that it is detached.\n yield* Effect.promise(() =>\n emitFaucetRequested(deps.telemetry, { amount, chainId: deps.chainId }),\n );\n return yield* deps.accountReadPort.fundFromFaucet({ chainId: deps.chainId, amount }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitFaucetFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n });\n}\n","import { Errors } from \"@capxul/config\";\nimport type { ChainId } from \"@capxul/types\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport { accountsDepsLayer, fundFromFaucetProgram, readAccountProgram } from \"./accounts-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\nimport type { Account, Money } from \"@capxul/types\";\n\nexport interface AccountsMethods {\n read(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Account>>;\n}\n\n/**\n * Faucet surface (dev-only). Deliberately OFF the public `AccountsMethods`;\n * reachable only via `client._internal.accounts` (production-surface-policy.md).\n * The reference CLI uses it behind a test-env gate — consumers never see `fund`.\n */\nexport interface AccountsFaucetMethods {\n fund(\n amount: Money,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly txHash: string }>>;\n}\n\nexport type AccountsBundle = AccountsMethods & AccountsFaucetMethods;\n\nexport interface MakeAccountsMethodsDeps {\n readonly accountReadPort: AccountReadPort;\n readonly chainId: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * Build the accounts bundle. `assembleCapxulClient` exposes the public `read`\n * half at `client.accounts` (typed `AccountsMethods`) and the dev-only `fund`\n * half at `client._internal.accounts` (typed `AccountsFaucetMethods`), so the\n * faucet never appears on the public client surface.\n */\nexport function makeAccountsMethods(deps: MakeAccountsMethodsDeps): AccountsBundle {\n return {\n async read(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"accounts.read\" }),\n };\n }\n return toCapxulResult(readAccountProgram, accountsDepsLayer(deps));\n },\n async fund(amount, options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"accounts.fund\" }),\n };\n }\n return toCapxulResult(fundFromFaucetProgram(amount), accountsDepsLayer(deps));\n },\n };\n}\n","import { Effect, Either } from \"effect\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { Errors, type CapxulError } from \"@capxul/config\";\nimport type { LineItemV1, OnchainEvidence, PaymentDocumentEnvelopeV1 } from \"@capxul/wire\";\n\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport type { CapxulResult } from \"./types\";\n\nexport type RecipientResolutionKind = \"email\" | \"org\" | \"payee\";\n\nexport interface MeProfile {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly personalSafeAddress: string;\n // D2 (#564): a profile names WHO you are, not WHERE money settles. `chainId`\n // is custody substrate — dropped from the public surface. The deposit TARGET\n // chain lives on `DepositInstructions` (the payload), not here.\n}\n\nexport interface DepositInstructions {\n readonly accountKind: \"personalSafe\";\n readonly chainId: number;\n readonly network: \"base-sepolia\";\n readonly currency: \"USD\";\n readonly address: string;\n readonly label: string;\n}\n\nexport interface RecipientResolution {\n readonly kind: RecipientResolutionKind;\n readonly recipient: string;\n readonly label: string;\n readonly safeAddress: string;\n // Recipient identity is chain-agnostic (D1 · #563): a resolution names WHO is\n // paid, not WHERE it settles. The chain is the SettlementPort's concern,\n // supplied at settlement — so no `chainId` here.\n readonly payeeId?: string;\n readonly orgId?: string;\n readonly handle?: string;\n readonly email?: string;\n}\n\nexport interface Payee {\n readonly payeeId: string;\n readonly label: string;\n readonly recipientRef: string;\n readonly handle: string | null;\n readonly destinationKind: \"email\" | \"org\" | \"payeeHandle\";\n readonly safeAddress: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface MeMethods {\n get(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<MeProfile>>;\n depositInstructions(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DepositInstructions>>;\n}\n\nexport interface HandlesMethods {\n resolve(\n handle: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<RecipientResolution>>;\n}\n\nexport interface PayeesMethods {\n create(\n input: { readonly label: string; readonly recipient: string; readonly handle?: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payee>>;\n get(\n payeeId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payee | null>>;\n resolve(\n recipient: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<RecipientResolution>>;\n}\n\nexport interface PaymentMoney {\n readonly currency: string;\n readonly value: string;\n readonly decimals: number;\n}\n\nexport type PaymentStatus =\n | \"pending\"\n | \"submitted\"\n | \"pending_claim\"\n | \"scheduled\"\n | \"streaming\"\n | \"settled\"\n | \"cancelled\"\n | \"redirected\"\n | \"expired\"\n | \"failed\";\n\nexport type PaymentType = \"unspecified\" | \"invoice\" | \"payroll\" | \"reimbursement\";\n\nexport interface PaymentDocumentRef {\n readonly documentHash: string;\n readonly kind: \"memo\" | \"invoice\" | \"payslip\" | \"receipt\" | \"withdrawal\";\n readonly title?: string;\n readonly uri?: string;\n readonly issuedAt?: number;\n}\n\nexport type PaymentRelease =\n | { readonly kind: \"instant\" }\n | { readonly kind: \"scheduled\"; readonly at: number }\n | {\n readonly kind: \"stream\";\n readonly startsAt: number;\n readonly endsAt: number;\n readonly cliffAt?: number;\n };\n\nexport interface Payment {\n readonly id: string;\n readonly status: PaymentStatus;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly recipient: {\n readonly kind: \"handle\" | \"email\" | \"payee\" | \"me\" | \"org\" | \"external_address\";\n readonly label: string;\n readonly payeeId?: string;\n };\n readonly documents: readonly PaymentDocumentRef[];\n readonly release: PaymentRelease;\n readonly released: PaymentMoney;\n readonly availableToClaim: PaymentMoney;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface PaymentsPayInput {\n readonly to: string;\n readonly amount: PaymentMoney;\n /** Full EIP-712 document envelope; hashed + stored, committed on-chain. */\n readonly document?: PaymentDocumentEnvelopeV1;\n /**\n * Release clause (G3 · #546). Omitted ⇒ `instant` (the G2 direct-send path).\n * A `scheduled`/`stream` clause turns the payment into a Commitment\n * (escrow-vest-claim) backed by `CapxulPayments.createCommitment`.\n */\n readonly release?: PaymentRelease;\n /**\n * #592: itemized line items backing an Invoice `document`. The backend asserts\n * `hashLineItems(lineItems) === document.lineItemsHash` AND `Σ(quantity ×\n * unitMinor) === document.amount`, then persists the list for itemized render.\n */\n readonly lineItems?: readonly LineItemV1[];\n}\n\n/**\n * B3 withdraw / cash-out input. Stripe-shaped: `to` is the EXTERNAL 0x wallet\n * (the ONE place the SDK accepts a raw address — the pay lane never does),\n * `amount` is a Money, `document` is the REQUIRED kind:4 Withdrawal envelope\n * (carries the audit-visible destAddress). No chain / Safe / token / hash\n * custody substrate on the input. Returns a leak-safe `Payment` whose recipient\n * label is the redacted address — never the full 0x.\n */\nexport interface PaymentsWithdrawInput {\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document: PaymentDocumentEnvelopeV1;\n}\n\n// D2 (#564): on-chain settlement evidence (userOpHash + txHash) is the\n// `OnchainEvidence` brand — internal-channel only, never the public surface.\nexport interface PaymentSettlementInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/**\n * Host-execution callback recording the on-chain escrow of a commitment\n * (G3 · #546): `createCommitment` returned `onchainCommitmentId`, escrowing\n * the total. `onchainCommitmentId` + the userOp/tx hashes are internal evidence,\n * never on the wire (internal channel only).\n */\nexport interface CommitmentCreatedInput {\n readonly paymentId: string;\n readonly onchainCommitmentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/** Host-execution callback recording a recipient-side `claim` (G3 · #546). */\nexport interface CommitmentClaimInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/**\n * Host-execution callback recording a creator-side `cancel` (G3 · #546):\n * on-chain the unvested remainder returns to the creator; vested-unclaimed\n * stays the recipient's. An optional credit-note document is appended.\n */\nexport interface CommitmentCancelInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n readonly document?: PaymentDocumentEnvelopeV1;\n}\n\n/**\n * Host-execution callback recording a pre-claim `redirect` to a new validated\n * recipient (G3 · #546). `to` is a validated recipient (handle/email/payee id),\n * never a raw address.\n */\nexport interface CommitmentRedirectInput {\n readonly paymentId: string;\n readonly to: string;\n readonly evidence: OnchainEvidence;\n readonly document?: PaymentDocumentEnvelopeV1;\n}\n\n/**\n * Host-execution callback recording a settled ORG spend/payroll on the ONE\n * `payments` ledger (D3 · #565). An org spend is a KIND of Payment — it lands a\n * real `payments` row with `source:\"org\"` + `orgId` (no parallel `orgSpends`\n * table, no synthetic client-side fabrication). The signer-side host calls this\n * AFTER the on-chain Roles-modifier spend settles; `evidence` carries the\n * internal userOp/tx hashes (never wire fields). `recipient` is the validated\n * recipient ref label; `recipientSafeAddress` is internal evidence on the row.\n */\nexport interface OrgPaymentRecordInput {\n readonly orgId: string;\n readonly recipientLabel: string;\n readonly recipientSafeAddress: string;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly document?: PaymentDocumentEnvelopeV1;\n /** The org Safe the spend debited — bound as the `from` of the settlement transfer. */\n readonly orgSafeAddress: string;\n /**\n * 0-based occurrence among batch runs with the same (recipient, amount), so\n * each run binds to + de-dupes on its own on-chain `Transfer` (D3 · #565).\n */\n readonly occurrenceIndex: number;\n readonly evidence: OnchainEvidence;\n}\n\nexport interface PaymentDocumentVerification {\n readonly documentHash: string;\n readonly ok: boolean;\n readonly derivedHash: string;\n readonly kind: \"memo\" | \"invoice\" | \"payslip\" | \"receipt\" | \"withdrawal\";\n}\n\n/**\n * #577 render-on-demand result. `html` is self-contained user-visible document\n * HTML (stylesheet + rendered document). The MCP `paymentDocuments.render` tool\n * exposes only `{documentHash, kind, ok}` to the model and returns `html` in an\n * audience:[\"user\"] content block (#506 redaction matrix).\n */\nexport interface PaymentDocumentRender {\n readonly documentHash: string;\n readonly ok: boolean;\n readonly kind: \"memo\" | \"invoice\" | \"payslip\" | \"receipt\" | \"withdrawal\";\n readonly html: string;\n}\n\n/**\n * Internal commitment execution reference (G3 · #546). The on-chain\n * `onchainCommitmentId` is internal evidence (like userOp/tx hashes) — it never\n * appears on the wire `Payment` or any MCP tool output, but the signer-side host\n * needs it to build a claim/cancel/redirect UserOp. This is the server-internal\n * channel that carries it (and the recipient Safe address for an auto-claim\n * relayer), never a consumer-facing surface.\n */\nexport interface PaymentCommitmentRef {\n readonly paymentId: string;\n readonly onchainCommitmentId: string | null;\n readonly status: PaymentStatus;\n}\n\n/**\n * The host-execution + on-chain-evidence channel for Payments (D2 · #564).\n * SPLIT OFF the public `PaymentsMethods` so an external builder consuming\n * `@capxul/sdk` directly never sees the custody substrate. Reached only via\n * `client.payments._internal` (mirrors `client._internal.*`); the signer-side\n * host (the dev MCP edge / a self-custody integrator) drives it AFTER executing\n * a UserOp. Every input carries the `OnchainEvidence` brand — never a wire field.\n */\nexport interface PaymentsInternalMethods {\n /** Report on-chain settlement evidence for an instant payment. */\n markSettled(\n input: PaymentSettlementInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * B3: report on-chain settlement evidence for a withdraw/cash-out. The\n * backend binds the userOp to a matching external `Transfer` before settling.\n */\n markWithdrawalSettled(\n input: PaymentSettlementInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Record the on-chain escrow of a commitment after `createCommitment` returns\n * its `onchainCommitmentId` (G3 · #546).\n */\n markCommitmentCreated(\n input: CommitmentCreatedInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Record a settled ORG spend/payroll on the one `payments` ledger\n * (D3 · #565) — `source:\"org\"` + `orgId`, read back as a leak-safe Payment.\n */\n recordOrgPayment(\n input: OrgPaymentRecordInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a recipient-side `claim` after the on-chain claim UserOp settles. */\n claim(\n input: CommitmentClaimInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a creator-side `cancel` reclaiming only the unvested remainder. */\n cancel(\n input: CommitmentCancelInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a pre-claim `redirect` to a new validated recipient. */\n redirect(\n input: CommitmentRedirectInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * The on-chain commitment reference the signer-side host needs to build a\n * claim/cancel/redirect UserOp. `onchainCommitmentId` is internal evidence.\n */\n commitmentRef(\n paymentId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentCommitmentRef | null>>;\n}\n\n/**\n * The PUBLIC, Stripe-shaped Payments surface (D2 · #564). Genus verbs only —\n * `pay` / `list` / `get`. No `userOpHash` / `txHash` / `onchainCommitmentId` /\n * `chainId` / `safeAddress`. Host-execution + on-chain evidence live on the\n * `_internal` channel below; an external builder never touches custody substrate.\n */\nexport interface PaymentsMethods {\n pay(\n input: PaymentsPayInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * B3 withdraw / cash-out: send USDX from the user's custody Safe to an\n * external 0x wallet, minting a kind:4 Withdrawal document. Returns a\n * leak-safe `Payment` (recipient label is the redacted address).\n */\n withdraw(\n input: PaymentsWithdrawInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n list(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly Payment[]>>;\n get(\n paymentId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment | null>>;\n /**\n * Host-execution + on-chain-evidence channel — off the public surface\n * (production-surface-policy.md pattern). Self-custody integrators drive this;\n * a Stripe-shaped consumer never does.\n *\n * @internal-use\n */\n readonly _internal: PaymentsInternalMethods;\n}\n\nexport interface PaymentDocumentsMethods {\n verify(\n documentHash: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDocumentVerification>>;\n /**\n * #577: render-on-demand. Loads the owner's stored document by `documentHash`,\n * re-verifies its EIP-712 hash, and renders it to self-contained HTML using the\n * verified stored line items. Returns `{documentHash, kind, ok, html}`.\n */\n render(\n documentHash: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDocumentRender>>;\n}\n\n// ── Receivables (G5 · #548) ──────────────────────────────────────────────────\n// A PaymentRequest is the inverse of a Payment — money owed to the owner.\n// Lifecycle draft→sent→viewed→paid, with cancelled/expired off-ramps. Collection\n// settles the receivable into the Payment ledger and mints a receipt document\n// linked by `documentHash`. Leak-safe: only `documentHash` ever crosses.\n\nexport type PaymentRequestStatus = \"draft\" | \"sent\" | \"viewed\" | \"paid\" | \"expired\" | \"cancelled\";\n\nexport interface PaymentRequest {\n readonly id: string;\n readonly status: PaymentRequestStatus;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo: string | null;\n /** Fixed-amount payment link token (HITL #519: basic, not replay-hardened). */\n readonly linkToken: string;\n /** Minimal entitlement (HITL #501): true once paid. */\n readonly entitlementGranted: boolean;\n /** The Payment this receivable settled into (set on collect). */\n readonly settledPaymentId: string | null;\n /** The receipt document committed for this receivable (set on collect). */\n readonly receiptDocumentHash: string | null;\n readonly expiresAt: number | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface ReconciliationEntry {\n readonly paymentRequestId: string;\n readonly reference: string;\n readonly status: \"paid\" | \"exception\";\n readonly settledPaymentId: string | null;\n readonly receiptDocumentHash: string | null;\n}\n\nexport interface PaymentRequestsCreateInput {\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo?: string;\n /** Optional expiry (epoch ms). HITL #519: expiry policy is a basic timestamp. */\n readonly expiresAt?: number;\n}\n\nexport interface PaymentRequestsMethods {\n /** Open a receivable in `draft` with a fixed-amount payment link. */\n create(\n input: PaymentRequestsCreateInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest>>;\n markSent(\n paymentRequestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest>>;\n markViewed(\n paymentRequestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest>>;\n cancel(\n paymentRequestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest>>;\n /**\n * Collect the receivable (HERMETIC until a live inbound path exists): settle\n * it into the Payment ledger and mint a receipt linked by `documentHash`.\n */\n collect(\n paymentRequestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest>>;\n list(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly PaymentRequest[]>>;\n get(\n paymentRequestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest | null>>;\n getByLink(\n linkToken: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentRequest | null>>;\n /** Inbound reconciliation: paid / exception status per receivable. */\n reconcile(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly ReconciliationEntry[]>>;\n}\n\n// ── Workbench (G6 · #549) ────────────────────────────────────────────────────\n\nexport type PaymentDraftStatus =\n | \"draft\"\n | \"simulated\"\n | \"approval_pending\"\n | \"approved\"\n | \"executed\"\n | \"cancelled\"\n | \"expired\";\n\n/** The leak-safe, model-visible draft/approval (#506). */\nexport interface PaymentDraft {\n readonly id: string;\n readonly status: PaymentDraftStatus;\n readonly recipient: { readonly kind: string; readonly label: string };\n readonly amount: PaymentMoney;\n readonly documentHash: string | null;\n /** The canonical-plan binding fingerprint (set at approvals.request). */\n readonly planHash: string | null;\n /** The opaque read-model version the draft was simulated against (stale-state). */\n readonly readModelVersion: string;\n readonly idempotencyKey: string;\n readonly policyDecision: \"allow\" | \"deny\";\n readonly expiresAt: number | null;\n readonly settledPaymentId: string | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface WorkbenchDraftInput {\n readonly clientId: string;\n readonly audience: string;\n readonly scopes: readonly string[];\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly idempotencyKey: string;\n /** Untrusted connector/model suggestion blob (default-deny taint). */\n readonly tainted?: Record<string, unknown>;\n}\n\nexport interface WorkbenchMintResult {\n readonly approvalToken: string;\n readonly planHash: string;\n readonly expiresAt: number;\n}\n\nexport interface WorkbenchExecuteInput {\n readonly draftId: string;\n readonly clientId: string;\n readonly approvalToken: string;\n readonly readModelVersion: string;\n readonly userOpHash: string;\n readonly txHash: string;\n}\n\n/**\n * The decomposed workbench (G6 · #549). The edge PROPOSES (draft → simulate →\n * request); the BACKEND mints the one-time plan-bound token via the human's\n * browser (`mint`); `execute` consumes it. `mint` is the human step — the edge\n * normally only reaches `request`, then hands the human a browser URL.\n */\nexport interface WorkbenchMethods {\n draft(\n input: WorkbenchDraftInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDraft>>;\n simulate(\n draftId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDraft>>;\n requestApproval(\n draftId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDraft>>;\n /**\n * THE HUMAN STEP: mint the one-time approval token (browser/approval app).\n * F2 (#549): the backend gates minting on a human-origin `capability` the\n * agent/edge does NOT possess (`CAPXUL_APPROVAL_CAPABILITY`); only the\n * apps/approve browser app passes it. The edge/SDK lane cannot self-approve.\n */\n mint(\n draftId: string,\n capability: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<WorkbenchMintResult>>;\n execute(\n input: WorkbenchExecuteInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n status(\n draftId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDraft | null>>;\n cancel(\n draftId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDraft>>;\n}\n\nexport interface FinancialOpsMethods {\n readonly me: MeMethods;\n readonly handles: HandlesMethods;\n readonly payees: PayeesMethods;\n readonly payments: PaymentsMethods;\n readonly paymentDocuments: PaymentDocumentsMethods;\n /** Receivables surface (G5 · #548). */\n readonly paymentRequests: PaymentRequestsMethods;\n /** Decomposed workbench + trust substrate (G6 · #549). */\n readonly workbench: WorkbenchMethods;\n}\n\ntype FinancialOpsFunctions = {\n readonly me: FunctionReference<\"query\", \"public\", Record<string, never>, MeProfile>;\n readonly depositInstructions: FunctionReference<\n \"query\",\n \"public\",\n Record<string, never>,\n DepositInstructions\n >;\n readonly resolveHandle: FunctionReference<\n \"query\",\n \"public\",\n { readonly handle: string },\n RecipientResolution\n >;\n readonly createPayee: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly label: string; readonly recipient: string; readonly handle?: string },\n Payee\n >;\n readonly getPayee: FunctionReference<\n \"query\",\n \"public\",\n { readonly payeeId: string },\n Payee | null\n >;\n readonly resolvePayee: FunctionReference<\n \"query\",\n \"public\",\n { readonly recipient: string },\n RecipientResolution\n >;\n readonly pay: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly release?: PaymentRelease;\n },\n Payment\n >;\n readonly withdraw: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document: PaymentDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly markPaymentSettled: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly markWithdrawalSettled: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly recordOrgPayment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly recipientLabel: string;\n readonly recipientSafeAddress: string;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly orgSafeAddress: string;\n readonly occurrenceIndex: number;\n readonly userOpHash: string;\n readonly txHash: string;\n },\n Payment\n >;\n readonly markCommitmentCreated: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly onchainCommitmentId: string;\n readonly userOpHash: string;\n readonly txHash: string;\n },\n Payment\n >;\n readonly claimCommitment: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly cancelCommitment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly userOpHash: string;\n readonly txHash: string;\n readonly document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly redirectCommitment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly to: string;\n readonly userOpHash: string;\n readonly txHash: string;\n readonly document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly listPayments: FunctionReference<\"query\", \"public\", Record<string, never>, Payment[]>;\n readonly getPayment: FunctionReference<\n \"query\",\n \"public\",\n { readonly paymentId: string },\n Payment | null\n >;\n readonly verifyPaymentDocument: FunctionReference<\n \"query\",\n \"public\",\n { readonly documentHash: string },\n PaymentDocumentVerification\n >;\n readonly renderStoredDocument: FunctionReference<\n \"query\",\n \"public\",\n { readonly documentHash: string },\n PaymentDocumentRender\n >;\n readonly getCommitmentRef: FunctionReference<\n \"query\",\n \"public\",\n { readonly paymentId: string },\n PaymentCommitmentRef | null\n >;\n // Receivables (G5 · #548).\n readonly createRequest: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo?: string;\n readonly expiresAt?: number;\n },\n PaymentRequest\n >;\n readonly markRequestSent: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly paymentRequestId: string },\n PaymentRequest\n >;\n readonly markRequestViewed: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly paymentRequestId: string },\n PaymentRequest\n >;\n readonly cancelRequest: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly paymentRequestId: string },\n PaymentRequest\n >;\n readonly collectRequest: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly paymentRequestId: string },\n PaymentRequest\n >;\n readonly listRequests: FunctionReference<\n \"query\",\n \"public\",\n Record<string, never>,\n PaymentRequest[]\n >;\n readonly getRequest: FunctionReference<\n \"query\",\n \"public\",\n { readonly paymentRequestId: string },\n PaymentRequest | null\n >;\n readonly getRequestByLink: FunctionReference<\n \"query\",\n \"public\",\n { readonly linkToken: string },\n PaymentRequest | null\n >;\n readonly reconcileRequests: FunctionReference<\n \"query\",\n \"public\",\n Record<string, never>,\n ReconciliationEntry[]\n >;\n // Workbench (G6 · #549).\n readonly draftPayment: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly clientId: string;\n readonly audience: string;\n readonly scopes: readonly string[];\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly idempotencyKey: string;\n readonly tainted?: Record<string, unknown>;\n },\n PaymentDraft\n >;\n readonly simulatePayment: FunctionReference<\n \"action\",\n \"public\",\n { readonly draftId: string },\n PaymentDraft\n >;\n readonly requestApproval: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly draftId: string },\n PaymentDraft\n >;\n readonly mintApprovalToken: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly draftId: string; readonly capability: string },\n WorkbenchMintResult\n >;\n readonly executePayment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly draftId: string;\n readonly clientId: string;\n readonly approvalToken: string;\n readonly readModelVersion: string;\n readonly userOpHash: string;\n readonly txHash: string;\n },\n Payment\n >;\n readonly getDraft: FunctionReference<\n \"query\",\n \"public\",\n { readonly draftId: string },\n PaymentDraft | null\n >;\n readonly cancelApproval: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly draftId: string },\n PaymentDraft\n >;\n};\n\nconst DEFAULT_FUNCTIONS: FinancialOpsFunctions = {\n me: makeFunctionReference<\"query\", Record<string, never>, MeProfile>(\"financialOps/queries:me\"),\n depositInstructions: makeFunctionReference<\"query\", Record<string, never>, DepositInstructions>(\n \"financialOps/queries:depositInstructions\",\n ),\n resolveHandle: makeFunctionReference<\"query\", { handle: string }, RecipientResolution>(\n \"financialOps/queries:resolveHandle\",\n ),\n createPayee: makeFunctionReference<\n \"mutation\",\n { label: string; recipient: string; handle?: string },\n Payee\n >(\"financialOps/mutations:createPayee\"),\n getPayee: makeFunctionReference<\"query\", { payeeId: string }, Payee | null>(\n \"financialOps/queries:getPayee\",\n ),\n resolvePayee: makeFunctionReference<\"query\", { recipient: string }, RecipientResolution>(\n \"financialOps/queries:resolvePayee\",\n ),\n pay: makeFunctionReference<\n \"mutation\",\n {\n to: string;\n amount: PaymentMoney;\n document?: PaymentDocumentEnvelopeV1;\n release?: PaymentRelease;\n lineItems?: readonly LineItemV1[];\n },\n Payment\n >(\"financialOps/mutations:pay\"),\n withdraw: makeFunctionReference<\n \"mutation\",\n { to: string; amount: PaymentMoney; document: PaymentDocumentEnvelopeV1 },\n Payment\n >(\"financialOps/mutations:withdraw\"),\n markPaymentSettled: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(\"financialOps/actions:markPaymentSettled\"),\n markWithdrawalSettled: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(\"financialOps/actions:markWithdrawalSettled\"),\n recordOrgPayment: makeFunctionReference<\n \"action\",\n {\n orgId: string;\n recipientLabel: string;\n recipientSafeAddress: string;\n amount: PaymentMoney;\n paymentType: PaymentType;\n document?: PaymentDocumentEnvelopeV1;\n orgSafeAddress: string;\n occurrenceIndex: number;\n userOpHash: string;\n txHash: string;\n },\n Payment\n >(\"financialOps/actions:recordOrgPayment\"),\n markCommitmentCreated: makeFunctionReference<\n \"action\",\n { paymentId: string; onchainCommitmentId: string; userOpHash: string; txHash: string },\n Payment\n >(\"financialOps/actions:markCommitmentCreated\"),\n claimCommitment: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(\"financialOps/actions:claimCommitment\"),\n cancelCommitment: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string; document?: PaymentDocumentEnvelopeV1 },\n Payment\n >(\"financialOps/actions:cancelCommitment\"),\n redirectCommitment: makeFunctionReference<\n \"action\",\n {\n paymentId: string;\n to: string;\n userOpHash: string;\n txHash: string;\n document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >(\"financialOps/actions:redirectCommitment\"),\n listPayments: makeFunctionReference<\"query\", Record<string, never>, Payment[]>(\n \"financialOps/queries:listPayments\",\n ),\n getPayment: makeFunctionReference<\"query\", { paymentId: string }, Payment | null>(\n \"financialOps/queries:getPayment\",\n ),\n verifyPaymentDocument: makeFunctionReference<\n \"query\",\n { documentHash: string },\n PaymentDocumentVerification\n >(\"financialOps/queries:verifyPaymentDocument\"),\n renderStoredDocument: makeFunctionReference<\n \"query\",\n { documentHash: string },\n PaymentDocumentRender\n >(\"financialOps/queries:renderStoredDocument\"),\n getCommitmentRef: makeFunctionReference<\n \"query\",\n { paymentId: string },\n PaymentCommitmentRef | null\n >(\"financialOps/queries:getCommitmentRef\"),\n createRequest: makeFunctionReference<\n \"mutation\",\n { amount: PaymentMoney; reference: string; memo?: string; expiresAt?: number },\n PaymentRequest\n >(\"financialOps/receivablesMutations:createRequest\"),\n markRequestSent: makeFunctionReference<\"mutation\", { paymentRequestId: string }, PaymentRequest>(\n \"financialOps/receivablesMutations:markSent\",\n ),\n markRequestViewed: makeFunctionReference<\n \"mutation\",\n { paymentRequestId: string },\n PaymentRequest\n >(\"financialOps/receivablesMutations:markViewed\"),\n cancelRequest: makeFunctionReference<\"mutation\", { paymentRequestId: string }, PaymentRequest>(\n \"financialOps/receivablesMutations:cancel\",\n ),\n collectRequest: makeFunctionReference<\"mutation\", { paymentRequestId: string }, PaymentRequest>(\n \"financialOps/receivablesMutations:collect\",\n ),\n listRequests: makeFunctionReference<\"query\", Record<string, never>, PaymentRequest[]>(\n \"financialOps/receivablesQueries:listRequests\",\n ),\n getRequest: makeFunctionReference<\"query\", { paymentRequestId: string }, PaymentRequest | null>(\n \"financialOps/receivablesQueries:getRequest\",\n ),\n getRequestByLink: makeFunctionReference<\"query\", { linkToken: string }, PaymentRequest | null>(\n \"financialOps/receivablesQueries:getRequestByLink\",\n ),\n reconcileRequests: makeFunctionReference<\"query\", Record<string, never>, ReconciliationEntry[]>(\n \"financialOps/receivablesQueries:reconcile\",\n ),\n draftPayment: makeFunctionReference<\n \"mutation\",\n {\n clientId: string;\n audience: string;\n scopes: readonly string[];\n to: string;\n amount: PaymentMoney;\n document?: PaymentDocumentEnvelopeV1;\n idempotencyKey: string;\n tainted?: Record<string, unknown>;\n },\n PaymentDraft\n >(\"financialOps/workbenchMutations:draftPayment\"),\n simulatePayment: makeFunctionReference<\"action\", { draftId: string }, PaymentDraft>(\n \"financialOps/workbenchActions:simulatePayment\",\n ),\n requestApproval: makeFunctionReference<\"mutation\", { draftId: string }, PaymentDraft>(\n \"financialOps/workbenchMutations:requestApproval\",\n ),\n mintApprovalToken: makeFunctionReference<\n \"mutation\",\n { draftId: string; capability: string },\n WorkbenchMintResult\n >(\"financialOps/workbenchMutations:mintApprovalToken\"),\n executePayment: makeFunctionReference<\n \"action\",\n {\n draftId: string;\n clientId: string;\n approvalToken: string;\n readModelVersion: string;\n userOpHash: string;\n txHash: string;\n },\n Payment\n >(\"financialOps/workbenchActions:executePayment\"),\n getDraft: makeFunctionReference<\"query\", { draftId: string }, PaymentDraft | null>(\n \"financialOps/workbenchQueries:getDraft\",\n ),\n cancelApproval: makeFunctionReference<\"mutation\", { draftId: string }, PaymentDraft>(\n \"financialOps/workbenchMutations:cancelApproval\",\n ),\n};\n\nexport function makeFinancialOpsMethods(deps: {\n readonly convexCall: ConvexCallPort;\n readonly functions?: FinancialOpsFunctions;\n}): FinancialOpsMethods {\n const fns = deps.functions ?? DEFAULT_FUNCTIONS;\n return {\n me: {\n get: (options) =>\n runIfActive(options?.signal, \"me.get\", () => deps.convexCall.query(fns.me, {})),\n depositInstructions: (options) =>\n runIfActive(options?.signal, \"me.depositInstructions\", () =>\n deps.convexCall.query(fns.depositInstructions, {}),\n ),\n },\n handles: {\n resolve: (handle, options) =>\n runIfActive(options?.signal, \"handles.resolve\", () =>\n deps.convexCall.query(fns.resolveHandle, { handle }),\n ),\n },\n payees: {\n create: (input, options) =>\n runIfActive(options?.signal, \"payees.create\", () =>\n deps.convexCall.mutation(fns.createPayee, {\n label: input.label,\n recipient: input.recipient,\n ...(input.handle === undefined ? {} : { handle: input.handle }),\n }),\n ),\n get: (payeeId, options) =>\n runIfActive(options?.signal, \"payees.get\", () =>\n deps.convexCall.query(fns.getPayee, { payeeId }),\n ),\n resolve: (recipient, options) =>\n runIfActive(options?.signal, \"payees.resolve\", () =>\n deps.convexCall.query(fns.resolvePayee, { recipient }),\n ),\n },\n payments: {\n pay: (input, options) =>\n runIfActive(options?.signal, \"payments.pay\", () =>\n deps.convexCall.mutation(fns.pay, {\n to: input.to,\n amount: input.amount,\n ...(input.document === undefined ? {} : { document: input.document }),\n ...(input.release === undefined ? {} : { release: input.release }),\n ...(input.lineItems === undefined ? {} : { lineItems: input.lineItems }),\n }),\n ),\n withdraw: (input, options) =>\n runIfActive(options?.signal, \"payments.withdraw\", () =>\n deps.convexCall.mutation(fns.withdraw, {\n to: input.to,\n amount: input.amount,\n document: input.document,\n }),\n ),\n list: (options) =>\n runIfActive(options?.signal, \"payments.list\", () =>\n deps.convexCall.query(fns.listPayments, {}),\n ),\n get: (paymentId, options) =>\n runIfActive(options?.signal, \"payments.get\", () =>\n deps.convexCall.query(fns.getPayment, { paymentId }),\n ),\n // D2 (#564): the host-execution + on-chain-evidence channel. Off the\n // public surface; the backend actions still receive the raw userOp/tx\n // hashes (behavior-preserving) — they are unwrapped from the brand here.\n _internal: {\n markSettled: (input, options) =>\n runIfActive(options?.signal, \"payments.markSettled\", () =>\n deps.convexCall.action(fns.markPaymentSettled, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n // B3: report withdraw/cash-out settlement evidence (external transfer).\n markWithdrawalSettled: (input, options) =>\n runIfActive(options?.signal, \"payments.markWithdrawalSettled\", () =>\n deps.convexCall.action(fns.markWithdrawalSettled, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n // D3 (#565): record a settled org spend on the one ledger (source:\"org\").\n recordOrgPayment: (input, options) =>\n runIfActive(options?.signal, \"payments.recordOrgPayment\", () =>\n deps.convexCall.action(fns.recordOrgPayment, {\n orgId: input.orgId,\n recipientLabel: input.recipientLabel,\n recipientSafeAddress: input.recipientSafeAddress,\n amount: input.amount,\n paymentType: input.paymentType,\n ...(input.document === undefined ? {} : { document: input.document }),\n orgSafeAddress: input.orgSafeAddress,\n occurrenceIndex: input.occurrenceIndex,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n markCommitmentCreated: (input, options) =>\n runIfActive(options?.signal, \"payments.markCommitmentCreated\", () =>\n deps.convexCall.action(fns.markCommitmentCreated, {\n paymentId: input.paymentId,\n onchainCommitmentId: input.onchainCommitmentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n claim: (input, options) =>\n runIfActive(options?.signal, \"payments.claim\", () =>\n deps.convexCall.action(fns.claimCommitment, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n cancel: (input, options) =>\n runIfActive(options?.signal, \"payments.cancel\", () =>\n deps.convexCall.action(fns.cancelCommitment, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n ...(input.document === undefined ? {} : { document: input.document }),\n }),\n ),\n redirect: (input, options) =>\n runIfActive(options?.signal, \"payments.redirect\", () =>\n deps.convexCall.action(fns.redirectCommitment, {\n paymentId: input.paymentId,\n to: input.to,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n ...(input.document === undefined ? {} : { document: input.document }),\n }),\n ),\n commitmentRef: (paymentId, options) =>\n runIfActive(options?.signal, \"payments.commitmentRef\", () =>\n deps.convexCall.query(fns.getCommitmentRef, { paymentId }),\n ),\n },\n },\n paymentDocuments: {\n verify: (documentHash, options) =>\n runIfActive(options?.signal, \"paymentDocuments.verify\", () =>\n deps.convexCall.query(fns.verifyPaymentDocument, { documentHash }),\n ),\n render: (documentHash, options) =>\n runIfActive(options?.signal, \"paymentDocuments.render\", () =>\n deps.convexCall.query(fns.renderStoredDocument, { documentHash }),\n ),\n },\n paymentRequests: {\n create: (input, options) =>\n runIfActive(options?.signal, \"paymentRequests.create\", () =>\n deps.convexCall.mutation(fns.createRequest, {\n amount: input.amount,\n reference: input.reference,\n ...(input.memo === undefined ? {} : { memo: input.memo }),\n ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),\n }),\n ),\n markSent: (paymentRequestId, options) =>\n runIfActive(options?.signal, \"paymentRequests.markSent\", () =>\n deps.convexCall.mutation(fns.markRequestSent, { paymentRequestId }),\n ),\n markViewed: (paymentRequestId, options) =>\n runIfActive(options?.signal, \"paymentRequests.markViewed\", () =>\n deps.convexCall.mutation(fns.markRequestViewed, { paymentRequestId }),\n ),\n cancel: (paymentRequestId, options) =>\n runIfActive(options?.signal, \"paymentRequests.cancel\", () =>\n deps.convexCall.mutation(fns.cancelRequest, { paymentRequestId }),\n ),\n collect: (paymentRequestId, options) =>\n runIfActive(options?.signal, \"paymentRequests.collect\", () =>\n deps.convexCall.mutation(fns.collectRequest, { paymentRequestId }),\n ),\n list: (options) =>\n runIfActive(options?.signal, \"paymentRequests.list\", () =>\n deps.convexCall.query(fns.listRequests, {}),\n ),\n get: (paymentRequestId, options) =>\n runIfActive(options?.signal, \"paymentRequests.get\", () =>\n deps.convexCall.query(fns.getRequest, { paymentRequestId }),\n ),\n getByLink: (linkToken, options) =>\n runIfActive(options?.signal, \"paymentRequests.getByLink\", () =>\n deps.convexCall.query(fns.getRequestByLink, { linkToken }),\n ),\n reconcile: (options) =>\n runIfActive(options?.signal, \"paymentRequests.reconcile\", () =>\n deps.convexCall.query(fns.reconcileRequests, {}),\n ),\n },\n workbench: {\n draft: (input, options) =>\n runIfActive(options?.signal, \"workbench.draft\", () =>\n deps.convexCall.mutation(fns.draftPayment, {\n clientId: input.clientId,\n audience: input.audience,\n scopes: input.scopes,\n to: input.to,\n amount: input.amount,\n idempotencyKey: input.idempotencyKey,\n ...(input.document === undefined ? {} : { document: input.document }),\n ...(input.tainted === undefined ? {} : { tainted: input.tainted }),\n }),\n ),\n simulate: (draftId, options) =>\n runIfActive(options?.signal, \"workbench.simulate\", () =>\n deps.convexCall.action(fns.simulatePayment, { draftId }),\n ),\n requestApproval: (draftId, options) =>\n runIfActive(options?.signal, \"workbench.requestApproval\", () =>\n deps.convexCall.mutation(fns.requestApproval, { draftId }),\n ),\n mint: (draftId, capability, options) =>\n runIfActive(options?.signal, \"workbench.mint\", () =>\n deps.convexCall.mutation(fns.mintApprovalToken, { draftId, capability }),\n ),\n execute: (input, options) =>\n runIfActive(options?.signal, \"workbench.execute\", () =>\n deps.convexCall.action(fns.executePayment, {\n draftId: input.draftId,\n clientId: input.clientId,\n approvalToken: input.approvalToken,\n readModelVersion: input.readModelVersion,\n userOpHash: input.userOpHash,\n txHash: input.txHash,\n }),\n ),\n status: (draftId, options) =>\n runIfActive(options?.signal, \"workbench.status\", () =>\n deps.convexCall.query(fns.getDraft, { draftId }),\n ),\n cancel: (draftId, options) =>\n runIfActive(options?.signal, \"workbench.cancel\", () =>\n deps.convexCall.mutation(fns.cancelApproval, { draftId }),\n ),\n },\n };\n}\n\nasync function runIfActive<T>(\n signal: AbortSignal | undefined,\n operation: string,\n effect: () => Effect.Effect<T, { readonly publicError: CapxulError }>,\n): Promise<CapxulResult<T>> {\n if (signal?.aborted === true) {\n return { ok: false, error: Errors.cancelled({ operation }) };\n }\n const result = await Effect.runPromise(\n effect().pipe(\n Effect.mapError((error) => error.publicError),\n Effect.catchAllDefect((defect) => Effect.fail(Errors.unknown(defect))),\n Effect.either,\n ),\n );\n if (Either.isLeft(result)) return { ok: false, error: result.left };\n return { ok: true, value: result.right };\n}\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError } from \"@capxul/config\";\nimport type { AccountId, SubAccount, SubAccountId } from \"@capxul/types\";\n\nimport type { SubAccountPort, TransferInput, TransferResult } from \"../ports/sub-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n emitSubAccountCreated,\n emitSubAccountDeleted,\n emitSubAccountOpFailed,\n emitSubAccountRenamed,\n emitTransferFailed,\n emitTransferRequested,\n} from \"./_shared/money-telemetry\";\n\nexport interface SubAccountsDeps {\n readonly subAccountPort: SubAccountPort;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class SubAccountsDepsTag extends Context.Tag(\"@capxul/sdk/SubAccountsDeps\")<\n SubAccountsDepsTag,\n SubAccountsDeps\n>() {}\n\nexport function subAccountsDepsLayer(deps: SubAccountsDeps): Layer.Layer<SubAccountsDepsTag> {\n return Layer.succeed(SubAccountsDepsTag, deps);\n}\n\nexport function createSubAccountProgram(\n accountId: AccountId,\n name: string,\n): Effect.Effect<SubAccount, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // `subaccount_created` is SDK-emitted on the server-confirmed row: the\n // backend write site is a Convex MUTATION, which cannot `fetch` PostHog\n // (V8 transactional runtime). Per the truth-source principle the returned\n // row IS the confirmed fact, so the SDK emits it the instant it lands. The\n // NAME never enters telemetry — only the branded `sub_account_id`. See\n // docs/canon/conventions/telemetry-spine.md \"Money domain\".\n const created = yield* deps.subAccountPort.create({ accountId, name }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"create\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountCreated(deps.telemetry, created.id));\n return created;\n });\n}\n\nexport function getSubAccountProgram(\n subAccountId: SubAccountId,\n): Effect.Effect<SubAccount | null, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n return yield* deps.subAccountPort\n .get({ subAccountId })\n .pipe(Effect.mapError((error) => error.publicError));\n });\n}\n\nexport function listSubAccountsProgram(\n accountId: AccountId,\n): Effect.Effect<readonly SubAccount[], CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n return yield* deps.subAccountPort\n .list({ accountId })\n .pipe(Effect.mapError((error) => error.publicError));\n });\n}\n\nexport function renameSubAccountProgram(\n subAccountId: SubAccountId,\n name: string,\n): Effect.Effect<SubAccount, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK-emitted server-confirmed `subaccount_renamed` (rename is a Convex\n // mutation — same fetch constraint as create). NAME excluded; only the\n // branded `sub_account_id`.\n const renamed = yield* deps.subAccountPort.rename({ subAccountId, name }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"rename\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountRenamed(deps.telemetry, renamed.id));\n return renamed;\n });\n}\n\nexport function deleteSubAccountProgram(\n subAccountId: SubAccountId,\n): Effect.Effect<void, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK-emitted server-confirmed `subaccount_deleted` (remove is a Convex\n // mutation — same fetch constraint). The deleted id is known client-side.\n yield* deps.subAccountPort.delete({ subAccountId }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"delete\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountDeleted(deps.telemetry, subAccountId));\n });\n}\n\nexport function transferSubAccountProgram(\n input: TransferInput,\n): Effect.Effect<TransferResult, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK producer for `transfer_requested` (before the backend transfer). The\n // server-confirmed `transfer_confirmed` is emitted backend-side\n // (`subAccount/actions:transfer`) after `applyTransfer` returns.\n yield* Effect.promise(() =>\n emitTransferRequested(deps.telemetry, {\n amount: input.amount,\n from: input.from,\n to: input.to,\n }),\n );\n return yield* deps.subAccountPort.transfer(input).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitTransferFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n });\n}\n","import { Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount, SubAccountId } from \"@capxul/types\";\n\nimport type { SubAccountPort, TransferInput, TransferResult } from \"../ports/sub-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n subAccountsDepsLayer,\n createSubAccountProgram,\n deleteSubAccountProgram,\n getSubAccountProgram,\n listSubAccountsProgram,\n renameSubAccountProgram,\n transferSubAccountProgram,\n} from \"./sub-accounts-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport interface SubAccountsMethods {\n create(\n accountId: AccountId,\n input: { readonly name: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount>>;\n get(\n subAccountId: SubAccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount | null>>;\n list(\n accountId: AccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly SubAccount[]>>;\n rename(\n subAccountId: SubAccountId,\n name: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount>>;\n delete(\n subAccountId: SubAccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<void>>;\n transfer(\n input: TransferInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<TransferResult>>;\n}\n\nexport interface MakeSubAccountsMethodsDeps {\n readonly subAccountPort: SubAccountPort;\n readonly telemetry?: TelemetryPort;\n}\n\nexport function makeSubAccountsMethods(deps: MakeSubAccountsMethodsDeps): SubAccountsMethods {\n const layer = subAccountsDepsLayer(deps);\n return {\n async create(accountId, input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.create\" }) };\n }\n return toCapxulResult(createSubAccountProgram(accountId, input.name), layer);\n },\n async get(subAccountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.get\" }) };\n }\n return toCapxulResult(getSubAccountProgram(subAccountId), layer);\n },\n async list(accountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.list\" }) };\n }\n return toCapxulResult(listSubAccountsProgram(accountId), layer);\n },\n async rename(subAccountId, name, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.rename\" }) };\n }\n return toCapxulResult(renameSubAccountProgram(subAccountId, name), layer);\n },\n async delete(subAccountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.delete\" }) };\n }\n return toCapxulResult(deleteSubAccountProgram(subAccountId), layer);\n },\n async transfer(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.transfer\" }) };\n }\n return toCapxulResult(transferSubAccountProgram(input), layer);\n },\n };\n}\n","// Organization-domain telemetry helpers for the SDK method bundles (canon\n// `docs/canon/decisions/org-domain-model.md` §C5, J1 `org_creation` funnel).\n//\n// Mirrors `money-telemetry.ts`: a thin, fire-and-forget bridge that emits a\n// catalogued `TelemetryEvent` through an optional `TelemetryPort`, swallowing\n// all failures (telemetry must never fail an org flow). The producer split\n// (which names the SDK emits vs which the backend emits) is documented in\n// `docs/canon/conventions/telemetry-spine.md` \"Organization domain\".\n//\n// PII discipline (canon §C5): raw emails NEVER enter telemetry — only\n// `email_domain`. `org_id` is the public `org_`-shaped brand (also the PostHog\n// `organization` group key); never an OTP, never a key.\n\nimport { Effect } from \"effect\";\n\nimport type { OrgId } from \"@capxul/types\";\n\nimport type { TelemetryEvent, TelemetryPort } from \"../../ports/telemetry\";\n\n/** Extract the domain from an email for telemetry (never the local part / PII). */\nfunction emailDomain(email: string): string | undefined {\n const at = email.lastIndexOf(\"@\");\n if (at < 0 || at === email.length - 1) return undefined;\n return email.slice(at + 1).toLowerCase();\n}\n\n/** Fire-and-forget emit through an optional port; never throws. */\nasync function emitOrgTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry.emit(event).pipe(\n Effect.catchAll((cause) =>\n Effect.sync(() => reportOrgTelemetryFailure(\"error\", event.name, cause)),\n ),\n Effect.catchAllDefect((cause) =>\n Effect.sync(() => reportOrgTelemetryFailure(\"defect\", event.name, cause)),\n ),\n ),\n );\n}\n\nexport function emitOrgCreateStarted(\n telemetry: TelemetryPort | undefined,\n input: { readonly template: string; readonly email?: string },\n): Promise<void> {\n const domain = input.email === undefined ? undefined : emailDomain(input.email);\n return emitOrgTelemetry(telemetry, {\n name: \"org_create_started\",\n props: {\n template: input.template,\n ...(domain === undefined ? {} : { email_domain: domain }),\n },\n });\n}\n\n/** Spread the `chainId` prop only when known — never emit a misleading `0`. */\nfunction chainIdProp(chainId: number | undefined): { chainId?: number } {\n return chainId === undefined ? {} : { chainId };\n}\n\nexport function emitOrgSafeCreated(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_safe_created\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgSafeConfirmed(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_safe_confirmed\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgRolesSeeded(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly role: string },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_roles_seeded\",\n props: { org_id: input.orgId, role: input.role },\n });\n}\n\nexport function emitOrgCreated(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_created\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgCreateFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitOrgTelemetry(telemetry, { name: \"org_create_failed\", props: { reason } });\n}\n\nexport function emitOrgInviteSent(\n telemetry: TelemetryPort | undefined,\n input: {\n readonly orgId: OrgId;\n readonly email: string;\n readonly role: string;\n readonly status: string;\n },\n): Promise<void> {\n const domain = emailDomain(input.email);\n return emitOrgTelemetry(telemetry, {\n name: \"org_invite_sent\",\n props: {\n org_id: input.orgId,\n ...(domain === undefined ? {} : { email_domain: domain }),\n role: input.role,\n status: input.status,\n },\n });\n}\n\n// D3 (#565): the `org_spend_*` telemetry family was retired. An org spend is now\n// a KIND of Payment on the one ledger; its lifecycle is observed through the\n// `payment_*` / financial-ops telemetry, not a parallel org_spend dialect.\n\nfunction reportOrgTelemetryFailure(kind: \"error\" | \"defect\", name: string, cause: unknown): void {\n if (!isOrgTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] org telemetry dropped\", { kind, name, cause });\n}\n\nfunction isOrgTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","import { Errors, type CapxulError } from \"@capxul/config\";\nimport type { Address, SubAccountId } from \"@capxul/types\";\n\n/**\n * The role's allowed recipients. The address form backs the S4 `spend` path\n * (recipient is a resolved `Address`); the string form backs the G4\n * `spendViaPayments` / `batchPayroll` path, whose recipient is a VALIDATED REF\n * (handle/email/payee/org) compared in the same ref space as the role's set.\n * Comparison is case-insensitive over the raw string value either way.\n */\nexport type SpendGateRecipients = \"anyone\" | readonly (Address | string)[];\n\nexport type SpendGateSubAccountScope =\n | { readonly scope: \"all\" }\n | { readonly scope: \"only\"; readonly subAccountIds: readonly SubAccountId[] };\n\nexport interface EvaluateSpendGateInput {\n readonly activeMember: boolean;\n readonly subAccountId: SubAccountId;\n readonly subAccountBalanceRaw: string;\n readonly amountRaw: string;\n readonly currency: string;\n /** Resolved `Address` (S4 spend) or VALIDATED REF (G4 spendViaPayments). */\n readonly recipient: Address | string;\n readonly recipients: SpendGateRecipients;\n readonly subAccounts: SpendGateSubAccountScope;\n readonly perTxCapRaw?: string | null;\n readonly perDayCapRaw?: string | null;\n readonly spentTodayRaw?: string | null;\n}\n\nexport type SpendGateRejectReason =\n | \"not_member\"\n | \"over_cap\"\n | \"daily_cap_exhausted\"\n | \"wrong_envelope\"\n | \"invalid_recipient\"\n | \"insufficient_subaccount_balance\";\n\nexport type SpendGateDecision =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly reason: SpendGateRejectReason;\n readonly error: CapxulError;\n };\n\nexport function evaluateSpendGate(input: EvaluateSpendGateInput): SpendGateDecision {\n if (!input.activeMember) {\n return reject(\"not_member\", Errors.invalidInput(\"member\", \"you are not an active member\"));\n }\n\n if (!recipientAllowed(input.recipients, input.recipient)) {\n return reject(\n \"invalid_recipient\",\n Errors.invalidRecipient(\"recipient is not allowed by this role\"),\n );\n }\n\n if (!subAccountAllowed(input.subAccounts, input.subAccountId)) {\n return reject(\n \"wrong_envelope\",\n Errors.invalidInput(\"subAccountId\", \"sub-account not in scope for this role\"),\n );\n }\n\n const amount = parseRaw(input.amountRaw, \"amountRaw\");\n const balance = parseRaw(input.subAccountBalanceRaw, \"subAccountBalanceRaw\");\n if (amount > balance) {\n return reject(\n \"insufficient_subaccount_balance\",\n Errors.insufficientBalance(input.currency, balance.toString(10), amount.toString(10)),\n );\n }\n\n const perTxCap = parseOptionalRaw(input.perTxCapRaw, \"perTxCapRaw\");\n if (perTxCap !== null && amount > perTxCap) {\n return reject(\n \"over_cap\",\n Errors.insufficientBalance(\n \"role per-transaction cap\",\n perTxCap.toString(10),\n amount.toString(10),\n ),\n );\n }\n\n const perDayCap = parseOptionalRaw(input.perDayCapRaw, \"perDayCapRaw\");\n if (perDayCap !== null) {\n const spentToday = parseOptionalRaw(input.spentTodayRaw, \"spentTodayRaw\") ?? 0n;\n const remaining = perDayCap - spentToday;\n if (remaining < amount) {\n return reject(\n \"daily_cap_exhausted\",\n Errors.insufficientBalance(\"role daily cap\", remaining.toString(10), amount.toString(10)),\n );\n }\n }\n\n return { ok: true };\n}\n\nfunction reject(reason: SpendGateRejectReason, error: CapxulError): SpendGateDecision {\n return { ok: false, reason, error } as const;\n}\n\nfunction recipientAllowed(recipients: SpendGateRecipients, recipient: Address | string): boolean {\n if (recipients === \"anyone\") return true;\n const normalized = String(recipient).toLowerCase();\n return recipients.some((allowed) => String(allowed).toLowerCase() === normalized);\n}\n\nfunction subAccountAllowed(scope: SpendGateSubAccountScope, subAccountId: SubAccountId): boolean {\n if (scope.scope === \"all\") return true;\n return scope.subAccountIds.includes(subAccountId);\n}\n\nfunction parseOptionalRaw(value: string | null | undefined, field: string): bigint | null {\n if (value === null || value === undefined) return null;\n return parseRaw(value, field);\n}\n\nfunction parseRaw(value: string, field: string): bigint {\n if (!/^[0-9]+$/.test(value)) {\n throw Errors.invalidInput(field, \"must be a non-negative integer string\");\n }\n return BigInt(value);\n}\n","// Effect program substrate for the Org method bundle (canon\n// `org-domain-model.md` §C2/§C3, D3/D10/D13). Mirrors `accounts-deps.ts`: a\n// `Context.Tag` + `Layer` carrying the deps, and per-operation `*Program`\n// functions the public methods compose through `toCapxulResult`.\n//\n// Two enforcement modes:\n// - LIVE: an `OrgPort` performs the SDK-orchestrated deploy (D10) + RPC\n// `balanceOf` treasury read (D3). Supplied by the CLI/live-proof slice.\n// - HERMETIC (L1): NO port — `createOrg` builds an `OrgView` with a\n// deterministic counterfactual-shaped placeholder and a `$0` treasury, and\n// `treasury` returns `$0`. A fresh Org has no on-chain funds, so `$0` is\n// the correct deterministic answer and what the L1 hermetic proof pins.\n//\n// The org-creation telemetry funnel (canon §C5, J1) is woven in here as the\n// non-test producer for every `org_creation` catalog event.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport {\n compileOrgRoleDefinitions,\n orgRoleKeyForLabel,\n orgRoleTemplateDefinitions,\n USDX_CURRENCY,\n USDX_DECIMALS,\n} from \"@capxul/config\";\nimport type { Account, Address, ChainId, Money, OrgId, SubAccountId } from \"@capxul/types\";\nimport {\n toAccountId,\n toAddress,\n toCurrencyCode,\n toEmail,\n toOrgId,\n toRoleKey,\n toSubAccountId,\n} from \"@capxul/types\";\n\nimport { fromWei } from \"../money/from-wei\";\nimport { toWei } from \"../money/to-wei\";\nimport type {\n OrgPort,\n OrgRolesDeploymentPort,\n OrgSpendAuthority,\n OrgSpendPort,\n} from \"../ports/org\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { Errors, isCapxulError, type CapxulError } from \"@capxul/config\";\n\nimport {\n emitOrgCreated,\n emitOrgCreateFailed,\n emitOrgCreateStarted,\n emitOrgInviteSent,\n emitOrgRolesSeeded,\n emitOrgSafeConfirmed,\n emitOrgSafeCreated,\n} from \"./_shared/org-telemetry\";\nimport type {\n AssignRoleInput,\n CreateOrgInput,\n DetectPendingOrgInvitationsResult,\n InviteMemberInput,\n MemberView,\n OrgView,\n OrgSpendViaPaymentsInput,\n OrgBatchPayrollInput,\n RemoveMemberInput,\n RoleDefinition,\n RoleView,\n} from \"./org\";\nimport type { Payment, PaymentMoney, PaymentType } from \"./financial-ops\";\nimport { evaluateSpendGate, type EvaluateSpendGateInput } from \"./org-spend-gate\";\nimport type { OrgRoleDefinition } from \"@capxul/config\";\n\nexport interface OrgDeps {\n /** Live org seam (deploy + RPC treasury). Absent in the hermetic L1 path. */\n readonly orgPort?: OrgPort;\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n readonly orgSpendPort?: OrgSpendPort;\n /** Chain the org's treasury Account is read on (defaults to Base Sepolia). */\n readonly chainId?: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class OrgDepsTag extends Context.Tag(\"@capxul/sdk/OrgDeps\")<OrgDepsTag, OrgDeps>() {}\n\nexport function orgDepsLayer(deps: OrgDeps): Layer.Layer<OrgDepsTag> {\n return Layer.succeed(OrgDepsTag, deps);\n}\n\nfunction isHermeticOrgDeps(deps: OrgDeps): boolean {\n return (\n deps.orgPort === undefined &&\n deps.orgRolesDeploymentPort === undefined &&\n deps.orgSpendPort === undefined\n );\n}\n\nfunction missingLiveOrgDep(portName: string): CapxulError {\n return Errors.invalidInput(\"orgDeps\", `${portName} is required in live org mode`);\n}\n\n/** Zero `Money` in the USDX-backed display currency (a fresh Org's treasury). */\nfunction zeroMoney(): Money {\n return fromWei(\"0\", USDX_DECIMALS, USDX_CURRENCY);\n}\n\n/** A fresh Org's treasury Account: `$0` balance, `available === balance`. */\nfunction zeroTreasury(orgId: OrgId): Account {\n const balance = zeroMoney();\n return {\n // Account ids are `account_`-shaped (NOT the Safe address, NOT the OrgId).\n // Hermetically derive a stable, valid id from the org handle/id seed.\n id: toAccountId(`account_${stripPrefix(orgId)}`),\n balance,\n available: balance,\n };\n}\n\n/** Drop a known `<prefix>_` so the remainder is reusable as another brand seed. */\nfunction stripPrefix(value: string): string {\n const underscore = value.indexOf(\"_\");\n const tail = underscore < 0 ? value : value.slice(underscore + 1);\n // Keep only the alphanumeric body so the `account_`/`org_` regexes accept it.\n const cleaned = tail.replace(/[^0-9A-Za-z]/g, \"\");\n return cleaned.length > 0 ? cleaned : \"0\";\n}\n\n/** Map an arbitrary string deterministically into lowercase hex chars. */\nfunction toHexSeed(value: string): string {\n let out = \"\";\n for (const ch of value) {\n out += (ch.codePointAt(0) ?? 0).toString(16).padStart(2, \"0\");\n }\n return out.length > 0 ? out : \"0\";\n}\n\n/**\n * Build the hermetic `OrgView` for the no-port L1 path: a deterministic\n * counterfactual-shaped placeholder Org Safe + a `$0` treasury (D3). The live\n * path replaces this with the real deployed address + RPC balance.\n */\nfunction hermeticOrgView(input: CreateOrgInput): OrgView {\n const orgId = toOrgId(`org_${stripPrefix(`x_${input.handle}`)}`);\n // A deterministic, well-formed lowercase 0x + 40 hex placeholder for the\n // hermetic path (the live path supplies the real `deriveCapxulOrgAddress`\n // counterfactual). Map the handle bytes into the hex alphabet so any handle\n // yields a valid `Address` shape.\n const placeholder = `0x${toHexSeed(input.handle).padEnd(40, \"0\").slice(0, 40)}`;\n return {\n id: orgId,\n name: input.name,\n handle: input.handle,\n safeAddress: toAddress(placeholder),\n // The founder is the creator → Owner role within their new org (D6/D7).\n role: \"Owner\",\n treasury: zeroTreasury(orgId),\n };\n}\n\nfunction moneyFromConfig(input: {\n readonly currency: \"USD\";\n readonly value: string;\n readonly decimals: 6;\n}): Money {\n return {\n currency: toCurrencyCode(input.currency),\n value: input.value,\n decimals: input.decimals,\n };\n}\n\nfunction recipientsFromConfig(\n toRecipients: \"anyone\" | readonly string[] | undefined,\n): \"anyone\" | readonly Address[] | undefined {\n if (toRecipients === undefined || toRecipients === \"anyone\") return toRecipients;\n return toRecipients.map((recipient) => toAddress(recipient));\n}\n\nfunction subAccountsFromConfig(\n subAccounts: OrgRoleDefinition[\"subAccounts\"],\n): { readonly scope: \"all\" | readonly SubAccountId[] } | undefined {\n if (subAccounts === undefined) return undefined;\n if (subAccounts.scope === \"all\") return { scope: \"all\" };\n return { scope: subAccounts.scope.map((subAccountId) => toSubAccountId(subAccountId)) };\n}\n\nfunction roleDefinitionFromConfig(definition: OrgRoleDefinition): RoleDefinition {\n const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);\n const subAccounts = subAccountsFromConfig(definition.subAccounts);\n return {\n label: definition.label,\n ...(definition.spend === undefined\n ? {}\n : {\n spend: {\n ...(definition.spend.perTx === undefined\n ? {}\n : { perTx: moneyFromConfig(definition.spend.perTx) }),\n ...(definition.spend.perDay === undefined\n ? {}\n : { perDay: moneyFromConfig(definition.spend.perDay) }),\n ...(toRecipients === undefined ? {} : { toRecipients }),\n },\n }),\n ...(subAccounts === undefined ? {} : { subAccounts }),\n ...(definition.canManageMembers === undefined\n ? {}\n : { canManageMembers: definition.canManageMembers }),\n ...(definition.canManageRoles === undefined\n ? {}\n : { canManageRoles: definition.canManageRoles }),\n };\n}\n\nfunction startupRoleViews(orgId: OrgId): readonly RoleView[] {\n const compiled = compileOrgRoleDefinitions(orgRoleTemplateDefinitions(\"Startup\"));\n return compiled.roles.map((role) => ({\n orgId,\n label: role.label,\n roleKey: toRoleKey(role.roleKey),\n definition: roleDefinitionFromConfig(role.definition),\n }));\n}\n\nfunction hermeticMember(input: {\n readonly orgId: OrgId;\n readonly email: string;\n readonly role: string;\n readonly status: \"pending\" | \"active\" | \"revoked\";\n readonly personalSafeAddress?: Address;\n readonly grantTxHash?: string | null;\n readonly revokeTxHash?: string | null;\n}): MemberView {\n return {\n orgId: input.orgId,\n email: toEmail(input.email),\n name: null,\n personalSafeAddress: input.personalSafeAddress ?? null,\n role: input.role,\n roleKey: toRoleKey(orgRoleKeyForLabel(input.role)),\n status: input.status,\n grantTxHash: input.grantTxHash ?? null,\n revokeTxHash: input.revokeTxHash ?? null,\n };\n}\n\n/**\n * The minimal `{from, to}` spend shape the gate + hermetic authority read off.\n * D3 (#565) removed the legacy `OrgSpendInput` (the address-keyed `org.spend`\n * lane); the leak-safe ref-based lane (`spendViaPayments`/`batchPayroll`)\n * constructs this shape internally with a placeholder `to` and enforces the real\n * validated recipient ref on the gate below.\n */\ntype SpendShape = {\n readonly from: SubAccountId;\n readonly to: Address;\n readonly amount: Money;\n};\n\nfunction hermeticSpendAuthority(input: SpendShape): OrgSpendAuthority {\n return {\n activeMember: true,\n subAccountBalanceRaw: \"100000000000\",\n recipients: \"anyone\",\n subAccounts: { scope: \"only\", subAccountIds: [input.from] },\n perTxCapRaw: \"25000000000\",\n perDayCapRaw: \"100000000000\",\n spentTodayRaw: \"0\",\n role: \"Finance Manager\",\n };\n}\n\nfunction spendGateInput(input: {\n readonly authority: OrgSpendAuthority;\n readonly spend: SpendShape;\n readonly amountRaw: string;\n readonly currency: string;\n}): EvaluateSpendGateInput {\n return {\n activeMember: input.authority.activeMember,\n subAccountId: input.spend.from,\n subAccountBalanceRaw: input.authority.subAccountBalanceRaw,\n amountRaw: input.amountRaw,\n currency: input.currency,\n recipient: input.spend.to,\n recipients: input.authority.recipients,\n subAccounts: input.authority.subAccounts,\n ...(input.authority.perTxCapRaw === undefined\n ? {}\n : { perTxCapRaw: input.authority.perTxCapRaw }),\n ...(input.authority.perDayCapRaw === undefined\n ? {}\n : { perDayCapRaw: input.authority.perDayCapRaw }),\n ...(input.authority.spentTodayRaw === undefined\n ? {}\n : { spentTodayRaw: input.authority.spentTodayRaw }),\n };\n}\n\nexport function createOrgProgram(\n input: CreateOrgInput,\n): Effect.Effect<OrgView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n const chainId = deps.chainId;\n\n // SDK producer for the `org_creation` funnel (canon §C5, J1). Awaited (not\n // forked) on purpose — pins client-side causal ordering (`org_create_started`\n // strictly before the later steps), mirroring the money flow.\n yield* Effect.promise(() => emitOrgCreateStarted(deps.telemetry, { template: input.template }));\n\n const body = Effect.gen(function* () {\n // LIVE path — the port performs the SDK-orchestrated deploy (D10).\n if (deps.orgPort !== undefined) {\n const org = yield* deps.orgPort\n .createOrg({ input })\n .pipe(Effect.mapError((error) => error.publicError));\n yield* emitCreationFunnelTail(deps.telemetry, org, chainId);\n return org;\n }\n\n // HERMETIC path (L1) — deterministic `$0` org, no network.\n const org = hermeticOrgView(input);\n yield* emitCreationFunnelTail(deps.telemetry, org, chainId);\n return org;\n });\n\n // `org_create_failed` is the funnel's `drops_on` event (canon §C5, J1):\n // emit it (carrying the `CapxulErrorCode` as `reason`) before the failure\n // propagates, so a dropped creation is attributable. Fire-and-forget — the\n // telemetry emit never alters the original error.\n return yield* body.pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitOrgCreateFailed(deps.telemetry, error.code)),\n ),\n );\n });\n}\n\n/** Emit the remaining `org_creation` funnel steps once the org is built. */\nfunction emitCreationFunnelTail(\n telemetry: TelemetryPort | undefined,\n org: OrgView,\n chainId: ChainId | undefined,\n): Effect.Effect<void, never, never> {\n return Effect.promise(async () => {\n // Omit `chainId` when unknown (hermetic L1 has no chain) rather than\n // emitting a misleading `0` — the schema's `chainId` is optional.\n const chain = chainId === undefined ? {} : { chainId };\n await emitOrgSafeCreated(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n await emitOrgSafeConfirmed(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n await emitOrgRolesSeeded(telemetry, { orgId: org.id, role: org.role });\n await emitOrgCreated(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n });\n}\n\nexport function readTreasuryProgram(orgId: OrgId): Effect.Effect<Account, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n // LIVE path — RPC `balanceOf` over the Org Safe (D3).\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .readTreasury({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n // HERMETIC path (L1) — a fresh org reads back at `$0` (D3).\n return zeroTreasury(orgId);\n });\n}\n\nexport function listRolesProgram(\n orgId: OrgId,\n): Effect.Effect<readonly RoleView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .listRoles({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return startupRoleViews(orgId);\n });\n}\n\nexport function deployRolesProgram(\n orgId: OrgId,\n): Effect.Effect<readonly RoleView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n const deployed = yield* deps.orgRolesDeploymentPort\n .deployRoles({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n return deployed.roles;\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n return startupRoleViews(orgId);\n });\n}\n\nexport function listMembersProgram(\n orgId: OrgId,\n): Effect.Effect<readonly MemberView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .listMembers({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return [];\n });\n}\n\nexport function inviteMemberProgram(\n orgId: OrgId,\n input: InviteMemberInput,\n): Effect.Effect<MemberView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n const member =\n deps.orgPort !== undefined\n ? yield* deps.orgPort\n .inviteMember({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError))\n : hermeticMember({ orgId, email: input.email, role: input.role, status: \"pending\" });\n yield* Effect.promise(() =>\n emitOrgInviteSent(deps.telemetry, {\n orgId,\n email: input.email,\n role: member.role,\n status: member.status,\n }),\n );\n return member;\n });\n}\n\nexport function detectAndAcceptPendingInvitationsProgram(): Effect.Effect<\n DetectPendingOrgInvitationsResult,\n CapxulError,\n OrgDepsTag\n> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .detectAndAcceptPendingInvitations({})\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return { matched: [] };\n });\n}\n\nexport function assignRoleProgram(\n orgId: OrgId,\n input: AssignRoleInput,\n): Effect.Effect<MemberView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n return yield* deps.orgRolesDeploymentPort\n .grantRole({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n return hermeticMember({\n orgId,\n email: \"member@example.com\",\n role: input.role,\n status: \"active\",\n personalSafeAddress: input.memberSafeAddress,\n grantTxHash: `0x${\"0\".repeat(64)}`,\n });\n });\n}\n\nexport function removeMemberProgram(\n orgId: OrgId,\n input: RemoveMemberInput,\n): Effect.Effect<void, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n return yield* deps.orgRolesDeploymentPort\n .revokeRole({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n });\n}\n\n// ── G4 (#547) — leak-safe org spend via the payments engine ──────────────────\n\n/**\n * Build a leak-safe settled `Payment` for an org spend (G4 · #547). NO `txHash`\n * / userOp / Safe internals and NO raw recipient address ever reach this record\n * — only the validated recipient ref label + the committed `documentHash`.\n */\nfunction leakSafeOrgPayment(input: {\n readonly orgId: OrgId;\n readonly to: string;\n readonly amount: Money;\n readonly paymentType: PaymentType;\n readonly documentHash?: string;\n readonly index: number;\n}): Payment {\n const now = Date.now();\n const id = `payment_${toHexSeed(`${input.orgId}:${input.to}:${input.amount.value}:${input.index}`)}`;\n const money: PaymentMoney = {\n currency: String(input.amount.currency),\n value: input.amount.value,\n decimals: input.amount.decimals,\n };\n return {\n id,\n status: \"settled\",\n amount: money,\n paymentType: input.paymentType,\n recipient: { kind: \"email\", label: input.to },\n documents:\n input.documentHash === undefined\n ? []\n : [\n {\n documentHash: input.documentHash,\n kind: input.paymentType === \"payroll\" ? \"payslip\" : \"memo\",\n },\n ],\n release: { kind: \"instant\" },\n released: money,\n availableToClaim: { ...money, value: \"0\" },\n createdAt: now,\n updatedAt: now,\n };\n}\n\n/** Resolve authority + run the spend gate for one org spend run (G4 · #547). */\nfunction gateOneRun(input: {\n readonly deps: OrgDeps;\n readonly orgId: OrgId;\n readonly from: SubAccountId;\n readonly to: string;\n readonly amount: Money;\n /**\n * Raw USDX units already committed by EARLIER runs in the same batch (G4 #547).\n * Charged against BOTH the per-day cap (added to `spentToday`) and the\n * sub-account balance (subtracted) so a batch of in-per-tx runs that SUMS over\n * the day cap or the balance is rejected as a whole — no partial drain.\n */\n readonly accumulatedRaw?: string;\n}): Effect.Effect<\n { readonly authority: OrgSpendAuthority; readonly amountRaw: string },\n CapxulError,\n never\n> {\n return Effect.gen(function* () {\n const amountRaw = yield* Effect.try({\n try: () => toWei(input.amount),\n catch: (cause) =>\n Errors.invalidInput(\"amount\", cause instanceof Error ? cause.message : \"invalid money\"),\n });\n const currency = String(input.amount.currency);\n // The authority read derives the role's caps/recipient set from the org +\n // member; it does NOT key off the recipient, so the `from`/amount shape is\n // sufficient. The recipient axis is enforced by the gate below against the\n // REAL validated ref (NOT a fabricated zero address) — `recipients` for this\n // ref-based path is the role's allowed-ref set (or \"anyone\").\n const spendShaped: SpendShape = {\n from: input.from,\n to: toAddress(`0x${\"0\".repeat(40)}`),\n amount: input.amount,\n };\n const authority =\n input.deps.orgSpendPort === undefined\n ? hermeticSpendAuthority(spendShaped)\n : yield* input.deps.orgSpendPort\n .readSpendAuthority({ orgId: input.orgId, input: spendShaped, amountRaw })\n .pipe(Effect.mapError((error) => error.publicError));\n const accumulated = BigInt(input.accumulatedRaw ?? \"0\");\n const baseGateInput = spendGateInput({ authority, spend: spendShaped, amountRaw, currency });\n const decision = yield* Effect.try({\n try: () =>\n evaluateSpendGate({\n ...baseGateInput,\n // Enforce the recipient axis on the REAL validated ref — fixes the\n // zero-address substitution that silently disabled it (G4 #547).\n recipient: input.to,\n // Cross-run accumulation: charge prior runs against the day cap and the\n // balance so the batch's running total is bounded, not each run alone.\n subAccountBalanceRaw: subtractNonNegative(\n baseGateInput.subAccountBalanceRaw,\n accumulated,\n ),\n spentTodayRaw: (BigInt(authority.spentTodayRaw ?? \"0\") + accumulated).toString(10),\n }),\n catch: (cause) => (isCapxulError(cause) ? cause : Errors.unknown(cause)),\n });\n if (!decision.ok) return yield* Effect.fail(decision.error);\n return { authority, amountRaw };\n });\n}\n\n/** Subtract `delta` from a raw amount, flooring at zero (never negative). */\nfunction subtractNonNegative(raw: string, delta: bigint): string {\n const remaining = BigInt(raw) - delta;\n return (remaining < 0n ? 0n : remaining).toString(10);\n}\n\nexport function spendViaPaymentsProgram(\n orgId: OrgId,\n input: OrgSpendViaPaymentsInput,\n): Effect.Effect<Payment, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgSpendPort === undefined && !isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgSpendPort\"));\n }\n const gated = yield* gateOneRun({\n deps,\n orgId,\n from: input.from,\n to: input.to,\n amount: input.amount,\n });\n const paymentType = input.paymentType ?? \"unspecified\";\n\n if (deps.orgSpendPort?.submitSpendViaPayments !== undefined) {\n return yield* deps.orgSpendPort\n .submitSpendViaPayments({\n orgId,\n input,\n amountRaw: gated.amountRaw,\n authority: gated.authority,\n })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n // Hermetic / adapter-without-payments-submit: build the leak-safe Payment\n // from the gated decision (the live adapter executes the on-chain spend).\n return leakSafeOrgPayment({ orgId, to: input.to, amount: input.amount, paymentType, index: 0 });\n });\n}\n\nexport function batchPayrollProgram(\n orgId: OrgId,\n input: OrgBatchPayrollInput,\n): Effect.Effect<readonly Payment[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgSpendPort === undefined && !isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgSpendPort\"));\n }\n if (input.runs.length === 0) {\n return yield* Effect.fail(\n Errors.invalidInput(\"runs\", \"payroll batch must include at least one run\"),\n );\n }\n // Gate EVERY run first — an over-cap run rejects the whole batch before any\n // submit, so a single bad row can never partially drain the treasury. Each\n // run is gated against the RUNNING TOTAL of the runs before it (G4 #547), so\n // a batch of in-per-tx runs that sums over the day cap / balance is rejected\n // as a whole rather than slipping through on independent per-run checks.\n const gated: { readonly authority: OrgSpendAuthority; readonly amountRaw: string }[] = [];\n let accumulatedRaw = 0n;\n for (const run of input.runs) {\n const result = yield* gateOneRun({\n deps,\n orgId,\n from: input.from,\n to: run.to,\n amount: run.amount,\n accumulatedRaw: accumulatedRaw.toString(10),\n });\n accumulatedRaw += BigInt(result.amountRaw);\n gated.push(result);\n }\n\n if (deps.orgSpendPort?.submitBatchPayroll !== undefined) {\n return yield* deps.orgSpendPort\n .submitBatchPayroll({\n orgId,\n from: input.from,\n runs: input.runs.map((run, index) => ({ run, amountRaw: gated[index]!.amountRaw })),\n authorities: gated.map((g) => g.authority),\n })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return input.runs.map((run, index) =>\n leakSafeOrgPayment({ orgId, to: run.to, amount: run.amount, paymentType: \"payroll\", index }),\n );\n });\n}\n\nexport function listOrgsProgram(): Effect.Effect<readonly OrgView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort.listOrgs({}).pipe(Effect.mapError((error) => error.publicError));\n }\n // HERMETIC path (L1) — no orgs without a backend.\n return [];\n });\n}\n","// Public consumer-facing Org method surface for the Organization domain\n// (canon `docs/canon/decisions/org-domain-model.md` §C2/§C3 + the D-scopes).\n//\n// This is the LOCKED public surface the §C3 hooks call and the S1→S4 slices\n// fill. Planned UP FRONT per the capstone-first DoD — not discovered per slice.\n//\n// Shape (canon §C2/§C3, D13 explicit entity scoping — NO stateful active\n// context):\n//\n// - `capxul.createOrg(input)` — create an Org (S1)\n// - `capxul.orgs()` — list Orgs you belong to\n// - `capxul.org(orgId)` — entity-scoped bundle:\n// .treasury() → the real M2 `Account` over the Org Safe (D3)\n// .members() → MemberView[] (D8/D9)\n// .roles() → RoleView[] (D4/D6)\n// .invite(input) → invite-by-email (D8 virality loop)\n// .removeMember() → on-chain REVOKE + Convex mirror (D8)\n// .assignRole() → on-chain GRANT + Convex mirror (D7/D9)\n// .spendViaPayments(input) → leak-safe org spend on the one ledger (D5; D3 #565)\n//\n// Every method returns `Promise<CapxulResult<T>>`. RED behavior: each impl\n// resolves `Errors.notImplemented(\"org\", \"<verb>\")`; the slices replace each\n// one. Treasury reuses the M2 `Account` type verbatim (D3) — never\n// `AccountStatus` (that is the deploy-readiness ladder, no balance).\n//\n// Per `docs/canon/rules/public-surface.md` + `.claude/rules/flow-internal-substrate.md`:\n// named exports only, no Effect/flow-actor/program leak on the surface, every\n// return type is a real plain record. Per D13 the entity is always named\n// explicitly (`orgId` flows in via the scope factory) — there is NO global\n// \"acting as\" state.\n\nimport { Errors } from \"@capxul/config\";\nimport type { PaymentDocumentEnvelopeV1 } from \"@capxul/wire\";\nimport type {\n Account,\n Address,\n ChainId,\n Email,\n Money,\n OrgId,\n RoleKey,\n SubAccountId,\n} from \"@capxul/types\";\n\nimport type { Payment, PaymentType } from \"./financial-ops\";\n\nimport type { OrgPort, OrgRolesDeploymentPort, OrgSpendPort } from \"../ports/org\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n assignRoleProgram,\n batchPayrollProgram,\n createOrgProgram,\n detectAndAcceptPendingInvitationsProgram,\n deployRolesProgram,\n inviteMemberProgram,\n listMembersProgram,\n listRolesProgram,\n listOrgsProgram,\n orgDepsLayer,\n readTreasuryProgram,\n removeMemberProgram,\n spendViaPaymentsProgram,\n} from \"./org-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\n/**\n * A member's lifecycle status (D9 — unified `Member` with status\n * `pending | active | revoked | expired`). `pending` = invited (incl. a\n * non-user emailed into existence) but not yet a provisioned member with an\n * on-chain grant; `active` = on-chain role granted; `revoked` = offboarded\n * (on-chain REVOKE fired); `expired` = pending invitation timed out.\n */\nexport type MemberStatus =\n | \"pending\"\n | \"pending_safe\"\n | \"pending_grant\"\n | \"active\"\n | \"revoked\"\n | \"expired\";\n\n/**\n * One Org you belong to (canon §C1 \"Org list\" — name, role, balance).\n * `role` is the member's role label within THIS org. `treasury` is the M2\n * `Account` over the Org Safe (D3). `handle` is the globally-unique,\n * normalized org handle (D10a). Pure record of brand-typed fields — not a\n * brand.\n */\nexport type OrgView = {\n readonly id: OrgId;\n readonly name: string;\n readonly handle: string;\n readonly safeAddress: Address;\n /** The viewing member's own role label within this org. */\n readonly role: string;\n /** The Org treasury — the real M2 Account over the Org Safe (D3). */\n readonly treasury: Account;\n};\n\n/**\n * One member of an Org (canon §C1 \"Members\" — name/email, role, status; D7/D8).\n * `personalSafeAddress` is the member-identity key (D7 — Safe-as-identity); it\n * is `null` while the member is still `pending` (emailed into existence but not\n * yet provisioned a personal Safe). `email` is the universal entry point (D8).\n */\nexport type MemberView = {\n readonly orgId: OrgId;\n readonly email: Email;\n readonly name: string | null;\n /** Member-identity key (D7). `null` until the invitee provisions a Safe. */\n readonly personalSafeAddress: Address | null;\n /** The member's role label (maps deterministically to the on-chain `roleKey`, D9). */\n readonly role: string;\n readonly roleKey: RoleKey | null;\n readonly status: MemberStatus;\n readonly grantTxHash: string | null;\n readonly revokeTxHash: string | null;\n};\n\n/**\n * A role's on-chain Level-1 spend cap (D4/D5 — physically enforced via Zodiac\n * Roles + Allowance). `perTx` / `perDay` are `Money`; `toRecipients` scopes the\n * allowed recipient set. Omitting a field means \"unbounded on that axis\"\n * (the Owner role).\n */\nexport type RoleSpendCap = {\n readonly perTx?: Money;\n readonly perDay?: Money;\n readonly toRecipients?: \"anyone\" | readonly Address[];\n};\n\n/**\n * The Capxul-owned Role DSL definition (D4). `label` becomes the sticky\n * bytes32 `roleKey` on-chain. `spend` compiles to Level-1 on-chain Zodiac\n * conditions; `subAccounts` + `canManage*` compile to Level-2 off-chain Convex\n * guards (D5).\n */\nexport type RoleDefinition = {\n readonly label: string;\n // Level 1 — on-chain (Zodiac Roles + Allowance), physically enforced:\n readonly spend?: RoleSpendCap;\n // Level 2 — off-chain (Convex), business logic:\n readonly subAccounts?: { readonly scope: \"all\" | readonly SubAccountId[] };\n readonly canManageMembers?: boolean;\n readonly canManageRoles?: boolean;\n};\n\n/**\n * One role seeded on an Org (canon §C1 \"Roles\" — label + caps; D4/D6).\n * `roleKey` is the on-chain bytes32 role key derived from the label. `definition`\n * is the full Role DSL entry.\n */\nexport type RoleView = {\n readonly orgId: OrgId;\n readonly label: string;\n readonly roleKey: RoleKey;\n readonly definition: RoleDefinition;\n};\n\n/** Built-in role templates that seed a new Org at creation (D6). */\nexport type OrgTemplate = \"Solo\" | \"Startup\" | \"Custom\";\n\n/**\n * Input to `capxul.createOrg` (S1, D10a, D14). `name` is the display name;\n * `handle` is the globally-unique normalized handle (`^[a-z0-9-]{3,32}$`, D10a);\n * `template` seeds the initial role set (D6); `country` is stored unvalidated\n * (D14 — KYB deferred). For `template: \"Custom\"`, `roles` carries the authored\n * `RoleDefinition[]`.\n */\nexport type CreateOrgInput = {\n readonly name: string;\n readonly handle: string;\n readonly template: OrgTemplate;\n readonly country?: string;\n readonly roles?: readonly RoleDefinition[];\n};\n\n/**\n * Input to `org(orgId).invite` (S3, D8). Email is the universal entry point —\n * inviting an address that is not yet a Capxul user auto-creates a `pending`\n * membership that resolves on sign-in (the virality loop). `role` names the\n * role label the invitee is granted on accept.\n */\nexport type InviteMemberInput = {\n readonly email: string;\n readonly role: string;\n};\n\n/**\n * Input to `org(orgId).removeMember` (S3, D8). Keyed on the member's personal\n * Safe address (D7 — Safe-as-identity). Drives the on-chain REVOKE + Convex\n * mirror.\n */\nexport type RemoveMemberInput = {\n readonly memberSafeAddress: Address;\n};\n\n/**\n * Input to `org(orgId).assignRole` (S3, D7/D9). Keyed on the member's personal\n * Safe address (D7). Drives the on-chain GRANT + Convex mirror; the `role`\n * label maps deterministically to the on-chain `roleKey`.\n */\nexport type AssignRoleInput = {\n readonly memberSafeAddress: Address;\n readonly role: string;\n};\n\n/**\n * Input to `org(orgId).spendViaPayments` (G4 · #547). The LEAK-SAFE org spend:\n * delegates `org.spend` to the payments engine WITH the member's org role\n * authority and returns a `Payment`, not a `txHash`. `to` is a VALIDATED\n * recipient ref (handle / email / payee id / org handle) — never a raw\n * `Address` (the legacy address-keyed `org.spend` lane was hard-removed in D3\n * #565 when `orgSpends` was folded into the one `payments` ledger).\n * `from` is the Level-2 sub-account envelope the spend draws from (D5).\n */\nexport type OrgSpendViaPaymentsInput = {\n readonly from: SubAccountId;\n /** Validated recipient ref (handle/email/payee/org) — never a raw address. */\n readonly to: string;\n readonly amount: Money;\n /** Full EIP-712 payment document; hashed + stored, committed on-chain. */\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly paymentType?: PaymentType;\n};\n\n/**\n * One run in an `org(orgId).batchPayroll` batch (G4 · #547): a validated\n * recipient, an amount, and an optional payslip document. Each run is gated\n * independently against the role's per-tx / per-day / recipient conditions.\n */\nexport type OrgPayrollRun = {\n /** Validated recipient ref (handle/email/payee/org) — never a raw address. */\n readonly to: string;\n readonly amount: Money;\n /** The payslip — an EIP-712 payment document, committed by `documentHash`. */\n readonly payslip?: PaymentDocumentEnvelopeV1;\n};\n\n/**\n * Input to `org(orgId).batchPayroll` (G4 · #547). Pays N employees in one\n * MultiSend through the Roles modifier; each carries a payslip and settles as\n * `paymentType = payroll`. Every run is gated; an over-cap run REJECTS the\n * whole batch (no partial treasury drain). Returns one leak-safe `Payment` per\n * run.\n */\nexport type OrgBatchPayrollInput = {\n readonly from: SubAccountId;\n readonly runs: readonly OrgPayrollRun[];\n};\n\nexport type DetectPendingOrgInvitationsResult = {\n readonly matched: readonly OrgId[];\n};\n\n/**\n * Entity-scoped Org method bundle, returned by `capxul.org(orgId)`. Every\n * method names the entity implicitly via the closed-over `orgId` (D13 — no\n * stateful active context). `treasury()` returns the real M2 `Account` over\n * the Org Safe (D3).\n */\nexport interface OrgScopedMethods {\n /** The Org treasury — the real M2 Account over the Org Safe (D3). */\n treasury(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Account>>;\n members(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly MemberView[]>>;\n roles(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly RoleView[]>>;\n deployRoles(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly RoleView[]>>;\n invite(\n input: InviteMemberInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<MemberView>>;\n removeMember(\n input: RemoveMemberInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<void>>;\n assignRole(\n input: AssignRoleInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<MemberView>>;\n /**\n * Leak-safe org spend (G4 · #547; D3 #565 — the one ledger of record): execute\n * the spend through the payments engine with the member's org role authority\n * and return a `Payment` (no `to: Address`, no `txHash`, no Safe / userOp\n * internals). Writes a real `payments` row (`source:\"org\"`).\n */\n spendViaPayments(\n input: OrgSpendViaPaymentsInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Org payroll batch (G4 · #547): pay N employees in one MultiSend through the\n * Roles modifier, each with a payslip. Every run is gated; an over-cap run\n * rejects the whole batch. Returns one leak-safe `Payment` per run.\n */\n batchPayroll(\n input: OrgBatchPayrollInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly Payment[]>>;\n}\n\nexport type OrgsMethod = {\n (options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly OrgView[]>>;\n detectAndAcceptPendingInvitations(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DetectPendingOrgInvitationsResult>>;\n};\n\n/**\n * Top-level Org method bundle, exposed at `client.org` / `client.orgs` /\n * `client.createOrg`. `org(orgId)` resolves the entity-scoped bundle (D13).\n */\nexport interface OrgMethods {\n createOrg(\n input: CreateOrgInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<OrgView>>;\n readonly orgs: OrgsMethod;\n /** Resolve the entity-scoped bundle for a specific Org (D13). */\n org(orgId: OrgId): OrgScopedMethods;\n}\n\nexport interface MakeOrgMethodsDeps {\n /**\n * Live org seam (canon D10 SDK-orchestrated deploy + D3 RPC treasury read).\n * Absent in the hermetic L1 path — `createOrg` then builds a deterministic\n * `$0` org and `treasury` returns `$0` (a fresh Org has no on-chain funds).\n */\n readonly orgPort?: OrgPort;\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n readonly orgSpendPort?: OrgSpendPort;\n /** Chain the org treasury Account is read on (defaults to Base Sepolia). */\n readonly chainId?: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * Org method surface (canon §C2/§C3, D13). S1 (#274) wires `createOrg` /\n * `orgs` / `treasury` to their Effect programs (`org-deps.ts`); the S2→S4\n * member/role/spend verbs stay `Errors.notImplemented(\"org\", \"<verb>\")` until\n * their slices land. The entity-scoped bundle is constructed per `org(orgId)`\n * call (D13 — explicit scoping, no shared mutable \"active org\" state); the\n * closed-over `orgId` is the only entity reference.\n */\nexport function makeOrgMethods(deps: MakeOrgMethodsDeps): OrgMethods {\n const layer = orgDepsLayer({\n ...(deps.orgPort === undefined ? {} : { orgPort: deps.orgPort }),\n ...(deps.orgRolesDeploymentPort === undefined\n ? {}\n : { orgRolesDeploymentPort: deps.orgRolesDeploymentPort }),\n ...(deps.orgSpendPort === undefined ? {} : { orgSpendPort: deps.orgSpendPort }),\n ...(deps.chainId === undefined ? {} : { chainId: deps.chainId }),\n ...(deps.telemetry === undefined ? {} : { telemetry: deps.telemetry }),\n });\n\n const orgs: OrgsMethod = Object.assign(\n (options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly OrgView[]>> => {\n if (options?.signal?.aborted) {\n return Promise.resolve({ ok: false, error: Errors.cancelled({ operation: \"org.orgs\" }) });\n }\n return toCapxulResult(listOrgsProgram(), layer);\n },\n {\n detectAndAcceptPendingInvitations(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DetectPendingOrgInvitationsResult>> {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"orgs.detectAndAcceptPendingInvitations\" }),\n });\n }\n return toCapxulResult(detectAndAcceptPendingInvitationsProgram(), layer);\n },\n },\n );\n\n return {\n createOrg(input, options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.createOrg\" }),\n });\n }\n return toCapxulResult(createOrgProgram(input), layer);\n },\n orgs,\n org(orgId: OrgId): OrgScopedMethods {\n return {\n treasury(options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.treasury\" }),\n });\n }\n return toCapxulResult(readTreasuryProgram(orgId), layer);\n },\n members(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.members\" }),\n });\n }\n return toCapxulResult(listMembersProgram(orgId), layer);\n },\n roles(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.roles\" }),\n });\n }\n return toCapxulResult(listRolesProgram(orgId), layer);\n },\n deployRoles(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.deployRoles\" }),\n });\n }\n return toCapxulResult(deployRolesProgram(orgId), layer);\n },\n invite(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.invite\" }),\n });\n }\n return toCapxulResult(inviteMemberProgram(orgId, _input), layer);\n },\n removeMember(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.removeMember\" }),\n });\n }\n return toCapxulResult(removeMemberProgram(orgId, _input), layer);\n },\n assignRole(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.assignRole\" }),\n });\n }\n return toCapxulResult(assignRoleProgram(orgId, _input), layer);\n },\n spendViaPayments(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.spendViaPayments\" }),\n });\n }\n return toCapxulResult(spendViaPaymentsProgram(orgId, _input), layer);\n },\n batchPayroll(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.batchPayroll\" }),\n });\n }\n return toCapxulResult(batchPayrollProgram(orgId, _input), layer);\n },\n };\n },\n };\n}\n","// Onboarding choreography (D-ONBOARD · #669).\n//\n// The deep module that bridges the post-OTP auth → provision bookends. It owns\n// the identity → (org) createOrg → provision choreography so it does NOT\n// reappear in every consumer (the deletion test). It REUSES existing\n// capabilities — the identity write (`identity/mutations.ts` via IdentityPort),\n// the existing `createOrg` verb, and the existing provisioning lane — and\n// reimplements none of them. The choreography is expressed over an `OnboardingOps`\n// seam: the assembled client supplies the real ops in prod; hermetic tests\n// supply an in-memory double (the \"real seam\" the PRD calls for).\n//\n// completePersonal = identity.completeOnboarding → provision → kick → readLifecycle\n// completeOrganization = identity.completeOnboarding → provision → createOrg → kick → readLifecycle\n//\n// The verb ends at \"profile persisted + provisioning kicked\": `triggerProvisioning`\n// ensures the counterfactual account row (a deterministic, awaited step) and\n// `kickProvisioning` drives the deploy/claim forward without blocking. The\n// returned `lifecycle` is the leak-safe `AccountLifecycle` snapshot; the existing\n// account-lifecycle query observes the rest.\n\nimport { CapxulError, Errors, type CapxulError as CapxulErrorType } from \"@capxul/config\";\nimport { toAddress, toCountryCode } from \"@capxul/types\";\nimport type { Address, AuthUserId, CountryCode, Email } from \"@capxul/types\";\n\nimport type { AccountLifecycle } from \"../client/account\";\nimport type {\n CompleteOrganizationOnboardingInput,\n CompleteOrganizationOnboardingResult,\n CompletePersonalOnboardingInput,\n CompletePersonalOnboardingResult,\n} from \"../client/onboarding\";\nimport type { CreateOrgInput, OrgTemplate, OrgView } from \"../client/org\";\nimport type { CapxulResult } from \"../client/types\";\n\nexport type {\n CompleteOrganizationOnboardingInput,\n CompleteOrganizationOnboardingResult,\n CompletePersonalOnboardingInput,\n CompletePersonalOnboardingResult,\n} from \"../client/onboarding\";\n\n/** Authenticated session the onboarding choreography acts within. */\nexport interface OnboardingSession {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n}\n\n/** Validated + branded identity-write payload handed to the persistence op. */\nexport interface OnboardingIdentityWrite {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string;\n readonly country: CountryCode;\n readonly withdrawalAddress?: Address;\n}\n\n/**\n * The composable seam. Each op is an EXISTING capability the verb reuses; the\n * choreography never reimplements identity, provisioning, or createOrg. In prod\n * `makeOnboardingMethods` wires these to the assembled client (IdentityPort +\n * the account lane + the org verb); hermetic tests pass an in-memory double.\n */\nexport interface OnboardingOps {\n /** Resolve the current authenticated session (null → not authenticated). */\n currentSession(): Promise<OnboardingSession | null>;\n /** Persist the onboarding profile (onboarded flag + optional withdrawalAddress). */\n completeIdentityOnboarding(input: OnboardingIdentityWrite): Promise<CapxulResult<unknown>>;\n /** Trigger the existing provisioning lane (awaited — ensures the account row). */\n triggerProvisioning(): Promise<CapxulResult<unknown>>;\n /** Drive the lane forward (deploy/claim) without blocking the verb. */\n kickProvisioning(): void;\n /** The leak-safe readiness snapshot (the existing `account.getLifecycle` read). */\n readLifecycle(): Promise<CapxulResult<AccountLifecycle>>;\n /** The existing `createOrg` verb — reused, never reimplemented. */\n createOrg(input: CreateOrgInput): Promise<CapxulResult<OrgView>>;\n}\n\n// The onboarding org seed. completeOrganization's input intentionally omits a\n// template (the PRD locks the DX to org name/handle/country/owner); the verb\n// seeds the standard \"Startup\" template (the org.create MCP tool's default).\nconst DEFAULT_ORG_TEMPLATE: OrgTemplate = \"Startup\";\n\nexport async function runCompletePersonalOnboarding(\n ops: OnboardingOps,\n input: CompletePersonalOnboardingInput,\n): Promise<CapxulResult<CompletePersonalOnboardingResult>> {\n const validated = validatePersonalInput(input);\n if (!validated.ok) return validated;\n\n const session = await ops.currentSession();\n if (session === null) return fail(Errors.notAuthenticated());\n\n const written = await ops.completeIdentityOnboarding({\n authUserId: session.authUserId,\n email: session.email,\n displayName: validated.value.displayName,\n country: validated.value.country,\n ...(validated.value.withdrawalAddress === undefined\n ? {}\n : { withdrawalAddress: validated.value.withdrawalAddress }),\n });\n if (!written.ok) return fail(written.error);\n\n const provisioned = await ops.triggerProvisioning();\n if (!provisioned.ok) return fail(provisioned.error);\n ops.kickProvisioning();\n\n const lifecycle = await ops.readLifecycle();\n if (!lifecycle.ok) return fail(lifecycle.error);\n return { ok: true, value: { lifecycle: lifecycle.value } };\n}\n\nexport async function runCompleteOrganizationOnboarding(\n ops: OnboardingOps,\n input: CompleteOrganizationOnboardingInput,\n): Promise<CapxulResult<CompleteOrganizationOnboardingResult>> {\n const validated = validateOrganizationInput(input);\n if (!validated.ok) return validated;\n\n const session = await ops.currentSession();\n if (session === null) return fail(Errors.notAuthenticated());\n\n const written = await ops.completeIdentityOnboarding({\n authUserId: session.authUserId,\n email: session.email,\n displayName: validated.value.ownerDisplayName,\n country: validated.value.country,\n });\n if (!written.ok) return fail(written.error);\n\n // The founder's personal Safe must exist before createOrg derives the Org Safe\n // (D7/D10a) — provision is awaited here, ahead of createOrg.\n const provisioned = await ops.triggerProvisioning();\n if (!provisioned.ok) return fail(provisioned.error);\n\n const org = await ops.createOrg({\n name: validated.value.organizationName,\n handle: validated.value.handle,\n template: DEFAULT_ORG_TEMPLATE,\n country: validated.value.country,\n });\n if (!org.ok) return fail(org.error);\n ops.kickProvisioning();\n\n const lifecycle = await ops.readLifecycle();\n if (!lifecycle.ok) return fail(lifecycle.error);\n return { ok: true, value: { org: org.value, lifecycle: lifecycle.value } };\n}\n\ntype ValidatedPersonal = {\n readonly displayName: string;\n readonly country: CountryCode;\n readonly withdrawalAddress?: Address;\n};\n\ntype ValidatedOrganization = {\n readonly organizationName: string;\n readonly handle: string;\n readonly country: CountryCode;\n readonly ownerDisplayName: string;\n};\n\nfunction validatePersonalInput(\n input: CompletePersonalOnboardingInput,\n): CapxulResult<ValidatedPersonal> {\n const displayName = requireNonEmpty(input.displayName, \"displayName\");\n if (!displayName.ok) return displayName;\n const country = parseCountry(input.country);\n if (!country.ok) return country;\n if (input.withdrawalAddress === undefined) {\n return { ok: true, value: { displayName: displayName.value, country: country.value } };\n }\n const withdrawalAddress = parseAddress(input.withdrawalAddress, \"withdrawalAddress\");\n if (!withdrawalAddress.ok) return withdrawalAddress;\n return {\n ok: true,\n value: {\n displayName: displayName.value,\n country: country.value,\n withdrawalAddress: withdrawalAddress.value,\n },\n };\n}\n\nfunction validateOrganizationInput(\n input: CompleteOrganizationOnboardingInput,\n): CapxulResult<ValidatedOrganization> {\n const organizationName = requireNonEmpty(input.organizationName, \"organizationName\");\n if (!organizationName.ok) return organizationName;\n const handle = requireNonEmpty(input.handle, \"handle\");\n if (!handle.ok) return handle;\n const ownerDisplayName = requireNonEmpty(input.ownerDisplayName, \"ownerDisplayName\");\n if (!ownerDisplayName.ok) return ownerDisplayName;\n const country = parseCountry(input.country);\n if (!country.ok) return country;\n return {\n ok: true,\n value: {\n organizationName: organizationName.value,\n handle: handle.value,\n country: country.value,\n ownerDisplayName: ownerDisplayName.value,\n },\n };\n}\n\nfunction requireNonEmpty(value: string, field: string): CapxulResult<string> {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n if (trimmed.length === 0) {\n return fail(Errors.invalidInput(field, \"must be a non-empty string\"));\n }\n return { ok: true, value: trimmed };\n}\n\nfunction parseCountry(value: string): CapxulResult<CountryCode> {\n try {\n return { ok: true, value: toCountryCode(value) };\n } catch (cause) {\n return fail(invalidFrom(\"country\", cause, \"must be an ISO-3166 alpha-2 code\"));\n }\n}\n\nfunction parseAddress(value: string, field: string): CapxulResult<Address> {\n try {\n return { ok: true, value: toAddress(value) };\n } catch (cause) {\n return fail(invalidFrom(field, cause, \"must be a 0x-prefixed 20-byte address\"));\n }\n}\n\nfunction invalidFrom(field: string, cause: unknown, fallback: string): CapxulErrorType {\n const message = cause instanceof Error && cause.message.length > 0 ? cause.message : fallback;\n return Errors.invalidInput(field, message);\n}\n\nfunction fail<T>(error: CapxulErrorType): CapxulResult<T> {\n return { ok: false, error: error instanceof CapxulError ? error : Errors.unknown(error) };\n}\n","// Public consumer-facing `client.onboarding` surface (D-ONBOARD · #669).\n//\n// The two post-OTP onboarding-complete verbs that bridge the auth → provision\n// bookends. Onboarding is PRE-SCOPE — the on-ramp that precedes the D-RELATE\n// actor scopes (`capxul.account` / `capxul.org(orgId)`): you onboard once, then\n// act within the resulting entity. The frontend expresses product intent; the\n// SDK owns the identity → link → (org) createOrg → provision choreography\n// (`flows/onboarding.ts`).\n//\n// Per `docs/canon/rules/public-surface.md`: named exports only, no Effect /\n// flow-actor / program leak on the surface, every return type is a real plain\n// record. Both verbs reuse existing types only — `AccountStatus` (the post-auth\n// readiness ladder, `account.ts`) as `lifecycle`, and `OrgView` (`org.ts`).\n// `lifecycle.status` is the single routing source of truth — no `nextStep`, no\n// `profileId`, no `accountType`.\n//\n// Leak rule (D-EXEC): no Safe / UserOp / wei / chain on the wire or surface;\n// `withdrawalAddress` is the one allowed raw-0x class (the withdrawal class).\n//\n// `lifecycle` is the existing leak-safe `AccountLifecycle` (the type\n// `useCapxulAccountLifecycle()` returns) — NOT the internal `AccountStatus`\n// readiness ladder, which carries the Safe address + chain. The PRD's DX\n// shorthand `lifecycle.status === \"accountReady\"` maps to AccountLifecycle's\n// terminal `\"ready\"` status (see docs/onboarding.md).\n\nimport { Errors } from \"@capxul/config\";\n\nimport {\n runCompleteOrganizationOnboarding,\n runCompletePersonalOnboarding,\n type OnboardingOps,\n} from \"../flows/onboarding\";\nimport type { AccountLifecycle } from \"./account\";\nimport type { OrgView } from \"./org\";\nimport type { CapxulResult } from \"./types\";\n\nexport type { OnboardingOps, OnboardingSession } from \"../flows/onboarding\";\n\n/**\n * Input to `capxul.onboarding.completePersonal`. `displayName` + `country`\n * (ISO-3166, persisted to `identities.country`) are required; `withdrawalAddress`\n * is the OPTIONAL cash-out destination — a `0x`-prefixed 20-byte address string\n * (the one allowed raw-0x class), validated + normalized at the boundary.\n */\nexport type CompletePersonalOnboardingInput = {\n readonly displayName: string;\n readonly country: string;\n readonly withdrawalAddress?: string;\n};\n\n/**\n * Input to `capxul.onboarding.completeOrganization`. `handle` is the org slug\n * (`createOrg` requires it); `ownerDisplayName` is the founder's personal\n * identity profile.\n */\nexport type CompleteOrganizationOnboardingInput = {\n readonly organizationName: string;\n readonly handle: string;\n readonly country: string;\n readonly ownerDisplayName: string;\n};\n\n/** Result of `completePersonal` — the post-onboarding readiness snapshot. */\nexport type CompletePersonalOnboardingResult = {\n readonly lifecycle: AccountLifecycle;\n};\n\n/** Result of `completeOrganization` — the created org + readiness snapshot. */\nexport type CompleteOrganizationOnboardingResult = {\n readonly org: OrgView;\n readonly lifecycle: AccountLifecycle;\n};\n\n/**\n * Onboarding method bundle, exposed at `client.onboarding`. Exactly two verbs;\n * the choreography lives in `flows/onboarding.ts`.\n */\nexport interface OnboardingMethods {\n completePersonal(\n input: CompletePersonalOnboardingInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<CompletePersonalOnboardingResult>>;\n completeOrganization(\n input: CompleteOrganizationOnboardingInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<CompleteOrganizationOnboardingResult>>;\n}\n\n/**\n * Onboarding method surface. The thin namespace over the `flows/onboarding.ts`\n * choreography: it adds the `signal`-abort pre-check and delegates to the run\n * functions. The `OnboardingOps` seam is supplied by `assembleCapxulClient`\n * (real ops over the account lane + createOrg + IdentityPort) or by tests\n * (in-memory double).\n */\nexport function makeOnboardingMethods(ops: OnboardingOps): OnboardingMethods {\n return {\n completePersonal(input, options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"onboarding.completePersonal\" }),\n });\n }\n return runCompletePersonalOnboarding(ops, input);\n },\n completeOrganization(input, options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"onboarding.completeOrganization\" }),\n });\n }\n return runCompleteOrganizationOnboarding(ops, input);\n },\n };\n}\n","// detectAuthCacheAdapter — browser-clean auto-detect (SDK publish readiness · I1).\n// Selects the AuthCachePort adapter for the default `@capxul/sdk` entry:\n//\n// - `globalThis.window?.localStorage` defined → BrowserAuthCacheAdapter\n// - else → InMemoryAuthCacheAdapter\n//\n// The Node filesystem adapter pulls in `@effect/platform-node`, which must NOT\n// reach a browser-shaped bundle (published-package-boundaries.md). Node\n// consumers that want on-disk persistence import `detectNodeAuthCacheAdapter`\n// (or `FileSystemAuthCacheAdapter`) from `@capxul/sdk/node` and pass it as\n// `createCapxulClient({ authCache })`.\n\nimport { BrowserAuthCacheAdapter } from \"../adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport { InMemoryAuthCacheAdapter } from \"../adapters/auth-cache/InMemoryAuthCacheAdapter\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { WindowLike } from \"./window-like\";\n\nexport function detectAuthCacheAdapter(): AuthCachePort {\n const globalAny = globalThis as unknown as {\n readonly window?: WindowLike;\n };\n if (globalAny.window?.localStorage !== undefined) {\n return new BrowserAuthCacheAdapter(globalAny.window.localStorage);\n }\n return new InMemoryAuthCacheAdapter();\n}\n","import { Effect, Layer } from \"effect\";\n\nimport { bootAuthFlow, createAuthFlowMachine, type AuthFlowObserver } from \"../flows/auth\";\nimport type { FlowPorts } from \"../flows/types\";\nimport { makeAuthMethods, type AuthMethods } from \"./auth\";\nimport { makeSmartAccountMethods, type SmartAccountMethods } from \"./smart-account\";\nimport { makeIdentityMethods, type IdentityMethods } from \"./identity\";\nimport { makeAccountMethods, type AccountMethods } from \"./account\";\nimport { makeAccountsMethods, type AccountsMethods, type AccountsFaucetMethods } from \"./accounts\";\nimport {\n makeFinancialOpsMethods,\n type HandlesMethods,\n type MeMethods,\n type PayeesMethods,\n type PaymentsMethods,\n type PaymentDocumentsMethods,\n type PaymentRequestsMethods,\n type WorkbenchMethods,\n} from \"./financial-ops\";\nimport { makeSubAccountsMethods, type SubAccountsMethods } from \"./sub-accounts\";\nimport { makeOrgMethods, type OrgMethods } from \"./org\";\nimport { makeOnboardingMethods, type OnboardingMethods } from \"./onboarding\";\nimport { currentSession } from \"./account-deps\";\nimport { runPortEffect } from \"./_shared/effect-actor-bridge\";\nimport type { OnboardingOps } from \"../flows/onboarding\";\nimport { detectAuthCacheAdapter } from \"./factory\";\nimport type { AccountRequirement } from \"./account-providers\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { SafeDeploymentConfig } from \"../ports/safe-deployment\";\nimport type { OrgPort, OrgRolesDeploymentPort, OrgSpendPort } from \"../ports/org\";\nimport type { CapxulSigner } from \"../signer\";\nimport { AuthClientPortTag } from \"../ports/auth-client\";\nimport { ClockPortTag } from \"../ports/clock\";\nimport { TelemetryPortTag, type TelemetryPort } from \"../ports/telemetry\";\n\nexport interface CapxulClient {\n readonly auth: AuthMethods;\n readonly smartAccount: SmartAccountMethods;\n readonly identity: IdentityMethods;\n /**\n * Consumer-facing account readiness surface (issue #159 · AC1+AC3).\n * Exactly `getStatus` + `ensureReady`; the `_internal.account`\n * namespace with `provision` + `deploySafe` lands in sibling #161.\n */\n readonly account: AccountMethods;\n /**\n * Consumer-facing logical Account money read (M2 Slice S1a · #265).\n * Returns `{ balance, available }` as `Money` — never wei or token units.\n */\n readonly accounts: AccountsMethods;\n readonly me: MeMethods;\n readonly handles: HandlesMethods;\n readonly payees: PayeesMethods;\n /**\n * Direct Payments surface (G2 · #545). `pay` records a validated-recipient\n * payment; `list`/`get` read the ledger; `markSettled` is the host-execution\n * callback. The MCP `draft → simulate → approve → execute` workbench is G6.\n */\n readonly payments: PaymentsMethods;\n /** Payment document verification (G2 · #545): re-derive the EIP-712 hash. */\n readonly paymentDocuments: PaymentDocumentsMethods;\n /**\n * Receivables surface (G5 · #548). `create` opens a `PaymentRequest` with a\n * fixed-amount link; `markSent`/`markViewed`/`cancel` move the funnel;\n * `collect` settles the receivable into the Payment ledger + mints a receipt\n * linked by `documentHash`; `list`/`get`/`getByLink`/`reconcile` read it.\n */\n readonly paymentRequests: PaymentRequestsMethods;\n /**\n * Decomposed workbench + trust substrate (G6 · #549). The MCP\n * `draft → simulate → approvals.request → execute` workbench: the edge\n * PROPOSES, the BACKEND mints a one-time plan-bound approval token via the\n * human's browser (#510), and `execute` consumes it. Taint / idempotency /\n * stale-state / scope guards are enforced backend-side.\n */\n readonly workbench: WorkbenchMethods;\n /** Sub-account lifecycle (M2 Slice S2a · #267). Transfer lands in S2b. */\n readonly subAccounts: SubAccountsMethods;\n /**\n * Organization domain surface (canon `org-domain-model.md` §C2/§C3, D13).\n * `createOrg(input)` creates an Org; `orgs()` lists the Orgs you belong to;\n * `org(orgId)` resolves the entity-scoped bundle (treasury / members / roles\n * / invite / removeMember / assignRole / spend). Explicit entity scoping —\n * NO stateful active context (D13). RED until the S1→S4 slices fill it.\n */\n readonly createOrg: OrgMethods[\"createOrg\"];\n readonly orgs: OrgMethods[\"orgs\"];\n readonly org: OrgMethods[\"org\"];\n /**\n * Onboarding domain surface (D-ONBOARD · #669). `completePersonal` /\n * `completeOrganization` bridge the post-OTP auth → provision bookends:\n * persist the first identity profile (+ org), then trigger the existing\n * provisioning lane. Pre-scope — the on-ramp before the D-RELATE actor\n * scopes. `lifecycle.status` is the single routing source of truth.\n */\n readonly onboarding: OnboardingMethods;\n /**\n * Internal observation namespace. Consumers MUST NOT drive the actor\n * directly — use the method bundles instead.\n *\n * @internal-use\n */\n readonly _internal: {\n readonly authActor: AuthFlowObserver;\n /**\n * Resolved bootstrap for this client instance (chain, auth URLs, etc.).\n * Off the public surface per production-surface-policy.md (#31).\n */\n readonly bootstrap: BootstrapResolution;\n /**\n * Dev-only faucet bundle (production-surface-policy.md). `fund` lives here,\n * NOT on the public `client.accounts` surface.\n */\n readonly accounts: AccountsFaucetMethods;\n /** Telemetry port for error reporting. Used by React hooks to report errors before throwing. */\n readonly telemetry?: TelemetryPort;\n readonly close?: () => Promise<void>;\n };\n}\n\nexport interface CreateCapxulClientInput {\n /**\n * The 13-port `FlowPorts` bundle. The factory narrows this to the\n * 3-port AuthFlow subset (`authClient`, `clock`, `telemetry`) for\n * the flow internally, and uses additional ports (`identity`,\n * `smartAccount`) for the method bundles.\n */\n readonly ports: FlowPorts;\n /**\n * Bootstrap resolution for this client instance. The factory closes over\n * `bootstrap.chainId` internally; consumers do not pass a standalone\n * chainId and no method boundary accepts one.\n */\n readonly bootstrap: BootstrapResolution;\n /**\n * Optional AuthCachePort. When omitted, `detectAuthCacheAdapter()` selects\n * the appropriate per-environment adapter (Browser/FileSystem/InMemory).\n */\n readonly authCache?: AuthCachePort;\n /**\n * Optional AbortSignal reserved for callers that coordinate client lifetime.\n */\n readonly signal?: AbortSignal;\n /**\n * OTP TTL window in ms. Default 300_000 (5 min).\n */\n readonly otpTtlMs?: number;\n /**\n * Optional per-call timeout for invoked auth requests.\n */\n readonly invokeTimeoutMs?: number;\n /**\n * Init-time account readiness target (issue #159 · AC4). The factory\n * closes over this so `client.account.{getStatus,ensureReady}` don't\n * need to take a per-call requirement arg. REQUIRED — there is no\n * hidden default. Consumers building flows that never need a smart\n * account pass `\"none\"`; flows that want a counterfactual deposit\n * address pass `\"counterfactual\"`; flows that need an on-chain Safe\n * pass `\"deployed\"` (deploy path lands in sibling #161).\n */\n readonly requirement: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n /**\n * Optional live Org-deploy lane (canon D10 SDK-orchestrated Org Safe deploy +\n * D3 RPC treasury). When supplied, `client.createOrg` / `org(id).treasury`\n * run the live path (real deploy + on-chain balance); when omitted, the\n * hermetic `$0` path runs (a fresh Org has no on-chain funds). The adapter\n * that CONSTRUCTS this port (deployer key + RPC + authenticated Convex seam)\n * is wired by the CLI deploy-stack; the factory only threads it through.\n */\n readonly orgDeploymentPort?: OrgPort;\n /** Locked D6 data-port name. Prefer over `orgDeploymentPort` in new code. */\n readonly orgPort?: OrgPort;\n /** S2 deploy/grant/revoke port. S2 uses deploy; S3 adds grant/revoke. */\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n /** S4 treasury-spend authority + submit port. */\n readonly orgSpendPort?: OrgSpendPort;\n readonly orgDeploymentConfig?: SafeDeploymentConfig;\n}\n\nexport function assembleCapxulClient(input: CreateCapxulClientInput): CapxulClient {\n const authCache = input.authCache ?? detectAuthCacheAdapter();\n\n const layer = Layer.mergeAll(\n Layer.succeed(AuthClientPortTag, input.ports.authClient),\n Layer.succeed(ClockPortTag, input.ports.clock),\n Layer.succeed(TelemetryPortTag, input.ports.telemetry),\n );\n const authFlowInput = input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs };\n const actor = Effect.runSync(\n bootAuthFlow(createAuthFlowMachine(), authFlowInput).pipe(Effect.provide(layer)),\n );\n if (input.signal !== undefined) {\n input.signal.addEventListener(\"abort\", () => actor.stop(), { once: true });\n }\n const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;\n let detectPendingOrgInvitations: (() => Promise<void>) | undefined;\n let kickProvisioning: (() => void) | undefined;\n const accountInput: Parameters<typeof makeAccountMethods>[0] = {\n actor,\n authCache,\n identityPort: input.ports.identity,\n smartAccountPort: input.ports.smartAccount,\n telemetry: input.ports.telemetry,\n chainId: input.bootstrap.chainId,\n requirement: input.requirement,\n accountReadPort: input.ports.accountRead,\n ...(input.signer === undefined ? {} : { signer: input.signer }),\n };\n const accountBundle = makeAccountMethods(accountInput);\n kickProvisioning = accountBundle.kickProvisioning;\n const account = accountBundle.methods;\n const authMethodsInput: Parameters<typeof makeAuthMethods>[0] = {\n actor,\n authClient: input.ports.authClient,\n authCache,\n clock: input.ports.clock,\n telemetry: input.ports.telemetry,\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n ...(input.invokeTimeoutMs === undefined ? {} : { invokeTimeoutMs: input.invokeTimeoutMs }),\n // PRD #462: no binding/pregen step exists — the lane provisions from the\n // authenticated email alone; the signer (when present) only claims.\n afterVerifyOtp: async () => {\n const browserSigner = input.signer;\n if (\n browserSigner !== undefined &&\n \"resetSession\" in browserSigner &&\n typeof browserSigner.resetSession === \"function\"\n ) {\n // Fresh OTP in the same browser tab reuses OpenFort localStorage + an\n // in-memory cached EOA unless we reset before the account lane runs.\n browserSigner.resetSession();\n }\n await detectPendingOrgInvitations?.();\n kickProvisioning?.();\n },\n };\n const auth = makeAuthMethods(authMethodsInput);\n const smartAccountInput: Parameters<typeof makeSmartAccountMethods>[0] = {\n actor,\n smartAccountPort: input.ports.smartAccount,\n chainId: input.bootstrap.chainId,\n sessionAuthUserIdFallback: null,\n telemetry: input.ports.telemetry,\n };\n const smartAccount = makeSmartAccountMethods(smartAccountInput);\n const identityInput: Parameters<typeof makeIdentityMethods>[0] = {\n identityPort: input.ports.identity,\n actor,\n };\n const identity = makeIdentityMethods(identityInput);\n const accountsInput: Parameters<typeof makeAccountsMethods>[0] = {\n accountReadPort: input.ports.accountRead,\n chainId: input.bootstrap.chainId,\n telemetry: input.ports.telemetry,\n };\n const accounts = makeAccountsMethods(accountsInput);\n const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });\n const subAccountsInput: Parameters<typeof makeSubAccountsMethods>[0] = {\n subAccountPort: input.ports.subAccount,\n telemetry: input.ports.telemetry,\n };\n const subAccounts = makeSubAccountsMethods(subAccountsInput);\n // Organization domain surface (canon §C2/§C3, D13). S1 wires `createOrg` /\n // `orgs` / `treasury` to their Effect programs; the live `OrgPort` (D10\n // SDK-orchestrated deploy + D3 RPC treasury) is supplied by the live-proof\n // slice — until then the hermetic `$0` path runs. Entity scoping is explicit\n // per `org(orgId)` call.\n const orgMethods = makeOrgMethods({\n chainId: input.bootstrap.chainId,\n telemetry: input.ports.telemetry,\n ...(selectedOrgPort === undefined ? {} : { orgPort: selectedOrgPort }),\n ...(input.orgRolesDeploymentPort === undefined\n ? {}\n : { orgRolesDeploymentPort: input.orgRolesDeploymentPort }),\n ...(input.orgSpendPort === undefined ? {} : { orgSpendPort: input.orgSpendPort }),\n });\n if (selectedOrgPort !== undefined) {\n detectPendingOrgInvitations = async () => {\n await orgMethods.orgs.detectAndAcceptPendingInvitations();\n };\n }\n // Onboarding domain surface (D-ONBOARD · #669). The choreography composes the\n // identity write (IdentityPort.completeOnboarding), the existing provisioning\n // lane (account._internal.provision + kickProvisioning), the leak-safe\n // lifecycle read (account.getLifecycle), and the existing createOrg verb — it\n // reimplements none of them.\n const onboardingOps: OnboardingOps = {\n currentSession: async () => {\n const session = await currentSession(actor, authCache);\n return session === null ? null : { authUserId: session.authUserId, email: session.email };\n },\n completeIdentityOnboarding: (write) =>\n runPortEffect(input.ports.identity.completeOnboarding(write)),\n triggerProvisioning: () => account._internal.provision(),\n kickProvisioning: () => kickProvisioning?.(),\n readLifecycle: () => account.getLifecycle(),\n createOrg: (createOrgInput) => orgMethods.createOrg(createOrgInput),\n };\n const onboarding = makeOnboardingMethods(onboardingOps);\n const client = {\n auth,\n smartAccount,\n identity,\n account,\n accounts,\n me: financialOps.me,\n handles: financialOps.handles,\n payees: financialOps.payees,\n payments: financialOps.payments,\n paymentDocuments: financialOps.paymentDocuments,\n paymentRequests: financialOps.paymentRequests,\n workbench: financialOps.workbench,\n subAccounts,\n createOrg: orgMethods.createOrg,\n orgs: orgMethods.orgs,\n org: orgMethods.org,\n onboarding,\n _internal: {\n authActor: {\n input: actor.input,\n getSnapshot: actor.getSnapshot,\n stop: actor.stop,\n },\n bootstrap: input.bootstrap,\n // Expose ONLY the dev faucet here, not the full bundle — the runtime\n // shape matches the narrower `AccountsFaucetMethods` type so `read`\n // never leaks onto `_internal.accounts` (production-surface-policy.md).\n accounts: { fund: accounts.fund },\n telemetry: input.ports.telemetry,\n },\n } satisfies CapxulClient;\n\n return client;\n}\n","import { Context, Effect, Either, Exit, Layer, Scope } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toAllowedOrigin, toPublishableKey, type ChainId } from \"@capxul/types\";\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\n\nimport { BetterAuthBrowserLayer, BetterAuthNodeLayer } from \"./adapters/auth-client\";\nimport { HttpBootstrapLayer } from \"./adapters/bootstrap\";\nimport { SystemClockLayer } from \"./adapters/clock\";\nimport { ConvexCallLayer, type ConvexClientShape } from \"./adapters/convex-call\";\nimport { ConvexCredentialsLayer } from \"./adapters/credentials\";\nimport { SystemEnvLayer } from \"./adapters/env\";\nimport { ConvexIdentityLayer } from \"./adapters/identity\";\nimport { ConvexAccountLayer } from \"./adapters/account-read\";\nimport { ConvexSubAccountLayer } from \"./adapters/sub-account/ConvexSubAccountAdapter\";\nimport { ConvexSmartAccountLayer } from \"./adapters/smart-account\";\nimport { PostHogTelemetryLayer } from \"./adapters/telemetry\";\nimport { ConvexTransportLayer } from \"./adapters/transport\";\nimport type { AccountRequirement } from \"./client/account-providers\";\nimport {\n createOpenfortBrowserSignerFromBootstrap,\n type OpenfortBrowserSigner,\n} from \"./openfort/create-openfort-browser-signer\";\nimport type { CapxulSigner } from \"./signer\";\nimport { assembleCapxulClient, type CapxulClient } from \"./client/create-capxul-client\";\nimport { detectAuthCacheAdapter } from \"./client/factory\";\nimport type { CapxulResult } from \"./client/types\";\nimport type { FlowPorts } from \"./flows/types\";\nimport { AuthClientPortTag, type AuthClientPort } from \"./ports/auth-client\";\nimport { AuthCachePortTag, type AuthCachePort } from \"./ports/auth-cache\";\nimport { BootstrapPortTag, type BootstrapPort, type BootstrapResolution } from \"./ports/bootstrap\";\nimport { ClockPortTag } from \"./ports/clock\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"./ports/convex-call\";\nimport { CredentialsPortTag } from \"./ports/credentials\";\nimport { EnvPortTag } from \"./ports/env\";\nimport { IdentityPortTag } from \"./ports/identity\";\nimport { AccountReadPortTag } from \"./ports/account-read\";\nimport { SubAccountPortTag } from \"./ports/sub-account\";\nimport { SmartAccountPortTag } from \"./ports/smart-account\";\nimport type { TelemetryEvent, TelemetryPort } from \"./ports/telemetry\";\nimport { TelemetryPortTag } from \"./ports/telemetry\";\nimport { TransportPortTag } from \"./ports/transport\";\n\nexport type ProductionRuntime = \"browser\" | \"node\";\nexport type ProductionAdapterClose = () => Promise<void>;\n\n/**\n * Interim default Capxul bootstrap host (SDK publish readiness · I3). Node\n * consumers pass neither `origin` nor `bootstrapBaseUrl`; both default here so\n * `createCapxulClient({ publishableKey })` reaches the Capxul backend with no\n * extra wiring. Superseded by the key-encoded host (`cap_pk_live_…`, out of\n * scope this milestone). See\n * `docs/canon/decisions/publishable-key-resolved-config.md`.\n */\nexport const DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL = \"https://api.capxul.com\";\n\n/** Default per-request auth invocation timeout (ms) when the consumer omits it. */\nexport const DEFAULT_INVOKE_TIMEOUT_MS = 30_000;\n\n/**\n * Consumer-facing `createCapxulClient` input (SDK DX public surface · #326).\n * The publishable key is the primary input; bootstrap host, invoke timeout,\n * runtime detection, and auth-cache selection are SDK-owned defaults.\n */\nexport interface CapxulClientInput {\n readonly publishableKey: string;\n /**\n * Init-time account readiness target (issue #159 · AC4). Threaded into\n * `assembleCapxulClient` so `client.account.{getStatus,ensureReady}` reflect\n * the consumer's chosen requirement. Optional — defaults to `\"none\"` (SDK\n * publish readiness · I3) so `createCapxulClient({ publishableKey })` works\n * with no account lane.\n */\n readonly requirement?: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n}\n\n/**\n * Internal production adapter input for `@capxul/sdk/production` and hermetic\n * tests. Extends the consumer contract with bootstrap/fetch/runtime/auth-cache/\n * telemetry/signal/timeout seams that must not appear on the bare\n * `@capxul/sdk` barrel. Org deployment port factories and deploy config live\n * on `@capxul/sdk/testing/org-deployment-client` (#327).\n */\nexport interface ProductionAdapterInput extends CapxulClientInput {\n readonly origin?: string;\n readonly bootstrapBaseUrl?: string;\n /** Optional BetterAuth host override (dogfood Vite proxy → same-origin `/api/auth`). */\n readonly authBaseUrl?: string;\n readonly runtime?: ProductionRuntime;\n readonly authCache?: AuthCachePort;\n readonly telemetry?: TelemetryPort;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n}\n\n/**\n * @internal Test-injection seam. `convexClientFactory` is intentionally NOT a\n * member of the public `ProductionAdapterInput` (production-surface-policy.md):\n * consumers must not inject a Convex client. Hermetic tests pass a fake through\n * the fixture; it is read back here.\n */\ninterface ProductionConvexClientFactorySeam {\n readonly convexClientFactory?: (convexUrl: string) => ConvexClientShape;\n}\n\nexport interface ProductionAdapters {\n readonly ports: FlowPorts;\n readonly bootstrap: BootstrapResolution;\n readonly close: ProductionAdapterClose;\n}\n\nexport type ProductionAdapterLayerName =\n | \"bootstrap\"\n | \"authClient\"\n | \"authCache\"\n | \"identity\"\n | \"smartAccount\"\n | \"accountRead\"\n | \"subAccount\"\n | \"credentials\"\n | \"clock\"\n | \"env\"\n | \"telemetry\"\n | \"transport\"\n | \"convexCall\";\n\ntype ProductionFlowPortTags =\n | AuthClientPortTag\n | AuthCachePortTag\n | BootstrapPortTag\n | ClockPortTag\n | ConvexCallPortTag\n | CredentialsPortTag\n | EnvPortTag\n | IdentityPortTag\n | SmartAccountPortTag\n | AccountReadPortTag\n | SubAccountPortTag\n | TelemetryPortTag\n | TransportPortTag;\n\ntype RefreshConvexAuthRef = {\n current: (() => void) | null;\n pending: boolean;\n};\n\nconst SDK_VERSION = sdkPackageJson.version;\n\ntype ProductionAdapterLayerOutput<N extends ProductionAdapterLayerName> = {\n readonly bootstrap: BootstrapPortTag;\n readonly authClient: AuthClientPortTag;\n readonly authCache: AuthCachePortTag;\n readonly identity: IdentityPortTag;\n readonly smartAccount: SmartAccountPortTag;\n readonly accountRead: AccountReadPortTag;\n readonly subAccount: SubAccountPortTag;\n readonly credentials: CredentialsPortTag;\n readonly clock: ClockPortTag;\n readonly env: EnvPortTag;\n readonly telemetry: TelemetryPortTag;\n readonly transport: TransportPortTag;\n readonly convexCall: ConvexCallPortTag;\n}[N];\n\nexport interface ProductionRuntimeUrls {\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n}\n\nexport interface ProductionAdapterLayerInput {\n readonly bootstrap: BootstrapPort;\n readonly runtime: ProductionRuntime;\n readonly origin?: string;\n readonly runtimeUrls: ProductionRuntimeUrls;\n /**\n * Bootstrap-resolved chain. The `ConvexSubAccountAdapter`'s `transfer`\n * action reads the Safe's live `balanceOf` on this chain (canon §2/§5);\n * the consumer-facing `transfer({ from, to, amount })` carries no chainId\n * (public-surface no-consumer-chainId rule), so the adapter closes over it.\n */\n readonly chainId: ChainId;\n readonly authCache?: AuthCachePort;\n readonly telemetry?: TelemetryPort;\n readonly convexClient?: ConvexClientShape;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}\n\nexport type ProductionAdapterLayerEntry<\n N extends ProductionAdapterLayerName = ProductionAdapterLayerName,\n> = {\n readonly [K in N]: {\n readonly name: K;\n readonly layer: Layer.Layer<ProductionAdapterLayerOutput<K>, unknown, unknown>;\n };\n}[N];\n\nexport const collectProductionFlowPorts: Effect.Effect<FlowPorts, never, ProductionFlowPortTags> =\n Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const authCache = yield* AuthCachePortTag;\n const bootstrap = yield* BootstrapPortTag;\n const clock = yield* ClockPortTag;\n const convexCall = yield* ConvexCallPortTag;\n const credentials = yield* CredentialsPortTag;\n const env = yield* EnvPortTag;\n const identity = yield* IdentityPortTag;\n const smartAccount = yield* SmartAccountPortTag;\n const accountRead = yield* AccountReadPortTag;\n const subAccount = yield* SubAccountPortTag;\n const telemetry = yield* TelemetryPortTag;\n const transport = yield* TransportPortTag;\n return {\n authClient,\n authCache,\n identity,\n smartAccount,\n accountRead,\n subAccount,\n credentials,\n bootstrap,\n clock,\n env,\n telemetry,\n transport,\n convexCall,\n };\n });\n\nexport function makeProductionAdapterLayerEntries(\n input: ProductionAdapterLayerInput,\n): readonly ProductionAdapterLayerEntry[] {\n const refreshConvexAuthRef: RefreshConvexAuthRef = { current: null, pending: false };\n return [\n {\n name: \"bootstrap\",\n layer: productionBootstrapPortLayer(input.bootstrap),\n },\n {\n name: \"authClient\",\n layer: productionAuthClientLayer(input, refreshConvexAuthRef),\n },\n {\n name: \"authCache\",\n layer: productionAuthCacheLayer(input),\n },\n {\n name: \"identity\",\n layer: ConvexIdentityLayer(),\n },\n {\n name: \"smartAccount\",\n layer: ConvexSmartAccountLayer(),\n },\n {\n name: \"accountRead\",\n layer: ConvexAccountLayer(),\n },\n {\n name: \"subAccount\",\n layer: ConvexSubAccountLayer(input.chainId),\n },\n {\n name: \"credentials\",\n layer: ConvexCredentialsLayer(),\n },\n {\n name: \"clock\",\n layer: SystemClockLayer(),\n },\n {\n name: \"env\",\n layer: SystemEnvLayer(),\n },\n {\n name: \"telemetry\",\n layer:\n input.telemetry === undefined\n ? PostHogTelemetryLayer({ capture: () => undefined })\n : Layer.succeed(TelemetryPortTag, input.telemetry),\n },\n {\n name: \"transport\",\n layer: ConvexTransportLayer(),\n },\n {\n name: \"convexCall\",\n layer: productionConvexCallLayer(input, refreshConvexAuthRef),\n },\n ];\n}\n\nexport function mergeProductionAdapterLayers(\n entries: readonly ProductionAdapterLayerEntry[],\n): Layer.Layer<ProductionFlowPortTags, unknown, never> {\n const byName = new Map<ProductionAdapterLayerName, Layer.Layer<never, unknown, unknown>>();\n for (const entry of entries) {\n byName.set(entry.name, entry.layer as Layer.Layer<never, unknown, unknown>);\n }\n const authClientLayer = byName.get(\"authClient\");\n const convexCallLayer = byName.get(\"convexCall\");\n // Phase 1: authClient -> convexCall. The auth wrapper reads\n // RefreshConvexAuthRef at call time, after this convex layer registers\n // the concrete refreshAuth callback during construction.\n const convexCallReadyLayer =\n convexCallLayer === undefined || authClientLayer === undefined\n ? convexCallLayer\n : convexCallLayer.pipe(Layer.provide(authClientLayer));\n\n const readyLayers = entries.map((entry) => {\n const layer = byName.get(entry.name) ?? (entry.layer as Layer.Layer<never, unknown, unknown>);\n if (entry.name === \"convexCall\") return convexCallReadyLayer ?? layer;\n if (isConvexDependentLayer(entry.name)) {\n // Phase 2: convexCallReady -> Convex-backed domain ports.\n return convexCallReadyLayer === undefined\n ? layer\n : layer.pipe(Layer.provide(convexCallReadyLayer));\n }\n return layer;\n });\n\n const merged = readyLayers.reduce((current, layer) => Layer.merge(current, layer), Layer.empty);\n // Entries are heterogeneous Layers stored behind one contract; the cast is\n // localized here, while production-layers.test.ts proves omissions fail\n // startup instead of silently assembling a partial FlowPorts graph.\n return merged as Layer.Layer<ProductionFlowPortTags, unknown, never>;\n}\n\nfunction isConvexDependentLayer(name: ProductionAdapterLayerName): boolean {\n return (\n name === \"identity\" ||\n name === \"smartAccount\" ||\n name === \"accountRead\" ||\n name === \"subAccount\" ||\n name === \"credentials\" ||\n name === \"transport\"\n );\n}\n\nfunction productionBootstrapPortLayer(\n bootstrap: BootstrapPort,\n): Layer.Layer<BootstrapPortTag, never, never> {\n return Layer.succeed(BootstrapPortTag, bootstrap);\n}\n\nfunction productionAuthClientLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n): Layer.Layer<AuthClientPortTag, never, never> {\n const baseLayer =\n input.runtime === \"browser\"\n ? BetterAuthBrowserLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n })\n : BetterAuthNodeLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n });\n\n return baseLayer.pipe(\n Layer.map((context) => {\n const authClient = Context.get(context, AuthClientPortTag);\n return Context.make(\n AuthClientPortTag,\n refreshConvexAuthOnSession(authClient, () => {\n const refresh = refreshConvexAuthRef.current;\n if (refresh === null) {\n refreshConvexAuthRef.pending = true;\n return;\n }\n refresh();\n }),\n );\n }),\n );\n}\n\nfunction productionAuthCacheLayer(\n input: ProductionAdapterLayerInput,\n): Layer.Layer<AuthCachePortTag, never, never> {\n return Layer.succeed(AuthCachePortTag, input.authCache ?? detectAuthCacheAdapter());\n}\n\nfunction productionConvexCallLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n): Layer.Layer<ConvexCallPortTag, never, AuthClientPortTag> {\n return Layer.unwrapEffect(\n Effect.map(AuthClientPortTag, (authClient) =>\n ConvexCallLayer({\n convexUrl: input.runtimeUrls.convexUrl,\n ...(input.convexClient === undefined ? {} : { client: input.convexClient }),\n tokenProvider: async ({ forceRefreshToken }) => {\n const tokenResult = await Effect.runPromise(\n Effect.either(\n authClient.getConvexJwt({\n forceRefresh: forceRefreshToken,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n }),\n ),\n );\n if (Either.isLeft(tokenResult)) return null;\n return String(tokenResult.right.token);\n },\n }).pipe(\n Layer.map((context) => {\n const convexCall = Context.get(context, ConvexCallPortTag);\n if (isRefreshableConvexCallPort(convexCall)) {\n refreshConvexAuthRef.current = () => convexCall.refreshAuth();\n if (refreshConvexAuthRef.pending) {\n refreshConvexAuthRef.pending = false;\n refreshConvexAuthRef.current();\n }\n }\n return context;\n }),\n ),\n ),\n );\n}\n\nfunction isRefreshableConvexCallPort(\n convexCall: ConvexCallPort,\n): convexCall is ConvexCallPort & { readonly refreshAuth: () => void } {\n return \"refreshAuth\" in convexCall && typeof convexCall.refreshAuth === \"function\";\n}\n\nexport async function createProductionAdapters(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<ProductionAdapters>> {\n const resolvedInput = resolveInput(input);\n if (!resolvedInput.ok) return resolvedInput;\n\n const scope = await Effect.runPromise(Scope.make());\n const closeScope = idempotentClose(() => Effect.runPromise(Scope.close(scope, Exit.void)));\n\n const bootstrapLayer = HttpBootstrapLayer({\n bootstrapBaseUrl: resolvedInput.value.bootstrapBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n });\n\n try {\n const bootstrapContext = await Effect.runPromise(Layer.buildWithScope(bootstrapLayer, scope));\n const bootstrap = Context.get(bootstrapContext, BootstrapPortTag);\n const bootstrapResult = await runBootstrap(\n bootstrap.resolve({\n publishableKey: resolvedInput.value.publishableKey,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n }),\n );\n if (!bootstrapResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n reason: bootstrapResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return bootstrapResult;\n }\n\n const runtimeUrlsResult = resolveRuntimeUrls(\n bootstrapResult.value,\n resolvedInput.value.runtime,\n input.authBaseUrl,\n );\n if (!runtimeUrlsResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n reason: runtimeUrlsResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return runtimeUrlsResult;\n }\n const runtimeUrls = runtimeUrlsResult;\n\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_resolved\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n },\n });\n\n let injectedClient: ConvexClientShape | undefined;\n const convexClientFactory = (input as ProductionConvexClientFactorySeam).convexClientFactory;\n if (convexClientFactory !== undefined) {\n try {\n injectedClient = convexClientFactory(runtimeUrls.value.convexUrl);\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n }\n\n const portsLayer = mergeProductionAdapterLayers(\n makeProductionAdapterLayerEntries({\n bootstrap,\n runtime: resolvedInput.value.runtime,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n runtimeUrls: runtimeUrls.value,\n chainId: bootstrapResult.value.chainId,\n ...(input.authCache === undefined ? {} : { authCache: input.authCache }),\n ...(input.telemetry === undefined ? {} : { telemetry: input.telemetry }),\n ...(injectedClient === undefined ? {} : { convexClient: injectedClient }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n }),\n );\n const portsContext = await Effect.runPromise(Layer.buildWithScope(portsLayer, scope));\n const ports = await Effect.runPromise(\n collectProductionFlowPorts.pipe(Effect.provide(portsContext)),\n );\n\n return { ok: true, value: { ports, bootstrap: bootstrapResult.value, close: closeScope } };\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nfunction refreshConvexAuthOnSession(\n authClient: AuthClientPort,\n refresh: () => void,\n): AuthClientPort {\n return {\n ...authClient,\n verifyOtp: (input, options) =>\n authClient.verifyOtp(input, options).pipe(Effect.tap(() => Effect.sync(refresh))),\n signOut: (options) => authClient.signOut(options).pipe(Effect.tap(() => Effect.sync(refresh))),\n };\n}\n\nfunction wireOpenfortSignerLifecycle(\n client: CapxulClient,\n signer: CapxulSigner | OpenfortBrowserSigner | undefined,\n): CapxulClient {\n if (signer === undefined || !(\"resetSession\" in signer)) {\n return client;\n }\n const { resetSession } = signer;\n const signOut = client.auth.signOut.bind(client.auth);\n return {\n ...client,\n auth: {\n ...client.auth,\n signOut: async (options) => {\n try {\n return await signOut(options);\n } finally {\n resetSession();\n }\n },\n },\n };\n}\n\nexport async function createCapxulClient(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<CapxulClient>> {\n const validation = validateCreateCapxulClientInput(input);\n if (!validation.ok) return validation;\n\n const adapters = await createProductionAdapters(input);\n if (!adapters.ok) return adapters;\n try {\n const runtime = input.runtime ?? detectRuntime();\n const resolvedAuthBaseUrl = resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: adapters.value.bootstrap.authBaseUrl,\n runtime,\n ...(input.authBaseUrl === undefined ? {} : { override: input.authBaseUrl }),\n });\n let signer: CapxulSigner | OpenfortBrowserSigner | undefined = input.signer;\n if (\n signer === undefined &&\n (input.requirement ?? \"none\") === \"deployed\" &&\n runtime === \"browser\"\n ) {\n signer = createOpenfortBrowserSignerFromBootstrap({\n ...adapters.value.bootstrap,\n authBaseUrl: resolvedAuthBaseUrl,\n });\n }\n const assembled = assembleCapxulClient({\n ports: adapters.value.ports,\n bootstrap: adapters.value.bootstrap,\n authCache: adapters.value.ports.authCache,\n requirement: input.requirement ?? \"none\",\n ...(signer === undefined ? {} : { signer }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n invokeTimeoutMs: input.invokeTimeoutMs ?? DEFAULT_INVOKE_TIMEOUT_MS,\n });\n const client = wireOpenfortSignerLifecycle(assembled, signer);\n const upstreamClose = adapters.value.close;\n const value = {\n ...client,\n _internal: {\n ...client._internal,\n close: async () => {\n if (\"resetSession\" in (signer ?? {})) {\n (signer as OpenfortBrowserSigner).resetSession();\n }\n await upstreamClose();\n },\n },\n };\n return {\n ok: true,\n value,\n };\n } catch (cause) {\n await adapters.value.close().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createCapxulClient\") };\n }\n}\n\nfunction validateCreateCapxulClientInput(input: ProductionAdapterInput): CapxulResult<void> {\n const runtime = input.runtime ?? detectRuntime();\n if (\n (input.requirement ?? \"none\") === \"deployed\" &&\n input.signer === undefined &&\n runtime !== \"browser\"\n ) {\n return {\n ok: false,\n error: Errors.invalidInput(\"signer\", 'required when requirement is \"deployed\"'),\n };\n }\n return { ok: true, value: undefined };\n}\n\ntype ResolvedInput = {\n readonly publishableKey: ReturnType<typeof toPublishableKey>;\n readonly origin?: ReturnType<typeof toAllowedOrigin>;\n readonly bootstrapBaseUrl: string;\n readonly runtime: ProductionRuntime;\n};\n\nfunction resolveInput(input: ProductionAdapterInput): CapxulResult<ResolvedInput> {\n try {\n const runtime = input.runtime ?? detectRuntime();\n const publishableKey = toPublishableKey(input.publishableKey);\n const origin =\n input.origin === undefined\n ? runtime === \"browser\"\n ? toAllowedOrigin(derivedBrowserOrigin(runtime))\n : undefined\n : toAllowedOrigin(input.origin);\n return {\n ok: true,\n value: {\n publishableKey,\n ...(origin === undefined ? {} : { origin }),\n bootstrapBaseUrl: normalizeHttpUrl(\n \"bootstrapBaseUrl\",\n input.bootstrapBaseUrl ??\n (runtime === \"browser\"\n ? derivedBrowserOrigin(runtime)\n : DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL),\n ),\n runtime,\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nfunction detectRuntime(): ProductionRuntime {\n const globalAny = globalThis as {\n readonly window?: unknown;\n readonly document?: unknown;\n };\n return globalAny.window !== undefined || globalAny.document !== undefined ? \"browser\" : \"node\";\n}\n\nfunction derivedBrowserOrigin(runtime: ProductionRuntime): string {\n if (runtime !== \"browser\") {\n throw Errors.invalidInput(\"origin\", \"required outside browser runtime\");\n }\n const globalAny = globalThis as { readonly location?: { readonly origin?: string } };\n if (typeof globalAny.location?.origin === \"string\" && globalAny.location.origin.length > 0) {\n return globalAny.location.origin;\n }\n throw Errors.invalidInput(\"origin\", \"required when browser location is unavailable\");\n}\n\n/**\n * Browser local dev serves `/api/auth` via the Vite proxy on `window.location.origin`\n * while bootstrap returns the remote Convex site host. Openfort wallet setup reads\n * Better Auth cookies from `get-session` — those only attach on the same origin the\n * OTP flow used, so rewrite when hosts differ.\n */\nexport function resolveBrowserAuthBaseUrl(input: {\n readonly bootstrapAuthBaseUrl: string;\n readonly runtime: ProductionRuntime;\n readonly override?: string;\n}): string {\n if (input.override !== undefined) {\n return normalizeHttpUrl(\"authBaseUrl\", input.override);\n }\n const bootstrapUrl = normalizeHttpUrl(\"authBaseUrl\", input.bootstrapAuthBaseUrl);\n if (input.runtime !== \"browser\") {\n return bootstrapUrl;\n }\n try {\n const origin = derivedBrowserOrigin(input.runtime);\n const localAuthBase = normalizeHttpUrl(\"authBaseUrl\", `${origin}/api/auth`);\n const remoteAuthBase = bootstrapUrl.endsWith(\"/api/auth\")\n ? bootstrapUrl\n : `${bootstrapUrl}/api/auth`;\n if (new URL(remoteAuthBase).host !== new URL(localAuthBase).host) {\n return localAuthBase;\n }\n return bootstrapUrl;\n } catch {\n return bootstrapUrl;\n }\n}\n\nfunction resolveRuntimeUrls(\n bootstrap: BootstrapResolution,\n runtime: ProductionRuntime,\n authBaseUrlOverride?: string,\n): CapxulResult<{ readonly authBaseUrl: string; readonly convexUrl: string }> {\n try {\n return {\n ok: true,\n value: {\n authBaseUrl: resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: bootstrap.authBaseUrl,\n runtime,\n ...(authBaseUrlOverride === undefined ? {} : { override: authBaseUrlOverride }),\n }),\n convexUrl: normalizeHttpUrl(\"convexUrl\", bootstrap.convexUrl),\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nasync function runBootstrap(\n effect: ReturnType<BootstrapPort[\"resolve\"]>,\n): Promise<CapxulResult<BootstrapResolution>> {\n const result = await Effect.runPromise(Effect.either(effect));\n if (Either.isRight(result)) return { ok: true, value: result.right };\n return { ok: false, error: toPublicError(result.left, \"bootstrap.resolve\") };\n}\n\nfunction bootstrapTelemetryEnvelope(\n input: ProductionAdapterInput,\n resolvedInput: ResolvedInput,\n): {\n readonly capxulEnv: ProductionRuntime;\n readonly env: AccountRequirement;\n readonly origin?: string;\n readonly sdkVersion: string;\n} {\n return {\n capxulEnv: resolvedInput.runtime,\n env: input.requirement ?? \"none\",\n ...(resolvedInput.origin === undefined ? {} : { origin: resolvedInput.origin }),\n sdkVersion: SDK_VERSION,\n };\n}\n\nasync function emitBootstrapTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(telemetry.emit(event).pipe(Effect.catchAllDefect(() => Effect.void)));\n}\n\nfunction normalizeHttpUrl(field: string, raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nfunction toPublicError(cause: unknown, operation: string): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const publicError = (cause as { readonly publicError?: unknown }).publicError;\n if (publicError instanceof CapxulError) return publicError;\n const nestedCause = (cause as { readonly cause?: unknown }).cause;\n if (nestedCause instanceof CapxulError) return nestedCause;\n }\n return Errors.providerError(\"sdk-production-adapters\", operation, cause);\n}\n\nfunction idempotentClose(close: () => Promise<void>): ProductionAdapterClose {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n}\n","import {\n createCapxulClient as createCapxulClientFromProductionAdapters,\n type CapxulClientInput,\n} from \"../production\";\nimport type { CapxulClient } from \"./create-capxul-client\";\nimport type { CapxulResult } from \"./types\";\n\n/** Consumer-facing factory — accepts only production-meaningful inputs (#326). */\nexport async function createCapxulClient(\n input: CapxulClientInput,\n): Promise<CapxulResult<CapxulClient>> {\n return createCapxulClientFromProductionAdapters(input);\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,4BAA4B;AA2BvC,0BAA0B,YAAY;;;ACnBxC,MAAa,wBAAwB;;;;;;;;;;;;;;AAoErC,SAAgB,uBAAuB,OAAuB;CAC5D,OAAO,MAAM,KAAK,EAAE,YAAY;AAClC;;;;;;ACzEA,SAAgB,sBAAsB,OAAuB;CAC3D,OAAO,uBAAuB,KAAK;AACrC;;;;AEkDA,MAAa,0BAAiC;CAC5C,SAAS;CACT,SAAS;CACT,UAAA;AACF;AAUW,wBAAwB;AAgBxB,wBAAwB;;;ACtDnC,MAAM,eAAe;AACrB,MAAM,YAAY,OAAO,OAAO,YAAY;AAC5C,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,6BAA6B;AACnC,MAAM,eA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AAM,OAAO,aAAa,OAAO,8BAA8B;CAEjE,OAAO,OAAO,SAAS,EAAE,QAAQ,OAAO,EAAE;AAC5C;AAEA,SAAS,cAAc,OAAgB,WAAgC;CACrE,IAAI,iBAAiB,aAAa,OAAO;CACzC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,MAAM,cAAe,MAA6C;EAClE,IAAI,uBAAuB,aAAa,OAAO;EAC/C,MAAM,cAAe,MAAuC;EAC5D,IAAI,uBAAuB,aAAa,OAAO;CACjD;CACA,OAAO,OAAO,cAAc,2BAA2B,WAAW,KAAK;AACzE;AAEA,SAAS,gBAAgB,OAAoD;CAC3E,IAAI,SAAS;CACb,OAAO,YAAY;EACjB,IAAI,QAAQ;EACZ,SAAS;EACT,MAAM,MAAM;CACd;AACF;;;;AChzBA,eAAsB,mBACpB,OACqC;CACrC,OAAOC,qBAAyC,KAAK;AACvD"}
1
+ {"version":3,"file":"index.mjs","names":["EVM_ADDRESS_HEX","ECDSA_SIGNATURE_HEX","SAFE_OP_DIGEST_HEX","recoverRawDigestSigner","withSignal","DEFAULT_JWT_LIFETIME_S","decodeJwtExp","authSessionFromBetterAuth","safeJson","isAbortError","mapFetchError","#client","#tokenProvider","#applicationId","#observation","#observedArgs","#convex","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#chainId","#runMutation","#runQuery","DEFAULT_FUNCTIONS","#convex","#fns","DEFAULT_FUNCTIONS","#convex","#fns","#readTreasuryWire","#convex","#signer","#chainId","#fns","#lifecycleAction","#capture","#identify","#group","#reset","#run","SDK_VERSION","sdkPackageJson.version","sdkPackageJson.version","createCapxulClient","createCapxulClientFromProductionAdapters"],"sources":["../src/surface/account-providers.ts","../src/signer.ts","../src/dev-signer.ts","../src/ports/embedded-wallet.ts","../src/openfort-embedded-signer.ts","../package.json","../../observability/src/engineering.ts","../src/adapters/auth-client/resolve-auth-url.ts","../src/internal/observation-http.ts","../src/adapters/auth-client/BetterAuthBrowserAdapter.ts","../src/adapters/auth-client/cookie-jar.ts","../src/adapters/auth-client/BetterAuthNodeAdapter.ts","../src/adapters/bootstrap/HttpBootstrapAdapter.ts","../src/adapters/clock/SystemClockAdapter.ts","../src/adapters/convex-call/ConvexCallAdapter.ts","../src/adapters/identity/ConvexIdentityAdapter.ts","../src/adapters/account-read/ConvexAccountAdapter.ts","../src/adapters/sub-account/ConvexSubAccountAdapter.ts","../src/adapters/smart-account/ConvexSmartAccountAdapter.ts","../src/ports/org.ts","../src/adapters/org/parse.ts","../src/adapters/org/ConvexOrganizationAdapter.ts","../src/adapters/org/ConvexOrganizationSetupAdapter.ts","../src/adapters/telemetry/PostHogTelemetryAdapter.ts","../src/adapters/diagnostic/ConsoleDiagnosticAdapter.ts","../src/openfort/create-openfort-browser-signer.ts","../src/observation.ts","../src/production.ts","../src/surface/create-capxul-client-from-production.ts","../src/telemetry/from-posthog.ts"],"sourcesContent":["import { Errors } from \"@capxul/config\";\nimport { toAddress, type Address } from \"@capxul/types\";\nimport type { Account as ViemAccount, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport type AccountProviderSource = \"local-private-key\" | \"openfort-embedded\" | \"injected-eip1193\";\n\nexport type AccountRequirement = \"none\" | \"counterfactual\" | \"deployed\";\n\nexport interface AccountProvider {\n readonly source: AccountProviderSource;\n /**\n * Resolve the signer's EVM address.\n *\n * @determinism MUST return the same `Address` across calls for the\n * lifetime of a single provider instance — the SDK-level deploy mutex\n * keys on `(authUserId, safeAddress)` where `safeAddress` is computed\n * from `getAddress()`'s result before the port's `prepare()` round-trip.\n * If two successive calls returned different addresses, concurrent\n * `deploySafe` invocations would compute different mutex keys and\n * bypass dedup, defeating the mutex.\n *\n * The two sanctioned providers both satisfy this invariant:\n * - `localPrivateKeyAccountProvider` — derives once from the key\n * - `eip1193AccountProvider` — reads `eth_accounts` (idempotent once\n * the wallet is connected; consumer is responsible for connection)\n *\n * The Openfort embedded path no longer needs a provider: the\n * `openfortEmbeddedSigner` `CapxulSigner` caches its own address and the\n * deploy is backend-orchestrated (backend-orchestrated-deploy.md).\n *\n * Custom providers MUST honor this contract.\n */\n getAddress(): Promise<CapxulResult<Address>>;\n getDeployAccount(): Promise<CapxulResult<ViemAccount>>;\n}\n\nexport interface Eip1193Provider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\nexport function localPrivateKeyAccountProvider(input: {\n readonly privateKey: Hex;\n}): AccountProvider {\n const account = privateKeyToAccount(input.privateKey);\n const address = toAddress(account.address);\n return {\n source: \"local-private-key\",\n async getAddress() {\n return { ok: true, value: address };\n },\n async getDeployAccount() {\n return { ok: true, value: account };\n },\n };\n}\n\nexport function eip1193AccountProvider(input: {\n readonly provider: Eip1193Provider;\n}): AccountProvider {\n // Cache the first successful address to honor the determinism contract on\n // `AccountProvider.getAddress` (see JSDoc above). Without this cache, a user\n // switching accounts in their browser wallet mid-flow would produce a\n // different `Address` on successive calls, defeating the deploy mutex.\n // Errors are intentionally NOT cached — transient wallet-not-connected or\n // RPC failures must remain retryable.\n //\n // `inFlight` memoizes the in-progress request so that concurrent first\n // callers (e.g. two `await provider.getAddress()` issued in parallel before\n // either resolves) share the same `eth_accounts` round-trip and the same\n // resolved Address. Without it, both calls would race, both would hit the\n // wallet, and the second resolver could overwrite `cachedAddress` with a\n // stale-vs-fresh wallet read — defeating determinism even with the resolved\n // cache. Cleared in `finally` so the lane stays retryable after errors.\n let cachedAddress: Address | null = null;\n let inFlight: Promise<CapxulResult<Address>> | null = null;\n\n const getAddress = async (): Promise<CapxulResult<Address>> => {\n if (cachedAddress !== null) {\n return { ok: true, value: cachedAddress };\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const accounts = await input.provider.request({ method: \"eth_accounts\" });\n const first = firstAccount(accounts);\n if (first === null) {\n return { ok: false, error: Errors.smartAccountMissing(\"eip1193-account\") };\n }\n const address = toAddress(first);\n cachedAddress = address;\n return { ok: true, value: address };\n } catch (err) {\n return {\n ok: false,\n error: Errors.providerError(\"eip1193\", \"eth_accounts\", err),\n };\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n return {\n source: \"injected-eip1193\",\n getAddress,\n async getDeployAccount() {\n return {\n ok: false,\n error: Errors.notImplemented(\"Eip1193AccountProvider\", \"getDeployAccount\"),\n };\n },\n };\n}\n\nfunction firstAccount(value: unknown): string | null {\n if (!Array.isArray(value)) return null;\n const first = value[0];\n return typeof first === \"string\" ? first : null;\n}\n","// CapxulSigner — the consumer-held key boundary (backend-orchestrated-deploy.md).\n//\n// The backend orchestrates the Safe deployment (build + gas + paymaster + submit)\n// but never holds the user's key. The consumer supplies a `CapxulSigner` that\n// signs exactly one thing: the EIP-712 `SafeOp` digest the backend returns for\n// the prepared deployment UserOperation. `safe4337SafeOpDigest` (@capxul/config)\n// computes that digest; this signer produces the owner signature; the backend\n// packs + submits. Verified equivalent to permissionless's inline signing in\n// `src/__tests__/safe4337-split-sign.test.ts`.\n//\n// Security note: the browser signer uses `eth_sign`, which can sign arbitrary\n// bytes. In the backend-orchestrated flow, `CapxulSigner` signs only the\n// backend-provided SafeOp digest, so consumers must trust the backend that\n// constructs the UserOperation and computes that digest. A malicious backend\n// could ask the wallet to sign a harmful digest; prefer typed structured\n// signing when that flow exists, and only enable raw-hash signing for trusted\n// Capxul deployments.\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport type { AccountProviderSource } from \"./surface/account-providers\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface CapxulDigestSigner {\n /**\n * Sign the EIP-712 `SafeOp` digest the backend returns for the prepared\n * deployment UserOperation. Returns the raw 65-byte ECDSA signature; the\n * backend packs `validAfter|validUntil|signature`.\n */\n signUserOpHash(hash: Hex): Promise<Hex>;\n}\n\nexport interface CapxulSigner extends CapxulDigestSigner {\n /**\n * Signer kind — surfaced on the `accountProviderReady` status so the\n * readiness ladder reports which signer the consumer wired.\n */\n readonly source: AccountProviderSource;\n /** Owner EOA address — the Safe's single owner. */\n getAddress(): Promise<Address>;\n}\n\n/** Minimal EIP-1193 surface an injected browser wallet exposes. */\nexport interface Eip1193RequestProvider {\n request(args: {\n readonly method: string;\n readonly params?: readonly unknown[];\n }): Promise<unknown>;\n}\n\n/**\n * Browser `CapxulSigner` backed by an injected EIP-1193 wallet (MetaMask, etc.).\n * Signs the SafeOp digest via `eth_sign`, then verifies the returned signature\n * recovers the selected account against that raw digest. Wallets that prefix\n * `eth_sign` payloads are rejected before the backend submits an invalid SafeOp.\n * The node key signer lives in `@capxul/sdk/node` (`localPrivateKeySigner`).\n */\nexport function injectedWalletSigner(provider: Eip1193RequestProvider): CapxulSigner {\n const resolveAddress = async (): Promise<Address> => {\n const accounts = await provider.request({ method: \"eth_requestAccounts\" });\n const first = Array.isArray(accounts) ? accounts[0] : undefined;\n if (typeof first !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned no accounts\");\n }\n if (!EVM_ADDRESS_HEX.test(first)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid address format\");\n }\n return toAddress(first);\n };\n return {\n source: \"injected-eip1193\",\n getAddress: resolveAddress,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"injectedWalletSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: unknown;\n try {\n signature = await provider.request({ method: \"eth_sign\", params: [address, hash] });\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: eth_sign failed; enable raw-hash signing for deployment (${detail})`,\n { cause },\n );\n }\n if (typeof signature !== \"string\") {\n throw new Error(\"injectedWalletSigner: wallet returned a non-string signature\");\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\"injectedWalletSigner: wallet returned invalid signature format\");\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"injectedWalletSigner: wallet signature did not recover the selected account for the raw SafeOp digest; use a raw-hash-capable wallet or @capxul/sdk/node localPrivateKeySigner for deployed flows\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `injectedWalletSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","// devPrivateKeySigner — browser-safe dev-mode `CapxulSigner` (dogfood only).\n//\n// Derives a deterministic throwaway EOA per email: privateKey =\n// keccak256(utf8(seed + normalizedEmail)). Re-login with the same email\n// reproduces the same signer, so binding resolution (signerAddress-hint\n// path) and the account lane stay coherent without Openfort. The seed is a\n// dev-only secret for unfunded keys; never fund these accounts.\n//\n// The signer is constructed before login, so the email is resolved lazily:\n// at first use it reads the cached `AuthSession` the SDK wrote to browser\n// localStorage (`capxul.session`, BrowserAuthCacheAdapter) — or uses the\n// explicit `email` override (tests / non-browser harnesses).\n\nimport { toAddress, type Address } from \"@capxul/types\";\nimport { keccak256, stringToHex, type Hex } from \"viem\";\nimport { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\n\nimport { BASE_SEPOLIA_CHAIN_ID, Errors, normalizeBindingEmail } from \"@capxul/config\";\n\nimport type { BrowserStorageShape } from \"./adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport type { CapxulResult } from \"./surface/types\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst SESSION_KEY = \"capxul.session\";\n\n/**\n * Chains a `local-private-key` signer may sign on. Base Sepolia only, and this\n * list does not grow without an ADR: the keys are deterministic throwaways\n * derived from a shared seed (see `deriveDevPrivateKey`), so anyone holding\n * the seed holds every account. A dev key on a value-bearing chain is a\n * custody incident, not a config mistake.\n */\nconst DEV_KEY_ALLOWED_CHAIN_IDS: readonly number[] = [BASE_SEPOLIA_CHAIN_ID];\n\n/**\n * Testnet fence for the dev-key signing lane (#1149, folds #1065; ADR-0018 P9\n * human/Openfort vs agent/dev-key split). Call it wherever a signer first\n * meets a resolved chain; it refuses before the signer can be used.\n *\n * Only `local-private-key` signers are fenced — Openfort-embedded and injected\n * wallets carry their own custody and are the sanctioned human paths.\n */\nexport function assertDevKeySignerIsTestnetOnly(\n signer: { readonly source?: string } | undefined,\n chainId: number,\n): CapxulResult<void> {\n if (signer?.source !== \"local-private-key\") return { ok: true, value: undefined };\n if (DEV_KEY_ALLOWED_CHAIN_IDS.includes(chainId)) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.invalidInput(\n \"signer\",\n `dev-key signer is testnet-only: chain ${chainId} is not allowed (expected ${DEV_KEY_ALLOWED_CHAIN_IDS.join(\", \")})`,\n ),\n };\n}\n\nexport interface DevPrivateKeySignerInput {\n /** Dev-only derivation seed (e.g. `VITE_CAPXUL_DEV_SIGNER_SEED`). Throwaway keys only. */\n readonly seed: string;\n /** Explicit email — skips the auth-cache lookup (tests, node harnesses). */\n readonly email?: string;\n /** Storage holding the cached session. Defaults to browser `localStorage`. */\n readonly storage?: BrowserStorageShape;\n}\n\n/** Deterministic dev private key for an email under a seed. Exported for probes. */\nexport function deriveDevPrivateKey(seed: string, email: string): Hex {\n return keccak256(stringToHex(seed + normalizeBindingEmail(email)));\n}\n\nfunction readSessionEmail(storage: BrowserStorageShape | undefined): string {\n const resolved =\n storage ??\n (globalThis as unknown as { window?: { localStorage?: BrowserStorageShape } }).window\n ?.localStorage;\n if (resolved === undefined) {\n throw new Error(\n \"devPrivateKeySigner: no browser localStorage available and no explicit email supplied\",\n );\n }\n const raw = resolved.getItem(SESSION_KEY);\n if (raw === null) {\n throw new Error(\n \"devPrivateKeySigner: no cached session yet — sign in before the account lane uses the signer\",\n );\n }\n let email: unknown;\n try {\n email = (JSON.parse(raw) as { email?: unknown }).email;\n } catch {\n throw new Error(\"devPrivateKeySigner: cached session is not valid JSON\");\n }\n if (typeof email !== \"string\" || email.length === 0) {\n throw new Error(\"devPrivateKeySigner: cached session has no email\");\n }\n return email;\n}\n\n/**\n * Browser-safe dev signer. Lazy: the email (and so the key) is resolved at\n * each `getAddress()` / `signUserOpHash()` from the cached session, so the\n * same signer instance follows whichever user is signed in.\n */\nexport function devPrivateKeySigner(input: DevPrivateKeySignerInput): CapxulSigner {\n if (input.seed.trim().length === 0) {\n throw new Error(\"devPrivateKeySigner: seed must be non-empty\");\n }\n const accounts = new Map<string, PrivateKeyAccount>();\n const resolveAccount = (): PrivateKeyAccount => {\n const email = normalizeBindingEmail(input.email ?? readSessionEmail(input.storage));\n const cached = accounts.get(email);\n if (cached !== undefined) return cached;\n const account = privateKeyToAccount(deriveDevPrivateKey(input.seed, email));\n accounts.set(email, account);\n return account;\n };\n return {\n source: \"local-private-key\",\n async getAddress(): Promise<Address> {\n return toAddress(resolveAccount().address);\n },\n async signUserOpHash(hash: Hex): Promise<Hex> {\n // Raw digest signing — same semantics as `localPrivateKeySigner` in\n // `@capxul/sdk/node`: no EIP-191 prefix on the SafeOp digest.\n return resolveAccount().sign({ hash });\n },\n };\n}\n","import type { Hex } from \"viem\";\n\n/**\n * Minimal Openfort embedded-wallet surface for hermetic tests and\n * `openfortEmbeddedSigner`. Keeps Convex / Shield secrets out of the SDK.\n */\nexport interface OpenfortEmbeddedWalletPort {\n /** Owner EOA address — must stay stable for the lifetime of this port. */\n getAddress(): Promise<string>;\n /**\n * Sign a 32-byte SafeOp digest without EIP-191 prefixing (backend-orchestrated\n * deploy contract).\n */\n signRawDigest(hash: Hex): Promise<Hex>;\n}\n\n/** Openfort `embeddedWallet` subset used by `openfortEmbeddedWalletPort`. */\nexport interface OpenfortEmbeddedWalletApi {\n get(): Promise<{ readonly address: string }>;\n signMessage(\n message: string | Uint8Array,\n options?: { readonly hashMessage?: boolean; readonly arrayifyMessage?: boolean },\n ): Promise<string>;\n}\n\nexport function openfortEmbeddedWalletPort(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureReady?: () => Promise<void>;\n}): OpenfortEmbeddedWalletPort {\n return {\n async getAddress() {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n const account = await input.embeddedWallet.get();\n return account.address;\n },\n async signRawDigest(hash) {\n if (input.ensureReady !== undefined) {\n await input.ensureReady();\n }\n // The digest must cross the Openfort iframe RPC as the 0x-hex STRING\n // with BOTH flags off — openfort-js's own raw-hash path\n // (walletHelpers: `signer.sign(hash, false, false)`) is the canon.\n // A Uint8Array mangles to UTF-8 across the RPC, and arrayifyMessage\n // triggers a double-arrayify inside the iframe; either way signing\n // dies with \"invalid arrayify value\" (first live signing proof,\n // mcp-stretch S4). hashMessage stays off: raw SafeOp digest, no\n // EIP-191 prefix.\n return (await input.embeddedWallet.signMessage(hash, {\n hashMessage: false,\n arrayifyMessage: false,\n })) as Hex;\n },\n };\n}\n","import { toAddress, type Address } from \"@capxul/types\";\nimport { recoverAddress, type Hex } from \"viem\";\n\nimport {\n openfortEmbeddedWalletPort,\n type OpenfortEmbeddedWalletApi,\n type OpenfortEmbeddedWalletPort,\n} from \"./ports/embedded-wallet\";\nimport type { CapxulSigner } from \"./signer\";\n\nconst EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;\nconst ECDSA_SIGNATURE_HEX = /^0x[0-9a-fA-F]{130}$/;\nconst SAFE_OP_DIGEST_HEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport interface OpenfortEmbeddedSignerInput {\n readonly wallet: OpenfortEmbeddedWalletPort;\n}\n\n/** Browser helper: wrap an initialized Openfort `embeddedWallet` API. */\nexport function openfortEmbeddedSignerFromWallet(input: {\n readonly embeddedWallet: OpenfortEmbeddedWalletApi;\n readonly ensureWalletReady?: () => Promise<void>;\n}): OpenfortEmbeddedSigner {\n return openfortEmbeddedSigner({\n wallet: openfortEmbeddedWalletPort({\n embeddedWallet: input.embeddedWallet,\n ...(input.ensureWalletReady === undefined ? {} : { ensureReady: input.ensureWalletReady }),\n }),\n });\n}\n\n/**\n * Browser `CapxulSigner` backed by an Openfort embedded wallet (#335).\n * Signs the backend's SafeOp digest via raw `signMessage` (no EIP-191 prefix)\n * and verifies recovery before the backend submits.\n */\nexport type OpenfortEmbeddedSigner = CapxulSigner & {\n /** Drop cached `getAddress()` so the next read hits the embedded wallet again. */\n readonly resetAddressCache: () => void;\n};\n\nexport function openfortEmbeddedSigner(input: OpenfortEmbeddedSignerInput): OpenfortEmbeddedSigner {\n let cachedAddress: Address | null = null;\n let addressInFlight: Promise<Address> | null = null;\n // Bumped on every reset so a resolve that started before the reset cannot\n // win the race and repopulate the cache with the now-stale session address.\n let cacheEpoch = 0;\n\n const resetAddressCache = (): void => {\n cacheEpoch += 1;\n cachedAddress = null;\n addressInFlight = null;\n };\n\n const resolveAddress = async (): Promise<Address> => {\n if (cachedAddress !== null) {\n return cachedAddress;\n }\n if (addressInFlight !== null) {\n return addressInFlight;\n }\n const epoch = cacheEpoch;\n addressInFlight = (async () => {\n try {\n const raw = await input.wallet.getAddress();\n if (!EVM_ADDRESS_HEX.test(raw)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid address format\",\n );\n }\n const address = toAddress(raw);\n // A reset during this resolve invalidates the result — don't cache it.\n if (epoch === cacheEpoch) {\n cachedAddress = address;\n }\n return address;\n } finally {\n if (epoch === cacheEpoch) {\n addressInFlight = null;\n }\n }\n })();\n return addressInFlight;\n };\n\n return {\n source: \"openfort-embedded\",\n getAddress: resolveAddress,\n resetAddressCache,\n async signUserOpHash(hash: Hex): Promise<Hex> {\n if (!SAFE_OP_DIGEST_HEX.test(hash)) {\n throw new Error(\"openfortEmbeddedSigner: SafeOp digest must be a 0x-prefixed 32-byte hex\");\n }\n const address = await resolveAddress();\n let signature: string;\n try {\n signature = await input.wallet.signRawDigest(hash);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: raw digest signing failed; ensure the embedded wallet is configured (${detail})`,\n { cause },\n );\n }\n if (!ECDSA_SIGNATURE_HEX.test(signature)) {\n throw new Error(\n \"openfortEmbeddedSigner: embedded wallet returned invalid signature format\",\n );\n }\n const recovered = await recoverRawDigestSigner({ hash, signature: signature as Hex });\n if (recovered.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n \"openfortEmbeddedSigner: signature did not recover the embedded wallet address for the raw SafeOp digest\",\n );\n }\n return signature as Hex;\n },\n };\n}\n\n/**\n * Canonical name for the embedded-wallet `CapxulSigner` constructor\n * (backend-orchestrated-deploy.md). The embedded-wallet (passkey / Openfort)\n * member of the named constructor trio `localPrivateKeySigner` /\n * `injectedWalletSigner` / `embeddedSigner`. Takes the provider-agnostic\n * `OpenfortEmbeddedWalletPort` (getAddress + signRawDigest); the Openfort-API\n * convenience wrapper is `openfortEmbeddedSignerFromWallet`.\n */\nexport const embeddedSigner = openfortEmbeddedSigner;\n\nasync function recoverRawDigestSigner(input: {\n readonly hash: Hex;\n readonly signature: Hex;\n}): Promise<Address> {\n try {\n return toAddress(await recoverAddress(input));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `openfortEmbeddedSigner: could not verify raw SafeOp digest signature (${detail})`,\n { cause },\n );\n }\n}\n","","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 ) {\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","/** Join bootstrap `authBaseUrl` with a BetterAuth route without duplicating `/api/auth`. */\nexport function resolveAuthClientUrl(authBaseUrl: string, path: string): string {\n const base = authBaseUrl.replace(/\\/$/, \"\");\n if (base.endsWith(\"/api/auth\") && path.startsWith(\"/api/auth\")) {\n return `${base}${path.slice(\"/api/auth\".length)}`;\n }\n return `${base}${path}`;\n}\n","import {\n encodeObservationContextHeader,\n OBSERVATION_CONTEXT_HEADER,\n} from \"@capxul/wire/observation-context\";\n\nimport type { ObservationAdapter } from \"../observation\";\n\n/** Resolve one bounded pre-auth snapshot for an outbound SDK HTTP request. */\nexport function observationRequestHeaders(\n adapter: ObservationAdapter | undefined,\n): Readonly<Record<string, string>> {\n if (adapter === undefined) return {};\n try {\n const encoded = encodeObservationContextHeader(adapter.resolveContext?.());\n return encoded === undefined ? {} : { [OBSERVATION_CONTEXT_HEADER]: encoded };\n } catch {\n return {};\n }\n}\n","// BetterAuthBrowserAdapter — TA3 production adapter for browser runtimes.\n// Aligned with W1/W2/W3/W6/W7 wire reality verified against\n// incredible-possum-990 (2026-05-19) using @convex-dev/better-auth@0.10.13.\n//\n// - W1 sendOtp POST /api/auth/email-otp/send-verification-otp\n// body `{email, type: \"sign-in\"}`\n// 200 `{success: true}` | 400 `{code, message}`\n// - W2 verifyOtp POST /api/auth/sign-in/email-otp\n// 200 `{token, user}` + Set-Cookie headers |\n// 400 `{code, message}` (OTP_EXPIRED, INVALID_OTP)\n// - W3 getSession GET /api/auth/get-session\n// 200 literal `null` body OR `{session, user}`\n// - W6 signOut POST /api/auth/sign-out body `\"{}\"`\n// (without body the server returns 500 — F11)\n// - W7 getConvexJwt GET /api/auth/convex/token\n// 200 `{token: <JWT>}`; decode `exp` for cache\n// eviction (Probe A: fresh JWT per call)\n//\n// Browser-runtime semantics: the browser fetch automatically attaches +\n// stores cookies for the same-origin domain. We send `credentials: \"include\"`\n// on requests that need cookies, but never read/write Set-Cookie ourselves —\n// that's the browser's job. The Node adapter takes a different path via\n// CookieJar (see BetterAuthNodeAdapter).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthBrowserAdapterDeps {\n readonly authBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n readonly emailVerified?: boolean;\n readonly name?: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface GetSessionBody {\n readonly session: { readonly id?: string; readonly token?: string; readonly expiresAt?: string };\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\n// Sentinel — a 15-min JWT lifetime per Probe A. Used when we can't decode\n// the `exp` claim from a malformed/opaque token (fixtures, defensive depth).\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n // Strip whitespace defensively (real JWTs don't have it; the fixture\n // builder's line-wrap can introduce some).\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = atob(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad);\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction mapBetterAuthError(\n operation: string,\n body: unknown,\n): ReturnType<typeof Errors.invalidInput | typeof Errors.providerError | typeof Errors.otpExpired> {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n const code = typeof errBody.code === \"string\" ? errBody.code : \"\";\n if (code === \"OTP_EXPIRED\") {\n return Errors.otpExpired();\n }\n if (code === \"INVALID_OTP\") {\n return Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\");\n }\n if (code === \"VALIDATION_ERROR\" || code === \"INVALID_EMAIL\") {\n return Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\");\n }\n }\n return Errors.providerError(\"better-auth\", operation, new Error(String(body)));\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthBrowserAdapter {\n private readonly authBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthBrowserAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...observationRequestHeaders(this.observation),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n if (res.status === 429) {\n return { ok: false, error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }) };\n }\n const body = await safeJson(res);\n // W1 errors: 400 with { code, message } shape — OTP_EXPIRED can't\n // appear on send; INVALID_EMAIL / VALIDATION_ERROR can.\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n const body = await safeJson(res);\n if (res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(\"unexpected 200 body\")),\n };\n }\n // W2 errors: structured 400 with `{ code, message }`.\n return { ok: false, error: mapBetterAuthError(\"verifyOtp\", body) };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n // W3 body is literal `null` OR a `{session, user}` object.\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<GetSessionBody>;\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n // Build a session synthetically — get-session doesn't return a\n // bearer token in the body (cookies carry it). For ports that\n // want a non-null AuthSession on success, we set token to the\n // session id if available.\n const token = okBody.session?.token ?? okBody.session?.id ?? \"session\";\n return { ok: true, value: authSessionFromBetterAuth(token, okBody.user) };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n // F11: BetterAuth REQUIRES a non-empty body + Content-Type:\n // application/json. Without it the route returns HTTP 500.\n headers: { \"Content-Type\": \"application/json\" },\n body: \"{}\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n if (res.ok) {\n return { ok: true, value: undefined };\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n // forceRefresh is observed by the caller (ConvexCallAdapter); the\n // bridge mints fresh on every call regardless (Probe A).\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n credentials: \"include\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthBrowserLayer(\n deps: BetterAuthBrowserAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthBrowserAdapter(deps)),\n );\n}\n","// Minimal in-tree cookie jar for the Node auth-client adapter (tactical\n// placeholder 4 resolution). Scope is tiny: set + replay via `Cookie`\n// header on subsequent requests, expiry tracking, scope-by-host.\n//\n// No `tough-cookie` dependency.\n\nexport interface ParsedCookie {\n readonly name: string;\n readonly value: string;\n readonly maxAgeSeconds: number | null;\n readonly expiresEpochMs: number | null;\n readonly path: string | null;\n readonly httpOnly: boolean;\n readonly secure: boolean;\n readonly sameSite: \"strict\" | \"lax\" | \"none\" | null;\n}\n\ninterface StoredCookie extends ParsedCookie {\n readonly storedAtEpochMs: number;\n}\n\nfunction parseSetCookie(raw: string): ParsedCookie | null {\n // Set-Cookie header format: `name=value; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax`\n const parts = raw.split(\";\").map((p) => p.trim());\n if (parts.length === 0 || parts[0] === undefined) return null;\n const nameValue = parts[0];\n const eq = nameValue.indexOf(\"=\");\n if (eq < 0) return null;\n const name = nameValue.slice(0, eq).trim();\n const value = nameValue.slice(eq + 1).trim();\n if (name.length === 0) return null;\n\n let maxAgeSeconds: number | null = null;\n let expiresEpochMs: number | null = null;\n let path: string | null = null;\n let httpOnly = false;\n let secure = false;\n let sameSite: \"strict\" | \"lax\" | \"none\" | null = null;\n\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (part === undefined) continue;\n const partEq = part.indexOf(\"=\");\n const key = (partEq < 0 ? part : part.slice(0, partEq)).trim().toLowerCase();\n const val = partEq < 0 ? \"\" : part.slice(partEq + 1).trim();\n if (key === \"max-age\") {\n const n = Number(val);\n if (Number.isFinite(n)) maxAgeSeconds = n;\n } else if (key === \"expires\") {\n const t = Date.parse(val);\n if (Number.isFinite(t)) expiresEpochMs = t;\n } else if (key === \"path\") {\n path = val;\n } else if (key === \"httponly\") {\n httpOnly = true;\n } else if (key === \"secure\") {\n secure = true;\n } else if (key === \"samesite\") {\n const lc = val.toLowerCase();\n if (lc === \"strict\" || lc === \"lax\" || lc === \"none\") sameSite = lc;\n }\n }\n\n return { name, value, maxAgeSeconds, expiresEpochMs, path, httpOnly, secure, sameSite };\n}\n\nfunction isExpired(cookie: StoredCookie, nowEpochMs: number): boolean {\n if (cookie.maxAgeSeconds !== null) {\n if (cookie.maxAgeSeconds <= 0) return true;\n return nowEpochMs >= cookie.storedAtEpochMs + cookie.maxAgeSeconds * 1000;\n }\n if (cookie.expiresEpochMs !== null) {\n return nowEpochMs >= cookie.expiresEpochMs;\n }\n // Session cookie — never expires in this process. The Node adapter does\n // not preserve the jar across processes; this is fine.\n return false;\n}\n\nexport class CookieJar {\n // host → name → cookie. Map preserves insertion order, which keeps the\n // serialized Cookie header deterministic for tests.\n private readonly store = new Map<string, Map<string, StoredCookie>>();\n\n set(host: string, setCookieHeaders: readonly string[]): void {\n let perHost = this.store.get(host);\n const now = Date.now();\n for (const raw of setCookieHeaders) {\n const parsed = parseSetCookie(raw);\n if (parsed === null) continue;\n if (perHost === undefined) {\n perHost = new Map();\n this.store.set(host, perHost);\n }\n // Max-Age=0 (or negative) immediately deletes; treat as a clear.\n if (parsed.maxAgeSeconds !== null && parsed.maxAgeSeconds <= 0) {\n perHost.delete(parsed.name);\n continue;\n }\n perHost.set(parsed.name, { ...parsed, storedAtEpochMs: now });\n }\n if (perHost !== undefined && perHost.size === 0) {\n this.store.delete(host);\n }\n }\n\n getCookieHeader(host: string): string | null {\n const perHost = this.store.get(host);\n if (perHost === undefined || perHost.size === 0) return null;\n const now = Date.now();\n const live: string[] = [];\n for (const [name, cookie] of perHost.entries()) {\n if (isExpired(cookie, now)) {\n perHost.delete(name);\n continue;\n }\n live.push(`${name}=${cookie.value}`);\n }\n if (live.length === 0) {\n this.store.delete(host);\n return null;\n }\n return live.join(\"; \");\n }\n}\n","// BetterAuthNodeAdapter — TA3 production adapter for Node + Ink runtimes.\n// Same surface as the browser adapter; cookies round-trip via the in-tree\n// CookieJar instead of being managed by the browser.\n//\n// Wire shapes are identical to BetterAuthBrowserAdapter (W1/W2/W3/W6/W7).\n\nimport { Errors } from \"@capxul/config\";\nimport {\n toAuthUserId,\n toDurationMs,\n toEmail,\n toEpochMs,\n toEpochSeconds,\n toJwtToken,\n toSessionToken,\n} from \"@capxul/types\";\nimport type { AuthSession } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport type {\n AuthClientOperationOptions,\n AuthClientResult,\n CanSendOtpInput,\n CanSendOtpStatus,\n GetConvexJwtOptions,\n SendOtpInput,\n VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport { AuthClientPortTag } from \"../../ports/auth-client\";\nimport { Layer } from \"effect\";\n\nimport { CookieJar } from \"./cookie-jar\";\nimport { resolveAuthClientUrl } from \"./resolve-auth-url\";\nimport { authClientPortFromPromiseAdapter } from \"./effect-port\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface BetterAuthNodeAdapterDeps {\n readonly authBaseUrl: string;\n /**\n * Some BetterAuth routes (notably sign-out) enforce an Origin check and will\n * return 403 if absent. For Node clients, pass the same origin a browser\n * would send (e.g. SITE_URL).\n */\n readonly origin?: string;\n readonly cookieJar?: CookieJar;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\ninterface BetterAuthErrorBody {\n readonly code?: string;\n readonly message?: string;\n}\n\ninterface BetterAuthUser {\n readonly id: string;\n readonly email: string;\n}\n\ninterface VerifyOtpBody {\n readonly token: string;\n readonly user: BetterAuthUser;\n}\n\ninterface ConvexTokenBody {\n readonly token: string;\n}\n\nfunction withSignal(init: RequestInit, signal: AbortSignal | undefined): RequestInit {\n return signal === undefined ? init : { ...init, signal };\n}\n\nconst DEFAULT_JWT_LIFETIME_S = 900;\n\nfunction decodeJwtExp(jwt: string): number {\n const parts = jwt.split(\".\");\n if (parts.length < 2 || parts[1] === undefined) {\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n }\n try {\n const raw = parts[1].replace(/\\s+/g, \"\");\n const pad = \"=\".repeat((4 - (raw.length % 4)) % 4);\n const decoded = Buffer.from(raw.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad, \"base64\").toString(\n \"utf-8\",\n );\n const payload = JSON.parse(decoded) as { readonly exp?: number };\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp) && payload.exp > 0) {\n return payload.exp;\n }\n } catch {\n // Fall through to default.\n }\n return Math.floor(Date.now() / 1000) + DEFAULT_JWT_LIFETIME_S;\n}\n\nfunction authSessionFromBetterAuth(token: string, user: BetterAuthUser): AuthSession {\n return {\n authUserId: toAuthUserId(user.id),\n email: toEmail(user.email),\n token: toSessionToken(token),\n expiresAt: toEpochMs(Date.now() + 7 * 24 * 60 * 60 * 1000),\n };\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n const raw = await res.text();\n if (raw.length === 0 || raw === \"null\") return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n try {\n return new URL(baseUrl).host;\n } catch {\n return baseUrl;\n }\n}\n\nfunction originFromBaseUrl(baseUrl: string): string | undefined {\n try {\n return new URL(baseUrl).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction setCookiesFromResponse(jar: CookieJar, host: string, res: Response): void {\n // Headers.getSetCookie() is the Node 19.7+ way; falls back to single header\n // splitting if unavailable.\n type HeadersExt = Headers & { getSetCookie?: () => string[] };\n const ext = res.headers as HeadersExt;\n let setCookies: string[] = [];\n if (typeof ext.getSetCookie === \"function\") {\n setCookies = ext.getSetCookie();\n } else {\n res.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\") setCookies.push(value);\n });\n }\n if (setCookies.length > 0) jar.set(host, setCookies);\n}\n\nfunction isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n signal?.aborted === true ||\n (err instanceof Error && err.name === \"AbortError\") ||\n (typeof DOMException !== \"undefined\" &&\n err instanceof DOMException &&\n err.name === \"AbortError\")\n );\n}\n\nfunction mapFetchError(operation: string, err: unknown, signal?: AbortSignal) {\n if (isAbortError(err, signal)) {\n return Errors.cancelled({ operation });\n }\n return Errors.networkError(operation, err instanceof Error ? err : new Error(String(err)));\n}\n\nexport class BetterAuthNodeAdapter {\n private readonly authBaseUrl: string;\n private readonly host: string;\n private readonly origin: string | undefined;\n private readonly cookieJar: CookieJar;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: BetterAuthNodeAdapterDeps) {\n this.authBaseUrl = deps.authBaseUrl.replace(/\\/$/, \"\");\n this.host = hostFromBaseUrl(this.authBaseUrl);\n this.origin = deps.origin?.replace(/\\/$/, \"\");\n this.cookieJar = deps.cookieJar ?? new CookieJar();\n this.fetchImpl = deps.fetch ?? fetch;\n this.observation = deps.observation;\n }\n\n private url(path: string): string {\n return resolveAuthClientUrl(this.authBaseUrl, path);\n }\n\n private headersWithCookie(extra: Record<string, string> = {}): Record<string, string> {\n const cookie = this.cookieJar.getCookieHeader(this.host);\n return cookie !== null ? { ...extra, cookie } : { ...extra };\n }\n\n async canSendOtp(\n _input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<CanSendOtpStatus>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n return { ok: true, value: { allowed: true, cooldownMs: toDurationMs(0) } };\n }\n\n async sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/email-otp/send-verification-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n ...observationRequestHeaders(this.observation),\n },\n body: JSON.stringify({ email: input.email, type: \"sign-in\" }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"sendOtp\" }) };\n }\n if (res.ok) return { ok: true, value: undefined };\n if (res.status === 429) {\n return {\n ok: false,\n error: Errors.rateLimited({ resource: \"better-auth/sendOtp\" }),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"INVALID_EMAIL\" || errBody.code === \"VALIDATION_ERROR\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"email\", errBody.message ?? \"invalid email\"),\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"sendOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"sendOtp\", err, options?.signal),\n };\n }\n }\n\n async verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-in/email-otp\"),\n withSignal(\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(this.origin ? { origin: this.origin } : {}),\n },\n body: JSON.stringify({ email: input.email, otp: input.otp }),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n setCookiesFromResponse(this.cookieJar, this.host, res);\n const body = await safeJson(res);\n if (res.ok && typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<VerifyOtpBody>;\n if (\n typeof okBody.token === \"string\" &&\n typeof okBody.user === \"object\" &&\n okBody.user !== null\n ) {\n return { ok: true, value: authSessionFromBetterAuth(okBody.token, okBody.user) };\n }\n }\n if (!res.ok) {\n if (typeof body === \"object\" && body !== null) {\n const errBody = body as BetterAuthErrorBody;\n if (errBody.code === \"OTP_EXPIRED\") {\n return { ok: false, error: Errors.otpExpired() };\n }\n if (errBody.code === \"INVALID_OTP\") {\n return {\n ok: false,\n error: Errors.invalidInput(\"otp\", errBody.message ?? \"invalid OTP\"),\n };\n }\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"verifyOtp\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"verifyOtp\", err, options?.signal),\n };\n }\n }\n\n async getSession(\n options?: AuthClientOperationOptions,\n ): Promise<AuthClientResult<AuthSession | null>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/get-session\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getSession\", new Error(`HTTP ${res.status}`)),\n };\n }\n const body = await safeJson(res);\n if (body === null) return { ok: true, value: null };\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as {\n readonly session?: { readonly id?: string; readonly token?: string };\n readonly user?: BetterAuthUser;\n };\n if (typeof okBody.user === \"object\" && okBody.user !== null) {\n return {\n ok: true,\n value: authSessionFromBetterAuth(\n okBody.session?.token ?? okBody.session?.id ?? \"session\",\n okBody.user,\n ),\n };\n }\n }\n return { ok: true, value: null };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getSession\", err, options?.signal),\n };\n }\n }\n\n async signOut(options?: AuthClientOperationOptions): Promise<AuthClientResult<void>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n try {\n const signOutOrigin = originFromBaseUrl(this.authBaseUrl) ?? this.origin;\n const res = await this.fetchImpl(\n this.url(\"/api/auth/sign-out\"),\n withSignal(\n {\n method: \"POST\",\n headers: this.headersWithCookie({\n \"content-type\": \"application/json\",\n ...(signOutOrigin ? { origin: signOutOrigin } : {}),\n }),\n body: \"{}\",\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // The sign-out response sets Max-Age=0 cookies — the jar treats those\n // as immediate deletions.\n setCookiesFromResponse(this.cookieJar, this.host, res);\n if (res.ok) return { ok: true, value: undefined };\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"signOut\", new Error(`HTTP ${res.status}`)),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"signOut\", err, options?.signal),\n };\n }\n }\n\n async getConvexJwt(options?: GetConvexJwtOptions): Promise<AuthClientResult<CachedJwt>> {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n try {\n const res = await this.fetchImpl(\n this.url(\"/api/auth/convex/token\"),\n withSignal(\n {\n method: \"GET\",\n headers: this.headersWithCookie(),\n },\n options?.signal,\n ),\n );\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getConvexJwt\" }) };\n }\n if (res.status === 401) {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (!res.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"better-auth\",\n \"getConvexJwt\",\n new Error(`HTTP ${res.status}`),\n ),\n };\n }\n const body = await safeJson(res);\n if (typeof body === \"object\" && body !== null) {\n const okBody = body as Partial<ConvexTokenBody>;\n if (typeof okBody.token === \"string\" && okBody.token.length > 0) {\n return {\n ok: true,\n value: {\n token: toJwtToken(okBody.token),\n expEpochSeconds: toEpochSeconds(decodeJwtExp(okBody.token)),\n },\n };\n }\n }\n return {\n ok: false,\n error: Errors.providerError(\"better-auth\", \"getConvexJwt\", new Error(\"unexpected body\")),\n };\n } catch (err) {\n return {\n ok: false,\n error: mapFetchError(\"getConvexJwt\", err, options?.signal),\n };\n }\n }\n}\n\nexport function BetterAuthNodeLayer(\n deps: BetterAuthNodeAdapterDeps,\n): Layer.Layer<AuthClientPortTag> {\n return Layer.succeed(\n AuthClientPortTag,\n authClientPortFromPromiseAdapter(new BetterAuthNodeAdapter(deps)),\n );\n}\n","// HttpBootstrapAdapter — TA3 production adapter. Calls\n// POST `/v1/client/bootstrap` on the backend. Per W4 + issue #119\n// (audit row B3), the 200 body is a versioned `BootstrapEnvelope`\n// shared with the producer via `@capxul/wire` — backend encodes,\n// SDK decodes, same schema both sides.\n//\n// Error mapping:\n// HTTP 401 and explicit NOT_AUTHENTICATED bodies map to NOT_AUTHENTICATED.\n// Schema-decode failures on a 200 body map to INVALID_INPUT per #119 AC1.\n// Provider 500s stay PROVIDER_ERROR so infrastructure faults are not collapsed\n// into auth failures.\n\nimport { Effect, Result, Layer } from \"effect\";\nimport { SchemaIssue, SchemaParser } from \"effect\";\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { BootstrapEnvelope } from \"@capxul/wire\";\n\nimport type { BootstrapInput, BootstrapPort, BootstrapResolution } from \"../../ports/bootstrap\";\nimport { BootstrapError, BootstrapPortTag, bootstrapErrorFromCapxul } from \"../../ports/bootstrap\";\nimport type { ObservationAdapter } from \"../../observation\";\nimport { observationRequestHeaders } from \"../../internal/observation-http\";\n\nexport interface HttpBootstrapAdapterDeps {\n readonly bootstrapBaseUrl: string;\n readonly fetch?: typeof fetch;\n readonly observation?: ObservationAdapter;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text();\n } catch {\n return \"\";\n }\n}\n\nexport class HttpBootstrapAdapter implements BootstrapPort {\n private readonly bootstrapBaseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly observation: ObservationAdapter | undefined;\n\n constructor(deps: HttpBootstrapAdapterDeps) {\n this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\\/$/, \"\");\n this.observation = deps.observation;\n // Bind through an arrow — assigning `fetch` to `this.fetchImpl` and calling it\n // as a method throws \"Illegal invocation\" in browsers.\n this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n }\n\n resolve(input: BootstrapInput): Effect.Effect<BootstrapResolution, BootstrapError> {\n return Effect.tryPromise({\n try: () => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...observationRequestHeaders(this.observation),\n };\n return this.fetchImpl(`${this.bootstrapBaseUrl}/v1/client/bootstrap`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ publishableKey: input.publishableKey }),\n });\n },\n catch: (cause) =>\n bootstrapErrorFromCapxul(\"network\", Errors.networkError(\"bootstrap\", cause)),\n }).pipe(Effect.flatMap((res) => this.mapResponse(res)));\n }\n\n private mapResponse(res: Response): Effect.Effect<BootstrapResolution, BootstrapError> {\n if (res.ok) {\n return Effect.tryPromise({\n try: async () => {\n const body: unknown = await res.json();\n // `BootstrapEnvelope` lives in `@capxul/wire` so the producer\n // (`packages/backend/convex/credentials/http.ts`) and this\n // consumer share one schema. Branded fields (`applicationId`,\n // `chainId`, `sessionToken`, `issuedAt`, `expiresIn`) come out\n // of decode already branded — no `to*` chain afterwards.\n const decoded = SchemaParser.decodeUnknownResult(BootstrapEnvelope)(body);\n if (Result.isFailure(decoded)) {\n // Schema validation failure → INVALID_INPUT per #119 AC1.\n // Unknown `version` literals, missing fields, and brand-rule\n // failures (e.g. `applicationId` not matching `APP_ID_RE`)\n // all land here.\n throw Errors.invalidInput(\n \"bootstrapEnvelope\",\n SchemaIssue.makeFormatterDefault()(decoded.failure),\n );\n }\n const { state } = decoded.success;\n return {\n applicationId: state.applicationId,\n chainId: state.chainId,\n sessionToken: state.sessionToken,\n issuedAt: state.issuedAt,\n expiresIn: state.expiresIn,\n authBaseUrl: normalizeRuntimeUrl(\"authBaseUrl\", state.authBaseUrl),\n convexUrl: normalizeRuntimeUrl(\"convexUrl\", state.convexUrl),\n siteBaseUrl: normalizeRuntimeUrl(\"siteBaseUrl\", state.siteBaseUrl),\n openfortPublishableKey: state.openfortPublishableKey,\n shieldPublishableKey: state.shieldPublishableKey,\n };\n },\n catch: (cause) => {\n if (cause instanceof CapxulError && cause.code === \"INVALID_INPUT\") {\n return bootstrapErrorFromCapxul(\"invalidInput\", cause);\n }\n return bootstrapErrorFromCapxul(\n \"malformedBody\",\n Errors.providerError(\n \"convex\",\n \"bootstrap\",\n cause instanceof Error ? cause : new Error(String(cause)),\n ),\n );\n },\n });\n }\n\n return Effect.promise(() => safeText(res)).pipe(\n Effect.flatMap((body) => {\n if (res.status === 401 || body.startsWith(\"NOT_AUTHENTICATED\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\"notAuthenticated\", Errors.notAuthenticated()),\n );\n }\n if (res.status === 400 || body.startsWith(\"INVALID_INPUT\")) {\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"invalidInput\",\n Errors.invalidInput(\"publishableKey\", \"rejected by bootstrap\"),\n ),\n );\n }\n return Effect.fail(\n bootstrapErrorFromCapxul(\n \"provider\",\n Errors.providerError(\"convex\", \"bootstrap\", new Error(`HTTP ${res.status}`)),\n ),\n );\n }),\n );\n }\n}\n\nexport function HttpBootstrapLayer(deps: HttpBootstrapAdapterDeps): Layer.Layer<BootstrapPortTag> {\n return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));\n}\n\nfunction normalizeRuntimeUrl(\n field: \"authBaseUrl\" | \"convexUrl\" | \"siteBaseUrl\",\n raw: string,\n): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n","import type { DurationMs, EpochMs } from \"@capxul/types\";\nimport { toEpochMs } from \"@capxul/types\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ClockError, ClockPortTag, type ClockPort } from \"../../ports/clock\";\n\nexport class SystemClockAdapter implements ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError, never> = Effect.try({\n try: () => toEpochMs(Date.now()),\n catch: (cause) => new ClockError({ operation: \"now\", cause }),\n });\n\n sleep(duration: DurationMs): Effect.Effect<void, ClockError, never> {\n return Effect.callback<void, ClockError>((resume) => {\n const timeout = setTimeout(() => resume(Effect.void), duration as number);\n return Effect.sync(() => clearTimeout(timeout));\n });\n }\n}\n\nexport function SystemClockLayer(): Layer.Layer<ClockPortTag, ClockError, never> {\n return Layer.succeed(ClockPortTag, new SystemClockAdapter());\n}\n","import { CapxulError, Errors, decodeConvexError } from \"@capxul/config\";\nimport { ConvexClient } from \"convex/browser\";\nimport { getFunctionName, type FunctionReference } from \"convex/server\";\nimport { Effect, Layer, Tracer } from \"effect\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport {\n ConvexCallPortTag,\n convexCallErrorFromCapxul,\n type ConvexCallError,\n type ConvexCallPort,\n type Snapshot,\n type Unsubscribe,\n} from \"../../ports/convex-call\";\nimport { readInvocationObservation } from \"../../internal/invocation-observation\";\nimport { formatTraceparent } from \"../../domain/machine/telemetry.ts\";\nimport type { ObservationAdapter } from \"../../observation\";\n\nexport type ConvexCallAuthFetcher = (args: {\n readonly forceRefreshToken: boolean;\n}) => Promise<string | null>;\n\nexport interface ConvexClientShape {\n setAuth(fetchToken: ConvexCallAuthFetcher): void;\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Promise<TOutput>;\n onUpdate<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n onValue: (value: TOutput) => void,\n onError: (err: Error) => void,\n ): () => void;\n close(): Promise<void>;\n}\n\nexport type ConvexCallLayerDeps = {\n readonly convexUrl: string;\n readonly tokenProvider?: ConvexCallAuthFetcher;\n readonly client?: ConvexClientShape;\n readonly applicationId?: string;\n readonly observation?: Pick<ObservationAdapter, \"resolveContext\">;\n};\n\n/** Exact floor-first allowlist; every additional handler must migrate its validator first. */\nconst OBSERVED_CONVEX_ACTIONS: ReadonlySet<string> = new Set([\n \"subAccount/actions:transfer\",\n \"smartAccount/actions:claim\",\n \"org/actions:prepareFounderAccount\",\n \"org/actions:prepareBootstrap\",\n \"org/actions:submitBootstrap\",\n \"org/actions:resumeBootstrapSubmission\",\n \"org/actions:confirmBootstrap\",\n]);\nconst OBSERVED_CONVEX_QUERIES: ReadonlySet<string> = new Set([\n \"identity/queries:loadByAuthUserId\",\n \"smartAccount/queries:loadByAuthUserId\",\n \"org/lifecycle:load\",\n]);\nconst OBSERVED_CONVEX_MUTATIONS: ReadonlySet<string> = new Set([\n \"identity/mutations:create\",\n \"identity/mutations:update\",\n \"identity/mutations:completeOnboarding\",\n \"smartAccount/mutations:provision\",\n \"org/lifecycle:startOrResume\",\n \"org/lifecycle:recordFailure\",\n \"org/lifecycle:retry\",\n]);\n\nexport class ConvexCallAdapter implements ConvexCallPort {\n readonly #client: ConvexClientShape;\n readonly #tokenProvider: ConvexCallAuthFetcher | undefined;\n readonly #applicationId: string | undefined;\n readonly #observation: Pick<ObservationAdapter, \"resolveContext\"> | undefined;\n\n constructor(deps: ConvexCallLayerDeps) {\n this.#client = deps.client ?? (new ConvexClient(deps.convexUrl) as ConvexClientShape);\n this.#tokenProvider = deps.tokenProvider;\n this.#applicationId = deps.applicationId;\n this.#observation = deps.observation;\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n refreshAuth(): void {\n if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);\n }\n\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.query(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_QUERIES, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.mutation(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_MUTATIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError> {\n const path = getFunctionName(fn);\n return Effect.serviceOption(Tracer.ParentSpan).pipe(\n Effect.flatMap((parent) => {\n const traceparent = parent._tag === \"Some\" ? formatTraceparent(parent.value) : undefined;\n return Effect.tryPromise({\n try: () =>\n this.#client.action(\n fn,\n this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args, traceparent),\n ),\n catch: (cause) => mapToConvexCallError(path, cause),\n });\n }),\n );\n }\n\n #observedArgs<TArgs extends Record<string, unknown>>(\n allowlist: ReadonlySet<string>,\n path: string,\n args: TArgs,\n traceparent: string | undefined,\n ): TArgs {\n if (!allowlist.has(path)) return args;\n\n const carriedContext = sanitizeObservationContext(\n (args as { readonly observationContext?: unknown }).observationContext,\n );\n let hostContext: WireObservationContext | undefined;\n const invocationSnapshot = readInvocationObservation(args);\n if (invocationSnapshot !== undefined) {\n hostContext = invocationSnapshot.context;\n } else {\n const resolveContext = this.#observation?.resolveContext;\n if (resolveContext !== undefined) {\n try {\n hostContext = resolveContext();\n } catch {\n hostContext = undefined;\n }\n }\n }\n if (hostContext === undefined && carriedContext === undefined && traceparent === undefined) {\n return args;\n }\n hostContext = sanitizeObservationContext({\n ...hostContext,\n ...carriedContext,\n ...(this.#applicationId === undefined ? {} : { applicationId: this.#applicationId }),\n ...(traceparent === undefined ? {} : { traceparent }),\n });\n if (hostContext === undefined) return args;\n\n // Never mutate caller-owned args. This cast is localized to the one handler\n // whose backend validator explicitly accepts the reserved context field.\n return { ...args, observationContext: hostContext } as TArgs;\n }\n\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError> {\n return Effect.try({\n try: () => {\n const path = getFunctionName(fn);\n const unsubscribe = this.#client.onUpdate(\n fn,\n args,\n (value) => callback({ status: \"ok\", value }),\n (err) => callback({ status: \"error\", error: mapToCapxulError(path, err) }),\n );\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n unsubscribe();\n };\n },\n catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause),\n }).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n callback({ status: \"loading\" });\n }),\n ),\n );\n }\n\n async close(): Promise<void> {\n await this.#client.close();\n }\n}\n\nexport function ConvexCallLayer(deps: ConvexCallLayerDeps): Layer.Layer<ConvexCallPortTag> {\n return Layer.effect(\n ConvexCallPortTag,\n Effect.acquireRelease(\n Effect.sync(() => new ConvexCallAdapter(deps)),\n (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie),\n ),\n );\n}\n\nfunction mapToCapxulError(operation: string, err: unknown): CapxulError {\n const decoded = decodeConvexError(err);\n if (decoded !== null) return decoded;\n if (err instanceof CapxulError) return err;\n if (err instanceof Error) {\n if (isTransportError(err)) return Errors.networkError(operation, err);\n return Errors.providerError(\"convex\", operation, err);\n }\n return Errors.providerError(\"convex\", operation, new Error(String(err)));\n}\n\nfunction mapToConvexCallError(operation: string, err: unknown): ConvexCallError {\n return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err));\n}\n\nfunction isTransportError(err: Error): boolean {\n const message = err.message.toLowerCase();\n return (\n message.includes(\"failed to fetch\") ||\n message.includes(\"network\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"enotfound\") ||\n message.includes(\"etimedout\") ||\n message.includes(\"socket\")\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, Profile } from \"@capxul/types\";\nimport {\n toAddress,\n toAuthUserId,\n toCountryCode,\n toEmail,\n toEpochMs,\n toKycTier,\n} from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CompleteOnboardingIdentityInput,\n CreateIdentityInput,\n IdentityError,\n IdentityPort,\n UpdateIdentityInput,\n} from \"../../ports/identity\";\nimport { identityErrorFromCapxul, IdentityPortTag } from \"../../ports/identity\";\n\ntype RawProfile = {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly country: string | null;\n readonly onboarded?: boolean;\n readonly withdrawalAddress?: string | null;\n readonly username?: string | null;\n readonly imageUrl?: string | null;\n readonly kycTier: 0 | 1 | 2 | 3;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nconst identityLoadByAuthUserIdQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: AuthUserId },\n RawProfile | null\n> = makeFunctionReference<\"query\", { readonly authUserId: AuthUserId }, RawProfile | null>(\n CAPXUL_FUNCTIONS[\"identity/queries\"].loadByAuthUserId,\n);\n\nconst identityCreateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CreateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CreateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].create,\n);\n\nconst identityUpdateMutation: FunctionReference<\n \"mutation\",\n \"public\",\n UpdateIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", UpdateIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].update,\n);\n\nconst identityCompleteOnboardingMutation: FunctionReference<\n \"mutation\",\n \"public\",\n CompleteOnboardingIdentityInput,\n RawProfile\n> = makeFunctionReference<\"mutation\", CompleteOnboardingIdentityInput, RawProfile>(\n CAPXUL_FUNCTIONS[\"identity/mutations\"].completeOnboarding,\n);\n\nexport class ConvexIdentityAdapter implements IdentityPort {\n readonly #convex: ConvexCallPort;\n\n constructor(deps: { readonly convex: ConvexCallPort }) {\n this.#convex = deps.convex;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError> {\n return this.#convex.query(identityLoadByAuthUserIdQuery, { authUserId }).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => (row === null ? null : brandProfile(row)),\n catch: (cause) => identityErrorFromUnknown(\"loadByAuthUserId\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCreateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"create\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"create\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"create\", cause))),\n );\n }\n\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityUpdateMutation, input).pipe(\n Effect.mapError((error) => identityErrorFromCapxul(\"update\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"update\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(identityErrorFromUnknown(\"update\", cause))),\n );\n }\n\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError> {\n return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(\n Effect.mapError((error) =>\n identityErrorFromCapxul(\"completeOnboarding\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProfile(row),\n catch: (cause) => identityErrorFromUnknown(\"completeOnboarding\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(identityErrorFromUnknown(\"completeOnboarding\", cause)),\n ),\n );\n }\n}\n\nexport function ConvexIdentityLayer(): Layer.Layer<\n IdentityPortTag,\n IdentityError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n IdentityPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })),\n );\n}\n\nfunction brandProfile(raw: RawProfile): Profile {\n return {\n authUserId: toAuthUserId(raw.authUserId),\n email: toEmail(raw.email),\n displayName: raw.displayName,\n country: raw.country === null ? null : toCountryCode(raw.country),\n onboarded: raw.onboarded ?? false,\n withdrawalAddress:\n raw.withdrawalAddress === null || raw.withdrawalAddress === undefined\n ? null\n : toAddress(raw.withdrawalAddress),\n // #1062 / #1061: plain strings on the wire and the surface — no brand.\n username: raw.username ?? null,\n imageUrl: raw.imageUrl ?? null,\n kycTier: toKycTier(raw.kycTier),\n createdAt: toEpochMs(raw.createdAt),\n updatedAt: toEpochMs(raw.updatedAt),\n };\n}\n\nfunction identityErrorFromUnknown(operation: string, cause: unknown): IdentityError {\n if (cause instanceof CapxulError) return identityErrorFromCapxul(operation, cause);\n return identityErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Account } from \"@capxul/types\";\nimport { toAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n AccountReadError,\n AccountReadPort,\n FundFromFaucetInput,\n FundFromFaucetResult,\n ReadAccountBalanceInput,\n} from \"../../ports/account-read\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { accountReadErrorFromCapxul, AccountReadPortTag } from \"../../ports/account-read\";\nimport { fromWei } from \"../../domain/money/from-wei\";\n\nexport type WireAccountBalance = {\n readonly accountId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\nexport type WireFaucetMintResult = {\n readonly txHash: string;\n};\n\nexport type ConvexAccountFunctions = {\n readonly readBalance: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number },\n WireAccountBalance\n >;\n readonly faucetMint: FunctionReference<\n \"action\",\n \"public\",\n { readonly chainId: number; readonly rawAmount: string },\n WireFaucetMintResult\n >;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexAccountFunctions = {\n readBalance: makeFunctionReference<\"action\", { chainId: number }, WireAccountBalance>(\n CAPXUL_FUNCTIONS[\"account/actions\"].readBalance,\n ),\n faucetMint: makeFunctionReference<\n \"action\",\n { chainId: number; rawAmount: string },\n WireFaucetMintResult\n >(CAPXUL_FUNCTIONS[\"account/actions\"].faucetMint),\n};\n\nexport class ConvexAccountAdapter implements AccountReadPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError> {\n return this.#convex.action(this.#fns.readBalance, { chainId: wireChainId(input.chainId) }).pipe(\n Effect.mapError((error) =>\n accountReadErrorFromCapxul(\"readBalance\", error.publicError, error),\n ),\n Effect.flatMap((wire) => brandAccountEffect(\"readBalance\", wire)),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(\"readBalance\", cause))),\n );\n }\n\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError> {\n const operation = \"fundFromFaucet\";\n // `toWei`/`parseUnits` throws on a malformed money string; suspend so the\n // throw surfaces as a defect below and maps to an AccountReadError, never an\n // escaped throw out of `fundFromFaucet` (mirrors ConvexSubAccountAdapter.transfer).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(this.#fns.faucetMint, {\n chainId: wireChainId(input.chainId),\n rawAmount,\n });\n }).pipe(\n Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => ({ txHash: wire.txHash })),\n Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexAccountLayer(): Layer.Layer<\n AccountReadPortTag,\n AccountReadError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n AccountReadPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })),\n );\n}\n\nfunction brandAccountEffect(\n operation: string,\n wire: WireAccountBalance,\n): Effect.Effect<Account, AccountReadError> {\n return Effect.try({\n try: () => brandAccount(wire),\n catch: (cause) => accountReadErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandAccount(wire: WireAccountBalance): Account {\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(\n wire.rawAvailableBalance ?? wire.rawBalance,\n wire.decimals,\n wire.currency,\n );\n return {\n id: toAccountId(wire.accountId),\n balance,\n available,\n };\n}\n\nfunction accountReadErrorFromUnknown(operation: string, cause: unknown): AccountReadError {\n if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);\n return accountReadErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount } from \"@capxul/types\";\nimport { toAccountId, toEpochMs, toSubAccountId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport { toWei } from \"../../domain/money/to-wei\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateSubAccountInput,\n RenameSubAccountInput,\n SubAccountError,\n SubAccountIdInput,\n SubAccountPort,\n TransferInput,\n TransferResult,\n} from \"../../ports/sub-account\";\nimport { subAccountErrorFromCapxul, SubAccountPortTag } from \"../../ports/sub-account\";\n\nexport type WireSubAccount = {\n readonly subAccountId: string;\n readonly accountId: string;\n readonly name: string;\n readonly rawBalance: string;\n readonly decimals: number;\n readonly currency: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\n/**\n * Wire result of `subAccount/actions:transfer`. `availableRaw` is the\n * recomputed `balanceOf − Σ` on-chain integer; the SDK lifts it to `Money`\n * via `fromWei`. `from`/`to` are the updated sub-account rows, or `null` when\n * that endpoint is the Account's MAIN balance (never a stored row).\n */\nexport type WireTransferResult = {\n readonly availableRaw: string;\n readonly decimals: number;\n readonly currency: string;\n readonly from: WireSubAccount | null;\n readonly to: WireSubAccount | null;\n};\n\nexport type WireTransferArgs = {\n readonly chainId: number;\n readonly from: string;\n readonly to: string;\n readonly rawAmount: string;\n};\n\nexport type ConvexSubAccountFunctions = {\n readonly create: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly accountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly get: FunctionReference<\n \"query\",\n \"public\",\n { readonly subAccountId: string },\n WireSubAccount | null\n >;\n readonly list: FunctionReference<\n \"query\",\n \"public\",\n { readonly accountId: string },\n readonly WireSubAccount[]\n >;\n readonly rename: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string; readonly name: string },\n WireSubAccount\n >;\n readonly remove: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly subAccountId: string },\n { readonly ok: true }\n >;\n readonly transfer: FunctionReference<\"action\", \"public\", WireTransferArgs, WireTransferResult>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSubAccountFunctions = {\n create: makeFunctionReference<\"mutation\", { accountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].create,\n ),\n get: makeFunctionReference<\"query\", { subAccountId: string }, WireSubAccount | null>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].get,\n ),\n list: makeFunctionReference<\"query\", { accountId: string }, readonly WireSubAccount[]>(\n CAPXUL_FUNCTIONS[\"subAccount/queries\"].list,\n ),\n rename: makeFunctionReference<\"mutation\", { subAccountId: string; name: string }, WireSubAccount>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].rename,\n ),\n remove: makeFunctionReference<\"mutation\", { subAccountId: string }, { ok: true }>(\n CAPXUL_FUNCTIONS[\"subAccount/mutations\"].remove,\n ),\n transfer: makeFunctionReference<\"action\", WireTransferArgs, WireTransferResult>(\n CAPXUL_FUNCTIONS[\"subAccount/actions\"].transfer,\n ),\n};\n\nexport class ConvexSubAccountAdapter implements SubAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSubAccountFunctions;\n readonly #chainId: number;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly chainId: number;\n readonly functions?: ConvexSubAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#chainId = deps.chainId;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"create\", this.#fns.create, {\n accountId: input.accountId as string,\n name: input.name,\n });\n }\n\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError> {\n return this.#runQuery(\n \"get\",\n this.#fns.get,\n { subAccountId: input.subAccountId as string },\n (wire) => (wire === null ? null : brandSubAccount(wire)),\n );\n }\n\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError> {\n return this.#runQuery(\n \"list\",\n this.#fns.list,\n { accountId: input.accountId as string },\n (wires) => wires.map((wire) => brandSubAccount(wire)),\n );\n }\n\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError> {\n return this.#runMutation(\"rename\", this.#fns.rename, {\n subAccountId: input.subAccountId as string,\n name: input.name,\n });\n }\n\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError> {\n const operation = \"delete\";\n return this.#convex\n .mutation(this.#fns.remove, { subAccountId: input.subAccountId as string })\n .pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.asVoid,\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError> {\n const operation = \"transfer\";\n // `toWei`/`parseUnits` throws on a malformed money string; that surfaces as\n // a defect below and is mapped to a SubAccountError (INVALID_INPUT-ish).\n return Effect.suspend(() => {\n const rawAmount = toWei(input.amount);\n return this.#convex.action(\n this.#fns.transfer,\n copyInvocationObservation(input, {\n chainId: this.#chainId,\n from: input.from as string,\n to: input.to as string,\n rawAmount,\n }),\n );\n }).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n // Branding (`fromWei` / `brandSubAccount`) runs INSIDE the guarded pipe so\n // a throw surfaces as a SubAccountError defect, never an escaped defect.\n Effect.map((wire) => brandTransferResult(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runMutation(\n operation: string,\n ref: FunctionReference<\"mutation\", \"public\", Record<string, string>, WireSubAccount>,\n args: Record<string, string>,\n ): Effect.Effect<SubAccount, SubAccountError> {\n return this.#convex.mutation(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map((wire) => brandSubAccount(wire)),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n\n #runQuery<TWire, TOut>(\n operation: string,\n ref: FunctionReference<\"query\", \"public\", Record<string, string>, TWire>,\n args: Record<string, string>,\n map: (wire: TWire) => TOut,\n ): Effect.Effect<TOut, SubAccountError> {\n // Branding (`map`) runs INSIDE the guarded pipe so a throw from\n // toAccountId/toSubAccountId/fromWei surfaces as a SubAccountError defect,\n // never an unhandled defect that escapes the typed channel.\n return this.#convex.query(ref, args).pipe(\n Effect.mapError((error) => subAccountErrorFromCapxul(operation, error.publicError, error)),\n Effect.map(map),\n Effect.catchDefect((cause) => Effect.fail(subAccountErrorFromUnknown(operation, cause))),\n );\n }\n}\n\nexport function ConvexSubAccountLayer(\n chainId: number,\n): Layer.Layer<SubAccountPortTag, SubAccountError, ConvexCallPortTag> {\n return Layer.effect(\n SubAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSubAccountAdapter({ convex, chainId })),\n );\n}\n\nfunction brandTransferResult(wire: WireTransferResult): TransferResult {\n return {\n available: fromWei(wire.availableRaw, wire.decimals, wire.currency),\n from: wire.from === null ? null : brandSubAccount(wire.from),\n to: wire.to === null ? null : brandSubAccount(wire.to),\n };\n}\n\nfunction brandSubAccount(wire: WireSubAccount): SubAccount {\n return {\n id: toSubAccountId(wire.subAccountId),\n accountId: toAccountId(wire.accountId),\n name: wire.name,\n balance: fromWei(wire.rawBalance, wire.decimals, wire.currency),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction subAccountErrorFromUnknown(operation: string, cause: unknown): SubAccountError {\n if (cause instanceof CapxulError) return subAccountErrorFromCapxul(operation, cause);\n return subAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","import { CapxulError, Errors } from \"@capxul/config\";\nimport type { Address, AuthUserId, SmartAccount } from \"@capxul/types\";\nimport { toAddress, toAuthUserId, toChainId, toEpochMs } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Layer } from \"effect\";\n\nimport { wireChainId } from \"../_shared/wire\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n ClaimInput,\n ConfirmDeploymentInput,\n ProvisionInput,\n SmartAccountError,\n SmartAccountPort,\n} from \"../../ports/smart-account\";\nimport { smartAccountErrorFromCapxul, SmartAccountPortTag } from \"../../ports/smart-account\";\n\nexport type WireSmartAccount = {\n readonly authUserId: string;\n readonly signerAddress: string | null;\n readonly smartAccountAddress: string;\n readonly chainId: number;\n readonly deployedAt: number | null;\n readonly claimedAt: number | null;\n readonly createdAt: number;\n};\n\nexport type WireConfirmDeploymentArgs = {\n readonly chainId: number;\n readonly safeAddress: string;\n readonly telemetryRunId?: string;\n readonly evidence: {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly safeAddress: string;\n readonly userOpHash?: string;\n readonly txHash?: string;\n readonly blockNumber?: number;\n };\n};\n\nexport type WireClaimArgs = {\n readonly chainId: number;\n readonly signerAddress: string;\n readonly telemetryRunId?: string;\n readonly observationContext?: WireObservationContext;\n};\n\nexport type ConvexSmartAccountFunctions = {\n readonly loadByAuthUserId: FunctionReference<\n \"query\",\n \"public\",\n { readonly authUserId: string },\n WireSmartAccount | null\n >;\n readonly loadBySmartAccountAddress: FunctionReference<\n \"query\",\n \"public\",\n { readonly address: string },\n WireSmartAccount | null\n >;\n readonly provision: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly chainId: number;\n },\n WireSmartAccount\n >;\n // `confirmDeployment` is an ACTION, not a mutation, because the\n // backend handler must perform outbound `fetch` calls to Alchemy\n // (eth_getCode / eth_getUserOperationReceipt / eth_getLogs /\n // eth_getBlockByNumber) — Convex mutations are transactional and\n // cannot do fetch. See `packages/backend/convex/smartAccount/actions.ts`.\n readonly confirmDeployment: FunctionReference<\n \"action\",\n \"public\",\n WireConfirmDeploymentArgs,\n WireSmartAccount\n >;\n // `claim` is an ACTION: the backend builds, bootstrap-signs, and submits\n // the claim userOp (deploy + swapOwner) via outbound bundler RPC (PRD #462).\n readonly claim: FunctionReference<\"action\", \"public\", WireClaimArgs, WireSmartAccount>;\n};\n\nconst DEFAULT_FUNCTIONS: ConvexSmartAccountFunctions = {\n loadByAuthUserId: makeFunctionReference<\"query\", { authUserId: string }, WireSmartAccount | null>(\n CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadByAuthUserId,\n ),\n loadBySmartAccountAddress: makeFunctionReference<\n \"query\",\n { address: string },\n WireSmartAccount | null\n >(CAPXUL_FUNCTIONS[\"smartAccount/queries\"].loadBySmartAccountAddress),\n provision: makeFunctionReference<\"mutation\", { chainId: number }, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/mutations\"].provision,\n ),\n confirmDeployment: makeFunctionReference<\"action\", WireConfirmDeploymentArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].confirmDeployment,\n ),\n claim: makeFunctionReference<\"action\", WireClaimArgs, WireSmartAccount>(\n CAPXUL_FUNCTIONS[\"smartAccount/actions\"].claim,\n ),\n};\n\nexport class ConvexSmartAccountAdapter implements SmartAccountPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: ConvexSmartAccountFunctions;\n\n constructor(deps: {\n readonly convex: ConvexCallPort;\n readonly functions?: ConvexSmartAccountFunctions;\n }) {\n this.#convex = deps.convex;\n this.#fns = deps.functions ?? DEFAULT_FUNCTIONS;\n }\n\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadByAuthUserId\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadByAuthUserId\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadByAuthUserId\", cause)),\n ),\n );\n }\n\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"loadBySmartAccountAddress\", error.publicError, error),\n ),\n Effect.flatMap((row) => brandSmartAccountEffect(\"loadBySmartAccountAddress\", row)),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"loadBySmartAccountAddress\", cause)),\n ),\n );\n }\n\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .mutation(this.#fns.provision, {\n chainId: wireChainId(input.chainId),\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"provision\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"provision\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"provision\", cause)),\n ),\n );\n }\n\n confirmDeployment(input: ConfirmDeploymentInput): Effect.Effect<SmartAccount, SmartAccountError> {\n const evidence: WireConfirmDeploymentArgs[\"evidence\"] = {\n chainId: wireChainId(input.evidence.chainId),\n signerAddress: input.evidence.signerAddress,\n safeAddress: input.evidence.safeAddress,\n ...(input.evidence.userOpHash === undefined ? {} : { userOpHash: input.evidence.userOpHash }),\n ...(input.evidence.txHash === undefined ? {} : { txHash: input.evidence.txHash }),\n ...(input.evidence.blockNumber === undefined\n ? {}\n : { blockNumber: input.evidence.blockNumber }),\n };\n return this.#convex\n .action(this.#fns.confirmDeployment, {\n chainId: wireChainId(input.chainId),\n safeAddress: input.safeAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n evidence,\n })\n .pipe(\n Effect.mapError((error) =>\n smartAccountErrorFromCapxul(\"confirmDeployment\", error.publicError, error),\n ),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"confirmDeployment\", cause),\n }),\n ),\n Effect.catchDefect((cause) =>\n Effect.fail(smartAccountErrorFromUnknown(\"confirmDeployment\", cause)),\n ),\n );\n }\n\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError> {\n return this.#convex\n .action(\n this.#fns.claim,\n copyInvocationObservation(input, {\n chainId: wireChainId(input.chainId),\n signerAddress: input.signerAddress,\n ...(input.telemetryRunId === undefined ? {} : { telemetryRunId: input.telemetryRunId }),\n }),\n )\n .pipe(\n Effect.mapError((error) => smartAccountErrorFromCapxul(\"claim\", error.publicError, error)),\n Effect.flatMap((row) =>\n Effect.try({\n try: () => brandProvisionedSmartAccount(input.authUserId, row),\n catch: (cause) => smartAccountErrorFromUnknown(\"claim\", cause),\n }),\n ),\n Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown(\"claim\", cause))),\n );\n }\n}\n\nexport function ConvexSmartAccountLayer(): Layer.Layer<\n SmartAccountPortTag,\n SmartAccountError,\n ConvexCallPortTag\n> {\n return Layer.effect(\n SmartAccountPortTag,\n Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })),\n );\n}\n\nfunction brandSmartAccountEffect(\n operation: string,\n wire: WireSmartAccount | null,\n): Effect.Effect<SmartAccount | null, SmartAccountError> {\n return Effect.try({\n try: () => (wire === null ? null : brandNonNullSmartAccount(wire)),\n catch: (cause) => smartAccountErrorFromUnknown(operation, cause),\n });\n}\n\nfunction brandNonNullSmartAccount(wire: WireSmartAccount): SmartAccount {\n return {\n authUserId: toAuthUserId(wire.authUserId),\n signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),\n smartAccountAddress: toAddress(wire.smartAccountAddress),\n chainId: toChainId(wire.chainId),\n deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),\n claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),\n createdAt: toEpochMs(wire.createdAt),\n };\n}\n\nfunction brandProvisionedSmartAccount(\n requestedAuthUserId: AuthUserId,\n wire: WireSmartAccount,\n): SmartAccount {\n if (wire.authUserId !== String(requestedAuthUserId)) {\n throw Errors.notAuthenticated();\n }\n return brandNonNullSmartAccount(wire);\n}\n\nfunction smartAccountErrorFromUnknown(operation: string, cause: unknown): SmartAccountError {\n if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);\n return smartAccountErrorFromCapxul(\n operation,\n Errors.providerError(\"convex\", operation, cause),\n cause,\n );\n}\n","// Organization domain port (owned by `packages/sdk/docs/architecture.md`).\n// The SEAM between the Effect org programs and the outside\n// world: the live adapter (added by the CLI/live-proof slice) performs the\n// SDK-orchestrated Org Safe deploy (D10 — permissionless + zodiac-roles-sdk,\n// no custom Solidity) and the RPC `balanceOf` treasury read (D3); the hermetic\n// L1 path runs with NO port and the org programs fall back to a deterministic\n// `$0` treasury (a fresh Org has no on-chain funds).\n//\n// The port returns plain records branded at this boundary (brand-at-source).\n// `OrgError` carries the public `CapxulError` so the program can surface a\n// typed failure channel exactly like `AccountReadPort`.\n\nimport { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/errors\";\nimport type { Account, OrgId } from \"@capxul/types\";\n\nimport type {\n AssignRoleInput,\n CreateOrgInput,\n InviteMemberInput,\n MemberView,\n OrgView,\n RemoveMemberInput,\n RoleView,\n OrgSpendViaPaymentsInput,\n OrgPayrollRun,\n} from \"../surface/org\";\nimport type { Address, Money, SubAccountId } from \"@capxul/types\";\n\n/**\n * The minimal `{from, to, amount}` spend shape the authority read keys off\n * (D3 #565). The legacy address-keyed `OrgSpendInput`/`org.spend` lane was\n * hard-removed when `orgSpends` folded into the one `payments` ledger; the\n * leak-safe ref-based lane (`spendViaPayments`/`batchPayroll`) constructs this\n * internally and enforces the real validated recipient on the gate.\n */\nexport type OrgSpendShape = {\n readonly from: SubAccountId;\n readonly to: Address;\n readonly amount: Money;\n};\nimport type { Payment } from \"../surface/money\";\nimport type { SpendGateRecipients, SpendGateSubAccountScope } from \"../domain/org/spend-gate\";\n\nexport type CreateOrgPortInput = {\n readonly input: CreateOrgInput;\n};\n\nexport type ReadOrgTreasuryInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgsInput = Record<never, never>;\n\nexport type ListOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type ListOrgMembersInput = {\n readonly orgId: OrgId;\n};\n\nexport type InviteOrgMemberInput = {\n readonly orgId: OrgId;\n readonly input: InviteMemberInput;\n};\n\nexport type ResendOrgInviteTokenInput = {\n readonly orgId: OrgId;\n readonly email: string;\n};\n\nexport type DetectPendingOrgInvitationsInput = Record<never, never>;\n\nexport type DetectPendingOrgInvitationsResult = {\n readonly matched: readonly OrgId[];\n};\n\nexport type DeployOrgRolesInput = {\n readonly orgId: OrgId;\n};\n\nexport type OrgRolesDeploymentResult = {\n readonly orgId: OrgId;\n readonly roles: readonly RoleView[];\n};\n\nexport type GrantOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: AssignRoleInput;\n};\n\nexport type RevokeOrgRoleInput = {\n readonly orgId: OrgId;\n readonly input: RemoveMemberInput;\n};\n\nexport type OrgSpendAuthority = {\n readonly activeMember: boolean;\n readonly subAccountBalanceRaw: string;\n readonly recipients: SpendGateRecipients;\n readonly subAccounts: SpendGateSubAccountScope;\n readonly perTxCapRaw?: string | null;\n readonly perDayCapRaw?: string | null;\n readonly spentTodayRaw?: string | null;\n readonly role?: string;\n};\n\nexport type ReadOrgSpendAuthorityInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendShape;\n readonly amountRaw: string;\n};\n\nexport class OrgError extends Data.TaggedError(\"OrgError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function orgErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): OrgError {\n return new OrgError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n/**\n * Live org seam. `createOrg` runs the SDK-orchestrated deploy (D10) and returns\n * the created `OrgView` (its treasury is the real M2 `Account` over the Org\n * Safe — $0 at creation, D3). `readTreasury` pulls the org's Account via RPC\n * `balanceOf` (D3). `listOrgs` lists the orgs the authenticated user belongs to.\n */\nexport interface OrgPort {\n createOrg(input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError, never>;\n readTreasury(input: ReadOrgTreasuryInput): Effect.Effect<Account, OrgError, never>;\n listOrgs(input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError, never>;\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError, never>;\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError, never>;\n pendingMembers?(\n input: ListOrgMembersInput,\n ): Effect.Effect<readonly MemberView[], OrgError, never>;\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError, never>;\n resendInviteToken?(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError, never>;\n detectAndAcceptPendingInvitations(\n input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError, never>;\n}\n\nexport class OrgPortTag extends Context.Service<OrgPortTag, OrgPort>()(\n \"@capxul/sdk/ports/OrgPort\",\n) {}\n\nexport interface OrgRolesDeploymentPort {\n deployRoles(input: DeployOrgRolesInput): Effect.Effect<OrgRolesDeploymentResult, OrgError, never>;\n grantRole(input: GrantOrgRoleInput): Effect.Effect<MemberView, OrgError, never>;\n revokeRole(input: RevokeOrgRoleInput): Effect.Effect<void, OrgError, never>;\n}\n\nexport class OrgRolesDeploymentPortTag extends Context.Service<\n OrgRolesDeploymentPortTag,\n OrgRolesDeploymentPort\n>()(\"@capxul/sdk/ports/OrgRolesDeploymentPort\") {}\n\nexport type SubmitOrgSpendViaPaymentsInput = {\n readonly orgId: OrgId;\n readonly input: OrgSpendViaPaymentsInput;\n readonly amountRaw: string;\n readonly authority: OrgSpendAuthority;\n};\n\nexport type SubmitOrgBatchPayrollInput = {\n readonly orgId: OrgId;\n readonly from: OrgSpendViaPaymentsInput[\"from\"];\n readonly runs: readonly { readonly run: OrgPayrollRun; readonly amountRaw: string }[];\n readonly authorities: readonly OrgSpendAuthority[];\n};\n\nexport interface OrgSpendPort {\n readSpendAuthority(\n input: ReadOrgSpendAuthorityInput,\n ): Effect.Effect<OrgSpendAuthority, OrgError, never>;\n /**\n * Leak-safe org spend (G4 · #547; D3 #565 — the one ledger of record): execute\n * the spend through the payments engine (Roles modifier → CapxulPayments),\n * write a real `payments` row (`source:\"org\"`) and read it back as a `Payment`\n * — the wire carries no `txHash` / Safe / userOp internals. Optional so a\n * hermetic adapter without a payments-submit lane still compiles; absent ⇒ the\n * program falls back to a deterministic hermetic `Payment`.\n */\n submitSpendViaPayments?(\n input: SubmitOrgSpendViaPaymentsInput,\n ): Effect.Effect<Payment, OrgError, never>;\n /** Leak-safe org payroll batch (G4 · #547): one MultiSend, one Payment per run. */\n submitBatchPayroll?(\n input: SubmitOrgBatchPayrollInput,\n ): Effect.Effect<readonly Payment[], OrgError, never>;\n}\n\nexport class OrgSpendPortTag extends Context.Service<OrgSpendPortTag, OrgSpendPort>()(\n \"@capxul/sdk/ports/OrgSpendPort\",\n) {}\n","/**\n * Pure brand-at-read-edge parser for the Org domain wire shape (canon D9/D10a;\n * `.claude/rules/typescript-style.md` \"Brand at DB read boundaries\" +\n * `.claude/rules/wire-fixture-discipline.md`). Maps the raw Convex `WireOrg`\n * row into the branded `OrgView`. No I/O, no viem — so the hermetic L2 fixture\n * test can load `__fixtures__/createOrg-actual.json` verbatim and assert this\n * parser narrows it.\n */\nimport type { Account, Address, Money } from \"@capxul/types\";\nimport {\n toAccountId,\n toAddress,\n toCurrencyCode,\n toEmail,\n toOrgId,\n toRoleKey,\n toSubAccountId,\n} from \"@capxul/types\";\n\nimport type { MemberView, OrgView, RoleDefinition, RoleView } from \"../../surface/org\";\n\n/** Raw Org row as returned by the backend `org/queries` + `org/mutations`. */\nexport type WireOrg = {\n readonly orgId: string;\n readonly name: string;\n readonly slug: string;\n readonly safeAddress: string;\n readonly chainId: number;\n readonly ownerPersonalSafeAddress: string;\n readonly founderEmail: string;\n readonly status?: \"safe_placeholder\" | \"safe_deployed\" | \"active\";\n readonly template?: string;\n readonly metadata: string | null;\n readonly country: string | null;\n // #1064 bio/size + #1061 logoUrl. Optional so pre-rollout recorded fixtures\n // stay verbatim-loadable; the parser maps absence to null.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly logoUrl?: string | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nexport type WireOrgRole = {\n readonly orgId: string;\n readonly roleKey: string;\n readonly label: string;\n readonly definitionJson: string;\n readonly permissions: readonly string[];\n readonly allowanceJson: string | null;\n readonly status: \"active\" | \"revoked\";\n readonly createdAt: number;\n readonly revokedAt: number | null;\n};\n\nexport type WireOrgMember = {\n readonly orgId: string;\n readonly email: string;\n readonly name: string | null;\n readonly authUserId: string | null;\n readonly personalSafeAddress: string | null;\n readonly role: string;\n readonly roleKey: string | null;\n readonly status: \"pending\" | \"pending_safe\" | \"pending_grant\" | \"active\" | \"revoked\" | \"expired\";\n readonly grantTxHash: string | null;\n readonly revokeTxHash: string | null;\n readonly invitedAt: number;\n readonly acceptedAt: number | null;\n readonly grantedAt: number | null;\n readonly revokedAt: number | null;\n readonly expiresAt: number;\n readonly updatedAt: number;\n};\n\ntype RawRoleDefinition = {\n readonly label?: unknown;\n readonly spend?: {\n readonly perTx?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly perDay?: {\n readonly currency: unknown;\n readonly value: unknown;\n readonly decimals: unknown;\n };\n readonly toRecipients?: unknown;\n };\n readonly subAccounts?: { readonly scope?: unknown };\n readonly canManageMembers?: unknown;\n readonly canManageRoles?: unknown;\n};\n\n/**\n * Map a `WireOrg` + its (separately read) treasury `Account` into the branded\n * `OrgView`. The viewer role is projected by the authenticated backend read;\n * it must never be inferred from Organization ownership. Brands at the read\n * edge: `orgId`, `safeAddress`.\n */\nexport function brandOrgView(wire: WireOrg, treasury: Account, viewerRole: string): OrgView {\n return {\n id: toOrgId(wire.orgId),\n name: wire.name,\n handle: wire.slug,\n safeAddress: toAddress(wire.safeAddress.toLowerCase()),\n role: viewerRole,\n treasury,\n bio: wire.bio ?? null,\n size: wire.size ?? null,\n logoUrl: wire.logoUrl ?? null,\n };\n}\n\n/**\n * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer\n * (the D3 RPC read). `available === balance` for a treasury with no envelope\n * partition yet (a fresh Org reads back $0).\n */\nexport function brandOrgTreasury(input: {\n readonly orgId: string;\n readonly money: Money;\n}): Account {\n return {\n id: toAccountId(`account_${orgIdBody(input.orgId)}`),\n balance: input.money,\n available: input.money,\n };\n}\n\nexport function brandOrgRole(wire: WireOrgRole): RoleView {\n return {\n orgId: toOrgId(wire.orgId),\n label: wire.label,\n roleKey: toRoleKey(wire.roleKey),\n definition: parseRoleDefinition(wire.definitionJson),\n };\n}\n\nexport function brandOrgMember(wire: WireOrgMember): MemberView {\n return {\n orgId: toOrgId(wire.orgId),\n email: toEmail(wire.email),\n name: wire.name,\n personalSafeAddress:\n wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),\n role: wire.role,\n roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),\n status: wire.status,\n grantTxHash: wire.grantTxHash,\n revokeTxHash: wire.revokeTxHash,\n };\n}\n\nfunction parseRoleDefinition(json: string): RoleDefinition {\n let raw: RawRoleDefinition;\n try {\n const parsed = JSON.parse(json) as unknown;\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"expected object\");\n }\n raw = parsed as RawRoleDefinition;\n } catch (err) {\n throw new Error(\n `Invalid role definition: malformed JSON - ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n if (typeof raw.label !== \"string\" || raw.label.trim().length === 0) {\n throw new Error(\"Invalid role definition: missing label\");\n }\n return {\n label: raw.label,\n ...(raw.spend === undefined\n ? {}\n : {\n spend: {\n ...(raw.spend.perTx === undefined\n ? {}\n : { perTx: parseRoleMoney(raw.spend.perTx, \"perTx\") }),\n ...(raw.spend.perDay === undefined\n ? {}\n : { perDay: parseRoleMoney(raw.spend.perDay, \"perDay\") }),\n ...(raw.spend.toRecipients === undefined\n ? {}\n : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }),\n },\n }),\n ...(raw.subAccounts === undefined\n ? {}\n : { subAccounts: parseRoleSubAccounts(raw.subAccounts) }),\n ...(typeof raw.canManageMembers === \"boolean\"\n ? { canManageMembers: raw.canManageMembers }\n : {}),\n ...(typeof raw.canManageRoles === \"boolean\" ? { canManageRoles: raw.canManageRoles } : {}),\n };\n}\n\nfunction parseRoleMoney(\n raw: { readonly currency: unknown; readonly value: unknown; readonly decimals: unknown },\n field: string,\n) {\n if (\n typeof raw.currency !== \"string\" ||\n typeof raw.value !== \"string\" ||\n !/^\\d+$/.test(raw.value) ||\n raw.decimals !== 6\n ) {\n throw new Error(`Invalid role money: ${field}`);\n }\n return {\n currency: toCurrencyCode(raw.currency),\n value: raw.value,\n decimals: raw.decimals,\n };\n}\n\nfunction parseRoleRecipients(raw: unknown): \"anyone\" | readonly Address[] {\n if (raw === \"anyone\") return \"anyone\";\n if (!Array.isArray(raw)) {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return raw.map((recipient) => {\n if (typeof recipient !== \"string\") {\n throw new Error('Invalid role definition: toRecipients must be \"anyone\" or an array');\n }\n return toAddress(recipient);\n });\n}\n\nfunction parseRoleSubAccounts(raw: { readonly scope?: unknown }) {\n if (raw.scope === \"all\") return { scope: \"all\" as const };\n if (!Array.isArray(raw.scope)) {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return {\n scope: raw.scope.map((subAccountId) => {\n if (typeof subAccountId !== \"string\") {\n throw new Error('Invalid role definition: subAccounts.scope must be \"all\" or an array');\n }\n return toSubAccountId(subAccountId);\n }),\n };\n}\n\n/** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */\nfunction orgIdBody(orgId: string): string {\n const underscore = orgId.indexOf(\"_\");\n const tail = underscore < 0 ? orgId : orgId.slice(underscore + 1);\n const cleaned = tail.replace(/[^0-9A-Za-z]/g, \"\");\n return cleaned.length > 0 ? cleaned : \"0\";\n}\n","import { CapxulError, Errors } from \"@capxul/errors\";\nimport { toOrgId } from \"@capxul/types\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect } from \"effect\";\n\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type {\n CreateOrgPortInput,\n DetectPendingOrgInvitationsInput,\n DetectPendingOrgInvitationsResult,\n InviteOrgMemberInput,\n ListOrgMembersInput,\n ListOrgRolesInput,\n ListOrgsInput,\n OrgError,\n OrgPort,\n ReadOrgTreasuryInput,\n ResendOrgInviteTokenInput,\n} from \"../../ports/org\";\nimport { orgErrorFromCapxul } from \"../../ports/org\";\nimport type { MemberView, OrgView, RoleView } from \"../../surface/org\";\nimport { fromWei } from \"../../domain/money/from-wei\";\nimport {\n brandOrgMember,\n brandOrgRole,\n brandOrgTreasury,\n brandOrgView,\n type WireOrg,\n type WireOrgMember,\n type WireOrgRole,\n} from \"./parse\";\n\ntype WireTreasury = {\n readonly orgId: string;\n readonly rawBalance: string;\n readonly rawAvailableBalance: string;\n readonly decimals: number;\n readonly currency: string;\n};\n\ntype WireOrgListItem = WireOrg & { readonly viewerRole: string };\n\ntype DetectInvitationsWire = {\n readonly matched: readonly string[];\n readonly members: readonly WireOrgMember[];\n};\n\ntype OrganizationFunctions = {\n readonly listAll: FunctionReference<\n \"query\",\n \"public\",\n Record<never, never>,\n readonly WireOrgListItem[]\n >;\n readonly listRoles: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgRole[]\n >;\n readonly listMembers: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n readonly WireOrgMember[]\n >;\n readonly readTreasury: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string },\n WireTreasury\n >;\n readonly inviteMember: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly email: string; readonly role: string },\n WireOrgMember\n >;\n readonly resendInvite: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly email: string },\n WireOrgMember\n >;\n readonly detectInvitations: FunctionReference<\n \"action\",\n \"public\",\n Record<never, never>,\n DetectInvitationsWire\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationFunctions = {\n listAll: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listAll),\n listRoles: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listRolesByOrgId),\n listMembers: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/queries\"].listMembersByOrgId),\n readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].readTreasury),\n inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].inviteMember),\n resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/mutations\"].resendInviteToken),\n detectInvitations: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].detectAndAcceptPendingInvitations,\n ),\n};\n\n/**\n * Standard production Organization read adapter. It intentionally has no\n * deployer/RPC/test configuration: authenticated Convex actions own live chain\n * reads, while the lifecycle adapter owns the single sponsored bootstrap.\n */\nexport class ConvexOrganizationAdapter implements OrgPort {\n readonly #convex: ConvexCallPort;\n readonly #fns: OrganizationFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly functions?: OrganizationFunctions;\n }) {\n this.#convex = input.convex;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n createOrg(_input: CreateOrgPortInput): Effect.Effect<OrgView, OrgError> {\n return Effect.fail(\n orgErrorFromCapxul(\n \"createOrg\",\n Errors.notImplemented(\"organizationSetup\", \"use onboarding.completeOrganization\"),\n ),\n );\n }\n\n listOrgs(_input: ListOrgsInput): Effect.Effect<readonly OrgView[], OrgError> {\n return this.#convex.query(this.#fns.listAll, {}).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listOrgs\", error.publicError, error)),\n Effect.flatMap((wires) =>\n Effect.forEach(wires, (wire) =>\n this.#readTreasuryWire(wire.orgId).pipe(\n Effect.map((treasury) => {\n const viewerRole = wire.viewerRole.trim();\n if (viewerRole.length === 0) {\n throw Errors.wrongState({\n method: \"listOrgs\",\n currentState: \"viewerRoleMissing\",\n validStates: [\"activeViewerRole\"],\n });\n }\n return brandOrgView(wire, treasury, viewerRole);\n }),\n ),\n ),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listOrgs\", cause))),\n );\n }\n\n readTreasury(input: ReadOrgTreasuryInput) {\n return this.#readTreasuryWire(String(input.orgId)).pipe(\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"readTreasury\", cause))),\n );\n }\n\n listRoles(input: ListOrgRolesInput): Effect.Effect<readonly RoleView[], OrgError> {\n return this.#convex.query(this.#fns.listRoles, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listRoles\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listRoles\", \"activeRoleMissing\"))\n : Effect.succeed(rows.map(brandOrgRole)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listRoles\", cause))),\n );\n }\n\n listMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.#convex.query(this.#fns.listMembers, { orgId: input.orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"listMembers\", error.publicError, error)),\n Effect.flatMap((rows) =>\n rows.length === 0\n ? Effect.fail(partialOrgTruth(\"listMembers\", \"activeMemberMissing\"))\n : Effect.succeed(rows.map(brandOrgMember)),\n ),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"listMembers\", cause))),\n );\n }\n\n pendingMembers(input: ListOrgMembersInput): Effect.Effect<readonly MemberView[], OrgError> {\n return this.listMembers(input).pipe(\n Effect.map((members) =>\n members.filter(\n (member) =>\n member.status === \"pending\" ||\n member.status === \"pending_safe\" ||\n member.status === \"pending_grant\",\n ),\n ),\n );\n }\n\n inviteMember(input: InviteOrgMemberInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .action(this.#fns.inviteMember, {\n orgId: input.orgId,\n email: input.input.email,\n role: input.input.role,\n })\n .pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"inviteMember\", error.publicError, error)),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"inviteMember\", cause))),\n );\n }\n\n resendInviteToken(input: ResendOrgInviteTokenInput): Effect.Effect<MemberView, OrgError> {\n return this.#convex\n .mutation(this.#fns.resendInvite, { orgId: input.orgId, email: input.email })\n .pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"resendInviteToken\", error.publicError, error),\n ),\n Effect.map(brandOrgMember),\n Effect.catchDefect((cause) => Effect.fail(toOrgError(\"resendInviteToken\", cause))),\n );\n }\n\n detectAndAcceptPendingInvitations(\n _input: DetectPendingOrgInvitationsInput,\n ): Effect.Effect<DetectPendingOrgInvitationsResult, OrgError> {\n return this.#convex.action(this.#fns.detectInvitations, {}).pipe(\n Effect.mapError((error) =>\n orgErrorFromCapxul(\"detectAndAcceptPendingInvitations\", error.publicError, error),\n ),\n Effect.map((result) => ({ matched: result.matched.map(toOrgId) })),\n Effect.catchDefect((cause) =>\n Effect.fail(toOrgError(\"detectAndAcceptPendingInvitations\", cause)),\n ),\n );\n }\n\n #readTreasuryWire(orgId: string) {\n return this.#convex.action(this.#fns.readTreasury, { orgId }).pipe(\n Effect.mapError((error) => orgErrorFromCapxul(\"readTreasury\", error.publicError, error)),\n Effect.map((wire) => {\n if (wire.orgId !== orgId) {\n throw Errors.invalidInput(\"orgId\", \"Organization treasury scope does not match\");\n }\n const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);\n const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);\n const account = brandOrgTreasury({ orgId: wire.orgId, money: balance });\n return { ...account, available };\n }),\n );\n }\n}\n\nfunction toOrgError(operation: string, cause: unknown): OrgError {\n if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);\n return orgErrorFromCapxul(operation, Errors.providerError(\"convex\", operation, cause), cause);\n}\n\nfunction partialOrgTruth(operation: string, currentState: string): OrgError {\n return orgErrorFromCapxul(\n operation,\n Errors.wrongState({\n method: operation,\n currentState,\n validStates: [\"completeProductionOrganizationTruth\"],\n }),\n );\n}\n","import { CapxulError, Errors, type CapxulErrorCode } from \"@capxul/errors\";\nimport { toOrgId, type OrgId } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport { Effect, Result } from \"effect\";\nimport type { Hex } from \"viem\";\n\nimport type {\n OrganizationSetupOps,\n OrganizationSetupStepInput,\n OrgLifecycle,\n RecordOrganizationSetupFailureInput,\n StartOrResumeOrganizationInput,\n} from \"../../surface/org-lifecycle\";\nimport type { CapxulResult } from \"../../surface/types\";\nimport { copyInvocationObservation } from \"../../internal/invocation-observation\";\nimport type { ConvexCallPort } from \"../../ports/convex-call\";\nimport type { CapxulSigner } from \"../../signer\";\n\ntype WireLifecycle =\n | { readonly status: \"loading\"; readonly orgId: string }\n | {\n readonly status: \"settingUp\";\n readonly orgId: string;\n readonly step: OrgLifecycle extends infer _ ? string : never;\n }\n | { readonly status: \"ready\"; readonly orgId: string; readonly canTransact: true }\n | {\n readonly status: \"failed\";\n readonly orgId: string;\n readonly at: string;\n readonly error: { readonly code: CapxulErrorCode; readonly message: string };\n readonly retryable: boolean;\n };\n\nexport type OrganizationBootstrapUserOp = {\n readonly sender: string;\n readonly nonce: string;\n readonly factory?: string;\n readonly factoryData?: string;\n readonly callData: string;\n readonly callGasLimit: string;\n readonly verificationGasLimit: string;\n readonly preVerificationGas: string;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n readonly paymaster: string;\n readonly paymasterVerificationGasLimit?: string;\n readonly paymasterPostOpGasLimit?: string;\n readonly paymasterData: string;\n};\n\ntype PreparedBootstrap = {\n readonly digest: string;\n readonly signerAddress: string;\n readonly founderPersonalAccount: string;\n readonly organizationAccountAddress: string;\n readonly userOp: OrganizationBootstrapUserOp;\n};\n\ntype OrganizationSetupFunctions = {\n readonly startOrResume: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly name: string;\n readonly handle: string;\n readonly country: string;\n // #1064: onboarding-collected description + size bucket, pass-through.\n readonly bio?: string | null;\n readonly size?: string | null;\n readonly chainId: number;\n readonly observationContext?: WireObservationContext;\n },\n { readonly orgId: string; readonly lifecycle: WireLifecycle }\n >;\n readonly prepareFounderAccount: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly prepareBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly observationContext?: WireObservationContext;\n },\n PreparedBootstrap\n >;\n readonly submitBootstrap: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly signerAddress: string;\n readonly signature: string;\n readonly userOp: OrganizationBootstrapUserOp;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly resumeBootstrapSubmission: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly confirmBootstrap: FunctionReference<\n \"action\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n readonly recordFailure: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly orgId: string;\n readonly errorCode: string;\n readonly errorProvider?: string;\n readonly errorOperation?: string;\n readonly retryable: boolean;\n readonly observationContext?: WireObservationContext;\n },\n WireLifecycle\n >;\n readonly load: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle | null\n >;\n readonly retry: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly observationContext?: WireObservationContext },\n WireLifecycle\n >;\n};\n\nconst DEFAULT_FUNCTIONS: OrganizationSetupFunctions = {\n startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].startOrResume),\n prepareFounderAccount: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].prepareFounderAccount,\n ),\n prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].prepareBootstrap),\n submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].submitBootstrap),\n resumeBootstrapSubmission: makeFunctionReference(\n CAPXUL_FUNCTIONS[\"org/actions\"].resumeBootstrapSubmission,\n ),\n confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/actions\"].confirmBootstrap),\n recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].recordFailure),\n load: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].load),\n retry: makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].retry),\n};\n\n/** Durable Organization setup capability composed by the standard client. */\nexport class ConvexOrganizationSetupAdapter implements OrganizationSetupOps {\n readonly #convex: ConvexCallPort;\n readonly #signer: CapxulSigner;\n readonly #chainId: number;\n readonly #fns: OrganizationSetupFunctions;\n\n constructor(input: {\n readonly convex: ConvexCallPort;\n readonly signer: CapxulSigner;\n readonly chainId: number;\n readonly functions?: OrganizationSetupFunctions;\n }) {\n this.#convex = input.convex;\n this.#signer = input.signer;\n this.#chainId = input.chainId;\n this.#fns = input.functions ?? DEFAULT_FUNCTIONS;\n }\n\n async startOrResume(\n input: StartOrResumeOrganizationInput,\n ): Promise<CapxulResult<{ readonly orgId: OrgId; readonly lifecycle: OrgLifecycle }>> {\n const result = await runCall<{\n readonly orgId: string;\n readonly lifecycle: WireLifecycle;\n }>(\n \"startOrResume\",\n this.#convex.mutation(\n this.#fns.startOrResume,\n copyInvocationObservation(input, { ...input, chainId: this.#chainId }),\n ),\n );\n if (!result.ok) return result;\n const lifecycle = parseLifecycle(\"startOrResume\", result.value.lifecycle);\n if (!lifecycle.ok) return lifecycle;\n const orgId = parseOrgId(\"startOrResume\", result.value.orgId);\n if (!orgId.ok) return orgId;\n if (String(orgId.value) !== String(lifecycle.value.orgId)) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle scope does not match\"));\n }\n return { ok: true, value: { orgId: orgId.value, lifecycle: lifecycle.value } } as const;\n }\n\n prepareFounderAccount(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"prepareFounderAccount\", input, () =>\n this.#convex.action(\n this.#fns.prepareFounderAccount,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async authorizeAndSubmitBootstrap(\n input: OrganizationSetupStepInput,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n\n const signerAddress = await signerResult(\"getAddress\", () => this.#signer.getAddress());\n if (!signerAddress.ok) return signerAddress;\n const prepared = await runCall(\n \"prepareBootstrap\",\n this.#convex.action(\n this.#fns.prepareBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!prepared.ok) return prepared;\n const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);\n if (!authority.ok) return authority;\n const cancelledAfterPrepare = cancellation(input.signal);\n if (cancelledAfterPrepare !== undefined) return cancelledAfterPrepare;\n\n const signature = await signerResult(\"signUserOpHash\", () =>\n this.#signer.signUserOpHash(prepared.value.digest as Hex),\n );\n if (!signature.ok) return signature;\n const cancelledAfterSign = cancellation(input.signal);\n if (cancelledAfterSign !== undefined) return cancelledAfterSign;\n\n const submitted = await runCall(\n \"submitBootstrap\",\n this.#convex.action(\n this.#fns.submitBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n signerAddress: signerAddress.value,\n signature: signature.value,\n userOp: prepared.value.userOp,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!submitted.ok) return submitted;\n return parseLifecycle(\"submitBootstrap\", submitted.value);\n }\n\n resumeSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"resumeBootstrapSubmission\", input, () =>\n this.#convex.action(\n this.#fns.resumeBootstrapSubmission,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n confirmSubmittedBootstrap(input: OrganizationSetupStepInput) {\n return this.#lifecycleAction(\"confirmBootstrap\", input, () =>\n this.#convex.action(\n this.#fns.confirmBootstrap,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n }\n\n async recordFailure(input: RecordOrganizationSetupFailureInput) {\n const errorProvider = input.error.details?.provider;\n const errorOperation = input.error.details?.operation;\n const result = await runCall(\n \"recordFailure\",\n this.#convex.mutation(\n this.#fns.recordFailure,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n errorCode: input.error.code,\n ...(typeof errorProvider === \"string\" && typeof errorOperation === \"string\"\n ? { errorProvider, errorOperation }\n : {}),\n retryable: input.retryable,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n return result.ok ? parseLifecycle(\"recordFailure\", result.value) : result;\n }\n\n async loadLifecycle(input: {\n readonly orgId: OrgId;\n readonly observationContext?: WireObservationContext;\n }): Promise<CapxulResult<OrgLifecycle>> {\n const result = await runCall<WireLifecycle | null>(\n \"loadLifecycle\",\n this.#convex.query(this.#fns.load, input),\n );\n if (!result.ok) return result;\n if (result.value === null) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle was not found\"));\n }\n return parseLifecycle(\"loadLifecycle\", result.value);\n }\n\n async retry(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const current = await this.loadLifecycle({\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n });\n if (!current.ok) return current;\n if (\n current.value.status === \"failed\" &&\n current.value.retryable &&\n (current.value.at === \"awaitingFounderAuthorization\" ||\n current.value.at === \"submittingBootstrap\")\n ) {\n const reset = resetSignerSession(this.#signer);\n if (!reset.ok) return reset;\n }\n const result = await runCall(\n \"retry\",\n this.#convex.mutation(\n this.#fns.retry,\n copyInvocationObservation(input, {\n orgId: input.orgId,\n ...(input.observationContext === undefined\n ? {}\n : { observationContext: input.observationContext }),\n }),\n ),\n );\n if (!result.ok) return result;\n return parseLifecycle(\"retry\", result.value);\n }\n\n async #lifecycleAction(\n operation: string,\n input: OrganizationSetupStepInput,\n call: () => Effect.Effect<WireLifecycle, unknown>,\n ): Promise<CapxulResult<OrgLifecycle>> {\n const cancelled = cancellation(input.signal);\n if (cancelled !== undefined) return cancelled;\n const result = await runCall(operation, call());\n if (!result.ok) return result;\n const cancelledAfter = cancellation(input.signal);\n if (cancelledAfter !== undefined) return cancelledAfter;\n return parseLifecycle(operation, result.value);\n }\n}\n\nfunction resetSignerSession(signer: CapxulSigner): CapxulResult<void> {\n const resetSession = (signer as CapxulSigner & { readonly resetSession?: unknown }).resetSession;\n if (typeof resetSession !== \"function\") return { ok: true, value: undefined };\n try {\n resetSession.call(signer);\n return { ok: true, value: undefined };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", \"resetSession\", cause, {\n failure_mode: \"unknown\",\n }),\n );\n }\n}\n\nasync function runCall<T>(\n operation: string,\n effect: Effect.Effect<T, unknown>,\n): Promise<CapxulResult<T>> {\n try {\n const result = await Effect.runPromise(Effect.result(effect));\n return Result.isSuccess(result)\n ? { ok: true, value: result.success }\n : fail(publicError(operation, result.failure));\n } catch (cause) {\n return fail(publicError(operation, cause));\n }\n}\n\nfunction publicError(operation: string, cause: unknown): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const carried = (cause as { readonly publicError?: unknown }).publicError;\n if (carried instanceof CapxulError) return carried;\n }\n return Errors.providerError(\"convex-organization\", operation, cause);\n}\n\nasync function signerResult<T>(operation: string, run: () => Promise<T>): Promise<CapxulResult<T>> {\n try {\n return { ok: true, value: await run() };\n } catch (cause) {\n return fail(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"organization-signer\", operation, cause),\n );\n }\n}\n\nfunction validatePreparedAuthorities(\n prepared: PreparedBootstrap,\n signerAddress: string,\n): CapxulResult<void> {\n const signer = signerAddress.toLowerCase();\n const preparedSigner = prepared.signerAddress.toLowerCase();\n const founder = prepared.founderPersonalAccount.toLowerCase();\n const organization = prepared.organizationAccountAddress.toLowerCase();\n const sender = prepared.userOp.sender.toLowerCase();\n if (preparedSigner !== signer) {\n return fail(\n Errors.invalidInput(\"signerAddress\", \"Prepared signer does not match configured signer\"),\n );\n }\n if (founder === signer || organization === signer || organization === founder) {\n return fail(\n Errors.invalidInput(\n \"organizationAuthority\",\n \"Signer EOA, founder Account, and Organization Account must be distinct\",\n ),\n );\n }\n if (sender !== founder) {\n return fail(\n Errors.invalidInput(\"userOp.sender\", \"Bootstrap sender must be the founder Account\"),\n );\n }\n if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) {\n return fail(Errors.invalidInput(\"digest\", \"Prepared bootstrap digest must be 32-byte hex\"));\n }\n return { ok: true, value: undefined };\n}\n\nfunction parseLifecycle(operation: string, wire: WireLifecycle): CapxulResult<OrgLifecycle> {\n const orgId = parseOrgId(operation, wire.orgId);\n if (!orgId.ok) return orgId;\n if (wire.status === \"loading\")\n return { ok: true, value: { status: \"loading\", orgId: orgId.value } };\n if (wire.status === \"ready\") {\n return { ok: true, value: { status: \"ready\", orgId: orgId.value, canTransact: true } };\n }\n if (wire.status === \"failed\") {\n if (!isSetupStep(wire.at))\n return fail(Errors.invalidInput(\"lifecycle.at\", \"Unknown setup step\"));\n return {\n ok: true,\n value: {\n status: \"failed\",\n orgId: orgId.value,\n at: wire.at,\n error: new CapxulError(wire.error.code, wire.error.message),\n retryable: wire.retryable,\n },\n };\n }\n if (!isSetupStep(wire.step)) {\n return fail(Errors.invalidInput(\"lifecycle.step\", `Unknown setup step from ${operation}`));\n }\n return { ok: true, value: { status: \"settingUp\", orgId: orgId.value, step: wire.step } };\n}\n\nfunction parseOrgId(operation: string, value: string): CapxulResult<OrgId> {\n try {\n return { ok: true, value: toOrgId(value) };\n } catch (cause) {\n return fail(Errors.providerError(\"convex-organization\", operation, cause));\n }\n}\n\nfunction isSetupStep(\n value: string,\n): value is Extract<OrgLifecycle, { status: \"settingUp\" }>[\"step\"] {\n return (\n value === \"preparingFounderAccount\" ||\n value === \"awaitingFounderAuthorization\" ||\n value === \"submittingBootstrap\" ||\n value === \"confirmingBootstrap\"\n );\n}\n\nfunction cancellation(signal: AbortSignal | undefined): CapxulResult<never> | undefined {\n return signal?.aborted ? fail(Errors.cancelled({ operation: \"organization.setup\" })) : undefined;\n}\n\nfunction fail<T>(error: CapxulError): CapxulResult<T> {\n return { ok: false, error };\n}\n","import { Effect, Layer } from \"effect\";\n\nimport {\n redactTelemetryProps,\n TelemetryPortTag,\n type TelemetryEvent,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEventName,\n type TelemetryPort,\n type TelemetryProps,\n} from \"../../ports/telemetry\";\n\nexport type PostHogCapture = (\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n) => void | Promise<void>;\nexport type PostHogIdentify = (input: TelemetryIdentifyInput) => void | Promise<void>;\nexport type PostHogGroup = (input: TelemetryGroupInput) => void | Promise<void>;\nexport type PostHogReset = () => void | Promise<void>;\n\nexport type PostHogTelemetryLayerDeps = {\n readonly capture: PostHogCapture;\n readonly identify?: PostHogIdentify;\n readonly group?: PostHogGroup;\n readonly reset?: PostHogReset;\n};\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: PostHogCapture;\n readonly #identify: PostHogIdentify;\n readonly #group: PostHogGroup;\n readonly #reset: PostHogReset;\n\n constructor(deps: PostHogTelemetryLayerDeps) {\n this.#capture = deps.capture;\n this.#identify = deps.identify ?? (() => undefined);\n this.#group = deps.group ?? (() => undefined);\n this.#reset = deps.reset ?? (() => undefined);\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never, never> {\n return this.#run(\n () => this.#capture(event.name, redactTelemetryProps(event.name, cloneProps(event.props))),\n \"emit\",\n event.name,\n );\n }\n\n identify(input: TelemetryIdentifyInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#identify(cloneIdentifyInput(input)), \"identify\");\n }\n\n group(input: TelemetryGroupInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#group(cloneGroupInput(input)), \"group\");\n }\n\n reset(): Effect.Effect<void, never, never> {\n return this.#run(() => this.#reset(), \"reset\");\n }\n\n #run(\n operation: () => void | Promise<void>,\n operationName: \"emit\" | \"identify\" | \"group\" | \"reset\",\n eventName?: TelemetryEventName,\n ): Effect.Effect<void, never> {\n const diagnose = Effect.logWarning(\"product.telemetry.transport.dropped\").pipe(\n Effect.annotateLogs({\n operation: operationName,\n ...(eventName === undefined ? {} : { product_event: eventName }),\n }),\n Effect.catchCause(() => Effect.void),\n );\n return Effect.suspend(() => {\n let pending: void | Promise<void>;\n try {\n pending = operation();\n } catch {\n return diagnose;\n }\n if (pending === undefined) return Effect.void;\n const transport = Effect.tryPromise({\n try: () => pending,\n catch: () => undefined,\n }).pipe(Effect.catch(() => diagnose));\n return Effect.forkDetach(transport, { startImmediately: true }).pipe(Effect.asVoid);\n });\n }\n}\n\nexport function PostHogTelemetryLayer(\n deps: PostHogTelemetryLayerDeps,\n): Layer.Layer<TelemetryPortTag, never, never> {\n return Layer.succeed(TelemetryPortTag, new PostHogTelemetryAdapter(deps));\n}\n\nfunction cloneIdentifyInput(input: TelemetryIdentifyInput): TelemetryIdentifyInput {\n const traits = input.traits === undefined ? undefined : cloneProps(input.traits);\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return {\n distinctId: input.distinctId,\n ...(input.anonDistinctId === undefined ? {} : { anonDistinctId: input.anonDistinctId }),\n ...(traits === undefined ? {} : { traits }),\n ...(properties === undefined ? {} : { properties }),\n };\n}\n\nfunction cloneGroupInput(input: TelemetryGroupInput): TelemetryGroupInput {\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return properties === undefined\n ? { groupType: input.groupType, groupKey: input.groupKey }\n : {\n groupType: input.groupType,\n groupKey: input.groupKey,\n properties,\n };\n}\n\nfunction cloneProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\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","import type { DiagnosticDetail, DiagnosticPort } from \"../../ports/diagnostic\";\n\nconst DEFAULT_ACCOUNT_SETUP_LOG_PREFIX = \"[capxul:account-setup]\";\n\nexport class ConsoleDiagnosticAdapter implements DiagnosticPort {\n private readonly prefix: string;\n\n constructor(prefix: string = DEFAULT_ACCOUNT_SETUP_LOG_PREFIX) {\n this.prefix = prefix;\n }\n\n trace(scope: string, detail: DiagnosticDetail): void {\n globalThis.console?.debug?.(`${this.prefix} ${scope}`, detail);\n }\n}\n\nexport function ConsoleDiagnosticLayer(prefix?: string): DiagnosticPort {\n return new ConsoleDiagnosticAdapter(prefix);\n}\n","import {\n AccountTypeEnum,\n ChainTypeEnum,\n EmbeddedState,\n Openfort,\n RecoveryMethod,\n ThirdPartyOAuthProvider,\n} from \"@openfort/openfort-js\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\n\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { DiagnosticPort } from \"../ports/diagnostic\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport type { CapxulSigner } from \"../signer\";\nimport { openfortEmbeddedSignerFromWallet } from \"../openfort-embedded-signer\";\n\nexport interface OpenfortBrowserSigner extends CapxulSigner {\n readonly resetSession: () => void;\n}\n\nfunction openfortProviderError(operation: string, cause: unknown): CapxulError {\n return cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", operation, cause, { failure_mode: \"unknown\" });\n}\n\nexport interface OpenfortBrowserSignerOptions {\n readonly diagnostic?: DiagnosticPort;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * True when the browser cannot perform Web Crypto — sandboxed iframes, headless\n * agent browsers, or non-HTTPS origins. OpenFort's embedded-wallet `configure`\n * silently produces no address in this state, so we detect it up front and name\n * it `no-secure-context` instead of letting it decay into `unknown`.\n */\nfunction isInsecureBrowserContext(): boolean {\n return globalThis.isSecureContext === false || globalThis.crypto?.subtle === undefined;\n}\n\n/** Openfort SDK storage keys (`@openfort/openfort-js` StorageKeys). */\nconst OPENFORT_BROWSER_STORAGE_KEYS = [\n \"openfort.authentication\",\n \"openfort.account\",\n \"openfort.session\",\n \"openfort.configuration\",\n] as const;\n\n/**\n * Matches `@openfort/openfort-js` ScopedStorage.createScope — chars 8–15 of the\n * publishable key, prefixed onto each StorageKeys entry in localStorage.\n */\nexport function openfortBrowserStorageScope(publishableKey: string): string | undefined {\n const trimmed = publishableKey.trim();\n if (trimmed.length < 16) {\n return undefined;\n }\n return trimmed.substring(8, 16);\n}\n\n/**\n * Drop cached Openfort auth/account state so third-party login re-runs for the\n * current Better Auth session. The SDK skips `authenticateThirdParty` when a\n * stale `userId` is already in storage, which yields 401 on `v2/accounts`.\n */\nfunction clearStaleOpenfortBrowserStorage(publishableKey: string): void {\n if (typeof localStorage === \"undefined\") {\n return;\n }\n const scope = openfortBrowserStorageScope(publishableKey);\n if (scope === undefined) {\n return;\n }\n for (const key of OPENFORT_BROWSER_STORAGE_KEYS) {\n localStorage.removeItem(`${scope}.${key}`);\n }\n}\n\nexport function createOpenfortBrowserSignerFromBootstrap(\n bootstrap: BootstrapResolution,\n options: OpenfortBrowserSignerOptions = {},\n): OpenfortBrowserSigner {\n const diagnostic = options.diagnostic;\n const telemetry = options.telemetry;\n const authBaseUrl = normalizeBetterAuthBaseUrl(bootstrap.authBaseUrl);\n\n /**\n * Closes the black hole: when the browser has no Web Crypto, OpenFort's\n * `configure` would resolve to no address and the failure would be reported\n * as `unknown`. Detect it before any network/wallet work, tag it\n * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`, breadcrumb\n * it via DiagnosticPort, and self-report via TelemetryPort.\n */\n function failNoSecureContext(): never {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"no-secure-context\",\n });\n const error = Errors.providerError(\n \"openfort\",\n \"configure\",\n new Error(\"Web Crypto unavailable: browser is not a secure context\"),\n { failure_mode: \"no-secure-context\" },\n );\n if (telemetry) {\n captureExceptionSync(telemetry, error, {\n layer: \"openfort\",\n operation: \"configure\",\n provider: \"openfort\",\n failure_mode: \"no-secure-context\",\n });\n }\n throw error;\n }\n\n function betterAuthSessionUrl(): string {\n return `${authBaseUrl}/get-session`;\n }\n\n function encryptionSessionUrl(): string {\n return `${authBaseUrl}/encryption-session`;\n }\n\n async function fetchBetterAuthAccessToken(): Promise<string | null> {\n try {\n const response = await fetch(betterAuthSessionUrl(), { credentials: \"include\" });\n if (!response.ok) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n httpStatus: response.status,\n failure_mode: \"unknown\",\n });\n return null;\n }\n const body = (await response.json()) as { session?: { token?: string } };\n const token = body.session?.token?.trim();\n if (token === undefined || token.length === 0) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n return null;\n }\n diagnostic?.trace(\"openfort.token\", { ok: true, tokenPresent: true });\n return token;\n } catch (cause) {\n diagnostic?.trace(\"openfort.token\", {\n ok: false,\n tokenPresent: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"token\", cause);\n }\n }\n\n const openfort = new Openfort({\n baseConfiguration: {\n publishableKey: bootstrap.openfortPublishableKey,\n },\n shieldConfiguration: {\n shieldPublishableKey: bootstrap.shieldPublishableKey,\n },\n thirdPartyAuth: {\n provider: ThirdPartyOAuthProvider.BETTER_AUTH,\n getAccessToken: fetchBetterAuthAccessToken,\n },\n });\n\n let walletReadyPromise: Promise<void> | null = null;\n\n function startWalletReady(): Promise<void> {\n return (async () => {\n if (isInsecureBrowserContext()) {\n failNoSecureContext();\n }\n await openfort.waitForInitialization();\n\n const accessToken = await fetchBetterAuthAccessToken();\n if (accessToken === null) {\n throw openfortProviderError(\n \"token\",\n new Error(\"Better Auth access token unavailable for Openfort\"),\n );\n }\n\n let encryptionResponse: Response;\n try {\n encryptionResponse = await fetch(encryptionSessionUrl(), {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n });\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n if (!encryptionResponse.ok) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw Errors.providerError(\n \"openfort\",\n \"encryptionSession\",\n new Error(`Openfort encryption session failed (${encryptionResponse.status})`),\n { failure_mode: \"unknown\" },\n );\n }\n let encryptionBody: { sessionId?: string };\n try {\n encryptionBody = (await encryptionResponse.json()) as { sessionId?: string };\n if (typeof encryptionBody.sessionId !== \"string\" || encryptionBody.sessionId.length === 0) {\n throw new Error(\"Openfort encryption session response missing sessionId\");\n }\n } catch (cause) {\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: false,\n httpStatus: encryptionResponse.status,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"encryptionSession\", cause);\n }\n diagnostic?.trace(\"openfort.encryptionSession\", {\n ok: true,\n httpStatus: encryptionResponse.status,\n });\n\n let embeddedState: EmbeddedState;\n try {\n embeddedState = await openfort.embeddedWallet.getEmbeddedState();\n diagnostic?.trace(\"openfort.embeddedState\", { state: embeddedState });\n } catch (cause) {\n diagnostic?.trace(\"openfort.embeddedState\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"embeddedState\", cause);\n }\n if (embeddedState !== EmbeddedState.READY) {\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n diagnostic?.trace(\"openfort.storageCleared\", { beforeConfigure: true });\n try {\n await openfort.embeddedWallet.configure({\n accountType: AccountTypeEnum.EOA,\n chainType: ChainTypeEnum.EVM,\n recoveryParams: {\n recoveryMethod: RecoveryMethod.AUTOMATIC,\n encryptionSession: encryptionBody.sessionId,\n },\n });\n diagnostic?.trace(\"openfort.configure\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.configure\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"configure\", cause);\n }\n }\n\n try {\n await openfort.embeddedWallet.get();\n diagnostic?.trace(\"openfort.get\", { ok: true });\n } catch (cause) {\n diagnostic?.trace(\"openfort.get\", {\n ok: false,\n failure_mode: \"unknown\",\n });\n throw openfortProviderError(\"get\", cause);\n }\n })();\n }\n\n async function ensureOpenfortWalletReady(): Promise<void> {\n walletReadyPromise ??= startWalletReady();\n try {\n await walletReadyPromise;\n } catch (cause) {\n walletReadyPromise = null;\n throw cause;\n }\n }\n\n const signer = openfortEmbeddedSignerFromWallet({\n embeddedWallet: openfort.embeddedWallet,\n ensureWalletReady: ensureOpenfortWalletReady,\n });\n\n return {\n ...signer,\n getAddress: async () => {\n try {\n const address = await signer.getAddress();\n diagnostic?.trace(\"openfort.address\", { ok: true });\n return address;\n } catch (cause) {\n diagnostic?.trace(\"openfort.address\", { ok: false, failure_mode: \"unknown\" });\n throw openfortProviderError(\"getAddress\", cause);\n }\n },\n resetSession: () => {\n walletReadyPromise = null;\n clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);\n signer.resetAddressCache();\n },\n };\n}\n\nfunction normalizeBetterAuthBaseUrl(raw: string): string {\n const trimmed = raw.replace(/\\/$/, \"\");\n return trimmed.endsWith(\"/api/auth\") ? trimmed : `${trimmed}/api/auth`;\n}\n","import { EXPECTED_OPERATION_OUTCOMES, isCapxulError, type CapxulErrorCode } from \"@capxul/errors\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport {\n hasFailureInvocationSnapshot,\n markFailureInvocationSnapshot,\n} from \"./internal/invocation-observation\";\nimport { EXCEPTION_MESSAGE } from \"./telemetry/capture-exception\";\n\n/** Host-owned correlation fields that are safe to attach to an SDK failure. */\nexport interface ObservationContext extends Omit<WireObservationContext, \"applicationId\"> {}\n\n/**\n * The small, SDK-owned failure envelope delivered to observation adapters.\n * Method arguments, response bodies, wallet payloads, and arbitrary error\n * details are deliberately absent.\n */\nexport interface SdkFailureObservation {\n readonly exception: Error;\n readonly sdkVersion: string;\n readonly operation: string;\n readonly errorKind: string;\n /** Invocation snapshot; failure correlation wins over later host state. */\n readonly context?: ObservationContext;\n}\n\nexport type ObservationDelivery = void | PromiseLike<void>;\n\n/**\n * High-level host observation boundary. The SDK owns when each method is\n * called; the host owns the destination client, consent, and delivery policy.\n */\nexport interface ObservationAdapter {\n /**\n * Optional read-only invocation context. Transport adapters snapshot it once\n * at call start; implementations must not mutate global SDK state.\n */\n readonly resolveContext?: () => ObservationContext | undefined;\n /** A method returned the SDK's typed `{ ok: false, error }` result. */\n captureOperationFailure(failure: SdkFailureObservation): ObservationDelivery;\n /** A method unexpectedly threw or rejected instead of returning a typed result. */\n captureException(exception: SdkFailureObservation): ObservationDelivery;\n}\n\n/** The host-owned PostHog capabilities consumed by the supported adapter. */\nexport interface PostHogObservationClient {\n capture(event: string, properties?: Readonly<Record<string, unknown>>): unknown;\n /** Optional host capability; the supported adapter uses ordinary capture for slim clients. */\n captureException?(exception: Error, properties?: Readonly<Record<string, unknown>>): unknown;\n}\n\nexport interface PostHogObservationOptions {\n /** Consent / kill-switch seam. Defaults to enabled. */\n readonly enabled?: boolean | (() => boolean);\n /** Snapshotted at invocation start and resolved again for direct adapter capture. */\n readonly context?: ObservationContext | (() => ObservationContext | undefined);\n}\n\nconst SDK_VERSION = sdkPackageJson.version;\n\n/** Stable PostHog event used for typed failures that are expected product outcomes. */\nexport const CAPXUL_SDK_EXPECTED_OUTCOME_EVENT = \"capxul_sdk_expected_outcome\";\n\n/**\n * Adapt the host's already-initialized PostHog-like client. This function does\n * not import, initialize, configure, or own PostHog.\n */\nexport function fromPostHog(\n client: PostHogObservationClient | null | undefined,\n options: PostHogObservationOptions = {},\n): ObservationAdapter {\n const prepare = (\n failure: SdkFailureObservation,\n ): readonly [SdkFailureObservation, Readonly<Record<string, unknown>>] | undefined => {\n if (!isEnabled(options.enabled)) return;\n if (client === null || client === undefined) return;\n\n const safeFailure = sanitizeFailureObservation(failure);\n const directContext = hasFailureInvocationSnapshot(failure)\n ? undefined\n : resolveContext(options.context);\n const properties = postHogProperties(safeFailure, directContext);\n return [safeFailure, properties];\n };\n\n const captureOperationFailure = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || client === null || client === undefined) return;\n const [safeFailure, properties] = prepared;\n\n if (classifyOperationOutcome(safeFailure.errorKind) === \"expected\") {\n if (typeof client.capture !== \"function\") return;\n deliver(() =>\n client.capture(CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, {\n ...properties,\n outcome_class: \"expected\",\n }),\n );\n return;\n }\n\n deliver(() =>\n client.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n const captureException = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || client === null || client === undefined) return;\n const [safeFailure, properties] = prepared;\n deliver(() =>\n client.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n return {\n resolveContext: () => {\n if (!isEnabled(options.enabled) || client === null || client === undefined) return undefined;\n // Raw call-start snapshot: each consumer sanitizes at its own emission\n // boundary, so the pure sanitize is kept off the SDK success path.\n return resolveRawContext(options.context) ?? {};\n },\n captureOperationFailure,\n captureException,\n };\n}\n\nfunction classifyOperationOutcome(kind: string): \"expected\" | \"unexpected\" {\n return EXPECTED_OPERATION_OUTCOMES.has(kind as CapxulErrorCode) ? \"expected\" : \"unexpected\";\n}\n\nfunction deliver(capture: () => unknown): void {\n try {\n const delivery = capture();\n ignoreDeliveryFailure(delivery);\n } catch {\n // Observation is best effort and can never become an SDK failure.\n }\n}\n\n/**\n * Fan one SDK failure out to several adapters (issue #877). The SDK's own\n * first-party relay and an optional host-provided adapter both observe the same\n * failure. Order matters for `resolveContext`: the FIRST adapter that returns a\n * context wins, so pass the host adapter first to keep its call-start snapshot.\n * Each capture is isolated — a throwing adapter never blocks its peers or the\n * SDK. Returns `undefined` when no adapters are present (zero observation work).\n */\nexport function composeObservationAdapters(\n ...adapters: readonly (ObservationAdapter | undefined)[]\n): ObservationAdapter | undefined {\n const present = adapters.filter(\n (adapter): adapter is ObservationAdapter => adapter !== undefined,\n );\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n\n const fanOut = (select: (adapter: ObservationAdapter) => ObservationDelivery): void => {\n for (const adapter of present) {\n try {\n ignoreDeliveryFailure(select(adapter));\n } catch {\n // One adapter's defect is isolated from its peers and the SDK.\n }\n }\n };\n\n return {\n resolveContext: () => {\n for (const adapter of present) {\n try {\n const context = adapter.resolveContext?.();\n if (context !== undefined) return context;\n } catch {\n // Fall through to the next adapter's snapshot.\n }\n }\n return undefined;\n },\n captureOperationFailure: (failure) =>\n fanOut((adapter) => adapter.captureOperationFailure(failure)),\n captureException: (failure) => fanOut((adapter) => adapter.captureException(failure)),\n };\n}\n\n/** @internal Reports a factory-level typed failure without changing its identity. */\nexport function observeFailedResult<T extends { readonly ok: boolean }>(\n result: T,\n adapter: ObservationAdapter | undefined,\n operation: string,\n): T {\n if (adapter !== undefined && isFailedResult(result)) {\n report(adapter, \"operation\", operation, result.error, resolveAdapterContext(adapter));\n }\n return result;\n}\n\nfunction report(\n adapter: ObservationAdapter,\n kind: \"operation\" | \"exception\",\n operation: string,\n cause: unknown,\n invocationContext?: ObservationContext,\n): void {\n const operationName = normalizeOperation(operation);\n const kindName = normalizeErrorKind(errorKind(cause));\n const context = sanitizeObservationContext({\n ...invocationContext,\n ...(isCapxulError(cause) && cause.correlationId !== undefined\n ? { correlationId: cause.correlationId }\n : {}),\n }) as ObservationContext | undefined;\n const failure = markFailureInvocationSnapshot<SdkFailureObservation>({\n exception: syntheticException(operationName, kindName),\n sdkVersion: SDK_VERSION,\n operation: operationName,\n errorKind: kindName,\n ...(context === undefined ? {} : { context }),\n });\n\n try {\n const delivery =\n kind === \"operation\"\n ? adapter.captureOperationFailure(failure)\n : adapter.captureException(failure);\n ignoreDeliveryFailure(delivery);\n } catch {\n // Adapter failures are isolated from SDK return values and control flow.\n }\n}\n\nfunction resolveAdapterContext(adapter: ObservationAdapter): ObservationContext | undefined {\n // The adapter snapshot is the raw call-start context. Sanitize is deferred to\n // failure time in `report` and to each transport's own emission boundary, so\n // a successful call pays no per-call sanitize cost.\n try {\n return adapter.resolveContext?.();\n } catch {\n return undefined;\n }\n}\n\nfunction ignoreDeliveryFailure(delivery: unknown): void {\n if (!isPromiseLike(delivery)) return;\n try {\n void Promise.resolve(delivery).catch(() => undefined);\n } catch {\n // A malformed thenable is an adapter defect, not an SDK failure.\n }\n}\n\n/**\n * Map an ALREADY-sanitized observation context to the snake_case PostHog\n * property keys. Shared by the failure boundary here and the host\n * success-telemetry seam (`telemetry/from-posthog.ts`) so both attach identical\n * correlation fields from one definition.\n */\nexport function observationContextProps(\n context: WireObservationContext | undefined,\n): Record<string, string> {\n const props: Record<string, string> = {};\n if (context?.application !== undefined) props.application = context.application;\n if (context?.release !== undefined) props.release = context.release;\n if (context?.sessionId !== undefined) props.session_id = context.sessionId;\n if (context?.organizationId !== undefined) props.organization_id = context.organizationId;\n if (context?.journeyId !== undefined) props.journey_id = context.journeyId;\n if (context?.correlationId !== undefined) props.correlation_id = context.correlationId;\n if (context?.anonymousId !== undefined) props.anonymous_id = context.anonymousId;\n return props;\n}\n\nfunction postHogProperties(\n failure: SdkFailureObservation,\n context: ObservationContext | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = sanitizeObservationContext({ ...context, ...failure.context });\n return {\n sdk_version: failure.sdkVersion,\n operation: failure.operation,\n error_kind: failure.errorKind,\n handled: true,\n ...observationContextProps(merged),\n };\n}\n\nfunction postHogExceptionProperties(\n failure: SdkFailureObservation,\n properties: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> {\n const filename = `capxul-sdk-observation://boundary/${failure.operation}`;\n return {\n ...properties,\n $exception_type: failure.errorKind,\n $exception_message: EXCEPTION_MESSAGE,\n $exception_level: \"error\",\n $exception_list: [\n {\n type: failure.errorKind,\n value: EXCEPTION_MESSAGE,\n mechanism: { type: \"capxul_sdk_boundary\", handled: true, synthetic: true },\n stacktrace: {\n type: \"raw\",\n frames: [\n {\n platform: \"javascript\",\n filename,\n function: `CapxulSdkBoundary.${failure.operation}`,\n lineno: 1,\n colno: 1,\n in_app: true,\n },\n ],\n },\n },\n ],\n };\n}\n\nfunction resolveContext(\n context: PostHogObservationOptions[\"context\"],\n): ObservationContext | undefined {\n return sanitizeObservationContext(resolveRawContext(context)) as ObservationContext | undefined;\n}\n\n/** Resolve the host context closure without sanitizing — the call-start snapshot. */\nfunction resolveRawContext(\n context: PostHogObservationOptions[\"context\"],\n): ObservationContext | undefined {\n try {\n return (typeof context === \"function\" ? context() : context) as ObservationContext | undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isEnabled(enabled: PostHogObservationOptions[\"enabled\"]): boolean {\n try {\n return typeof enabled === \"function\" ? enabled() : (enabled ?? true);\n } catch {\n return false;\n }\n}\n\nfunction errorKind(cause: unknown): string {\n try {\n if (isCapxulError(cause)) return normalizeErrorKind(cause.code);\n if (cause instanceof Error) return normalizeErrorKind(cause.name);\n return \"UnknownFailure\";\n } catch {\n return \"Error\";\n }\n}\n\nfunction sanitizeFailureObservation(failure: SdkFailureObservation): SdkFailureObservation {\n const operation = normalizeOperation(failure.operation);\n const kind = normalizeErrorKind(failure.errorKind);\n const context = sanitizeObservationContext(failure.context) as ObservationContext | undefined;\n return {\n exception: syntheticException(operation, kind),\n sdkVersion: normalizeSdkVersion(failure.sdkVersion),\n operation,\n errorKind: kind,\n ...(context === undefined ? {} : { context }),\n };\n}\n\nfunction normalizeSdkVersion(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeOperation(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,255}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeErrorKind(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(value)\n ? value\n : \"Error\";\n}\n\nfunction syntheticException(operation: string, kind: string): Error {\n const error = new Error(EXCEPTION_MESSAGE);\n error.name = kind;\n error.stack =\n `${kind}: ${error.message}\\n` +\n ` at CapxulSdkBoundary.${operation} ` +\n `(capxul-sdk-observation://boundary/${operation}:1:1)`;\n return error;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === \"function\"\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isCapxulResult(\n value: unknown,\n): value is\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; error: unknown } {\n return isPlainObject(value) && typeof value.ok === \"boolean\";\n}\n\nfunction isFailedResult(value: unknown): value is { readonly ok: false; readonly error: unknown } {\n return isCapxulResult(value) && value.ok === false && \"error\" in value;\n}\n","import { Context, Effect, Result, Exit, Layer, Scope } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toAllowedOrigin, toPublishableKey, type ChainId } from \"@capxul/types\";\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport {\n makeEngineeringTelemetryLayer,\n type EngineeringTelemetryConfig,\n} from \"@capxul/observability/engineering\";\n\nimport { BetterAuthBrowserLayer, BetterAuthNodeLayer } from \"./adapters/auth-client\";\nimport { HttpBootstrapLayer } from \"./adapters/bootstrap\";\nimport { SystemClockLayer } from \"./adapters/clock\";\nimport { ConvexCallLayer, type ConvexClientShape } from \"./adapters/convex-call\";\nimport { ConvexIdentityLayer } from \"./adapters/identity\";\nimport { ConvexAccountLayer } from \"./adapters/account-read\";\nimport { ConvexSubAccountLayer } from \"./adapters/sub-account/ConvexSubAccountAdapter\";\nimport { ConvexSmartAccountLayer } from \"./adapters/smart-account\";\nimport { ConvexOrganizationAdapter } from \"./adapters/org/ConvexOrganizationAdapter\";\nimport { ConvexOrganizationSetupAdapter } from \"./adapters/org/ConvexOrganizationSetupAdapter\";\nimport { PostHogTelemetryLayer } from \"./adapters/telemetry\";\nimport { ConsoleDiagnosticAdapter } from \"./adapters/diagnostic/ConsoleDiagnosticAdapter\";\nimport { assertDevKeySignerIsTestnetOnly } from \"./dev-signer\";\nimport type { AccountRequirement } from \"./surface/account-providers\";\nimport {\n createOpenfortBrowserSignerFromBootstrap,\n type OpenfortBrowserSigner,\n} from \"./openfort/create-openfort-browser-signer\";\nimport type { CapxulSigner } from \"./signer\";\nimport { assembleCapxulClient, type CapxulClient } from \"./surface/create-capxul-client\";\nimport { detectAuthCacheAdapter } from \"./surface/factory\";\nimport type { CapxulResult } from \"./surface/types\";\nimport { observeFailedResult, type ObservationAdapter } from \"./observation\";\nimport type { FlowPorts } from \"./flows/types\";\nimport { AuthClientPortTag, type AuthClientPort } from \"./ports/auth-client\";\nimport { AuthCachePortTag, type AuthCachePort } from \"./ports/auth-cache\";\nimport { BootstrapPortTag, type BootstrapPort, type BootstrapResolution } from \"./ports/bootstrap\";\nimport { ClockPortTag } from \"./ports/clock\";\nimport { ConvexCallPortTag, type ConvexCallPort } from \"./ports/convex-call\";\nimport { IdentityPortTag } from \"./ports/identity\";\nimport { OrgPortTag, type OrgPort } from \"./ports/org\";\nimport { AccountReadPortTag } from \"./ports/account-read\";\nimport { SubAccountPortTag } from \"./ports/sub-account\";\nimport { SmartAccountPortTag } from \"./ports/smart-account\";\nimport type { TelemetryEvent, TelemetryPort } from \"./ports/telemetry\";\nimport { TelemetryPortTag } from \"./ports/telemetry\";\n\nexport type ProductionRuntime = \"browser\" | \"node\";\nexport type ProductionAdapterClose = () => Promise<void>;\n\n/**\n * Interim default Capxul bootstrap host (SDK publish readiness · I3). Node\n * consumers pass neither `origin` nor `bootstrapBaseUrl`; both default here so\n * `createCapxulClient({ publishableKey })` reaches the Capxul backend with no\n * extra wiring. Superseded by the key-encoded host (`cap_pk_live_…`, out of\n * scope this milestone). See `packages/sdk/CONTEXT.md`.\n */\nexport const DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL = \"https://api.capxul.com\";\n\n/** Default per-request auth invocation timeout (ms) when the consumer omits it. */\nexport const DEFAULT_INVOKE_TIMEOUT_MS = 30_000;\n\n/**\n * Consumer-facing `createCapxulClient` input (SDK DX public surface · #326).\n * The publishable key is the primary input; bootstrap host, invoke timeout,\n * runtime detection, and auth-cache selection are SDK-owned defaults.\n */\nexport interface CapxulClientInput {\n readonly publishableKey: string;\n /**\n * Optional high-level observation adapter. The host supplies an adapter\n * around its existing analytics client; Capxul never initializes or bundles\n * another vendor SDK. Omit this property for zero observation work.\n */\n readonly observation?: ObservationAdapter;\n /**\n * Optional host success-telemetry sink. Build it from your posthog-js client\n * with `telemetryFromPostHog(posthog, …)`; events from SDK producers wired to\n * this port then reach the host's PostHog person after the host calls\n * `identify()`. Capxul never initializes or bundles a vendor SDK. Omit for no\n * host telemetry.\n */\n readonly telemetry?: TelemetryPort;\n /**\n * Optional engineering OTLP sink. The SDK supplies producer and version;\n * the host supplies its environment, PostHog host, and receipt-safe headers.\n */\n readonly engineeringTelemetry?: Omit<EngineeringTelemetryConfig, \"producer\" | \"sdkVersion\">;\n /**\n * Init-time account readiness target (issue #159 · AC4). Threaded into\n * `assembleCapxulClient` so `client.account.{getStatus,ensureReady}` reflect\n * the consumer's chosen requirement. Optional — defaults to `\"none\"` (SDK\n * publish readiness · I3) so `createCapxulClient({ publishableKey })` works\n * with no account lane.\n */\n readonly requirement?: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n}\n\n/**\n * Internal production adapter input for `@capxul/sdk/production` and hermetic\n * tests. Extends the consumer contract with bootstrap/fetch/runtime/auth-cache/\n * signal/timeout seams that must not appear on the bare `@capxul/sdk` barrel.\n * Org deployment port factories and deploy config live on\n * `@capxul/sdk/testing/org-deployment-client` (#327).\n */\nexport interface ProductionAdapterInput extends CapxulClientInput {\n readonly origin?: string;\n readonly bootstrapBaseUrl?: string;\n /** Optional BetterAuth host override (dogfood Vite proxy → same-origin `/api/auth`). */\n readonly authBaseUrl?: string;\n readonly runtime?: ProductionRuntime;\n readonly authCache?: AuthCachePort;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n}\n\n/**\n * @internal Test-injection seam. `convexClientFactory` is intentionally NOT a\n * member of the public `ProductionAdapterInput` (production-surface-policy.md):\n * consumers must not inject a Convex client. Hermetic tests pass a fake through\n * the fixture; it is read back here.\n */\ninterface ProductionConvexClientFactorySeam {\n readonly convexClientFactory?: (convexUrl: string) => ConvexClientShape;\n}\n\nexport interface ProductionAdapters {\n /**\n * THE RUNTIME (A2-Q1A, blueprint §2: \"the graph is the runtime, never\n * flattened to a record\"). This is the built Layer graph, alive in the same\n * `Scope` as `close`. Anything that needs a port resolves it from here.\n *\n * `ports` below is a PROJECTION of this context for the method bundles,\n * which still take ports as plain values — that is the shape L1 replaces\n * when it rebuilds the flows. Until then the projection is a convenience\n * VIEW of the graph, not a replacement for it: before the re-cut the graph\n * was discarded the moment the record was made, so nothing downstream could\n * resolve a tag, run an Effect against the real wiring, or add a port\n * without widening a hand-written record.\n */\n readonly context: Context.Context<ProductionFlowPortTags>;\n readonly ports: FlowPorts;\n readonly bootstrap: BootstrapResolution;\n readonly close: ProductionAdapterClose;\n}\n\nexport type ProductionAdapterLayerName =\n | \"bootstrap\"\n | \"authClient\"\n | \"authCache\"\n | \"identity\"\n | \"smartAccount\"\n | \"accountRead\"\n | \"subAccount\"\n | \"clock\"\n | \"telemetry\"\n | \"convexCall\"\n | \"org\";\n\nexport type ProductionFlowPortTags =\n | AuthClientPortTag\n | AuthCachePortTag\n | BootstrapPortTag\n | ClockPortTag\n | ConvexCallPortTag\n | IdentityPortTag\n | SmartAccountPortTag\n | AccountReadPortTag\n | SubAccountPortTag\n | TelemetryPortTag\n | OrgPortTag;\n\ntype RefreshConvexAuthRef = {\n current: (() => void) | null;\n pending: boolean;\n};\n\n/**\n * The embedded signer's session-reset callback, resolved after the graph is\n * built (the browser signer is derived from the bootstrap the graph itself\n * needs). Same late-binding idiom as `RefreshConvexAuthRef` above — the auth\n * layer closes over the ref and reads `current` at call time.\n */\ntype ResetSignerSessionRef = {\n current: (() => void) | null;\n};\n\nconst SDK_VERSION = sdkPackageJson.version;\n\ntype ProductionAdapterLayerOutput<N extends ProductionAdapterLayerName> = {\n readonly bootstrap: BootstrapPortTag;\n readonly authClient: AuthClientPortTag;\n readonly authCache: AuthCachePortTag;\n readonly identity: IdentityPortTag;\n readonly smartAccount: SmartAccountPortTag;\n readonly accountRead: AccountReadPortTag;\n readonly subAccount: SubAccountPortTag;\n readonly clock: ClockPortTag;\n readonly telemetry: TelemetryPortTag;\n readonly convexCall: ConvexCallPortTag;\n readonly org: OrgPortTag;\n}[N];\n\nexport interface ProductionRuntimeUrls {\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n}\n\nexport interface ProductionAdapterLayerInput {\n readonly bootstrap: BootstrapPort;\n readonly runtime: ProductionRuntime;\n readonly origin?: string;\n readonly runtimeUrls: ProductionRuntimeUrls;\n /**\n * Bootstrap-resolved chain. The `ConvexSubAccountAdapter`'s `transfer`\n * action reads the Safe's live `balanceOf` on this chain (canon §2/§5);\n * the consumer-facing `transfer({ from, to, amount })` carries no chainId\n * (public-surface no-consumer-chainId rule), so the adapter closes over it.\n */\n readonly chainId: ChainId;\n readonly authCache?: AuthCachePort;\n readonly telemetry?: TelemetryPort;\n readonly convexClient?: ConvexClientShape;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n /** Bootstrap-verified hint; the backend independently verifies it again. */\n readonly applicationId?: string;\n readonly observation?: ObservationAdapter;\n /**\n * Late-bound signer session reset (see `ResetSignerSessionRef`). Present when\n * the composition root intends to attach an embedded signer; the auth layer\n * wraps `signOut` with it whether or not `current` is ever filled in.\n */\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\nexport type ProductionAdapterLayerEntry<\n N extends ProductionAdapterLayerName = ProductionAdapterLayerName,\n> = {\n readonly [K in N]: {\n readonly name: K;\n readonly layer: Layer.Layer<ProductionAdapterLayerOutput<K>, unknown, unknown>;\n };\n}[N];\n\n/**\n * Project the built graph into the flat `FlowPorts` record the method bundles\n * still take. It is a VIEW of `ProductionAdapters.context`, taken from the\n * graph and never instead of it — the graph stays alive in the scope and is\n * handed to every caller.\n */\nexport const collectProductionFlowPorts: Effect.Effect<FlowPorts, never, ProductionFlowPortTags> =\n Effect.gen(function* () {\n const authClient = yield* AuthClientPortTag;\n const authCache = yield* AuthCachePortTag;\n const bootstrap = yield* BootstrapPortTag;\n const clock = yield* ClockPortTag;\n const convexCall = yield* ConvexCallPortTag;\n const identity = yield* IdentityPortTag;\n const smartAccount = yield* SmartAccountPortTag;\n const accountRead = yield* AccountReadPortTag;\n const subAccount = yield* SubAccountPortTag;\n const telemetry = yield* TelemetryPortTag;\n return {\n authClient,\n authCache,\n identity,\n smartAccount,\n accountRead,\n subAccount,\n bootstrap,\n clock,\n telemetry,\n convexCall,\n };\n });\n\nexport function makeProductionAdapterLayerEntries(\n input: ProductionAdapterLayerInput,\n): readonly ProductionAdapterLayerEntry[] {\n const refreshConvexAuthRef: RefreshConvexAuthRef = { current: null, pending: false };\n return [\n {\n name: \"bootstrap\",\n layer: productionBootstrapPortLayer(input.bootstrap),\n },\n {\n name: \"authClient\",\n layer: productionAuthClientLayer(input, refreshConvexAuthRef, input.resetSignerSession),\n },\n {\n name: \"authCache\",\n layer: productionAuthCacheLayer(input),\n },\n {\n name: \"identity\",\n layer: ConvexIdentityLayer(),\n },\n {\n name: \"smartAccount\",\n layer: ConvexSmartAccountLayer(),\n },\n {\n name: \"accountRead\",\n layer: ConvexAccountLayer(),\n },\n {\n name: \"subAccount\",\n layer: ConvexSubAccountLayer(input.chainId),\n },\n {\n name: \"clock\",\n layer: SystemClockLayer(),\n },\n {\n name: \"telemetry\",\n layer:\n input.telemetry === undefined\n ? PostHogTelemetryLayer({ capture: () => undefined })\n : Layer.succeed(TelemetryPortTag, input.telemetry),\n },\n {\n name: \"convexCall\",\n layer: productionConvexCallLayer(input, refreshConvexAuthRef),\n },\n {\n // The org port used to be constructed by hand at the composition root\n // (`new ConvexOrganizationAdapter({ convex: ports.convexCall })`), which\n // is why `OrgPortTag` sat in `.fallowrc.json`'s ignore-list with zero\n // resolvers. It is a Convex-backed port like the four below it, so it\n // belongs IN the graph.\n name: \"org\",\n layer: Layer.effect(\n OrgPortTag,\n Effect.map(\n ConvexCallPortTag,\n (convex) => new ConvexOrganizationAdapter({ convex }) as OrgPort,\n ),\n ),\n },\n ];\n}\n\nexport function mergeProductionAdapterLayers(\n entries: readonly ProductionAdapterLayerEntry[],\n): Layer.Layer<ProductionFlowPortTags, unknown, never> {\n const byName = new Map<ProductionAdapterLayerName, Layer.Layer<never, unknown, unknown>>();\n for (const entry of entries) {\n byName.set(entry.name, entry.layer as Layer.Layer<never, unknown, unknown>);\n }\n const authClientLayer = byName.get(\"authClient\");\n const convexCallLayer = byName.get(\"convexCall\");\n // Phase 1: authClient -> convexCall. The auth wrapper reads\n // RefreshConvexAuthRef at call time, after this convex layer registers\n // the concrete refreshAuth callback during construction.\n const convexCallReadyLayer =\n convexCallLayer === undefined || authClientLayer === undefined\n ? convexCallLayer\n : convexCallLayer.pipe(Layer.provide(authClientLayer));\n\n const readyLayers = entries.map((entry) => {\n const layer = byName.get(entry.name) ?? (entry.layer as Layer.Layer<never, unknown, unknown>);\n if (entry.name === \"convexCall\") return convexCallReadyLayer ?? layer;\n if (isConvexDependentLayer(entry.name)) {\n // Phase 2: convexCallReady -> Convex-backed domain ports.\n return convexCallReadyLayer === undefined\n ? layer\n : layer.pipe(Layer.provide(convexCallReadyLayer));\n }\n return layer;\n });\n\n const merged = readyLayers.reduce((current, layer) => Layer.merge(current, layer), Layer.empty);\n // Entries are heterogeneous Layers stored behind one contract; the cast is\n // localized here, while production-layers.test.ts proves omissions fail\n // startup instead of silently assembling a partial FlowPorts graph.\n return merged as Layer.Layer<ProductionFlowPortTags, unknown, never>;\n}\n\nfunction isConvexDependentLayer(name: ProductionAdapterLayerName): boolean {\n return (\n name === \"identity\" ||\n name === \"smartAccount\" ||\n name === \"accountRead\" ||\n name === \"subAccount\" ||\n name === \"org\"\n );\n}\n\nfunction productionBootstrapPortLayer(\n bootstrap: BootstrapPort,\n): Layer.Layer<BootstrapPortTag, never, never> {\n return Layer.succeed(BootstrapPortTag, bootstrap);\n}\n\nfunction productionAuthClientLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n resetSignerSessionRef: ResetSignerSessionRef | undefined,\n): Layer.Layer<AuthClientPortTag, never, never> {\n const baseLayer =\n input.runtime === \"browser\"\n ? BetterAuthBrowserLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n })\n : BetterAuthNodeLayer({\n authBaseUrl: input.runtimeUrls.authBaseUrl,\n ...(input.origin === undefined ? {} : { origin: input.origin }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n });\n\n return baseLayer.pipe(\n Layer.flatMap((context) => {\n const authClient = Context.get(context, AuthClientPortTag);\n const refreshed = refreshConvexAuthOnSession(authClient, () => {\n const refresh = refreshConvexAuthRef.current;\n if (refresh === null) {\n refreshConvexAuthRef.pending = true;\n return;\n }\n refresh();\n });\n return Layer.succeedContext(\n Context.make(\n AuthClientPortTag,\n resetSignerSessionRef === undefined\n ? refreshed\n : resetSignerSessionOnSignOut(refreshed, resetSignerSessionRef),\n ),\n );\n }),\n );\n}\n\nfunction productionAuthCacheLayer(\n input: ProductionAdapterLayerInput,\n): Layer.Layer<AuthCachePortTag, never, never> {\n return Layer.succeed(AuthCachePortTag, input.authCache ?? detectAuthCacheAdapter());\n}\n\nfunction productionConvexCallLayer(\n input: ProductionAdapterLayerInput,\n refreshConvexAuthRef: RefreshConvexAuthRef,\n): Layer.Layer<ConvexCallPortTag, never, AuthClientPortTag> {\n return Layer.unwrap(\n Effect.map(AuthClientPortTag, (authClient) =>\n ConvexCallLayer({\n convexUrl: input.runtimeUrls.convexUrl,\n ...(input.applicationId === undefined ? {} : { applicationId: input.applicationId }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n ...(input.convexClient === undefined ? {} : { client: input.convexClient }),\n tokenProvider: async ({ forceRefreshToken }) => {\n const tokenResult = await Effect.runPromise(\n Effect.result(\n authClient.getConvexJwt({\n forceRefresh: forceRefreshToken,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n }),\n ),\n );\n if (Result.isFailure(tokenResult)) return null;\n return String(tokenResult.success.token);\n },\n }).pipe(\n Layer.flatMap((context) => {\n const convexCall = Context.get(context, ConvexCallPortTag);\n if (isRefreshableConvexCallPort(convexCall)) {\n refreshConvexAuthRef.current = () => convexCall.refreshAuth();\n if (refreshConvexAuthRef.pending) {\n refreshConvexAuthRef.pending = false;\n refreshConvexAuthRef.current();\n }\n }\n return Layer.succeedContext(context);\n }),\n ),\n ),\n );\n}\n\nfunction isRefreshableConvexCallPort(\n convexCall: ConvexCallPort,\n): convexCall is ConvexCallPort & { readonly refreshAuth: () => void } {\n return \"refreshAuth\" in convexCall && typeof convexCall.refreshAuth === \"function\";\n}\n\n/**\n * @internal Seam for the composition root only: `createCapxulClient` derives\n * the browser signer from the bootstrap this function resolves, so it hands in\n * a ref the auth layer closes over and fills the callback in afterwards. Not on\n * `ProductionAdapterInput` — a consumer must never reach the auth seam.\n */\ninterface ProductionResetSignerSeam {\n readonly resetSignerSession?: ResetSignerSessionRef;\n}\n\nexport async function createProductionAdapters(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<ProductionAdapters>> {\n const resolvedInput = resolveInput(input);\n if (!resolvedInput.ok) return resolvedInput;\n\n const scope = await Effect.runPromise(Scope.make());\n const closeScope = idempotentClose(() => Effect.runPromise(Scope.close(scope, Exit.void)));\n\n const bootstrapLayer = HttpBootstrapLayer({\n bootstrapBaseUrl: resolvedInput.value.bootstrapBaseUrl,\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n });\n\n try {\n const bootstrapContext = await Effect.runPromise(Layer.buildWithScope(bootstrapLayer, scope));\n const bootstrap = Context.get(bootstrapContext, BootstrapPortTag);\n const bootstrapResult = await runBootstrap(\n bootstrap.resolve({\n publishableKey: resolvedInput.value.publishableKey,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n }),\n );\n if (!bootstrapResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n reason: bootstrapResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return bootstrapResult;\n }\n\n // Testnet fence for the dev-key lane (#1149, folds #1065; ADR-0018 P9).\n // A `local-private-key` signer is a disposable, deterministically derived\n // dev key — it is the AGENT signing path, never the human one. This is the\n // one place where such a signer meets a resolved chain, so the refusal\n // lives here: every consumer (MCP proof lane, exemplar, approve, reference)\n // constructs through `createProductionAdapters`. It fails BEFORE any\n // adapter, Convex client, or signer call exists.\n const chainFence = assertDevKeySignerIsTestnetOnly(input.signer, bootstrapResult.value.chainId);\n if (!chainFence.ok) {\n await closeScope().catch(() => undefined);\n return chainFence;\n }\n\n const runtimeUrlsResult = resolveRuntimeUrls(\n bootstrapResult.value,\n resolvedInput.value.runtime,\n input.authBaseUrl,\n );\n if (!runtimeUrlsResult.ok) {\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_failed\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n reason: runtimeUrlsResult.error.code,\n },\n });\n await closeScope().catch(() => undefined);\n return runtimeUrlsResult;\n }\n const runtimeUrls = runtimeUrlsResult;\n\n await emitBootstrapTelemetry(input.telemetry, {\n name: \"bootstrap_resolved\",\n props: {\n ...bootstrapTelemetryEnvelope(input, resolvedInput.value),\n applicationId: bootstrapResult.value.applicationId,\n },\n });\n\n let injectedClient: ConvexClientShape | undefined;\n const convexClientFactory = (input as ProductionConvexClientFactorySeam).convexClientFactory;\n if (convexClientFactory !== undefined) {\n try {\n injectedClient = convexClientFactory(runtimeUrls.value.convexUrl);\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n }\n\n const portsLayer = mergeProductionAdapterLayers(\n makeProductionAdapterLayerEntries({\n bootstrap,\n runtime: resolvedInput.value.runtime,\n ...(resolvedInput.value.origin === undefined ? {} : { origin: resolvedInput.value.origin }),\n runtimeUrls: runtimeUrls.value,\n chainId: bootstrapResult.value.chainId,\n applicationId: bootstrapResult.value.applicationId,\n ...(input.observation === undefined ? {} : { observation: input.observation }),\n ...(input.authCache === undefined ? {} : { authCache: input.authCache }),\n ...(input.telemetry === undefined ? {} : { telemetry: input.telemetry }),\n ...(injectedClient === undefined ? {} : { convexClient: injectedClient }),\n ...(input.fetch === undefined ? {} : { fetch: input.fetch }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...((input as ProductionResetSignerSeam).resetSignerSession === undefined\n ? {}\n : {\n resetSignerSession: (input as ProductionResetSignerSeam)\n .resetSignerSession as ResetSignerSessionRef,\n }),\n }),\n );\n const applicationLayer =\n input.engineeringTelemetry === undefined\n ? portsLayer\n : Layer.merge(\n portsLayer,\n makeEngineeringTelemetryLayer({\n ...input.engineeringTelemetry,\n producer: resolvedInput.value.runtime === \"browser\" ? \"browser\" : \"server\",\n sdkVersion: SDK_VERSION,\n }),\n );\n // The graph, built into the same scope as `close`. It is the runtime; the\n // `FlowPorts` record below is a projection taken FROM it (A2-Q1A).\n const context = await Effect.runPromise(Layer.buildWithScope(applicationLayer, scope));\n const ports = await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context)));\n\n return {\n ok: true,\n value: { context, ports, bootstrap: bootstrapResult.value, close: closeScope },\n };\n } catch (cause) {\n await closeScope().catch(() => undefined);\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nfunction refreshConvexAuthOnSession(\n authClient: AuthClientPort,\n refresh: () => void,\n): AuthClientPort {\n return {\n ...authClient,\n verifyOtp: (input, options) =>\n authClient.verifyOtp(input, options).pipe(Effect.tap(() => Effect.sync(refresh))),\n signOut: (options) => authClient.signOut(options).pipe(Effect.tap(() => Effect.sync(refresh))),\n };\n}\n\n/**\n * Signer-session reset, as a port wrapper INSIDE the Layer graph (blueprint §2:\n * \"wrappers become Layers, not post-hoc spreads/Proxies\").\n *\n * This was a spread over the assembled client — `{...client, auth: {...,\n * signOut}}` — applied after composition finished, so the reset lived on one\n * particular object rather than on the auth seam itself. Here it wraps\n * `AuthClientPort.signOut`, so it holds for every route to a sign-out.\n *\n * `Effect.ensuring` (not `Effect.tap`) is deliberate: the old wrapper used\n * `try/finally`, so the session was reset even when sign-out failed. Dropping\n * to `tap` would silently strand an Openfort session on the error path.\n */\nfunction resetSignerSessionOnSignOut(\n authClient: AuthClientPort,\n resetRef: ResetSignerSessionRef,\n): AuthClientPort {\n return {\n ...authClient,\n signOut: (options) =>\n authClient.signOut(options).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n resetRef.current?.();\n }),\n ),\n ),\n };\n}\n\nexport async function createCapxulClient(\n input: ProductionAdapterInput,\n): Promise<CapxulResult<CapxulClient>> {\n const validation = validateCreateCapxulClientInput(input);\n if (!validation.ok) {\n return observeFailedResult(validation, input.observation, \"createCapxulClient\");\n }\n\n // The auth layer closes over this ref while the graph is built; the signer\n // that fills it in is derived from the bootstrap the graph itself resolves,\n // so the callback lands one step later. The WRAPPER is part of the graph\n // either way — that is the point of moving it off the assembled object.\n const resetSignerSession: ResetSignerSessionRef = { current: null };\n const adapters = await createProductionAdapters({\n ...input,\n resetSignerSession,\n } as ProductionAdapterInput);\n if (!adapters.ok) {\n return observeFailedResult(adapters, input.observation, \"createCapxulClient\");\n }\n try {\n const runtime = input.runtime ?? detectRuntime();\n const resolvedAuthBaseUrl = resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: adapters.value.bootstrap.authBaseUrl,\n runtime,\n ...(input.authBaseUrl === undefined ? {} : { override: input.authBaseUrl }),\n });\n let signer: CapxulSigner | OpenfortBrowserSigner | undefined = input.signer;\n if (signer === undefined && runtime === \"browser\") {\n // Thread the diagnostic + telemetry options so the signer's breadcrumbs\n // (token, encryptionSession, embeddedState, configure, getAddress) and its\n // no-secure-context self-report actually fire on the real browser path —\n // building it with the bootstrap alone dropped #870's native cause (#1032).\n signer = createOpenfortBrowserSignerFromBootstrap(\n {\n ...adapters.value.bootstrap,\n authBaseUrl: resolvedAuthBaseUrl,\n },\n {\n diagnostic: new ConsoleDiagnosticAdapter(),\n telemetry: adapters.value.ports.telemetry,\n },\n );\n }\n if (signer !== undefined && \"resetSession\" in signer) {\n const { resetSession } = signer;\n resetSignerSession.current = () => {\n resetSession();\n };\n }\n const client = assembleCapxulClient({\n ports: adapters.value.ports,\n bootstrap: adapters.value.bootstrap,\n authCache: adapters.value.ports.authCache,\n requirement: input.requirement ?? \"none\",\n ...(signer === undefined ? {} : { signer }),\n // Resolved FROM the graph rather than constructed beside it — the org\n // adapter is a Convex-backed port and now has a layer entry like its\n // siblings (`OrgPortTag` had zero resolvers before the re-cut).\n orgPort: Context.get(adapters.value.context, OrgPortTag),\n ...(signer === undefined\n ? {}\n : {\n // Still hand-built: this adapter closes over the SIGNER, which is\n // derived from the bootstrap the graph resolves, so it cannot be a\n // layer entry until the signer moves ahead of composition. ADR-0019\n // P3 / L1 owns that; noted rather than faked.\n organizationSetup: new ConvexOrganizationSetupAdapter({\n convex: adapters.value.ports.convexCall,\n signer,\n chainId: adapters.value.bootstrap.chainId,\n }),\n }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n invokeTimeoutMs: input.invokeTimeoutMs ?? DEFAULT_INVOKE_TIMEOUT_MS,\n effectRunner: {\n runSync: Effect.runSyncWith(adapters.value.context as Context.Context<never>),\n runPromise: Effect.runPromiseWith(adapters.value.context as Context.Context<never>),\n },\n });\n const upstreamClose = adapters.value.close;\n const close = idempotentClose(async () => {\n try {\n if (\"resetSession\" in (signer ?? {})) {\n (signer as OpenfortBrowserSigner).resetSession();\n }\n } finally {\n await Promise.all([client._internal.close?.(), upstreamClose()]);\n }\n });\n const value = {\n ...client,\n _internal: {\n ...client._internal,\n close,\n },\n };\n return { ok: true, value };\n } catch (cause) {\n await adapters.value.close().catch(() => undefined);\n return observeFailedResult(\n { ok: false, error: toPublicError(cause, \"createCapxulClient\") } as const,\n input.observation,\n \"createCapxulClient\",\n );\n }\n}\n\nfunction validateCreateCapxulClientInput(input: ProductionAdapterInput): CapxulResult<void> {\n const runtime = input.runtime ?? detectRuntime();\n if (\n (input.requirement ?? \"none\") === \"deployed\" &&\n input.signer === undefined &&\n runtime !== \"browser\"\n ) {\n return {\n ok: false,\n error: Errors.invalidInput(\"signer\", 'required when requirement is \"deployed\"'),\n };\n }\n return { ok: true, value: undefined };\n}\n\ntype ResolvedInput = {\n readonly publishableKey: ReturnType<typeof toPublishableKey>;\n readonly origin?: ReturnType<typeof toAllowedOrigin>;\n readonly bootstrapBaseUrl: string;\n readonly runtime: ProductionRuntime;\n};\n\nfunction resolveInput(input: ProductionAdapterInput): CapxulResult<ResolvedInput> {\n try {\n const runtime = input.runtime ?? detectRuntime();\n const publishableKey = toPublishableKey(input.publishableKey);\n const origin =\n input.origin === undefined\n ? runtime === \"browser\"\n ? toAllowedOrigin(derivedBrowserOrigin(runtime))\n : undefined\n : toAllowedOrigin(input.origin);\n return {\n ok: true,\n value: {\n publishableKey,\n ...(origin === undefined ? {} : { origin }),\n bootstrapBaseUrl: normalizeHttpUrl(\n \"bootstrapBaseUrl\",\n input.bootstrapBaseUrl ??\n (runtime === \"browser\"\n ? derivedBrowserOrigin(runtime)\n : DEFAULT_CAPXUL_BOOTSTRAP_BASE_URL),\n ),\n runtime,\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\n/**\n * Address of the Capxul client-relay ingest endpoint (Pipe 1, issue #877). The\n * HTTP router that serves `/v1/client/observe` lives on the deployment's\n * `.convex.site` host, while the bootstrap-resolved `convexUrl` is the sibling\n * `.convex.cloud` (WebSocket/query) host — the same deterministic pairing\n * `mintQuickstartKey` inverts. For any standard Convex deployment (including\n * production) rewriting the suffix targets the router directly with no host\n * proxy, so it is the primary rule.\n *\n * `siteBaseUrl` is deliberately NOT the primary source: it is an app-configured\n * field that defaults to a placeholder (`https://capxul.local`, see\n * `credentials/applications.ts`) for registered applications, so trusting it\n * outright would POST to a dead host for the common case. It is only consulted\n * as a fallback for a custom-domain `convexUrl` (no deterministic `.convex.site`\n * sibling) when it carries a real, non-placeholder origin.\n */\nexport function deriveObserveIngestUrl(bootstrap: BootstrapResolution): string {\n const convexUrl = bootstrap.convexUrl.replace(/\\/+$/, \"\");\n if (convexUrl.endsWith(\".convex.cloud\")) {\n return `${convexUrl.replace(/\\.convex\\.cloud$/, \".convex.site\")}/v1/client/observe`;\n }\n const site = usableSiteOrigin(bootstrap.siteBaseUrl) ?? convexUrl;\n return `${site.replace(/\\/+$/, \"\")}/v1/client/observe`;\n}\n\n/** A configured `siteBaseUrl` usable as a router host, or `undefined` if it is the placeholder. */\nfunction usableSiteOrigin(siteBaseUrl: string): string | undefined {\n try {\n const url = new URL(siteBaseUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return undefined;\n if (url.hostname === \"capxul.local\") return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n\nfunction detectRuntime(): ProductionRuntime {\n const globalAny = globalThis as {\n readonly window?: unknown;\n readonly document?: unknown;\n };\n return globalAny.window !== undefined || globalAny.document !== undefined ? \"browser\" : \"node\";\n}\n\nfunction derivedBrowserOrigin(runtime: ProductionRuntime): string {\n if (runtime !== \"browser\") {\n throw Errors.invalidInput(\"origin\", \"required outside browser runtime\");\n }\n const globalAny = globalThis as { readonly location?: { readonly origin?: string } };\n if (typeof globalAny.location?.origin === \"string\" && globalAny.location.origin.length > 0) {\n return globalAny.location.origin;\n }\n throw Errors.invalidInput(\"origin\", \"required when browser location is unavailable\");\n}\n\n/**\n * Browser local dev serves `/api/auth` via the Vite proxy on `window.location.origin`\n * while bootstrap returns the remote Convex site host. Openfort wallet setup reads\n * Better Auth cookies from `get-session` — those only attach on the same origin the\n * OTP flow used, so rewrite when hosts differ.\n */\nexport function resolveBrowserAuthBaseUrl(input: {\n readonly bootstrapAuthBaseUrl: string;\n readonly runtime: ProductionRuntime;\n readonly override?: string;\n}): string {\n if (input.override !== undefined) {\n return normalizeHttpUrl(\"authBaseUrl\", input.override);\n }\n const bootstrapUrl = normalizeHttpUrl(\"authBaseUrl\", input.bootstrapAuthBaseUrl);\n if (input.runtime !== \"browser\") {\n return bootstrapUrl;\n }\n try {\n const origin = derivedBrowserOrigin(input.runtime);\n const localAuthBase = normalizeHttpUrl(\"authBaseUrl\", `${origin}/api/auth`);\n const remoteAuthBase = bootstrapUrl.endsWith(\"/api/auth\")\n ? bootstrapUrl\n : `${bootstrapUrl}/api/auth`;\n if (new URL(remoteAuthBase).host !== new URL(localAuthBase).host) {\n return localAuthBase;\n }\n return bootstrapUrl;\n } catch {\n return bootstrapUrl;\n }\n}\n\nfunction resolveRuntimeUrls(\n bootstrap: BootstrapResolution,\n runtime: ProductionRuntime,\n authBaseUrlOverride?: string,\n): CapxulResult<{ readonly authBaseUrl: string; readonly convexUrl: string }> {\n try {\n return {\n ok: true,\n value: {\n authBaseUrl: resolveBrowserAuthBaseUrl({\n bootstrapAuthBaseUrl: bootstrap.authBaseUrl,\n runtime,\n ...(authBaseUrlOverride === undefined ? {} : { override: authBaseUrlOverride }),\n }),\n convexUrl: normalizeHttpUrl(\"convexUrl\", bootstrap.convexUrl),\n },\n };\n } catch (cause) {\n return { ok: false, error: toPublicError(cause, \"createProductionAdapters\") };\n }\n}\n\nasync function runBootstrap(\n effect: ReturnType<BootstrapPort[\"resolve\"]>,\n): Promise<CapxulResult<BootstrapResolution>> {\n const result = await Effect.runPromise(Effect.result(effect));\n if (Result.isSuccess(result)) return { ok: true, value: result.success };\n return { ok: false, error: toPublicError(result.failure, \"bootstrap.resolve\") };\n}\n\n/**\n * Bootstrap-event props. `runtime` used to be called `capxulEnv`, which was a\n * name collision, not a value: it carried \"browser\"/\"node\", never an\n * environment. ADR-0020 A1 makes `capxul_env` the environment discriminator\n * every synced artifact filters on, so this field was renamed to what it\n * actually is. `sdk_version` follows the canon envelope spelling.\n */\nfunction bootstrapTelemetryEnvelope(\n input: ProductionAdapterInput,\n resolvedInput: ResolvedInput,\n): {\n readonly runtime: ProductionRuntime;\n readonly env: AccountRequirement;\n readonly origin?: string;\n readonly sdk_version: string;\n} {\n return {\n runtime: resolvedInput.runtime,\n env: input.requirement ?? \"none\",\n ...(resolvedInput.origin === undefined ? {} : { origin: resolvedInput.origin }),\n sdk_version: SDK_VERSION,\n };\n}\n\nasync function emitBootstrapTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(telemetry.emit(event).pipe(Effect.catchDefect(() => Effect.void)));\n}\n\nfunction normalizeHttpUrl(field: string, raw: string): string {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw Errors.invalidInput(field, \"must be an http or https URL\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nfunction toPublicError(cause: unknown, operation: string): CapxulError {\n if (cause instanceof CapxulError) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const publicError = (cause as { readonly publicError?: unknown }).publicError;\n if (publicError instanceof CapxulError) return publicError;\n const nestedCause = (cause as { readonly cause?: unknown }).cause;\n if (nestedCause instanceof CapxulError) return nestedCause;\n }\n return Errors.providerError(\"sdk-production-adapters\", operation, cause);\n}\n\nfunction idempotentClose(close: () => Promise<void>): ProductionAdapterClose {\n let closed = false;\n return async () => {\n if (closed) return;\n closed = true;\n await close();\n };\n}\n","import {\n createCapxulClient as createCapxulClientFromProductionAdapters,\n type CapxulClientInput,\n} from \"../production\";\nimport type { CapxulClient } from \"./create-capxul-client\";\nimport type { CapxulResult } from \"./types\";\n\n/** Consumer-facing factory — accepts only production-meaningful inputs (#326). */\nexport async function createCapxulClient(\n input: CapxulClientInput,\n): Promise<CapxulResult<CapxulClient>> {\n return createCapxulClientFromProductionAdapters(input);\n}\n","// Host-facing SUCCESS-telemetry seam — the twin of `fromPostHog` in\n// `observation.ts` (which covers failures). The host passes its own\n// already-initialized posthog-js client; the SDK's rich success events\n// (`org_created`, `faucet_requested`, `transfer_requested`, …) are delivered to\n// it and, because it is the same client the consumer called `identify()` on,\n// they attach to the browser person and light up the journey funnel.\n//\n// The SDK never imports, initializes, configures, or owns posthog. Event props\n// are PII-redacted by the shared `PostHogTelemetryAdapter`; the host-owned\n// context is sanitized with the SAME `sanitizeObservationContext` the failure\n// path uses; and the `$exception` `details` blob (amounts / org names / account\n// IDs — the one field the shared redactor has no rule for) is dropped at this\n// host boundary — so no addresses, names, or amounts reach the host sink\n// (infra#1037).\n\nimport { sanitizeObservationContext } from \"@capxul/wire/observation-context\";\nimport { stampTelemetryEnvelope, type CapxulEnv } from \"@capxul/observability\";\n\nimport { PostHogTelemetryAdapter } from \"../adapters/telemetry/PostHogTelemetryAdapter\";\nimport { observationContextProps, type ObservationContext } from \"../observation\";\nimport type { TelemetryPort, TelemetryProps } from \"../ports/telemetry\";\n\n/**\n * Drop props that must never cross to a host-owned external sink. Today that is\n * the `$exception` `details` blob: `captureException` serializes\n * `CapxulError.details` (e.g. `{ asset, available, required }`, `{ name }`,\n * `{ accountId }` — errors.ts) into it, and the shared redactor has no\n * `$exception` rule, so it is stripped here at the boundary (infra#1037). The\n * safe fields (error code, operation, failure_mode, the fixed leak-safe message,\n * stack frames) are preserved.\n */\nfunction stripHostUnsafeProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n const { details: _details, ...safe } = props;\n return safe;\n}\n\n/**\n * The subset of a posthog-js client the seam calls. `identify` / `group` /\n * `reset` are optional — a host that only wants event capture can omit them.\n */\nexport interface PostHogTelemetryClient {\n capture(event: string, properties?: Record<string, unknown>): unknown;\n identify?(distinctId: string, properties?: Record<string, unknown>): unknown;\n group?(groupType: string, groupKey: string, properties?: Record<string, unknown>): unknown;\n reset?(): unknown;\n}\n\nexport interface PostHogTelemetryOptions {\n /** Consent / kill-switch seam. Defaults to enabled. */\n readonly enabled?: boolean | (() => boolean);\n /** Host environment stamped on every SDK-owned product event. */\n readonly capxulEnv?: CapxulEnv;\n /** Host-owned correlation context, merged (sanitized) onto every captured event. */\n readonly context?: ObservationContext | (() => ObservationContext | undefined);\n}\n\n/**\n * Adapt the host's already-initialized posthog-like client into a\n * `TelemetryPort` for the `telemetry` prop / input. This port SUPPLANTS the\n * SDK's no-op default telemetry sink (`production.ts` binds it via\n * `Layer.succeed`, not `compose` — there is no client-side success relay to\n * compose with); it is additive to Capxul's backend first-party record and\n * never owns the client.\n */\nexport function telemetryFromPostHog(\n client: PostHogTelemetryClient | null | undefined,\n options: PostHogTelemetryOptions = {},\n): TelemetryPort {\n const active = (): boolean => {\n if (client === null || client === undefined) return false;\n try {\n return typeof options.enabled === \"function\" ? options.enabled() : (options.enabled ?? true);\n } catch {\n return false;\n }\n };\n\n const contextProps = (): Record<string, string> => {\n let raw: ObservationContext | undefined;\n try {\n raw = typeof options.context === \"function\" ? options.context() : options.context;\n } catch {\n return {};\n }\n // Same sanitizer + snake_case mapping as the failure path, so success and\n // failure events carry identical correlation fields.\n return observationContextProps(sanitizeObservationContext(raw));\n };\n\n // Reuse the existing adapter for per-event PII redaction, prop cloning, and\n // fire-and-forget isolation; the deps here add consent gating + context merge.\n return new PostHogTelemetryAdapter({\n capture: (name, props) => {\n if (!active() || client === null || client === undefined) return;\n const event = stampTelemetryEnvelope(\n { name, props },\n { capxul_env: options.capxulEnv ?? \"unknown\", producer: \"sdk\" },\n );\n client.capture(name, { ...stripHostUnsafeProps(event.props), ...contextProps() });\n },\n // NOTE: identify traits / group properties are forwarded structurally and are\n // NOT run through the per-event redactor the capture arm relies on. Callers\n // MUST pre-minimize them (send `email_domain`, never a raw email). Do not\n // pass raw PII here — it would reach the host un-redacted.\n identify: (input) => {\n if (!active() || client?.identify === undefined) return;\n client.identify(input.distinctId, { ...input.traits, ...input.properties });\n },\n group: (input) => {\n if (!active() || client?.group === undefined) return;\n client.group(\n input.groupType,\n input.groupKey,\n input.properties === undefined ? undefined : { ...input.properties },\n );\n },\n reset: () => {\n if (!active() || client?.reset === undefined) return;\n client.reset();\n },\n });\n}\n"],"mappings":";;;;;;;;;;;AA8CA,SAAgB,+BAA+B,OAE3B;CAClB,MAAM,UAAU,oBAAoB,MAAM,UAAU;CACpD,MAAM,UAAU,UAAU,QAAQ,O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