@securitydept/client 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-transport-DtnSRWAH.mjs","names":[],"sources":["../src/errors/types.ts","../src/errors/client-error.ts","../src/logging/types.ts","../src/logging/operation-tracer.ts","../src/scheduling/default-clock.ts","../src/scheduling/default-scheduler.ts","../src/runtime/create-runtime.ts","../src/scheduling/helpers.ts","../src/web/input-sources.ts","../src/web/cancellation.ts","../src/transport/fetch-transport.ts"],"sourcesContent":["// --- Error model ---\n// Dual-layer: machine-facing runtime error + user-facing presentation / recovery hint.\n\n/** Recovery actions the user might take. Aligned with server-side `UserRecovery`. */\nexport const UserRecovery = {\n\tNone: \"none\",\n\tRetry: \"retry\",\n\tRestartFlow: \"restart_flow\",\n\tReauthenticate: \"reauthenticate\",\n\tContactSupport: \"contact_support\",\n} as const;\n\nexport type UserRecovery = (typeof UserRecovery)[keyof typeof UserRecovery];\n\n/** User-facing error presentation. `code` is the cross-platform stable contract. */\nexport interface ErrorPresentation {\n\tcode: string;\n\tmessage: string;\n\trecovery: UserRecovery;\n}\n\nexport const ErrorPresentationTone = {\n\tNeutral: \"neutral\",\n\tWarning: \"warning\",\n\tDanger: \"danger\",\n} as const;\n\nexport type ErrorPresentationTone =\n\t(typeof ErrorPresentationTone)[keyof typeof ErrorPresentationTone];\n\nexport interface ErrorPresentationActionDescriptor {\n\trecovery: UserRecovery;\n\tlabel: string;\n\thref: string | null;\n}\n\nexport interface ErrorPresentationDescriptor {\n\tcode: string | null;\n\tkind: ClientErrorKind | null;\n\tsource?: string;\n\ttitle: string;\n\tdescription: string;\n\trecovery: UserRecovery;\n\tretryable: boolean;\n\ttone: ErrorPresentationTone;\n\tprimaryAction: ErrorPresentationActionDescriptor | null;\n}\n\nexport interface ReadErrorPresentationDescriptorOptions {\n\tfallbackTitle?: string;\n\tfallbackDescription?: string;\n\trecoveryLinks?: Partial<Record<UserRecovery, string>>;\n\trecoveryLabels?: Partial<Record<UserRecovery, string>>;\n}\n\n/** Machine-facing error kind discriminator. */\nexport const ClientErrorKind = {\n\tAuthorization: \"authorization\",\n\tTransport: \"transport\",\n\tServer: \"server\",\n\tProtocol: \"protocol\",\n\tPresentation: \"presentation\",\n\tValidation: \"validation\",\n\tStorage: \"storage\",\n\tScheduler: \"scheduler\",\n\tConfiguration: \"configuration\",\n\tUnauthenticated: \"unauthenticated\",\n\tUnauthorized: \"unauthorized\",\n\tRedirectRequired: \"redirect_required\",\n\tCancelled: \"cancelled\",\n\tTimeout: \"timeout\",\n\tInternal: \"internal\",\n} as const;\n\nexport type ClientErrorKind =\n\t(typeof ClientErrorKind)[keyof typeof ClientErrorKind];\n\n/** Stable source vocabulary for common client error producers. */\nexport const ClientErrorSource = {\n\tTransport: \"transport\",\n\tServer: \"server\",\n\tClientRuntime: \"client_runtime\",\n} as const;\n\nexport type ClientErrorSource =\n\t(typeof ClientErrorSource)[keyof typeof ClientErrorSource];\n","import {\n\tClientErrorKind,\n\tClientErrorSource,\n\ttype ErrorPresentation,\n\tUserRecovery,\n\ttype UserRecovery as UserRecoveryType,\n} from \"./types\";\n\ntype ServerErrorBody = {\n\tkind?: string;\n\tcode?: string;\n\tmessage?: string;\n\trecovery?: string;\n\tpresentation?: {\n\t\tcode?: string;\n\t\tmessage?: string;\n\t\trecovery?: string;\n\t};\n};\n\nfunction mapServerErrorKind(\n\tkind: string | undefined,\n\tstatus: number,\n): ClientErrorKind {\n\tswitch (kind) {\n\t\tcase \"unauthenticated\":\n\t\t\treturn ClientErrorKind.Unauthenticated;\n\t\tcase \"unauthorized\":\n\t\t\treturn ClientErrorKind.Unauthorized;\n\t\tcase \"unavailable\":\n\t\tcase \"internal\":\n\t\t\treturn ClientErrorKind.Server;\n\t\tcase \"invalid_request\":\n\t\tcase \"conflict\":\n\t\t\treturn ClientErrorKind.Protocol;\n\t\tdefault:\n\t\t\treturn status === 401\n\t\t\t\t? ClientErrorKind.Unauthenticated\n\t\t\t\t: status === 403\n\t\t\t\t\t? ClientErrorKind.Unauthorized\n\t\t\t\t\t: status >= 500\n\t\t\t\t\t\t? ClientErrorKind.Server\n\t\t\t\t\t\t: ClientErrorKind.Protocol;\n\t}\n}\n\nfunction readServerErrorBody(body: unknown): ServerErrorBody | undefined {\n\tif (!body || typeof body !== \"object\") return undefined;\n\tconst record = body as Record<string, unknown>;\n\tconst error =\n\t\trecord.error && typeof record.error === \"object\"\n\t\t\t? (record.error as Record<string, unknown>)\n\t\t\t: record;\n\n\treturn {\n\t\tkind: typeof error.kind === \"string\" ? error.kind : undefined,\n\t\tcode: typeof error.code === \"string\" ? error.code : undefined,\n\t\tmessage: typeof error.message === \"string\" ? error.message : undefined,\n\t\trecovery: typeof error.recovery === \"string\" ? error.recovery : undefined,\n\t\tpresentation:\n\t\t\terror.presentation && typeof error.presentation === \"object\"\n\t\t\t\t? {\n\t\t\t\t\t\tcode:\n\t\t\t\t\t\t\ttypeof (error.presentation as Record<string, unknown>).code ===\n\t\t\t\t\t\t\t\"string\"\n\t\t\t\t\t\t\t\t? ((error.presentation as Record<string, unknown>)\n\t\t\t\t\t\t\t\t\t\t.code as string)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\ttypeof (error.presentation as Record<string, unknown>).message ===\n\t\t\t\t\t\t\t\"string\"\n\t\t\t\t\t\t\t\t? ((error.presentation as Record<string, unknown>)\n\t\t\t\t\t\t\t\t\t\t.message as string)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\trecovery:\n\t\t\t\t\t\t\ttypeof (error.presentation as Record<string, unknown>)\n\t\t\t\t\t\t\t\t.recovery === \"string\"\n\t\t\t\t\t\t\t\t? ((error.presentation as Record<string, unknown>)\n\t\t\t\t\t\t\t\t\t\t.recovery as string)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t};\n}\n\n/**\n * Base client error carrying both machine-facing context and an optional\n * user-facing presentation layer.\n *\n * Top-level `code` and `recovery` provide stable machine contracts for\n * policy decisions without requiring callers to unwrap `presentation`.\n */\nexport class ClientError extends Error {\n\treadonly kind: ClientErrorKind;\n\n\t/**\n\t * Stable machine-readable error code.\n\t * Matches `presentation.code` when present, otherwise a default\n\t * derived from `kind`.\n\t */\n\treadonly code: string;\n\n\t/** Recovery hint at the machine level. */\n\treadonly recovery: UserRecoveryType;\n\n\t/** Whether this error is safe to retry. */\n\treadonly retryable: boolean;\n\n\t/** Structured user-facing error presentation from the server. */\n\treadonly presentation?: ErrorPresentation;\n\n\t/** Source subsystem or component that produced the error. */\n\treadonly source?: string;\n\n\tconstructor(options: {\n\t\tkind: ClientErrorKind;\n\t\tmessage: string;\n\t\tcode?: string;\n\t\trecovery?: UserRecoveryType;\n\t\tretryable?: boolean;\n\t\tpresentation?: ErrorPresentation;\n\t\tsource?: string;\n\t\tcause?: unknown;\n\t}) {\n\t\tsuper(options.message, { cause: options.cause });\n\t\tthis.name = \"ClientError\";\n\t\tthis.kind = options.kind;\n\t\tthis.code =\n\t\t\toptions.code ?? options.presentation?.code ?? `client.${options.kind}`;\n\t\tthis.recovery =\n\t\t\toptions.recovery ?? options.presentation?.recovery ?? UserRecovery.None;\n\t\tthis.retryable = options.retryable ?? this.recovery === UserRecovery.Retry;\n\t\tthis.presentation = options.presentation;\n\t\tthis.source = options.source;\n\t}\n\n\t/** Create a `ClientError` from a server error response body. */\n\tstatic fromServerError(\n\t\tbody: {\n\t\t\tkind?: string;\n\t\t\tcode?: string;\n\t\t\tmessage?: string;\n\t\t\trecovery?: string;\n\t\t\tpresentation?: {\n\t\t\t\tcode?: string;\n\t\t\t\tmessage?: string;\n\t\t\t\trecovery?: string;\n\t\t\t};\n\t\t},\n\t\toverrides?: { kind?: ClientErrorKind; source?: string },\n\t): ClientError {\n\t\tconst rawPresentation = body.presentation;\n\t\tconst presentation: ErrorPresentation | undefined =\n\t\t\t(rawPresentation?.code ?? body.code) &&\n\t\t\t(rawPresentation?.message ?? body.message)\n\t\t\t\t? {\n\t\t\t\t\t\tcode: rawPresentation?.code ?? body.code ?? \"unknown_server_error\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\trawPresentation?.message ??\n\t\t\t\t\t\t\tbody.message ??\n\t\t\t\t\t\t\t\"Unknown server error\",\n\t\t\t\t\t\trecovery:\n\t\t\t\t\t\t\t(rawPresentation?.recovery as ErrorPresentation[\"recovery\"]) ??\n\t\t\t\t\t\t\t(body.recovery as ErrorPresentation[\"recovery\"]) ??\n\t\t\t\t\t\t\tUserRecovery.None,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\treturn new ClientError({\n\t\t\tkind: overrides?.kind ?? mapServerErrorKind(body.kind, 400),\n\t\t\tmessage: presentation?.message ?? body.message ?? \"Unknown server error\",\n\t\t\tpresentation,\n\t\t\tsource: overrides?.source,\n\t\t});\n\t}\n\n\t/**\n\t * Create a `ClientError` from an HTTP response status and optional body.\n\t * Used when a non-success status is unexpected.\n\t */\n\tstatic fromHttpResponse(status: number, body?: unknown): ClientError {\n\t\tconst serverBody = readServerErrorBody(body);\n\n\t\t// Derive kind and source from HTTP status first — these apply\n\t\t// whether or not the response carries a structured error body.\n\t\tconst kind = mapServerErrorKind(serverBody?.kind, status);\n\n\t\tconst source =\n\t\t\tstatus >= 500\n\t\t\t\t? ClientErrorSource.Server\n\t\t\t\t: ClientErrorSource.ClientRuntime;\n\n\t\t// If the server returned a structured error body, preserve it\n\t\t// but keep the status-derived kind/source.\n\t\tif (serverBody?.code && serverBody?.message) {\n\t\t\treturn ClientError.fromServerError(serverBody, { kind, source });\n\t\t}\n\n\t\tconst recovery: UserRecoveryType =\n\t\t\tkind === ClientErrorKind.Unauthenticated\n\t\t\t\t? UserRecovery.Reauthenticate\n\t\t\t\t: status >= 500\n\t\t\t\t\t? UserRecovery.Retry\n\t\t\t\t\t: UserRecovery.None;\n\n\t\treturn new ClientError({\n\t\t\tkind,\n\t\t\tmessage: serverBody?.message ?? `HTTP ${status}`,\n\t\t\tcode: serverBody?.code ?? `http.${status}`,\n\t\t\trecovery,\n\t\t\tretryable: status >= 500,\n\t\t\tsource,\n\t\t});\n\t}\n}\n","// --- Logging and observability ---\n\nexport const LogLevel = {\n\tDebug: \"debug\",\n\tInfo: \"info\",\n\tWarn: \"warn\",\n\tError: \"error\",\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\nexport interface LogEntry {\n\tlevel: LogLevel;\n\tmessage: string;\n\tscope?: string;\n\tcode?: string;\n\tattributes?: Record<string, unknown>;\n\terror?: unknown;\n\tat?: number;\n}\n\nexport interface LoggerTrait {\n\tlog(entry: LogEntry): void;\n}\n\nexport const OperationTraceEventType = {\n\tStarted: \"operation.started\",\n\tEvent: \"operation.event\",\n\tError: \"operation.error\",\n\tEnded: \"operation.ended\",\n} as const;\n\nexport type OperationTraceEventType =\n\t(typeof OperationTraceEventType)[keyof typeof OperationTraceEventType];\n\nexport interface TraceEvent {\n\ttype: string;\n\tat: number;\n\tscope?: string;\n\toperationId?: string;\n\tsource?: string;\n\tattributes?: Record<string, unknown>;\n}\n\nexport interface TraceEventSinkTrait {\n\trecord(event: TraceEvent): void;\n}\n\nexport interface OperationScope {\n\tid: string;\n\taddEvent(type: string, attributes?: Record<string, unknown>): void;\n\tsetAttribute(key: string, value: unknown): void;\n\trecordError(error: unknown, attributes?: Record<string, unknown>): void;\n\tend(attributes?: Record<string, unknown>): void;\n}\n\nexport interface OperationTracerTrait {\n\tstartOperation(\n\t\tname: string,\n\t\tattributes?: Record<string, unknown>,\n\t): OperationScope;\n}\n","import type { Clock } from \"../scheduling/types\";\nimport type {\n\tLoggerTrait,\n\tOperationScope,\n\tOperationTracerTrait,\n\tTraceEventSinkTrait,\n} from \"./types\";\nimport { LogLevel, OperationTraceEventType } from \"./types\";\n\nexport interface CreateOperationTracerOptions {\n\ttraceSink?: TraceEventSinkTrait;\n\tlogger?: LoggerTrait;\n\tclock?: Clock;\n\tscope?: string;\n\tsource?: string;\n\tidFactory?: () => string;\n}\n\nconst defaultClock: Clock = {\n\tnow: () => Date.now(),\n};\n\nfunction createDefaultOperationId(): string {\n\treturn `op_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nclass DefaultOperationScope implements OperationScope {\n\treadonly id: string;\n\n\tprivate readonly _attributes: Record<string, unknown>;\n\tprivate _ended = false;\n\n\tconstructor(\n\t\tprivate readonly _name: string,\n\t\tprivate readonly _clock: Clock,\n\t\tprivate readonly _traceSink: TraceEventSinkTrait | undefined,\n\t\tprivate readonly _logger: LoggerTrait | undefined,\n\t\tprivate readonly _scope: string | undefined,\n\t\tprivate readonly _source: string | undefined,\n\t\tidFactory: () => string,\n\t\tattributes?: Record<string, unknown>,\n\t) {\n\t\tthis.id = idFactory();\n\t\tthis._attributes = { ...(attributes ?? {}) };\n\t\tthis._recordTrace(OperationTraceEventType.Started, {\n\t\t\toperationName: this._name,\n\t\t\t...this._attributes,\n\t\t});\n\t}\n\n\taddEvent(type: string, attributes?: Record<string, unknown>): void {\n\t\tthis._recordTrace(OperationTraceEventType.Event, {\n\t\t\toperationName: this._name,\n\t\t\teventType: type,\n\t\t\t...this._attributes,\n\t\t\t...(attributes ?? {}),\n\t\t});\n\t}\n\n\tsetAttribute(key: string, value: unknown): void {\n\t\tthis._attributes[key] = value;\n\t}\n\n\trecordError(error: unknown, attributes?: Record<string, unknown>): void {\n\t\tconst errorAttributes = describeError(error);\n\t\tthis._recordTrace(OperationTraceEventType.Error, {\n\t\t\toperationName: this._name,\n\t\t\t...this._attributes,\n\t\t\t...errorAttributes,\n\t\t\t...(attributes ?? {}),\n\t\t});\n\t\tthis._logger?.log({\n\t\t\tlevel: LogLevel.Error,\n\t\t\tmessage: `Operation failed: ${this._name}`,\n\t\t\tscope: this._scope,\n\t\t\tattributes: {\n\t\t\t\toperationId: this.id,\n\t\t\t\toperationName: this._name,\n\t\t\t\t...this._attributes,\n\t\t\t\t...errorAttributes,\n\t\t\t\t...(attributes ?? {}),\n\t\t\t},\n\t\t\terror,\n\t\t\tat: this._clock.now(),\n\t\t});\n\t}\n\n\tend(attributes?: Record<string, unknown>): void {\n\t\tif (this._ended) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._ended = true;\n\t\tthis._recordTrace(OperationTraceEventType.Ended, {\n\t\t\toperationName: this._name,\n\t\t\t...this._attributes,\n\t\t\t...(attributes ?? {}),\n\t\t});\n\t}\n\n\tprivate _recordTrace(\n\t\ttype: string,\n\t\tattributes?: Record<string, unknown>,\n\t): void {\n\t\tthis._traceSink?.record({\n\t\t\ttype,\n\t\t\tat: this._clock.now(),\n\t\t\tscope: this._scope,\n\t\t\tsource: this._source,\n\t\t\toperationId: this.id,\n\t\t\tattributes,\n\t\t});\n\t}\n}\n\nexport function createOperationTracer(\n\toptions: CreateOperationTracerOptions = {},\n): OperationTracerTrait {\n\tconst clock = options.clock ?? defaultClock;\n\tconst idFactory = options.idFactory ?? createDefaultOperationId;\n\n\treturn {\n\t\tstartOperation(name, attributes) {\n\t\t\treturn new DefaultOperationScope(\n\t\t\t\tname,\n\t\t\t\tclock,\n\t\t\t\toptions.traceSink,\n\t\t\t\toptions.logger,\n\t\t\t\toptions.scope,\n\t\t\t\toptions.source,\n\t\t\t\tidFactory,\n\t\t\t\tattributes,\n\t\t\t);\n\t\t},\n\t};\n}\n\nfunction describeError(error: unknown): Record<string, unknown> {\n\tif (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"name\" in error &&\n\t\t\"message\" in error\n\t) {\n\t\tconst genericError = error as Pick<Error, \"name\" | \"message\">;\n\t\treturn {\n\t\t\terrorName: genericError.name,\n\t\t\terrorMessage: genericError.message,\n\t\t};\n\t}\n\n\treturn { errorValue: String(error) };\n}\n","import type { Clock } from \"./types\";\n\n/** Default clock backed by `Date.now()`. */\nexport function createDefaultClock(): Clock {\n\treturn {\n\t\tnow() {\n\t\t\treturn Date.now();\n\t\t},\n\t};\n}\n","import type { CancelableHandle, Scheduler } from \"./types\";\n\n/** Default scheduler backed by platform `setTimeout`. */\nexport function createDefaultScheduler(): Scheduler {\n\treturn {\n\t\tsetTimeout(delayMs: number, fn: () => void): CancelableHandle {\n\t\t\tconst id = globalThis.setTimeout(fn, delayMs);\n\t\t\treturn {\n\t\t\t\tcancel() {\n\t\t\t\t\tglobalThis.clearTimeout(id);\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n","import { createOperationTracer } from \"../logging/operation-tracer\";\nimport { createDefaultClock } from \"../scheduling/default-clock\";\nimport { createDefaultScheduler } from \"../scheduling/default-scheduler\";\nimport type { HttpTransport } from \"../transport/types\";\nimport type { ClientRuntime } from \"./types\";\n\nexport interface CreateRuntimeOptions\n\textends Partial<Omit<ClientRuntime, \"transport\">> {\n\ttransport: HttpTransport;\n}\n\n/**\n * Create a `ClientRuntime` with non-host-specific defaults filled in for\n * convenience.\n *\n * Host-specific capabilities such as browser `fetch` should be supplied\n * explicitly or composed via adapter-specific helpers such as\n * `@securitydept/client/web`.\n */\nexport function createRuntime(overrides: CreateRuntimeOptions): ClientRuntime {\n\tconst clock = overrides.clock ?? createDefaultClock();\n\tconst traceSink = overrides.traceSink;\n\tconst logger = overrides.logger;\n\n\treturn {\n\t\ttransport: overrides.transport,\n\t\tscheduler: overrides.scheduler ?? createDefaultScheduler(),\n\t\tclock,\n\t\tlogger,\n\t\ttraceSink,\n\t\toperationTracer:\n\t\t\toverrides.operationTracer ??\n\t\t\tcreateOperationTracer({\n\t\t\t\tclock,\n\t\t\t\tlogger,\n\t\t\t\ttraceSink,\n\t\t\t}),\n\t\tpersistentStore: overrides.persistentStore,\n\t\tsessionStore: overrides.sessionStore,\n\t};\n}\n","// Scheduling helpers — foundation-owned convenience over raw Scheduler.\n//\n// These helpers sit above the injectable Scheduler / Clock and provide\n// reusable, cancelable wrappers for common scheduling patterns.\n\nimport type { ReadableSignalTrait } from \"../signals/types\";\nimport type { CancelableHandle, Clock, Scheduler } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Shared types\n// ---------------------------------------------------------------------------\n\n/** Subscription handle returned by input-source adapters. */\nexport interface Subscription {\n\t/** Unsubscribe and release resources. */\n\tunsubscribe(): void;\n}\n\nexport interface FromSignalOptions<T> {\n\t/** Signal to observe. */\n\tsignal: ReadableSignalTrait<T>;\n\t/** Callback invoked when the signal value changes. */\n\tcallback: (value: T) => void;\n\t/**\n\t * Emit the current snapshot immediately after subscription.\n\t * Defaults to `false`.\n\t */\n\temitInitialValue?: boolean;\n}\n\nexport const PromiseSettlementKind = {\n\tFulfilled: \"fulfilled\",\n\tRejected: \"rejected\",\n} as const;\n\nexport type PromiseSettlementKind =\n\t(typeof PromiseSettlementKind)[keyof typeof PromiseSettlementKind];\n\nexport type PromiseSettlement<T> =\n\t| {\n\t\t\tkind: typeof PromiseSettlementKind.Fulfilled;\n\t\t\tvalue: T;\n\t }\n\t| {\n\t\t\tkind: typeof PromiseSettlementKind.Rejected;\n\t\t\treason: unknown;\n\t };\n\nexport interface FromPromiseOptions<T> {\n\t/** Promise-like source to observe. */\n\tpromise: PromiseLike<T>;\n\t/** Callback invoked when the promise settles. */\n\tcallback: (settlement: PromiseSettlement<T>) => void;\n}\n\n// ---------------------------------------------------------------------------\n// timer\n// ---------------------------------------------------------------------------\n\n/** Options for {@link timer}. */\nexport interface TimerOptions {\n\t/** Scheduler to use (platform default if omitted). */\n\tscheduler: Scheduler;\n\t/** Delay in milliseconds. */\n\tdelayMs: number;\n\t/** Callback to invoke after the delay. */\n\tcallback: () => void;\n}\n\n/**\n * Schedule a one-shot callback after a delay.\n *\n * Returns a {@link CancelableHandle} that can cancel the pending timer.\n *\n * @example\n * ```ts\n * const handle = timer({\n * scheduler: runtime.scheduler,\n * delayMs: 5000,\n * callback: () => console.log(\"fired\"),\n * });\n * // Cancel before it fires:\n * handle.cancel();\n * ```\n */\nexport function timer(options: TimerOptions): CancelableHandle {\n\treturn options.scheduler.setTimeout(options.delayMs, options.callback);\n}\n\n// ---------------------------------------------------------------------------\n// interval\n// ---------------------------------------------------------------------------\n\n/** Options for {@link interval}. */\nexport interface IntervalOptions {\n\t/** Scheduler to use. */\n\tscheduler: Scheduler;\n\t/** Interval period in milliseconds. */\n\tperiodMs: number;\n\t/** Callback to invoke on each tick. */\n\tcallback: () => void;\n}\n\n/**\n * Schedule a repeating callback at a fixed interval.\n *\n * Built on top of `Scheduler.setTimeout` so it works with deterministic\n * test schedulers. Returns a {@link CancelableHandle} to stop the interval.\n *\n * @example\n * ```ts\n * const handle = interval({\n * scheduler: runtime.scheduler,\n * periodMs: 30_000,\n * callback: () => refreshTokens(),\n * });\n * // Stop:\n * handle.cancel();\n * ```\n */\nexport function interval(options: IntervalOptions): CancelableHandle {\n\tlet canceled = false;\n\tlet currentHandle: CancelableHandle | null = null;\n\n\tfunction tick(): void {\n\t\tif (canceled) return;\n\t\toptions.callback();\n\t\tscheduleNext();\n\t}\n\n\tfunction scheduleNext(): void {\n\t\tif (canceled) return;\n\t\tcurrentHandle = options.scheduler.setTimeout(options.periodMs, tick);\n\t}\n\n\t// Start the first tick.\n\tscheduleNext();\n\n\treturn {\n\t\tcancel() {\n\t\t\tcanceled = true;\n\t\t\tcurrentHandle?.cancel();\n\t\t\tcurrentHandle = null;\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// scheduleAt\n// ---------------------------------------------------------------------------\n\n/** Options for {@link scheduleAt}. */\nexport interface ScheduleAtOptions {\n\t/** Scheduler to use. */\n\tscheduler: Scheduler;\n\t/** Clock to use for computing the delay. */\n\tclock: Clock;\n\t/** Target epoch milliseconds at which the callback should fire. */\n\tatMs: number;\n\t/** Callback to invoke at (or after) the target time. */\n\tcallback: () => void;\n}\n\n/**\n * Schedule a callback at a specific wall-clock time.\n *\n * Computes the delay from `clock.now()` to `atMs` and delegates to\n * `Scheduler.setTimeout`. If the target time is already in the past,\n * the callback fires on the next scheduler tick (delay 0).\n *\n * @example\n * ```ts\n * const handle = scheduleAt({\n * scheduler: runtime.scheduler,\n * clock: runtime.clock,\n * atMs: tokenExpiresAtMs - 30_000,\n * callback: () => refreshToken(),\n * });\n * ```\n */\nexport function scheduleAt(options: ScheduleAtOptions): CancelableHandle {\n\tconst delay = Math.max(0, options.atMs - options.clock.now());\n\treturn options.scheduler.setTimeout(delay, options.callback);\n}\n\n// ---------------------------------------------------------------------------\n// fromSignal\n// ---------------------------------------------------------------------------\n\n/**\n * Adapt an SDK signal into the shared {@link Subscription} callback model.\n *\n * @example\n * ```ts\n * const sub = fromSignal({\n * signal: authState,\n * callback: (snapshot) => console.log(snapshot),\n * });\n * sub.unsubscribe();\n * ```\n */\nexport function fromSignal<T>(options: FromSignalOptions<T>): Subscription {\n\tif (options.emitInitialValue) {\n\t\toptions.callback(options.signal.get());\n\t}\n\n\tconst unsubscribe = options.signal.subscribe(() => {\n\t\toptions.callback(options.signal.get());\n\t});\n\n\treturn {\n\t\tunsubscribe() {\n\t\t\tunsubscribe();\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// fromPromise\n// ---------------------------------------------------------------------------\n\n/**\n * Adapt a promise settlement into the shared {@link Subscription} callback model.\n *\n * This helper is intentionally thin: it reports one settlement and lets the\n * consumer decide how to model pending/fulfilled/error state.\n *\n * @example\n * ```ts\n * const sub = fromPromise({\n * promise: fetchConfig(),\n * callback: (settlement) => {\n * if (settlement.kind === PromiseSettlementKind.Fulfilled) {\n * console.log(settlement.value);\n * }\n * },\n * });\n * sub.unsubscribe();\n * ```\n */\nexport function fromPromise<T>(options: FromPromiseOptions<T>): Subscription {\n\tlet active = true;\n\n\tvoid Promise.resolve(options.promise).then(\n\t\t(value) => {\n\t\t\tif (!active) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.callback({\n\t\t\t\tkind: PromiseSettlementKind.Fulfilled,\n\t\t\t\tvalue,\n\t\t\t});\n\t\t},\n\t\t(reason) => {\n\t\t\tif (!active) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.callback({\n\t\t\t\tkind: PromiseSettlementKind.Rejected,\n\t\t\t\treason,\n\t\t\t});\n\t\t},\n\t);\n\n\treturn {\n\t\tunsubscribe() {\n\t\t\tactive = false;\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// fromEventPattern\n// ---------------------------------------------------------------------------\n\n/** Options for {@link fromEventPattern}. */\nexport interface FromEventPatternOptions<T> {\n\t/**\n\t * Called to install the event listener. Should return whatever handle\n\t * is needed by `removeHandler` to unsubscribe.\n\t */\n\taddHandler: (handler: (value: T) => void) => void;\n\t/**\n\t * Called to uninstall the event listener.\n\t */\n\tremoveHandler: (handler: (value: T) => void) => void;\n\t/** Callback invoked each time the event fires. */\n\tcallback: (value: T) => void;\n}\n\n/**\n * Adapt an arbitrary add/remove event pattern into a {@link Subscription}.\n *\n * This is a thin bridge between imperative event APIs (e.g. `addEventListener`\n * / `removeEventListener`) and the SDK's subscription model.\n *\n * @example\n * ```ts\n * const sub = fromEventPattern<Event>({\n * addHandler: (h) => document.addEventListener(\"visibilitychange\", h),\n * removeHandler: (h) => document.removeEventListener(\"visibilitychange\", h),\n * callback: () => onVisibilityChange(),\n * });\n * // Cleanup:\n * sub.unsubscribe();\n * ```\n */\nexport function fromEventPattern<T>(\n\toptions: FromEventPatternOptions<T>,\n): Subscription {\n\tconst handler = (value: T): void => {\n\t\toptions.callback(value);\n\t};\n\toptions.addHandler(handler);\n\treturn {\n\t\tunsubscribe() {\n\t\t\toptions.removeHandler(handler);\n\t\t},\n\t};\n}\n","import { fromEventPattern, type Subscription } from \"../scheduling/helpers\";\n\nexport interface AbortSignalSource {\n\taborted: boolean;\n\treason: unknown;\n\taddEventListener(type: string, listener: EventListener): void;\n\tremoveEventListener(type: string, listener: EventListener): void;\n}\n\nexport interface FromAbortSignalOptions {\n\t/** AbortSignal to observe. */\n\tsignal?: AbortSignalSource;\n\t/** Callback invoked when the signal aborts. */\n\tcallback: (reason: unknown) => void;\n\t/**\n\t * Emit immediately when the signal is already aborted at subscribe time.\n\t * Defaults to `false`.\n\t */\n\temitIfAborted?: boolean;\n}\n\nexport interface StorageEventTarget {\n\taddEventListener(type: string, listener: EventListener): void;\n\tremoveEventListener(type: string, listener: EventListener): void;\n}\n\nexport interface FromStorageEventOptions {\n\t/**\n\t * Storage-event target. Defaults to `globalThis`, which is appropriate for\n\t * browser hosts and jsdom-based tests.\n\t */\n\ttarget?: StorageEventTarget;\n\t/** Callback invoked for each browser `storage` event. */\n\tcallback: (event: StorageEvent) => void;\n}\n\n/**\n * Adapt a browser AbortSignal into the shared Subscription model.\n */\nexport function fromAbortSignal(options: FromAbortSignalOptions): Subscription {\n\tconst signal = options.signal;\n\tif (!signal) {\n\t\treturn {\n\t\t\tunsubscribe() {},\n\t\t};\n\t}\n\n\tif (options.emitIfAborted && signal.aborted) {\n\t\toptions.callback(signal.reason);\n\t}\n\n\treturn fromEventPattern<Event>({\n\t\taddHandler: (handler) => {\n\t\t\tsignal.addEventListener(\"abort\", handler);\n\t\t},\n\t\tremoveHandler: (handler) => {\n\t\t\tsignal.removeEventListener(\"abort\", handler);\n\t\t},\n\t\tcallback: () => {\n\t\t\toptions.callback(signal.reason);\n\t\t},\n\t});\n}\n\n/**\n * Adapt browser `storage` events into the shared Subscription model.\n */\nexport function fromStorageEvent(\n\toptions: FromStorageEventOptions,\n): Subscription {\n\tconst target = options.target ?? (globalThis as StorageEventTarget);\n\n\treturn fromEventPattern<Event>({\n\t\taddHandler: (handler) => {\n\t\t\ttarget.addEventListener(\"storage\", handler);\n\t\t},\n\t\tremoveHandler: (handler) => {\n\t\t\ttarget.removeEventListener(\"storage\", handler);\n\t\t},\n\t\tcallback: (event) => {\n\t\t\toptions.callback(event as StorageEvent);\n\t\t},\n\t});\n}\n","import type {\n\tCancellationTokenTrait,\n\tDisposableTrait,\n} from \"../cancellation/types\";\nimport { ClientError } from \"../errors/client-error\";\nimport { ClientErrorKind, ClientErrorSource } from \"../errors/types\";\nimport { fromAbortSignal } from \"./input-sources\";\n\nexport interface AbortSignalBridge {\n\tsignal?: AbortSignal;\n\tdispose(): void;\n}\n\n/**\n * Bridge a web `AbortSignal` back into the foundation cancellation contract.\n *\n * This is the canonical consumer-side path for browser hosts that receive an\n * `AbortSignal` from framework/runtime APIs (for example React Query queryFns)\n * but need to call SDK surfaces that accept `CancellationTokenTrait`.\n */\nexport function createCancellationTokenFromAbortSignal(\n\tsignal?: AbortSignal,\n): CancellationTokenTrait | undefined {\n\tif (!signal) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tget isCancellationRequested() {\n\t\t\treturn signal.aborted;\n\t\t},\n\t\tget reason() {\n\t\t\treturn signal.reason;\n\t\t},\n\t\tonCancellationRequested(listener: (reason: unknown) => void) {\n\t\t\tconst subscription = fromAbortSignal({\n\t\t\t\tsignal,\n\t\t\t\tcallback: listener,\n\t\t\t\temitIfAborted: true,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tdispose() {\n\t\t\t\t\tsubscription.unsubscribe();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\tthrowIfCancellationRequested() {\n\t\t\tif (signal.aborted) {\n\t\t\t\tthrow new ClientError({\n\t\t\t\t\tkind: ClientErrorKind.Cancelled,\n\t\t\t\t\tmessage: \"Request was cancelled via AbortSignal\",\n\t\t\t\t\tcode: \"client.cancelled\",\n\t\t\t\t\tsource: ClientErrorSource.Transport,\n\t\t\t\t\tcause: signal.reason,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Bridge foundation cancellation to web `AbortSignal` without exposing\n * `AbortSignal` in core contracts.\n */\nexport function createAbortSignalBridge(\n\ttoken?: CancellationTokenTrait,\n): AbortSignalBridge {\n\tif (!token) {\n\t\treturn {\n\t\t\tsignal: undefined,\n\t\t\tdispose() {},\n\t\t};\n\t}\n\n\tconst controller = new AbortController();\n\tlet subscription: DisposableTrait | null = token.onCancellationRequested(\n\t\t(reason) => {\n\t\t\tcontroller.abort(reason);\n\t\t},\n\t);\n\n\tif (token.isCancellationRequested) {\n\t\tcontroller.abort(token.reason);\n\t}\n\n\treturn {\n\t\tsignal: controller.signal,\n\t\tdispose() {\n\t\t\tsubscription?.dispose();\n\t\t\tsubscription = null;\n\t\t},\n\t};\n}\n\nexport function normalizeAbortError(\n\ttoken: CancellationTokenTrait | undefined,\n\terror: unknown,\n): unknown {\n\tif (!isAbortError(error) && !token?.isCancellationRequested) {\n\t\treturn error;\n\t}\n\n\tconst reason = token?.reason;\n\tif (reason instanceof ClientError) {\n\t\treturn reason;\n\t}\n\n\tif (reason instanceof Error) {\n\t\treturn new ClientError({\n\t\t\tkind: ClientErrorKind.Cancelled,\n\t\t\tmessage: reason.message,\n\t\t\tcode: \"client.cancelled\",\n\t\t\tsource: ClientErrorSource.Transport,\n\t\t\tcause: reason,\n\t\t});\n\t}\n\n\treturn new ClientError({\n\t\tkind: ClientErrorKind.Cancelled,\n\t\tmessage: \"HTTP request was cancelled\",\n\t\tcode: \"client.cancelled\",\n\t\tsource: ClientErrorSource.Transport,\n\t\tcause: reason ?? error,\n\t});\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"name\" in error &&\n\t\terror.name === \"AbortError\"\n\t);\n}\n","import {\n\tcreateAbortSignalBridge,\n\tnormalizeAbortError,\n} from \"../web/cancellation\";\nimport type { HttpRequest, HttpResponse, HttpTransport } from \"./types\";\n\nexport const FetchTransportRedirectKind = {\n\tFollow: \"follow\",\n\tManual: \"manual\",\n} as const;\n\nexport type FetchTransportRedirectKind =\n\t(typeof FetchTransportRedirectKind)[keyof typeof FetchTransportRedirectKind];\n\nexport interface FetchTransportOptions {\n\t/**\n\t * How to handle HTTP redirects.\n\t * - `\"follow\"`: automatically follow redirects (default fetch behavior)\n\t * - `\"manual\"`: capture redirect responses as-is (needed for fragment-based protocols)\n\t */\n\tredirect?: FetchTransportRedirectKind;\n}\n\n/**\n * Default `HttpTransport` backed by the global `fetch` API.\n *\n * The caller is responsible for ensuring `fetch` is available in the runtime.\n * No polyfill is injected — see the polyfill strategy in the design guide.\n */\nexport function createFetchTransport(\n\toptions: FetchTransportOptions = {},\n): HttpTransport {\n\tconst redirect = options.redirect ?? FetchTransportRedirectKind.Manual;\n\n\treturn {\n\t\tasync execute(request: HttpRequest): Promise<HttpResponse> {\n\t\t\tconst abortBridge = createAbortSignalBridge(request.cancellationToken);\n\t\t\tconst init: RequestInit = {\n\t\t\t\tmethod: request.method,\n\t\t\t\theaders: request.headers,\n\t\t\t\tredirect,\n\t\t\t\tsignal: abortBridge.signal,\n\t\t\t};\n\n\t\t\tif (\n\t\t\t\trequest.body !== undefined &&\n\t\t\t\trequest.method !== \"GET\" &&\n\t\t\t\trequest.method !== \"HEAD\"\n\t\t\t) {\n\t\t\t\tinit.body =\n\t\t\t\t\ttypeof request.body === \"string\"\n\t\t\t\t\t\t? request.body\n\t\t\t\t\t\t: JSON.stringify(request.body);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst res = await fetch(request.url, init);\n\n\t\t\t\tconst responseHeaders: Record<string, string> = {};\n\t\t\t\tres.headers.forEach((value, key) => {\n\t\t\t\t\tresponseHeaders[key] = value;\n\t\t\t\t});\n\n\t\t\t\tlet body: unknown;\n\t\t\t\tconst contentType = res.headers.get(\"content-type\");\n\t\t\t\tif (contentType?.includes(\"application/json\")) {\n\t\t\t\t\tbody = await res.json();\n\t\t\t\t} else if (\n\t\t\t\t\tres.status !== 302 &&\n\t\t\t\t\tres.status !== 303 &&\n\t\t\t\t\tres.status !== 301\n\t\t\t\t) {\n\t\t\t\t\tbody = await res.text();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tstatus: res.status,\n\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\tbody,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeAbortError(request.cancellationToken, error);\n\t\t\t} finally {\n\t\t\t\tabortBridge.dispose();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SACV,MAAM,SAAS;;;;AC7HjB,MAAa,6BAA6B;CACzC,QAAQ;CACR,QAAQ;CACR;;;;;;;AAoBD,SAAgB,qBACf,UAAiC,EAAE,EACnB;CAChB,MAAM,WAAW,QAAQ,YAAY,2BAA2B;AAEhE,QAAO,EACN,MAAM,QAAQ,SAA6C;EAC1D,MAAM,cAAc,wBAAwB,QAAQ,kBAAkB;EACtE,MAAM,OAAoB;GACzB,QAAQ,QAAQ;GAChB,SAAS,QAAQ;GACjB;GACA,QAAQ,YAAY;GACpB;AAED,MACC,QAAQ,SAAS,KAAA,KACjB,QAAQ,WAAW,SACnB,QAAQ,WAAW,OAEnB,MAAK,OACJ,OAAO,QAAQ,SAAS,WACrB,QAAQ,OACR,KAAK,UAAU,QAAQ,KAAK;AAGjC,MAAI;GACH,MAAM,MAAM,MAAM,MAAM,QAAQ,KAAK,KAAK;GAE1C,MAAM,kBAA0C,EAAE;AAClD,OAAI,QAAQ,SAAS,OAAO,QAAQ;AACnC,oBAAgB,OAAO;KACtB;GAEF,IAAI;AAEJ,OADoB,IAAI,QAAQ,IAAI,eAAe,EAClC,SAAS,mBAAmB,CAC5C,QAAO,MAAM,IAAI,MAAM;YAEvB,IAAI,WAAW,OACf,IAAI,WAAW,OACf,IAAI,WAAW,IAEf,QAAO,MAAM,IAAI,MAAM;AAGxB,UAAO;IACN,QAAQ,IAAI;IACZ,SAAS;IACT;IACA;WACO,OAAO;AACf,SAAM,oBAAoB,QAAQ,mBAAmB,MAAM;YAClD;AACT,eAAY,SAAS;;IAGvB"}
@@ -0,0 +1,39 @@
1
+ import { a as RecordStore, n as EphemeralFlowStore, r as KeyedEphemeralFlowStore, t as Codec } from "./types-DKluXsWS.mjs";
2
+
3
+ //#region src/persistence/ephemeral-flow-store.d.ts
4
+ interface CreateEphemeralFlowStoreOptions<T> {
5
+ store: RecordStore;
6
+ key: string;
7
+ codec?: Codec<T>;
8
+ }
9
+ interface CreateKeyedEphemeralFlowStoreOptions<T> {
10
+ store: RecordStore;
11
+ keyPrefix: string;
12
+ codec?: Codec<T>;
13
+ }
14
+ /**
15
+ * Create a typed ephemeral flow-state store backed by a low-level `RecordStore`.
16
+ *
17
+ * Intended for short-lived browser/session coordination state such as pending
18
+ * redirects or callback fragments.
19
+ */
20
+ declare function createEphemeralFlowStore<T>(options: CreateEphemeralFlowStoreOptions<T>): EphemeralFlowStore<T>;
21
+ /**
22
+ * Create a typed keyed ephemeral flow-state store backed by a low-level
23
+ * `RecordStore`.
24
+ *
25
+ * Intended for short-lived browser/session coordination state where multiple
26
+ * pending records must coexist and be consumed independently.
27
+ */
28
+ declare function createKeyedEphemeralFlowStore<T>(options: CreateKeyedEphemeralFlowStoreOptions<T>): KeyedEphemeralFlowStore<T>;
29
+ //#endregion
30
+ //#region src/persistence/json-codec.d.ts
31
+ /** Default JSON codec. */
32
+ declare function createJsonCodec<T>(): Codec<T>;
33
+ //#endregion
34
+ //#region src/persistence/memory-store.d.ts
35
+ /** In-memory `RecordStore` — useful for tests and SSR. */
36
+ declare function createInMemoryRecordStore(): RecordStore;
37
+ //#endregion
38
+ export { createEphemeralFlowStore as a, CreateKeyedEphemeralFlowStoreOptions as i, createJsonCodec as n, createKeyedEphemeralFlowStore as o, CreateEphemeralFlowStoreOptions as r, createInMemoryRecordStore as t };
39
+ //# sourceMappingURL=index-XkwmYaJF.d.mts.map
@@ -0,0 +1,426 @@
1
+ import { A as LogLevel, B as DisposableTrait, C as HttpRequest, D as Clock, E as CancelableHandle$1, F as TraceEvent, I as TraceEventSinkTrait, L as CancelableHandle, M as OperationScope, N as OperationTraceEventType, O as Scheduler, P as OperationTracerTrait, R as CancellationTokenSourceTrait, S as ClientRuntime, T as HttpTransport, _ as scheduleAt, a as FromPromiseOptions, b as ReadableSignalTrait, c as PromiseSettlement, d as Subscription, f as TimerOptions, g as interval, h as fromSignal, i as FromEventPatternOptions, j as LoggerTrait, k as LogEntry, l as PromiseSettlementKind, m as fromPromise, n as FetchTransportRedirectKind, o as FromSignalOptions, p as fromEventPattern, s as IntervalOptions, u as ScheduleAtOptions, v as timer, w as HttpResponse, x as WritableSignalTrait, y as ComputedSignalTrait, z as CancellationTokenTrait } from "./fetch-transport-CMG4tfDu.mjs";
2
+ import { a as RecordStore, i as PersistentAuthStore, n as EphemeralFlowStore, o as RecoverableStateStore, r as KeyedEphemeralFlowStore, s as StoredEnvelope, t as Codec } from "./types-DKluXsWS.mjs";
3
+ import { a as createEphemeralFlowStore, n as createJsonCodec, o as createKeyedEphemeralFlowStore, t as createInMemoryRecordStore } from "./index-XkwmYaJF.mjs";
4
+ import { StandardSchemaV1 } from "@standard-schema/spec";
5
+
6
+ //#region src/cancellation/cancellation-token.d.ts
7
+ /**
8
+ * Create a `CancellationTokenSource` that produces a cooperative cancellation token.
9
+ */
10
+ declare function createCancellationTokenSource(): CancellationTokenSourceTrait;
11
+ //#endregion
12
+ //#region src/cancellation/linked-cancellation-token.d.ts
13
+ /**
14
+ * Create a cancellation token that fires when ANY of the given source tokens
15
+ * is cancelled.
16
+ *
17
+ * - Zero sources → returns a token that is never cancelled.
18
+ * - One source → returns that source directly (no allocation).
19
+ * - N sources → creates a linked source, subscribes to all, and cleans up
20
+ * subscriptions once the linked token fires.
21
+ *
22
+ * @example
23
+ * const cts = createCancellationTokenSource();
24
+ * const linked = createLinkedCancellationToken(clientRoot.token, cts.token);
25
+ * await transport.execute({ ..., cancellationToken: linked });
26
+ */
27
+ declare function createLinkedCancellationToken(...sources: CancellationTokenTrait[]): CancellationTokenTrait;
28
+ //#endregion
29
+ //#region src/errors/types.d.ts
30
+ /** Recovery actions the user might take. Aligned with server-side `UserRecovery`. */
31
+ declare const UserRecovery: {
32
+ readonly None: "none";
33
+ readonly Retry: "retry";
34
+ readonly RestartFlow: "restart_flow";
35
+ readonly Reauthenticate: "reauthenticate";
36
+ readonly ContactSupport: "contact_support";
37
+ };
38
+ type UserRecovery = (typeof UserRecovery)[keyof typeof UserRecovery];
39
+ /** User-facing error presentation. `code` is the cross-platform stable contract. */
40
+ interface ErrorPresentation {
41
+ code: string;
42
+ message: string;
43
+ recovery: UserRecovery;
44
+ }
45
+ declare const ErrorPresentationTone: {
46
+ readonly Neutral: "neutral";
47
+ readonly Warning: "warning";
48
+ readonly Danger: "danger";
49
+ };
50
+ type ErrorPresentationTone = (typeof ErrorPresentationTone)[keyof typeof ErrorPresentationTone];
51
+ interface ErrorPresentationActionDescriptor {
52
+ recovery: UserRecovery;
53
+ label: string;
54
+ href: string | null;
55
+ }
56
+ interface ErrorPresentationDescriptor {
57
+ code: string | null;
58
+ kind: ClientErrorKind | null;
59
+ source?: string;
60
+ title: string;
61
+ description: string;
62
+ recovery: UserRecovery;
63
+ retryable: boolean;
64
+ tone: ErrorPresentationTone;
65
+ primaryAction: ErrorPresentationActionDescriptor | null;
66
+ }
67
+ interface ReadErrorPresentationDescriptorOptions {
68
+ fallbackTitle?: string;
69
+ fallbackDescription?: string;
70
+ recoveryLinks?: Partial<Record<UserRecovery, string>>;
71
+ recoveryLabels?: Partial<Record<UserRecovery, string>>;
72
+ }
73
+ /** Machine-facing error kind discriminator. */
74
+ declare const ClientErrorKind: {
75
+ readonly Authorization: "authorization";
76
+ readonly Transport: "transport";
77
+ readonly Server: "server";
78
+ readonly Protocol: "protocol";
79
+ readonly Presentation: "presentation";
80
+ readonly Validation: "validation";
81
+ readonly Storage: "storage";
82
+ readonly Scheduler: "scheduler";
83
+ readonly Configuration: "configuration";
84
+ readonly Unauthenticated: "unauthenticated";
85
+ readonly Unauthorized: "unauthorized";
86
+ readonly RedirectRequired: "redirect_required";
87
+ readonly Cancelled: "cancelled";
88
+ readonly Timeout: "timeout";
89
+ readonly Internal: "internal";
90
+ };
91
+ type ClientErrorKind = (typeof ClientErrorKind)[keyof typeof ClientErrorKind];
92
+ /** Stable source vocabulary for common client error producers. */
93
+ declare const ClientErrorSource: {
94
+ readonly Transport: "transport";
95
+ readonly Server: "server";
96
+ readonly ClientRuntime: "client_runtime";
97
+ };
98
+ type ClientErrorSource = (typeof ClientErrorSource)[keyof typeof ClientErrorSource];
99
+ //#endregion
100
+ //#region src/errors/client-error.d.ts
101
+ /**
102
+ * Base client error carrying both machine-facing context and an optional
103
+ * user-facing presentation layer.
104
+ *
105
+ * Top-level `code` and `recovery` provide stable machine contracts for
106
+ * policy decisions without requiring callers to unwrap `presentation`.
107
+ */
108
+ declare class ClientError extends Error {
109
+ readonly kind: ClientErrorKind;
110
+ /**
111
+ * Stable machine-readable error code.
112
+ * Matches `presentation.code` when present, otherwise a default
113
+ * derived from `kind`.
114
+ */
115
+ readonly code: string;
116
+ /** Recovery hint at the machine level. */
117
+ readonly recovery: UserRecovery;
118
+ /** Whether this error is safe to retry. */
119
+ readonly retryable: boolean;
120
+ /** Structured user-facing error presentation from the server. */
121
+ readonly presentation?: ErrorPresentation;
122
+ /** Source subsystem or component that produced the error. */
123
+ readonly source?: string;
124
+ constructor(options: {
125
+ kind: ClientErrorKind;
126
+ message: string;
127
+ code?: string;
128
+ recovery?: UserRecovery;
129
+ retryable?: boolean;
130
+ presentation?: ErrorPresentation;
131
+ source?: string;
132
+ cause?: unknown;
133
+ });
134
+ /** Create a `ClientError` from a server error response body. */
135
+ static fromServerError(body: {
136
+ kind?: string;
137
+ code?: string;
138
+ message?: string;
139
+ recovery?: string;
140
+ presentation?: {
141
+ code?: string;
142
+ message?: string;
143
+ recovery?: string;
144
+ };
145
+ }, overrides?: {
146
+ kind?: ClientErrorKind;
147
+ source?: string;
148
+ }): ClientError;
149
+ /**
150
+ * Create a `ClientError` from an HTTP response status and optional body.
151
+ * Used when a non-success status is unexpected.
152
+ */
153
+ static fromHttpResponse(status: number, body?: unknown): ClientError;
154
+ }
155
+ //#endregion
156
+ //#region src/errors/presentation-descriptor.d.ts
157
+ declare function readErrorPresentationDescriptor(error: unknown, options?: ReadErrorPresentationDescriptorOptions): ErrorPresentationDescriptor;
158
+ //#endregion
159
+ //#region src/events/types.d.ts
160
+ /** Subscription handle with explicit unsubscribe. */
161
+ interface EventSubscriptionTrait {
162
+ unsubscribe(): void;
163
+ }
164
+ /** Observer for event streams — mirrors the Observable observer pattern. */
165
+ interface EventObserver<T> {
166
+ next?(value: T): void;
167
+ error?(error: unknown): void;
168
+ complete?(): void;
169
+ }
170
+ /** Read-only event stream — lazy push-based sequence. */
171
+ interface EventStreamTrait<T> {
172
+ subscribe(observer: EventObserver<T>): EventSubscriptionTrait;
173
+ }
174
+ declare const EventSourceKind: {
175
+ readonly User: "user";
176
+ readonly Timer: "timer";
177
+ readonly Http: "http";
178
+ readonly Storage: "storage";
179
+ readonly Framework: "framework";
180
+ readonly System: "system";
181
+ };
182
+ type EventSourceKind = (typeof EventSourceKind)[keyof typeof EventSourceKind];
183
+ type EventSource = {
184
+ kind: typeof EventSourceKind.User;
185
+ actor?: string;
186
+ } | {
187
+ kind: typeof EventSourceKind.Timer;
188
+ timer: string;
189
+ } | {
190
+ kind: typeof EventSourceKind.Http;
191
+ requestId: string;
192
+ endpoint?: string;
193
+ } | {
194
+ kind: typeof EventSourceKind.Storage;
195
+ operation: string;
196
+ } | {
197
+ kind: typeof EventSourceKind.Framework;
198
+ name: string;
199
+ } | {
200
+ kind: typeof EventSourceKind.System;
201
+ subsystem: string;
202
+ };
203
+ interface RuntimeEventEnvelope<TType extends string, TPayload> {
204
+ id: string;
205
+ type: TType;
206
+ at: number;
207
+ source: EventSource;
208
+ payload: TPayload;
209
+ }
210
+ //#endregion
211
+ //#region src/events/event-stream.d.ts
212
+ /**
213
+ * Create a new event stream from a producer function.
214
+ *
215
+ * The producer receives an observer and should call `next()` to emit values,
216
+ * `error()` to signal an error, and `complete()` to signal completion.
217
+ * It may return a teardown function that will be called on unsubscribe.
218
+ */
219
+ declare function createEventStream<T>(producer: (observer: EventObserver<T>) => (() => void) | void): EventStreamTrait<T>;
220
+ //#endregion
221
+ //#region src/events/operators.d.ts
222
+ type EventOperator<A, B> = (source: EventStreamTrait<A>) => EventStreamTrait<B>;
223
+ declare function pipe<A>(source: EventStreamTrait<A>): EventStreamTrait<A>;
224
+ declare function pipe<A, B>(source: EventStreamTrait<A>, op1: EventOperator<A, B>): EventStreamTrait<B>;
225
+ declare function pipe<A, B, C>(source: EventStreamTrait<A>, op1: EventOperator<A, B>, op2: EventOperator<B, C>): EventStreamTrait<C>;
226
+ declare function pipe<A, B, C, D>(source: EventStreamTrait<A>, op1: EventOperator<A, B>, op2: EventOperator<B, C>, op3: EventOperator<C, D>): EventStreamTrait<D>;
227
+ declare function map<A, B>(fn: (value: A) => B): EventOperator<A, B>;
228
+ declare function filter<A>(predicate: (value: A) => boolean): EventOperator<A, A>;
229
+ declare function tap<A>(fn: (value: A) => void): EventOperator<A, A>;
230
+ declare function takeUntil<A>(notifier: EventStreamTrait<unknown>): EventOperator<A, A>;
231
+ declare function finalize<A>(fn: () => void): EventOperator<A, A>;
232
+ declare function merge<A>(...sources: EventStreamTrait<A>[]): EventStreamTrait<A>;
233
+ //#endregion
234
+ //#region src/identity/principal.d.ts
235
+ interface AuthenticatedPrincipal {
236
+ subject: string;
237
+ displayName: string;
238
+ picture?: string;
239
+ issuer?: string;
240
+ claims?: Record<string, unknown>;
241
+ }
242
+ type PrincipalObject = Record<string, unknown>;
243
+ declare function normalizeAuthenticatedPrincipal(input: PrincipalObject): AuthenticatedPrincipal | null;
244
+ declare function normalizeAuthenticatedPrincipalWire(input: PrincipalObject): AuthenticatedPrincipal | null;
245
+ interface ProjectAuthenticatedPrincipalOptions {
246
+ principal?: AuthenticatedPrincipal | null;
247
+ fallbackDisplayName?: string;
248
+ fallbackSubject?: string;
249
+ fallbackIssuer?: string;
250
+ fallbackClaims?: Record<string, unknown>;
251
+ }
252
+ declare function projectAuthenticatedPrincipal(options: ProjectAuthenticatedPrincipalOptions): AuthenticatedPrincipal;
253
+ //#endregion
254
+ //#region src/logging/console-logger.d.ts
255
+ /** Simple console-based logger implementation. */
256
+ declare function createConsoleLogger(scope?: string): LoggerTrait;
257
+ //#endregion
258
+ //#region src/logging/noop-logger.d.ts
259
+ /** No-op logger — default when no logger is provided. */
260
+ declare function createNoopLogger(): LoggerTrait;
261
+ //#endregion
262
+ //#region src/logging/operation-tracer.d.ts
263
+ interface CreateOperationTracerOptions {
264
+ traceSink?: TraceEventSinkTrait;
265
+ logger?: LoggerTrait;
266
+ clock?: Clock;
267
+ scope?: string;
268
+ source?: string;
269
+ idFactory?: () => string;
270
+ }
271
+ declare function createOperationTracer(options?: CreateOperationTracerOptions): OperationTracerTrait;
272
+ //#endregion
273
+ //#region src/logging/trace-timeline-store.d.ts
274
+ interface TraceTimelineEntry extends TraceEvent {
275
+ id: number;
276
+ recordedAtIso: string;
277
+ }
278
+ interface TraceTimelineStore extends TraceEventSinkTrait {
279
+ get(): readonly TraceTimelineEntry[];
280
+ subscribe(listener: () => void): () => void;
281
+ clear(): void;
282
+ }
283
+ declare function createTraceTimelineStore(limit?: number): TraceTimelineStore;
284
+ //#endregion
285
+ //#region src/runtime/create-runtime.d.ts
286
+ interface CreateRuntimeOptions extends Partial<Omit<ClientRuntime, "transport">> {
287
+ transport: HttpTransport;
288
+ }
289
+ /**
290
+ * Create a `ClientRuntime` with non-host-specific defaults filled in for
291
+ * convenience.
292
+ *
293
+ * Host-specific capabilities such as browser `fetch` should be supplied
294
+ * explicitly or composed via adapter-specific helpers such as
295
+ * `@securitydept/client/web`.
296
+ */
297
+ declare function createRuntime(overrides: CreateRuntimeOptions): ClientRuntime;
298
+ //#endregion
299
+ //#region src/scheduling/default-clock.d.ts
300
+ /** Default clock backed by `Date.now()`. */
301
+ declare function createDefaultClock(): Clock;
302
+ //#endregion
303
+ //#region src/scheduling/default-scheduler.d.ts
304
+ /** Default scheduler backed by platform `setTimeout`. */
305
+ declare function createDefaultScheduler(): Scheduler;
306
+ //#endregion
307
+ //#region src/signals/computed.d.ts
308
+ /**
309
+ * Create a computed signal that derives its value from other signals.
310
+ *
311
+ * Semantics: lazy + cached.
312
+ * - The compute function is NOT called at construction time.
313
+ * - `get()` recomputes only when dirty (a dependency changed since last read).
314
+ * - Subscribers are notified only when a dependency changes (dirty-flagged),
315
+ * and the next `get()` will produce the fresh value.
316
+ *
317
+ * Dependency subscriptions are permanent for the lifetime of the computed signal.
318
+ */
319
+ declare function createComputed<T>(compute: () => T, deps: ReadableSignalTrait<unknown>[]): ComputedSignalTrait<T>;
320
+ //#endregion
321
+ //#region src/signals/signal.d.ts
322
+ /**
323
+ * Minimal writable signal implementation.
324
+ * Snapshot-first: values are immutable snapshots, mutations go through `set()`.
325
+ */
326
+ declare function createSignal<T>(initial: T): WritableSignalTrait<T>;
327
+ /**
328
+ * Create a read-only view of a writable signal.
329
+ */
330
+ declare function readonlySignal<T>(signal: WritableSignalTrait<T>): ReadableSignalTrait<T>;
331
+ //#endregion
332
+ //#region src/validation/index.d.ts
333
+ /**
334
+ * Successful validation result.
335
+ *
336
+ * Contains the parsed, typed output value from the schema.
337
+ */
338
+ interface ValidationSuccess<T> {
339
+ readonly success: true;
340
+ readonly value: T;
341
+ }
342
+ /**
343
+ * Failed validation result.
344
+ *
345
+ * Contains the list of issues reported by the schema.
346
+ */
347
+ interface ValidationFailure {
348
+ readonly success: false;
349
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
350
+ }
351
+ /**
352
+ * Discriminated union of validation outcomes.
353
+ *
354
+ * Consumers can narrow on `success` to access either the typed value
355
+ * or the issue list.
356
+ */
357
+ type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;
358
+ /**
359
+ * Validate an unknown input against a `@standard-schema`-compatible schema.
360
+ *
361
+ * This is the foundation-level entry point for SDK validation. It accepts
362
+ * any schema implementing `StandardSchemaV1` and returns a discriminated
363
+ * `ValidationResult`.
364
+ *
365
+ * @example
366
+ * ```ts
367
+ * import { validateWithSchema } from "@securitydept/client";
368
+ * import { z } from "zod";
369
+ *
370
+ * const UserSchema = z.object({ name: z.string() });
371
+ * const result = await validateWithSchema(UserSchema, { name: "Alice" });
372
+ * if (result.success) {
373
+ * console.log(result.value.name);
374
+ * } else {
375
+ * console.error(result.issues);
376
+ * }
377
+ * ```
378
+ */
379
+ declare function validateWithSchema<I, O>(schema: StandardSchemaV1<I, O>, input: unknown): Promise<ValidationResult<O>>;
380
+ /**
381
+ * Validate an unknown input synchronously against a `@standard-schema`-compatible schema.
382
+ *
383
+ * Only use this when you know the schema's validate function returns synchronously.
384
+ * Throws if the schema returns a Promise.
385
+ */
386
+ declare function validateWithSchemaSync<I, O>(schema: StandardSchemaV1<I, O>, input: unknown): ValidationResult<O>;
387
+ /**
388
+ * Options for creating a foundation schema.
389
+ */
390
+ interface CreateSchemaOptions<O> {
391
+ /** Validation function: returns typed output or returns issues. */
392
+ readonly validate: (input: unknown) => {
393
+ readonly value: O;
394
+ } | {
395
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
396
+ };
397
+ }
398
+ /**
399
+ * Create a minimal `@standard-schema`-compatible schema without requiring
400
+ * an external validation library.
401
+ *
402
+ * This is useful for SDK-internal schemas where pulling in zod/valibot
403
+ * would be excessive. For adopter-facing schemas, prefer a real validation
404
+ * library.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * import { createSchema, validateWithSchema } from "@securitydept/client";
409
+ *
410
+ * const NameSchema = createSchema<unknown, { name: string }>({
411
+ * validate(input) {
412
+ * if (typeof input === "object" && input !== null && "name" in input &&
413
+ * typeof (input as any).name === "string") {
414
+ * return { value: { name: (input as any).name } };
415
+ * }
416
+ * return { issues: [{ message: "Expected object with string 'name'" }] };
417
+ * },
418
+ * });
419
+ *
420
+ * const result = await validateWithSchema(NameSchema, { name: "Alice" });
421
+ * ```
422
+ */
423
+ declare function createSchema<O>(options: CreateSchemaOptions<O>): StandardSchemaV1<unknown, O>;
424
+ //#endregion
425
+ export { type AuthenticatedPrincipal, type CancelableHandle, type CancellationTokenSourceTrait, type CancellationTokenTrait, ClientError, ClientErrorKind, ClientErrorSource, type ClientRuntime, type Clock, type Codec, type ComputedSignalTrait, type CreateOperationTracerOptions, type CreateRuntimeOptions, type DisposableTrait, type EphemeralFlowStore, type ErrorPresentation, type ErrorPresentationActionDescriptor, type ErrorPresentationDescriptor, ErrorPresentationTone, type EventObserver, type EventOperator, type EventSource, EventSourceKind, type EventStreamTrait, type EventSubscriptionTrait, FetchTransportRedirectKind, type FromEventPatternOptions, type FromPromiseOptions, type FromSignalOptions, type HttpRequest, type HttpResponse, type HttpTransport, type IntervalOptions, type KeyedEphemeralFlowStore, type LogEntry, LogLevel, type LoggerTrait, type OperationScope, OperationTraceEventType, type OperationTracerTrait, type PersistentAuthStore, type ProjectAuthenticatedPrincipalOptions, type PromiseSettlement, PromiseSettlementKind, type ReadErrorPresentationDescriptorOptions, type ReadableSignalTrait, type RecordStore, type RecoverableStateStore, type RuntimeEventEnvelope, type ScheduleAtOptions, type Scheduler, type CancelableHandle$1 as SchedulerCancelableHandle, type StoredEnvelope, type Subscription, type TimerOptions, type TraceEvent, type TraceEventSinkTrait, type TraceTimelineEntry, type TraceTimelineStore, UserRecovery, type ValidationFailure, type ValidationResult, type ValidationSuccess, type WritableSignalTrait, createCancellationTokenSource, createComputed, createConsoleLogger, createDefaultClock, createDefaultScheduler, createEphemeralFlowStore, createEventStream, createInMemoryRecordStore, createJsonCodec, createKeyedEphemeralFlowStore, createLinkedCancellationToken, createNoopLogger, createOperationTracer, createRuntime, createSchema, createSignal, createTraceTimelineStore, filter, finalize, fromEventPattern, fromPromise, fromSignal, interval, map, merge, normalizeAuthenticatedPrincipal, normalizeAuthenticatedPrincipalWire, pipe, projectAuthenticatedPrincipal, readErrorPresentationDescriptor, readonlySignal, scheduleAt, takeUntil, tap, timer, validateWithSchema, validateWithSchemaSync };
426
+ //# sourceMappingURL=index.d.mts.map