@invisible-labs/sdk 0.6.0-devnet.4 → 0.6.0-devnet.5

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 (46) hide show
  1. package/README.md +70 -13
  2. package/dist/.invisible-sdk-build-target.json +2 -2
  3. package/dist/{chunk-UADJCUPK.js → chunk-3MDHAS4D.js} +6 -5
  4. package/dist/chunk-3MDHAS4D.js.map +1 -0
  5. package/dist/{chunk-E4DCEDAG.js → chunk-3TGQ4CZ3.js} +178 -2
  6. package/dist/chunk-3TGQ4CZ3.js.map +1 -0
  7. package/dist/chunk-DCTYBUY3.js +258 -0
  8. package/dist/chunk-DCTYBUY3.js.map +1 -0
  9. package/dist/{chunk-NHEHCUS5.js → chunk-EBWTAXNT.js} +3 -3
  10. package/dist/{chunk-NHEHCUS5.js.map → chunk-EBWTAXNT.js.map} +1 -1
  11. package/dist/{chunk-V5HXJRBW.js → chunk-HJFMDMPY.js} +3 -3
  12. package/dist/chunk-HJFMDMPY.js.map +1 -0
  13. package/dist/{chunk-GHBQF3A7.js → chunk-QRN46R3F.js} +5 -2
  14. package/dist/chunk-QRN46R3F.js.map +1 -0
  15. package/dist/chunk-Y7AK6RBV.js +4189 -0
  16. package/dist/chunk-Y7AK6RBV.js.map +1 -0
  17. package/dist/{coordinator-ZNLGAYXD.js → coordinator-PEWHNZ7I.js} +3 -3
  18. package/dist/{coordinator-ZNLGAYXD.js.map → coordinator-PEWHNZ7I.js.map} +1 -1
  19. package/dist/events.js +3 -3
  20. package/dist/index.d.ts +14 -4
  21. package/dist/index.js +74 -11
  22. package/dist/index.js.map +1 -1
  23. package/dist/lp.d.ts +33 -9
  24. package/dist/lp.js +305 -45
  25. package/dist/lp.js.map +1 -1
  26. package/dist/presets.d.ts +6 -2
  27. package/dist/presets.js +8 -8
  28. package/dist/presets.js.map +1 -1
  29. package/dist/stats.js +1 -1
  30. package/dist/storage.js +2 -243
  31. package/dist/storage.js.map +1 -1
  32. package/dist/{types.generated-DJBTjLpP.d.ts → types.generated-YhFu9ZBR.d.ts} +29 -4
  33. package/dist/user.d.ts +31 -4
  34. package/dist/user.js +409 -57
  35. package/dist/user.js.map +1 -1
  36. package/package.json +4 -1
  37. package/dist/chunk-5NNEO7IK.js +0 -1150
  38. package/dist/chunk-5NNEO7IK.js.map +0 -1
  39. package/dist/chunk-BRDLLGCZ.js +0 -59
  40. package/dist/chunk-BRDLLGCZ.js.map +0 -1
  41. package/dist/chunk-DIA6U2CV.js +0 -1927
  42. package/dist/chunk-DIA6U2CV.js.map +0 -1
  43. package/dist/chunk-E4DCEDAG.js.map +0 -1
  44. package/dist/chunk-GHBQF3A7.js.map +0 -1
  45. package/dist/chunk-UADJCUPK.js.map +0 -1
  46. package/dist/chunk-V5HXJRBW.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/errors.ts"],"names":[],"mappings":";AAsIO,IAAe,cAAA,GAAf,cAAsC,KAAA,CAAM;AAAA,EAIjD,WAAA,CAAY,SAAiB,OAAA,EAAiC;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AAGb,IAAA,IAAI,OAAA,EAAS,UAAU,MAAA,EAAW;AAChC,MAAC,IAAA,CAA6B,QAAQ,OAAA,CAAQ,KAAA;AAAA,IAChD;AACA,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAGvB,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAGO,IAAM,gBAAA,GAAN,cAA+B,cAAA,CAAe;AAAA,EAEnD,WAAA,CAAY,IAAA,EAA4B,OAAA,EAAiB,OAAA,EAAiC;AACxF,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGO,IAAM,cAAA,GAAN,cAA6B,cAAA,CAAe;AAAA,EAEjD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AAAA,EAC9D;AAEA,EAAA,OAAO,IAAA;AACT;AAEA,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA;AAChD;AAEA,SAAS,UAAA,CAAW,MAAe,OAAA,EAAyB;AAC1D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,CAAK,IAAA,GAAO,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA,CAAQ,IAAA,EAAK;AAC9E,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,OAAO,OAAA,CAAQ,QAAA,CAAS,CAAA,CAAA,EAAI,OAAO,GAAG,CAAA,GAAI,OAAA,CAAQ,IAAA,EAAK,GAAI,CAAA,CAAA,EAAI,OAAO,CAAA,EAAA,EAAK,OAAA,CAAQ,MAAM,CAAA,CAAA;AAC3F;AAEA,SAAS,WAAW,KAAA,EAAuC;AACzD,EAAA,IAAI,KAAA,KAAU,MAAM,OAAO,KAAA;AAC3B,EAAA,MAAM,OAAA,GAAU,MAAM,IAAA,EAAK;AAC3B,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AACjC,EAAA,OAAO,CAAC,gEAAA,CAAiE,IAAA,CAAK,OAAO,CAAA;AACvF","file":"chunk-GHBQF3A7.js","sourcesContent":["/**\n * The closed error taxonomy from docs/sdk-specification.md section 8.3.\n *\n * Every error the SDK throws extends {@link InvisibleError} and carries a\n * `code` drawn from a closed, per-class string-literal union. Consumers can\n * branch on `error instanceof CommandError` and then exhaustively `switch` on\n * `error.code` with compile-time completeness.\n *\n * Error classes are the one deliberate exception to the SDK's \"no classes\"\n * rule: JavaScript errors must extend `Error` to carry a stack and support\n * `instanceof`. This mirrors @solana/kit, whose only class is `SolanaError`.\n * The conformance lint allowlists this file for that reason.\n */\n\n// ---------------------------------------------------------------------------\n// Code unions (closed sets, section 8.3)\n// ---------------------------------------------------------------------------\n\n/** Attestation verification failures. Stop; do not retry without a new pin. */\nexport type AttestationErrorCode =\n | \"CERT_CHAIN_INVALID\"\n | \"TCB_REJECTED\"\n | \"FRESHNESS_NONCE_MISMATCH\"\n | \"NOISE_BINDING_MISMATCH\"\n | \"DEBUG_BIT_SET\"\n | \"MRTD_MISMATCH\"\n | \"RUNTIME_PROFILE_MISMATCH\"\n | \"AZURE_MAA_ISSUER_MISMATCH\"\n | \"AZURE_MAA_JWKS_INVALID\"\n | \"AZURE_MAA_POLICY_HASH_MISMATCH\"\n | \"AZURE_MAA_NOT_COMPLIANT\"\n | \"AZURE_MAA_DCAP_MISMATCH\"\n | \"AZURE_HCL_KEYS_MISMATCH\"\n | \"AZURE_AK_PUB_INVALID\"\n | \"AZURE_TPM_AK_QUOTE_INVALID\"\n | \"AZURE_TPM_QUALIFYING_DATA_MISMATCH\"\n | \"NOT_ATTESTED\";\n\n/** Transport-level failures. Reconnect through the pool and re-attest. */\nexport type TransportErrorCode =\n | \"WS_HANDSHAKE_FAILED\"\n | \"NOISE_HANDSHAKE_FAILED\"\n | \"NOISE_FRAME_TOO_LARGE\"\n | \"CONNECTION_LOST\";\n\n/** Leader/role routing failures. Failover and re-attest. */\nexport type RoutingErrorCode =\n | \"WRONG_ROLE\"\n | \"STALE_LEADER_EPOCH\"\n | \"POOL_DEGRADED\"\n | \"VERSION_NOT_SUPPORTED\";\n\n/** Coordinator-side command rejections. Product decides whether to retry. */\nexport type CommandErrorCode =\n | \"REJECTED_GUARD\"\n | \"REJECTED_STATE\"\n | \"REJECTED_EXPIRED\"\n | \"REJECTED_STALE_JOB\"\n | \"REJECTED_RESOURCE_CAP\";\n\n/** Coordinator wire error code preserved on command rejections. */\nexport type CoordinatorWireErrorCode =\n | \"ERR_INVALID_PAYLOAD\"\n | \"ERR_UNEXPECTED_TYPE\"\n | \"ERR_UNKNOWN_SWAP\"\n | \"ERR_POLICY_VIOLATION\"\n | \"ERR_INVALID_RECOVERY_CODE\"\n | \"ERR_SWAP_NOT_REFUNDABLE\"\n | \"ERR_DKG_FAILURE\"\n | \"ERR_INTERNAL\"\n | \"ERR_INVALID_DEPOSIT\"\n | \"ERR_SETTLEMENT_FAILED\";\n\n/** Local input-validation failures. Never sent on the wire; fix the input. */\nexport type PolicyValidationErrorCode =\n | \"INVALID_PAYOUT_PLAN\"\n | \"INVALID_WITHDRAWAL_PLAN\"\n | \"INVALID_POSITION_AUTH\"\n | \"INVALID_REDEMPTION_PLAN\"\n | \"INVALID_DESTINATION_ADDRESS\"\n | \"INVALID_AMOUNT\";\n\n/** Storage-adapter failures. */\nexport type StorageErrorCode =\n | \"STORAGE_NOT_AVAILABLE\"\n | \"STORAGE_KEY_MISSING\"\n | \"STORAGE_DECRYPT_FAILED\";\n\n/** Wallet-adapter failures. Bubble to the integrator UX. */\nexport type WalletErrorCode =\n | \"WALLET_NOT_CONNECTED\"\n | \"WALLET_USER_REJECTED\"\n | \"WALLET_INVALID_SIGNATURE\";\n\n/** LP lifecycle local state that callers can branch on. */\nexport type LpLifecycleErrorCode = \"LP_POSITION_AUTH_MISSING\" | \"LP_REDEMPTION_RECONCILING\";\n\n/** Skeleton-only: a surface that exists but has no implementation yet. */\nexport type NotImplementedErrorCode = \"NOT_IMPLEMENTED\";\n\n/** Every code the SDK can surface, across all classes. */\nexport type InvisibleErrorCode =\n | AttestationErrorCode\n | TransportErrorCode\n | RoutingErrorCode\n | CommandErrorCode\n | PolicyValidationErrorCode\n | StorageErrorCode\n | WalletErrorCode\n | LpLifecycleErrorCode\n | NotImplementedErrorCode;\n\n// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\n/** Options accepted by every {@link InvisibleError}. */\nexport interface InvisibleErrorOptions {\n /** The underlying error, preserved for debugging. */\n readonly cause?: unknown;\n}\n\n/** Options accepted by {@link CommandError}. */\nexport interface CommandErrorOptions extends InvisibleErrorOptions {\n /** Exact coordinator `Error` envelope code, when the rejection came from the wire. */\n readonly coordinatorCode?: CoordinatorWireErrorCode;\n /** Request id rejected by the coordinator, when present in the `Error` envelope. */\n readonly failedReqId?: number;\n}\n\n/**\n * Base class for every error the SDK throws. Carries a closed `code` and sets\n * `name` to the concrete subclass name so logs and `instanceof` agree.\n */\nexport abstract class InvisibleError extends Error {\n /** The closed error code for this error's class. */\n abstract readonly code: InvisibleErrorCode;\n\n constructor(message: string, options?: InvisibleErrorOptions) {\n super(message);\n // Set `cause` directly rather than through the Error constructor option so\n // the package stays on the ES2020 lib (the option is ES2022).\n if (options?.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n this.name = new.target.name;\n // Restore the prototype chain across the transpiled `Error` boundary so\n // `instanceof` works for subclasses.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Attestation verification failure. */\nexport class AttestationError extends InvisibleError {\n readonly code: AttestationErrorCode;\n constructor(code: AttestationErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Transport-level failure. */\nexport class TransportError extends InvisibleError {\n readonly code: TransportErrorCode;\n constructor(code: TransportErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Leader/role routing failure. */\nexport class RoutingError extends InvisibleError {\n readonly code: RoutingErrorCode;\n constructor(code: RoutingErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Coordinator-side command rejection. */\nexport class CommandError extends InvisibleError {\n readonly code: CommandErrorCode;\n readonly coordinatorCode?: CoordinatorWireErrorCode;\n readonly failedReqId?: number;\n\n constructor(code: CommandErrorCode, message: string, options?: CommandErrorOptions) {\n super(message, options);\n this.code = code;\n if (options?.coordinatorCode !== undefined) this.coordinatorCode = options.coordinatorCode;\n if (options?.failedReqId !== undefined) this.failedReqId = options.failedReqId;\n }\n}\n\n/** User deposit did not match the coordinator policy amount. */\nexport class InvalidDepositAmountError extends CommandError {\n readonly receivedLamports: bigint;\n readonly expectedLamports: bigint;\n\n constructor(receivedLamports: bigint, expectedLamports: bigint) {\n super(\n \"REJECTED_GUARD\",\n `on-chain deposit balance ${receivedLamports.toString()} does not match expected ${expectedLamports.toString()} lamports`,\n );\n this.name = \"InvalidDepositAmountError\";\n this.receivedLamports = receivedLamports;\n this.expectedLamports = expectedLamports;\n }\n}\n\n/** Local input-validation failure; never reaches the wire. */\nexport class PolicyValidationError extends InvisibleError {\n readonly code: PolicyValidationErrorCode;\n constructor(code: PolicyValidationErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Storage-adapter failure. */\nexport class StorageError extends InvisibleError {\n readonly code: StorageErrorCode;\n constructor(code: StorageErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** Wallet-adapter failure. */\nexport class WalletError extends InvisibleError {\n readonly code: WalletErrorCode;\n constructor(code: WalletErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/** LP lifecycle state that is local to the SDK client. */\nexport class LpLifecycleError extends InvisibleError {\n readonly code: LpLifecycleErrorCode;\n constructor(code: LpLifecycleErrorCode, message: string, options?: InvisibleErrorOptions) {\n super(message, options);\n this.code = code;\n }\n}\n\n/**\n * A surface that exists in the typed contract but has no runtime behavior yet.\n * The skeleton throws this from every command that is not the connection layer.\n * The message carries the fully-qualified command name (e.g. `user.contractRequest`).\n */\nexport class NotImplementedError extends InvisibleError {\n readonly code = \"NOT_IMPLEMENTED\" as const;\n /** The command that is not yet implemented, e.g. `lp.redeem`. */\n readonly command: string;\n constructor(command: string, options?: InvisibleErrorOptions) {\n super(`${command} is not implemented in this SDK build`, options);\n this.command = command;\n }\n}\n\n/** Type guard: is `value` any SDK error. */\nexport function isInvisibleError(value: unknown): value is InvisibleError {\n return value instanceof InvisibleError;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization (analog of web/src/lib/user-facing-error.ts)\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_ERROR_MESSAGE = \"Something went wrong. Please try again.\";\n\ninterface MessageLike {\n readonly message?: unknown;\n readonly reason?: unknown;\n readonly error?: unknown;\n readonly code?: unknown;\n}\n\n/**\n * Reduce any thrown value to a readable, single-line message. Guarantees the\n * SDK never surfaces `[object Object]` / `[object ErrorEvent]` (spec section\n * 8.3). For an {@link InvisibleError} the code is prefixed as `[CODE] message`.\n */\nexport function normalizeError(error: unknown, fallback: string = DEFAULT_ERROR_MESSAGE): string {\n const direct = extractMessage(error);\n if (isReadable(direct)) return direct;\n if (isReadable(fallback)) return fallback.trim();\n return DEFAULT_ERROR_MESSAGE;\n}\n\nfunction extractMessage(error: unknown): string | null {\n if (error instanceof CommandError && error.coordinatorCode !== undefined) {\n return formatCode(error.coordinatorCode, error.message);\n }\n if (error instanceof InvisibleError) return formatCode(error.code, error.message);\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n if (error === null || error === undefined) return null;\n\n if (isMessageLike(error)) {\n if (typeof error.message === \"string\" && isReadable(error.message)) {\n return formatCode(error.code, error.message);\n }\n const nested = extractMessage(error.error);\n if (isReadable(nested)) return formatCode(error.code, nested);\n const reason = extractMessage(error.reason);\n if (isReadable(reason)) return formatCode(error.code, reason);\n }\n\n return null;\n}\n\nfunction isMessageLike(value: unknown): value is MessageLike {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction formatCode(code: unknown, message: string): string {\n if (typeof code !== \"string\" || code.trim().length === 0) return message.trim();\n const trimmed = code.trim();\n return message.includes(`[${trimmed}]`) ? message.trim() : `[${trimmed}] ${message.trim()}`;\n}\n\nfunction isReadable(value: string | null): value is string {\n if (value === null) return false;\n const trimmed = value.trim();\n if (trimmed.length === 0) return false;\n return !/^\\[object (?:Object|Event|ErrorEvent|PromiseRejectionEvent)\\]$/.test(trimmed);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/coordinator/protocolClient.ts"],"names":["pending"],"mappings":";;;;AAWA,IAAM,0BAAA,G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AW,CAAC,IAAA,EAAM,OAAO,KAAK,OAAA,CAAQ,WAAA,CAAY,SAAQ,EAAG;AAC3D,IAAA,OAAA,CAAQ,WAAA,CAAY,OAAO,IAAI,CAAA;AAC/B,IAAA,KAAA,MAAW,UAAU,OAAA,EAAS;AAC5B,MAAA,IAAI,MAAA,CAAO,KAAA,EAAO,YAAA,CAAa,MAAA,CAAO,KAAK,CAAA;AAC3C,MAAA,MAAA,CAAO,OAAO,KAAK,CAAA;AAAA,IACrB;AAAA,EACF;AACF","file":"chunk-UADJCUPK.js","sourcesContent":["import {\n CommandError,\n TransportError,\n type CommandErrorCode,\n type CoordinatorWireErrorCode,\n} from \"../core/errors.js\";\nimport type { Session } from \"../core/session.js\";\nimport { getSessionState, type SessionState } from \"../session/state.js\";\nimport type { Unsubscribe } from \"../transport/types.js\";\n\nconst COORDINATOR_ENVELOPE_VERSION = 2;\nconst MAX_COORDINATOR_REQUEST_ID = 0xffff_ffff;\nconst OUT_OF_BAND_REQUEST_ID = 0;\n\nexport const EnvelopeKind = {\n REQUEST: \"request\",\n RESPONSE: \"response\",\n PUSH: \"push\",\n ERROR: \"error\",\n} as const;\n\nexport type EnvelopeKind = (typeof EnvelopeKind)[keyof typeof EnvelopeKind];\n\nexport const CoordinatorMessageType = {\n ContractRequest: \"ContractRequest\",\n DkgInit: \"DkgInit\",\n DkgRound1: \"DkgRound1\",\n DkgRound2: \"DkgRound2\",\n DkgComplete: \"DkgComplete\",\n DelegateShare: \"DelegateShare\",\n DelegateAck: \"DelegateAck\",\n DepositConfirmed: \"DepositConfirmed\",\n Sync: \"Sync\",\n SyncRequired: \"SyncRequired\",\n Refill: \"Refill\",\n PayoutExecuted: \"PayoutExecuted\",\n WithdrawRequest: \"WithdrawRequest\",\n WithdrawAccepted: \"WithdrawAccepted\",\n WithdrawExecuted: \"WithdrawExecuted\",\n LpCommand: \"LpCommand\",\n Error: \"Error\",\n} as const;\n\nexport type CoordinatorMessageType =\n (typeof CoordinatorMessageType)[keyof typeof CoordinatorMessageType];\n\nexport type Envelope = {\n readonly version: typeof COORDINATOR_ENVELOPE_VERSION;\n readonly kind: EnvelopeKind;\n readonly type: CoordinatorMessageType;\n readonly swap_id: string | null;\n readonly req_id: number;\n readonly timestamp_ms: number;\n readonly payload: unknown;\n};\n\ntype ProtocolModule = {\n readonly ENVELOPE_VERSION: typeof COORDINATOR_ENVELOPE_VERSION;\n readonly EnvelopeKind: typeof EnvelopeKind;\n readonly CoordinatorMessageType: typeof CoordinatorMessageType;\n readonly encodeValidated: (envelope: Envelope) => Uint8Array;\n readonly decode: (raw: Uint8Array) => { ok: true; value: Envelope } | { ok: false; error: Error };\n readonly asErrorPayload: (envelope: Envelope) => {\n readonly code: string;\n readonly failed_req_id?: number;\n readonly message: string;\n };\n};\n\nlet protocolPromise: Promise<ProtocolModule> | null = null;\n\nfunction loadProtocol(): Promise<ProtocolModule> {\n protocolPromise ??= import(\"protocol/coordinator\") as Promise<ProtocolModule>;\n return protocolPromise;\n}\n\nexport type ProtocolLogDirection = \"in\" | \"out\" | \"info\";\nexport type ProtocolLogHandler = (message: string, direction: ProtocolLogDirection) => void;\nexport type ProtocolEnvelopeHandler = (envelope: Envelope) => void;\n\nexport interface RequestEnvelopeOptions {\n readonly swapId?: string | null;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly onLog?: ProtocolLogHandler;\n /** Reject this request when the coordinator reports a swap-scoped error without a request id. */\n readonly rejectMatchingOutOfBandErrors?: boolean;\n /** Contract allocation responses must carry the server-assigned swap_id. */\n readonly requireNonNullResponseSwapId?: boolean;\n}\n\nexport interface AwaitPushOptions {\n /** Exact business routing key. Omit only for legacy wildcard waiters. */\n readonly swapId?: string | null;\n readonly timeoutMs?: number | null;\n}\n\ntype PendingRequest = {\n readonly expectedSwapId: string | null;\n readonly resolve: (envelope: Envelope) => void;\n readonly reject: (error: Error) => void;\n readonly timer: ReturnType<typeof setTimeout> | null;\n readonly signal?: AbortSignal;\n readonly abortHandler?: () => void;\n readonly swapId: string | null;\n readonly rejectMatchingOutOfBandErrors: boolean;\n readonly requireNonNullResponseSwapId: boolean;\n};\n\ntype PushWaiter = {\n readonly swapId?: string | null;\n readonly resolve: (envelope: Envelope) => void;\n readonly reject: (error: Error) => void;\n readonly timer: ReturnType<typeof setTimeout> | null;\n};\n\ntype ProtocolRuntime = {\n reqCounter: number;\n readonly pending: Map<number, PendingRequest>;\n readonly pushWaiters: Map<CoordinatorMessageType, PushWaiter[]>;\n readonly envelopeHandlers: Set<ProtocolEnvelopeHandler>;\n unsubscribeChannel: Unsubscribe | null;\n unsubscribeTransport: Unsubscribe | null;\n};\n\nconst runtimes = new WeakMap<SessionState, ProtocolRuntime>();\n\nexport async function requestEnvelope(\n session: Session,\n type: CoordinatorMessageType,\n payload: unknown,\n options: RequestEnvelopeOptions = {},\n): Promise<Envelope> {\n throwIfRequestAborted(options.signal);\n const protocol = await loadProtocol();\n throwIfRequestAborted(options.signal);\n const state = getSessionState(session);\n const runtime = ensureProtocolRuntime(state);\n const channel = state.channel;\n if (!state.attested || channel === null) {\n throw new TransportError(\"CONNECTION_LOST\", \"coordinator request requires an attested channel\");\n }\n\n if (runtime.reqCounter >= MAX_COORDINATOR_REQUEST_ID) {\n throw new CommandError(\"REJECTED_STATE\", \"coordinator request id space exhausted\");\n }\n const reqId = runtime.reqCounter + 1;\n runtime.reqCounter = reqId;\n const envelope: Envelope = {\n version: protocol.ENVELOPE_VERSION,\n kind: protocol.EnvelopeKind.REQUEST,\n type,\n swap_id: options.swapId ?? null,\n req_id: reqId,\n timestamp_ms: Date.now(),\n payload,\n };\n const frame = protocol.encodeValidated(envelope);\n\n return new Promise((resolve, reject) => {\n const abortHandler =\n options.signal === undefined\n ? undefined\n : () => rejectPending(runtime, reqId, createRequestAbortError());\n const timer =\n options.timeoutMs === undefined\n ? null\n : setTimeout(() => {\n rejectPending(\n runtime,\n reqId,\n new CommandError(\n \"REJECTED_STALE_JOB\",\n `coordinator request timed out for ${type} after ${options.timeoutMs}ms`,\n ),\n );\n }, options.timeoutMs);\n\n runtime.pending.set(reqId, {\n expectedSwapId: options.swapId ?? null,\n resolve,\n reject,\n timer,\n signal: options.signal,\n abortHandler,\n swapId: envelope.swap_id,\n rejectMatchingOutOfBandErrors: options.rejectMatchingOutOfBandErrors === true,\n requireNonNullResponseSwapId: options.requireNonNullResponseSwapId === true,\n });\n if (abortHandler !== undefined) {\n options.signal?.addEventListener(\"abort\", abortHandler, { once: true });\n if (options.signal?.aborted === true) {\n abortHandler();\n return;\n }\n }\n options.onLog?.(`-> ${type} req_id=${reqId}`, \"out\");\n try {\n channel.send(frame);\n } catch (error) {\n rejectPending(runtime, reqId, error instanceof Error ? error : new Error(String(error)));\n }\n });\n}\n\nexport function awaitPush(\n session: Session,\n type: CoordinatorMessageType,\n options: AwaitPushOptions = {},\n): Promise<Envelope> {\n const state = getSessionState(session);\n const runtime = ensureProtocolRuntime(state);\n const timeoutMs = options.timeoutMs === undefined ? 30_000 : options.timeoutMs;\n\n return new Promise((resolve, reject) => {\n const timer =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n removePushWaiter(runtime, type, waiter);\n reject(new CommandError(\"REJECTED_STALE_JOB\", `timed out waiting for ${type} push`));\n }, timeoutMs);\n const waiter: PushWaiter = { swapId: options.swapId, resolve, reject, timer };\n const waiters = runtime.pushWaiters.get(type) ?? [];\n waiters.push(waiter);\n runtime.pushWaiters.set(type, waiters);\n });\n}\n\nexport function onEnvelope(session: Session, handler: ProtocolEnvelopeHandler): Unsubscribe {\n const runtime = ensureProtocolRuntime(getSessionState(session));\n runtime.envelopeHandlers.add(handler);\n return () => runtime.envelopeHandlers.delete(handler);\n}\n\nexport function closeProtocolRuntime(session: Session): void {\n const state = getSessionState(session);\n const runtime = runtimes.get(state);\n if (!runtime) return;\n const error = new TransportError(\"CONNECTION_LOST\", \"coordinator protocol runtime closed\");\n rejectAll(runtime, error);\n runtime.unsubscribeChannel?.();\n runtime.unsubscribeTransport?.();\n runtimes.delete(state);\n}\n\nfunction ensureProtocolRuntime(state: SessionState): ProtocolRuntime {\n const existing = runtimes.get(state);\n if (existing) return existing;\n\n const runtime: ProtocolRuntime = {\n reqCounter: 0,\n pending: new Map(),\n pushWaiters: new Map(),\n envelopeHandlers: new Set(),\n unsubscribeChannel: null,\n unsubscribeTransport: null,\n };\n\n if (state.channel === null) {\n throw new TransportError(\"CONNECTION_LOST\", \"coordinator protocol requires a live channel\");\n }\n runtime.unsubscribeChannel = state.channel.onMessage((frame) => handleFrame(runtime, frame));\n runtime.unsubscribeTransport = state.transport.onStateChange((transportState) => {\n if (transportState === \"closing\" || transportState === \"closed\") {\n rejectAll(runtime, new TransportError(\"CONNECTION_LOST\", \"coordinator transport closed\"));\n }\n });\n\n runtimes.set(state, runtime);\n return runtime;\n}\n\nfunction handleFrame(runtime: ProtocolRuntime, frame: Uint8Array): void {\n void handleFrameAsync(runtime, frame);\n}\n\nasync function handleFrameAsync(runtime: ProtocolRuntime, frame: Uint8Array): Promise<void> {\n const protocol = await loadProtocol();\n const decoded = protocol.decode(frame);\n if (!decoded.ok) {\n rejectAll(runtime, decoded.error);\n return;\n }\n\n const envelope = decoded.value;\n if (envelope.kind === protocol.EnvelopeKind.RESPONSE) {\n const pending = runtime.pending.get(envelope.req_id);\n if (pending && !pendingRequestMatchesSwapId(pending, envelope.swap_id)) {\n rejectPending(\n runtime,\n envelope.req_id,\n requestSwapIdMismatchError(envelope.req_id, pending.expectedSwapId, envelope.swap_id),\n );\n return;\n }\n }\n\n const errorPayload =\n envelope.kind === protocol.EnvelopeKind.ERROR ? protocol.asErrorPayload(envelope) : null;\n if (errorPayload?.failed_req_id !== undefined) {\n const pending = runtime.pending.get(errorPayload.failed_req_id);\n if (pending && !pendingRequestMatchesSwapId(pending, envelope.swap_id, false)) {\n rejectPending(\n runtime,\n errorPayload.failed_req_id,\n requestSwapIdMismatchError(\n errorPayload.failed_req_id,\n pending.expectedSwapId,\n envelope.swap_id,\n ),\n );\n return;\n }\n }\n\n for (const handler of runtime.envelopeHandlers) handler(envelope);\n\n if (envelope.kind === protocol.EnvelopeKind.ERROR) {\n const payload = errorPayload!;\n const error = commandErrorFromCoordinatorError(payload);\n if (payload.failed_req_id === undefined || payload.failed_req_id === OUT_OF_BAND_REQUEST_ID) {\n if (envelope.swap_id !== null) {\n rejectMatchingOutOfBandErrors(runtime, envelope.swap_id, error);\n }\n return;\n }\n const pending = runtime.pending.get(payload.failed_req_id);\n if (!pending) return;\n if (!pendingRequestMatchesSwapId(pending, envelope.swap_id, false)) {\n rejectPending(\n runtime,\n payload.failed_req_id,\n requestSwapIdMismatchError(payload.failed_req_id, pending.expectedSwapId, envelope.swap_id),\n );\n return;\n }\n rejectPending(runtime, payload.failed_req_id, error);\n return;\n }\n\n if (envelope.kind === protocol.EnvelopeKind.PUSH) {\n resolvePushWaiter(runtime, envelope);\n return;\n }\n\n if (envelope.kind !== protocol.EnvelopeKind.RESPONSE) return;\n const pending = runtime.pending.get(envelope.req_id);\n if (!pending) return;\n if (!pendingRequestMatchesSwapId(pending, envelope.swap_id)) {\n rejectPending(\n runtime,\n envelope.req_id,\n requestSwapIdMismatchError(envelope.req_id, pending.expectedSwapId, envelope.swap_id),\n );\n return;\n }\n runtime.pending.delete(envelope.req_id);\n cleanupPendingRequest(pending);\n pending.resolve(envelope);\n}\n\nfunction pendingRequestMatchesSwapId(\n pending: PendingRequest,\n responseSwapId: string | null,\n enforceNonNullResponseSwapId = true,\n): boolean {\n if (\n enforceNonNullResponseSwapId &&\n pending.requireNonNullResponseSwapId &&\n responseSwapId === null\n ) {\n return false;\n }\n return pending.expectedSwapId === null || pending.expectedSwapId === responseSwapId;\n}\n\nfunction requestSwapIdMismatchError(\n reqId: number,\n expectedSwapId: string | null,\n receivedSwapId: string | null,\n): CommandError {\n return new CommandError(\n \"REJECTED_STATE\",\n `coordinator response swap_id mismatch for req_id=${reqId}: expected ${expectedSwapId ?? \"null\"}, received ${receivedSwapId ?? \"null\"}`,\n { failedReqId: reqId },\n );\n}\n\nfunction resolvePushWaiter(runtime: ProtocolRuntime, envelope: Envelope): void {\n const waiters = runtime.pushWaiters.get(envelope.type);\n const waiterIndex = waiters?.findIndex(\n (candidate) => candidate.swapId === undefined || candidate.swapId === envelope.swap_id,\n );\n const waiter =\n waiters && waiterIndex !== undefined && waiterIndex >= 0\n ? waiters.splice(waiterIndex, 1)[0]\n : undefined;\n if (!waiter || !waiters) return;\n if (waiters.length === 0) {\n runtime.pushWaiters.delete(envelope.type);\n }\n if (waiter.timer) clearTimeout(waiter.timer);\n waiter.resolve(envelope);\n}\n\nfunction rejectPending(runtime: ProtocolRuntime, reqId: number, error: Error): void {\n const pending = runtime.pending.get(reqId);\n if (!pending) return;\n runtime.pending.delete(reqId);\n cleanupPendingRequest(pending);\n pending.reject(error);\n}\n\nfunction cleanupPendingRequest(pending: PendingRequest): void {\n if (pending.timer) clearTimeout(pending.timer);\n if (pending.signal !== undefined && pending.abortHandler !== undefined) {\n pending.signal.removeEventListener(\"abort\", pending.abortHandler);\n }\n}\n\nfunction throwIfRequestAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw createRequestAbortError();\n}\n\nfunction createRequestAbortError(): DOMException {\n return new DOMException(\"coordinator request aborted\", \"AbortError\");\n}\n\nfunction rejectMatchingOutOfBandErrors(\n runtime: ProtocolRuntime,\n swapId: string,\n error: Error,\n): void {\n for (const [reqId, pending] of runtime.pending) {\n if (!pending.rejectMatchingOutOfBandErrors || pending.swapId !== swapId) continue;\n rejectPending(runtime, reqId, error);\n }\n}\n\nfunction commandErrorFromCoordinatorError(payload: {\n readonly code: string;\n readonly failed_req_id?: number;\n readonly message: string;\n}): CommandError {\n const coordinatorCode = toCoordinatorWireErrorCode(payload.code);\n return new CommandError(commandCodeFromCoordinatorCode(coordinatorCode), payload.message, {\n coordinatorCode,\n ...(payload.failed_req_id !== undefined ? { failedReqId: payload.failed_req_id } : {}),\n });\n}\n\nfunction commandCodeFromCoordinatorCode(code: CoordinatorWireErrorCode): CommandErrorCode {\n switch (code) {\n case \"ERR_UNEXPECTED_TYPE\":\n case \"ERR_UNKNOWN_SWAP\":\n case \"ERR_SWAP_NOT_REFUNDABLE\":\n return \"REJECTED_STATE\";\n case \"ERR_INTERNAL\":\n case \"ERR_SETTLEMENT_FAILED\":\n return \"REJECTED_STALE_JOB\";\n case \"ERR_INVALID_PAYLOAD\":\n case \"ERR_POLICY_VIOLATION\":\n case \"ERR_INVALID_RECOVERY_CODE\":\n case \"ERR_DKG_FAILURE\":\n case \"ERR_INVALID_DEPOSIT\":\n return \"REJECTED_GUARD\";\n }\n}\n\nfunction toCoordinatorWireErrorCode(code: string): CoordinatorWireErrorCode {\n switch (code) {\n case \"ERR_INVALID_PAYLOAD\":\n case \"ERR_UNEXPECTED_TYPE\":\n case \"ERR_UNKNOWN_SWAP\":\n case \"ERR_POLICY_VIOLATION\":\n case \"ERR_INVALID_RECOVERY_CODE\":\n case \"ERR_SWAP_NOT_REFUNDABLE\":\n case \"ERR_DKG_FAILURE\":\n case \"ERR_INTERNAL\":\n case \"ERR_INVALID_DEPOSIT\":\n case \"ERR_SETTLEMENT_FAILED\":\n return code;\n default:\n return \"ERR_INTERNAL\";\n }\n}\n\nfunction removePushWaiter(\n runtime: ProtocolRuntime,\n type: CoordinatorMessageType,\n waiter: PushWaiter,\n): void {\n const waiters = runtime.pushWaiters.get(type);\n if (!waiters) return;\n const index = waiters.indexOf(waiter);\n if (index >= 0) waiters.splice(index, 1);\n if (waiters.length === 0) runtime.pushWaiters.delete(type);\n}\n\nfunction rejectAll(runtime: ProtocolRuntime, error: Error): void {\n for (const [reqId, pending] of runtime.pending.entries()) {\n runtime.pending.delete(reqId);\n cleanupPendingRequest(pending);\n pending.reject(error);\n }\n for (const [type, waiters] of runtime.pushWaiters.entries()) {\n runtime.pushWaiters.delete(type);\n for (const waiter of waiters) {\n if (waiter.timer) clearTimeout(waiter.timer);\n waiter.reject(error);\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {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AAM,OAAA;AACtB,EAAA,KAAA,CAAM,QAAA,GAAW,KAAA;AACjB,EAAA,KAAA,CAAM,WAAA,GAAc,IAAA;AACpB,EAAA,KAAA,CAAM,OAAA,GAAU,IAAA;AAChB,EAAA,KAAA,CAAM,KAAA,GAAQ,IAAA;AACd,EAAA,KAAA,CAAM,qBAAA,GAAwB,IAAA;AAE9B,EAAA,OAAA,EAAS,KAAA,EAAM;AACf,EAAA,KAAA,CAAM,UAAU,KAAA,EAAM;AAEtB,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,KAAA,MAAW,OAAA,IAAW,KAAA,CAAM,uBAAA,EAAyB,OAAA,CAAQ,KAAK,CAAA;AAAA,EACpE;AACF","file":"chunk-V5HXJRBW.js","sourcesContent":["/**\n * Internal session state and the opaque-handle registry.\n *\n * The public {@link Session} is opaque: consumers only read `session.attested`.\n * The real state (transport, endpoint pool, attestation result) is held here\n * and reached through {@link getSessionState}, keyed off the handle in a\n * `WeakMap` so it is never reachable from the public surface.\n */\n\nimport type { Session } from \"../core/session.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport type { AttestationResult } from \"../transport/handshake.js\";\nimport type { SecureChannel } from \"./secureChannel.js\";\nimport type { CoordinatorPoolConfig } from \"../schemas/types.generated.js\";\nimport { TransportError } from \"../core/errors.js\";\n\nexport interface SessionState {\n /** Flipped to `true` once attestation passes. */\n attested: boolean;\n /** The byte channel this session runs over. */\n readonly transport: Transport;\n /** The endpoint pool the session was created with. */\n readonly pool: CoordinatorPoolConfig;\n /** The last verified attestation result, or `null` before first attestation. */\n attestation: AttestationResult | null;\n /**\n * The live attested Noise channel, or `null` before/after attestation. All\n * application I/O Noise-encrypts through this.\n */\n channel: SecureChannel | null;\n /**\n * The per-connection 32-byte CSPRNG nonce bound into the attestation request.\n * Retained for re-attestation over the same channel.\n */\n nonce: Uint8Array | null;\n /** The coordinator's pinned Noise static public key, or `null` if unattested. */\n remoteStaticPublicKey: Uint8Array | null;\n /** Pending re-attestation timer, cleared on close. */\n reattestTimer: ReturnType<typeof setTimeout> | null;\n /** In-flight re-attestation shared by explicit and periodic checks. */\n reattestPromise: Promise<AttestationResult> | null;\n /** Fatal secure-channel cause preserved across transport close notifications. */\n lastFatalError: Error | null;\n /** Handlers invoked when an out-of-band re-attestation fails. */\n readonly policyViolationHandlers: Set<(error: Error) => void>;\n /** Tear down the session: clear the re-attest timer and close the channel. */\n close(): void;\n}\n\nconst registry = new WeakMap<Session, SessionState>();\n\n/** Build an opaque {@link Session} handle backed by `state`. */\nexport function createSessionHandle(state: SessionState): Session {\n const handle = {\n get attested() {\n return state.attested;\n },\n } as unknown as Session;\n registry.set(handle, state);\n return handle;\n}\n\n/**\n * Resolve the internal state for a session.\n *\n * @throws Error if the handle was not produced by `createSession`.\n */\nexport function getSessionState(session: Session): SessionState {\n const state = registry.get(session);\n if (!state) {\n throw new Error(\"invalid Session: this handle was not created by createSession\");\n }\n return state;\n}\n\nexport function closeSessionState(state: SessionState): void {\n failSessionClosed(state, new TransportError(\"CONNECTION_LOST\", \"session closed\"), {\n notifyPolicyViolation: false,\n });\n}\n\nexport function failSessionClosed(\n state: SessionState,\n cause: Error,\n options: { readonly notifyPolicyViolation?: boolean } = {},\n): void {\n const notifyPolicyViolation = options.notifyPolicyViolation ?? true;\n const shouldNotify =\n notifyPolicyViolation &&\n (state.attested || state.attestation !== null || state.channel !== null);\n\n if (state.reattestTimer !== null) {\n clearTimeout(state.reattestTimer);\n state.reattestTimer = null;\n }\n state.reattestPromise = null;\n state.lastFatalError = cause;\n\n const channel = state.channel;\n state.attested = false;\n state.attestation = null;\n state.channel = null;\n state.nonce = null;\n state.remoteStaticPublicKey = null;\n\n channel?.close();\n state.transport.close();\n\n if (shouldNotify) {\n for (const handler of state.policyViolationHandlers) handler(cause);\n }\n}\n"]}