better-ship 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{application-C4JOf71r.js → application-Cf9SER-i.js} +2 -2
  2. package/dist/{application-C4JOf71r.js.map → application-Cf9SER-i.js.map} +1 -1
  3. package/dist/application.d.ts +2 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.d.ts +1 -1
  6. package/dist/better-auth/apple-client-secret.js +1 -1
  7. package/dist/better-auth/auth-client.js +1 -1
  8. package/dist/better-auth/rate-limit.d.ts +1 -1
  9. package/dist/better-auth/rate-limit.js +1 -1
  10. package/dist/better-auth.js +1 -1
  11. package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
  12. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  13. package/dist/cloudflare/durable-object-client.js +1 -1
  14. package/dist/cloudflare/durable-object-errors.d.ts +1 -1
  15. package/dist/cloudflare/durable-object-errors.js +1 -1
  16. package/dist/cloudflare/kv-client.d.ts +31 -0
  17. package/dist/cloudflare/kv-client.d.ts.map +1 -0
  18. package/dist/cloudflare/kv-client.js +62 -0
  19. package/dist/cloudflare/kv-client.js.map +1 -0
  20. package/dist/cloudflare/kv-errors.d.ts +52 -0
  21. package/dist/cloudflare/kv-errors.d.ts.map +1 -0
  22. package/dist/cloudflare/kv-errors.js +144 -0
  23. package/dist/cloudflare/kv-errors.js.map +1 -0
  24. package/dist/cloudflare/queue.d.ts +2 -2
  25. package/dist/cloudflare/queue.js +2 -2
  26. package/dist/cloudflare/scheduled.d.ts +1 -1
  27. package/dist/cloudflare/scheduled.js +1 -1
  28. package/dist/cloudflare.d.ts +10 -5
  29. package/dist/cloudflare.d.ts.map +1 -1
  30. package/dist/cloudflare.js +21 -10
  31. package/dist/cloudflare.js.map +1 -1
  32. package/dist/{core-hdaNiCOU.js → core-ClSP5-V9.js} +94 -44
  33. package/dist/core-ClSP5-V9.js.map +1 -0
  34. package/dist/core.d.ts +2 -2
  35. package/dist/core.js +2 -2
  36. package/dist/http.d.ts +2 -2
  37. package/dist/http.js +2 -2
  38. package/dist/{index-B45Dr5gs.d.ts → index-Cchdg2aQ.d.ts} +2 -2
  39. package/dist/{index-B45Dr5gs.d.ts.map → index-Cchdg2aQ.d.ts.map} +1 -1
  40. package/dist/{index-G1QG0P5g.d.ts → index-DvJUcSW1.d.ts} +102 -48
  41. package/dist/{index-G1QG0P5g.d.ts.map → index-DvJUcSW1.d.ts.map} +1 -1
  42. package/dist/{outbox-repository-options-CwTTuy7B.d.ts → outbox-repository-options-AkihEaik.d.ts} +3 -3
  43. package/dist/{outbox-repository-options-CwTTuy7B.d.ts.map → outbox-repository-options-AkihEaik.d.ts.map} +1 -1
  44. package/dist/{outbox-repository-options-DOTpJH-e.js → outbox-repository-options-ICOF8g2h.js} +2 -2
  45. package/dist/{outbox-repository-options-DOTpJH-e.js.map → outbox-repository-options-ICOF8g2h.js.map} +1 -1
  46. package/dist/postgres.d.ts +10 -5
  47. package/dist/postgres.d.ts.map +1 -1
  48. package/dist/postgres.js +21 -10
  49. package/dist/postgres.js.map +1 -1
  50. package/dist/posthog/metrics.d.ts +1 -1
  51. package/dist/posthog/server.d.ts +2 -2
  52. package/dist/posthog/server.js +1 -1
  53. package/dist/resend.d.ts +3 -3
  54. package/dist/resend.js +2 -2
  55. package/dist/sentry/client.d.ts +1 -1
  56. package/dist/sentry/client.js +1 -1
  57. package/dist/sentry/server.d.ts +2 -2
  58. package/dist/tanstack.d.ts +1 -1
  59. package/dist/tanstack.js +1 -1
  60. package/dist/testing/outbox-repository.d.ts +2 -2
  61. package/dist/{webhook-verification-D7DIhH6C.d.ts → webhook-verification-BcQQG-vY.d.ts} +2 -2
  62. package/dist/{webhook-verification-D7DIhH6C.d.ts.map → webhook-verification-BcQQG-vY.d.ts.map} +1 -1
  63. package/dist/{webhook-verification-trEgyz7I.js → webhook-verification-D6aGQfNi.js} +2 -2
  64. package/dist/{webhook-verification-trEgyz7I.js.map → webhook-verification-D6aGQfNi.js.map} +1 -1
  65. package/package.json +3 -1
  66. package/src/core/define-messages.ts +209 -103
  67. package/src/core/index.ts +3 -1
  68. package/src/core/messages.ts +1 -1
  69. package/src/infrastructure/cloudflare/d1-database-execution.ts +27 -6
  70. package/src/infrastructure/cloudflare/kv-client.ts +79 -0
  71. package/src/infrastructure/cloudflare/kv-errors.ts +157 -0
  72. package/src/infrastructure/postgres/postgres-database-execution.ts +27 -6
  73. package/dist/core-hdaNiCOU.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { D as DatabaseError, E as unreachable, a as createLogger, f as classifyFailure, tt as AppError } from "./core-hdaNiCOU.js";
1
+ import { O as unreachable, a as createLogger, f as classifyFailure, k as DatabaseError, rt as AppError } from "./core-ClSP5-V9.js";
2
2
  import { panic } from "better-result";
3
3
 
4
4
  //#region src/application/analytics-service.ts
@@ -288,4 +288,4 @@ var UnitOfWorkAlreadyActiveError = class extends AppError {
288
288
 
289
289
  //#endregion
290
290
  export { MessageBus as a, RecordingEmailService as c, OutboxRelay as i, NULL_METRICS_SERVICE as l, UnitOfWork as n, MessageAlreadyProcessedError as o, OutboxRetention as r, recordEmailEvent as s, UnitOfWorkAlreadyActiveError as t, NULL_ANALYTICS as u };
291
- //# sourceMappingURL=application-C4JOf71r.js.map
291
+ //# sourceMappingURL=application-Cf9SER-i.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"application-C4JOf71r.js","names":["logger"],"sources":["../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/email-service.ts","../src/application/record-email-event.ts","../src/application/message-already-processed.error.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/outbox-retention.ts","../src/application/unit-of-work.ts","../src/application/unit-of-work.errors.ts"],"sourcesContent":["import type { AnalyticsEventIdentity, AnalyticsEventInput, AnalyticsProperties } from '@/core'\n\n/** Product analytics without an SDK dependency, ported from Typist and Porte. */\nexport interface AnalyticsService<TEvent extends AnalyticsEventInput = AnalyticsEventInput> {\n /** Attach traits to one person. */\n identify(distinctId: string, properties?: AnalyticsProperties): void\n /** Merge a previous ID into this person; the application must establish that both identify the same person. */\n alias(distinctId: string, previousDistinctId: string): void\n /** Schedule an event for a person; returning does not confirm remote acceptance. */\n track(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n /** Schedule an event without creating a person profile for its distinct ID. */\n trackAnonymous(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n}\n\n/** Reports to nobody. The composition root selects this service when analytics is disabled. */\nexport const NULL_ANALYTICS: AnalyticsService = {\n identify: () => {},\n alias: () => {},\n track: () => {},\n trackAnonymous: () => {},\n}\n","/** A metric dimension; use a small, bounded value set and never user or request IDs. */\nexport type MetricAttributeValue = string | number | boolean\n\n/** Dimensions shared by observations in one time series. */\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>\n\n/** Unit and dimensions for an operational measurement. */\nexport interface MetricOptions {\n readonly attributes?: MetricAttributes\n readonly unit?: string\n}\n\n/** Operational measurements, ported from Typist's metrics-service.ts; applications own metric names. */\nexport interface MetricsService<TName extends string = string> {\n /** Add a nonnegative value to a total; the default increment is one. */\n count(name: TName, value?: number, options?: MetricOptions): void\n /** Record a current value. */\n gauge(name: TName, value: number, options?: MetricOptions): void\n /** Record one observation in a distribution. */\n histogram(name: TName, value: number, options?: MetricOptions): void\n}\n\n/** Records nothing when the composition root disables metrics. */\nexport const NULL_METRICS_SERVICE: MetricsService = {\n count: () => {},\n gauge: () => {},\n histogram: () => {},\n}\n","import type { EmailIdempotencyKey } from '@/core'\n\n/** A media type such as `application/pdf`. */\nexport type MimeType = `${string}/${string}`\n\n/** A file to attach. Binary content is bytes; the adapter encodes it for the provider. */\nexport type EmailAttachment = {\n readonly filename: string\n readonly content: string | Uint8Array\n /** Optional MIME metadata; Resend accepts filename and content without it. */\n readonly contentType?: MimeType\n}\n\n/**\n * One transactional email. Resend accepts 50 recipients, 75 tags with ASCII names and values,\n * and 40 MB of attachments after base64. Sources: https://resend.com/docs/api-reference/emails/send-email\n * and https://resend.com/docs/dashboard/emails/tags\n */\nexport type OutboundEmail = {\n /** Override the default for this email, for example \"Display Name <address@domain.com>\". */\n readonly from?: string\n readonly to: string | readonly string[]\n readonly subject: string\n readonly html: string\n /** Optional stable identity of this send. Resend deduplicates supplied keys for 24 hours. */\n readonly idempotencyKey?: EmailIdempotencyKey\n /** Resend generates plain text from html when omitted. An empty string disables that generation. */\n readonly text?: string\n readonly replyTo?: string\n /** Labels the provider stores with the email and returns on every delivery event. */\n readonly tags?: Readonly<Record<string, string>>\n readonly attachments?: readonly EmailAttachment[]\n}\n\n/** The provider accepted the email and assigned its id. */\nexport type EmailAccepted = { readonly providerId: string }\n\n/**\n * The adapter supplies the default sender and maps provider errors. Each email can override the sender.\n * A provider rejection throws `EmailServiceError`; unexpected SDK rejections propagate unchanged.\n */\nexport interface IEmailService {\n /** Resolve after provider acceptance; this does not confirm delivery to the recipient. */\n sendEmail(email: OutboundEmail): Promise<EmailAccepted>\n}\n\n/** Records every send for a test. Provider ids count up as `recorded-1`, `recorded-2`. */\nexport class RecordingEmailService implements IEmailService {\n /** Sends in call order, including repeated idempotency keys. */\n readonly sent: OutboundEmail[] = []\n\n /** Record the send before returning its provider id. */\n async sendEmail(email: OutboundEmail): Promise<EmailAccepted> {\n this.sent.push(email)\n return { providerId: `recorded-${this.sent.length}` }\n }\n}\n","import type { BounceType, DomainCommand, EmailAddress, RecordEmailEventPayload } from '@/core'\n\nimport type { IUnitOfWork } from './unit-of-work.ts'\n\n/** What a bounce records for one address. */\nexport type EmailBounceRecord = {\n readonly type: BounceType\n readonly subType: string | null\n}\n\n/**\n * The application's deliverability state per address. An implementation keeps the higher bounce\n * severity with `shouldUpdateBounce`, and treats an unknown address as nothing to record.\n */\nexport interface IEmailDeliverabilityStore {\n /** Keep the higher severity atomically. Equal severity permits replacement; the store owns timestamp ordering. */\n recordBounce(address: EmailAddress, bounce: EmailBounceRecord): Promise<void>\n /** Record a complaint without clearing existing suppression state. */\n recordComplaint(address: EmailAddress): Promise<void>\n}\n\n/** The repositories the handler needs from the unit of work. */\nexport type RecordEmailEventRepos = { readonly emailDeliverability: IEmailDeliverabilityStore }\n\n/** The container slice the handler reads. */\nexport type RecordEmailEventDeps = { readonly uow: IUnitOfWork<RecordEmailEventRepos> }\n\n/** The command, under whatever name the application registered the payload. */\nexport type RecordEmailEventCommand = DomainCommand & RecordEmailEventPayload\n\n/**\n * Record a bounce or a complaint for every recipient inside the command's unit of work.\n * The command id is the provider's event id, so a redelivered webhook is `MessageAlreadyProcessedError`.\n */\nexport async function recordEmailEvent(\n command: RecordEmailEventCommand,\n deps: RecordEmailEventDeps,\n): Promise<void> {\n await deps.uow.run(command.id, async ({ emailDeliverability }) => {\n for (const address of command.recipients) {\n if (command.event.type === 'bounced') {\n // oxlint-disable-next-line no-await-in-loop -- Finish each transaction write before starting another; a failure must leave no pending writes.\n await emailDeliverability.recordBounce(address, {\n type: command.event.bounceType,\n subType: command.event.bounceSubType,\n })\n } else {\n // oxlint-disable-next-line no-await-in-loop -- A rejected write must stop the transaction before another write starts.\n await emailDeliverability.recordComplaint(address)\n }\n }\n })\n}\n","import { AppError, DatabaseError, type MessageId } from '@/core'\n\n/** The message's effects already committed. A caller can skip duplicate delivery without repeating those effects. */\nexport class MessageAlreadyProcessedError extends AppError {\n readonly _tag = 'MessageAlreadyProcessedError'\n readonly classification = 'terminal'\n\n constructor(\n readonly messageId: MessageId,\n options?: { readonly cause: unknown },\n ) {\n super(`message ${messageId} already processed`, options)\n }\n\n /** Recognize only the processed-message primary key; preserve other failures unchanged at the call site. */\n static from(cause: unknown, messageId: MessageId): MessageAlreadyProcessedError | undefined {\n if (cause instanceof MessageAlreadyProcessedError) return cause\n if (!(cause instanceof DatabaseError)) return undefined\n const details = cause.details\n const duplicate =\n details.database === 'd1'\n ? details.kind === 'unique' &&\n details.table === 'processed_messages' &&\n details.column === 'message_id'\n : details.code === '23505' &&\n details.table_name === 'processed_messages' &&\n details.constraint_name === 'processed_messages_pkey'\n if (!duplicate) return undefined\n return new MessageAlreadyProcessedError(messageId, { cause })\n }\n}\n","import { panic } from 'better-result'\n\nimport {\n createLogger,\n unreachable,\n type DomainCommand,\n type DomainEvent,\n type DomainMessage,\n type DomainQuery,\n} from '@/core'\n\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { Handlers, MessageResult, RegistryMessage } from './registry.ts'\n\nconst logger = createLogger('message-bus')\n\n/** The port an entrypoint dispatches through. `AppDeps` names this as `IMessageBus<typeof registry>`. */\nexport interface IMessageBus<TRegistry extends Handlers<never>> {\n handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>>\n}\n\n/**\n * Routes one message to its slot. The bus opens no transaction and keeps no outbox:\n * a handler that writes opens the unit of work itself.\n */\nexport class MessageBus<Deps, TRegistry extends Handlers<Deps>> implements IMessageBus<TRegistry> {\n constructor(\n private readonly deps: Deps,\n private readonly registry: TRegistry,\n ) {}\n\n /** Resolves to the handler's own value for a command or query, and to void for an event. */\n async handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>> {\n // SAFETY: the slot for this name is what `MessageResult` names, and dispatch returns its value.\n return (await this.dispatch(message)) as MessageResult<TMessage, TRegistry>\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- one table holds every slot's value; `handle` names it.\n private dispatch(message: DomainMessage): Promise<unknown> {\n if (message.type === 'command') return this.handleCommand(message)\n if (message.type === 'query') return this.handleQuery(message)\n if (message.type === 'event') return this.handleEvent(message)\n // A message parsed at a boundary cannot reach here; one that does must not resolve silently.\n return unreachable(message)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleCommand(command: DomainCommand): Promise<unknown> {\n // `satisfies` proved the registry complete, so a missing slot is a broken registry object.\n const handler = this.registry.commands[command.name]\n if (handler === undefined) return panic(`No handler for command ${command.name}`)\n logger.debug('handling_command', { name: command.name, id: command.id })\n return handler(command, this.deps)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleQuery(query: DomainQuery): Promise<unknown> {\n const handler = this.registry.queries[query.name]\n if (handler === undefined) return panic(`No handler for query ${query.name}`)\n return handler(query, this.deps)\n }\n\n /**\n * Every subscriber runs to completion. One failure is rethrown as is. Several are thrown as\n * one `AggregateError`. A `MessageAlreadyProcessedError` means that subscriber already committed on\n * an earlier delivery, so it counts as delivered.\n */\n private async handleEvent(event: DomainEvent): Promise<void> {\n const subscriptions = this.registry.events[event.name] ?? []\n const outcomes = await Promise.allSettled(\n subscriptions.map((subscription) => subscription(event, this.deps)),\n )\n const failures: unknown[] = []\n for (const [subscriber, outcome] of outcomes.entries()) {\n if (outcome.status === 'fulfilled') continue\n if (outcome.reason instanceof MessageAlreadyProcessedError) {\n // The bus swallows this error, so this line is the only record that the skip happened.\n logger.info('duplicate_subscriber_ignored', { event: event.name, id: event.id, subscriber })\n continue\n }\n failures.push(outcome.reason)\n }\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${event.name}: ${failures.length} subscribers failed`)\n }\n }\n}\n","import { classifyFailure, createLogger, type DomainEvent } from '@/core'\n\nimport type {\n DeadLetterReason,\n IOutboxRepository,\n OutboxClaim,\n OutboxMessage,\n} from './outbox-repository.ts'\n\n/**\n * Delivers committed outbox rows. The unit of work only wakes it after a commit that wrote\n * events; the app decides what a wake is: `waitUntil`, a Durable Object alarm, nothing.\n * The sweep is the source of truth, so a lost wake loses no events.\n */\nexport interface IOutboxRelay {\n wake(): void\n}\n\n/** The publisher sends valid events and returns oversized events. QueueClient satisfies this port directly. */\nexport interface IOutboxPublisher {\n /** Resolves after queue acceptance; a rejected batch may already have sent some events. */\n sendBatchPartial(messages: ReadonlyArray<DomainEvent>): Promise<ReadonlyArray<DomainEvent>>\n}\n\n/** Optional limits for one relay; durable attempts exclude the publisher's immediate retries. */\nexport type OutboxRelayOptions = {\n readonly batchSize?: number\n readonly maxBatches?: number\n readonly maxAttempts?: number\n}\n\nconst logger = createLogger('outbox-relay')\n\n/**\n * Publishes committed events with bounded durable retries. Ported from Typist's relay with per-row exhaustion.\n * Send failures are recorded; repository failures propagate to the wake or scheduled boundary.\n */\nexport class OutboxRelay {\n private readonly options: Required<OutboxRelayOptions>\n\n constructor(\n private readonly publisher: IOutboxPublisher,\n private readonly repository: IOutboxRepository,\n options: OutboxRelayOptions = {},\n ) {\n this.options = {\n batchSize: options.batchSize ?? 50,\n maxBatches: options.maxBatches ?? 10,\n maxAttempts: options.maxAttempts ?? 10,\n }\n }\n\n /** Return the claimed count, including released and dead-lettered rows. Zero means no due rows. */\n async flush(): Promise<number> {\n const claim = await this.repository.claimPending(this.options.batchSize)\n const exhausted = claim.messages.filter((row) => row.attempts > this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', 'Claim attempt limit exceeded')\n const pending = claim.messages.filter((row) => row.attempts <= this.options.maxAttempts)\n if (pending.length === 0) return claim.messages.length\n\n let oversized: ReadonlyArray<DomainEvent>\n try {\n oversized = await this.publisher.sendBatchPartial(pending.map((row) => row.payload))\n } catch (error) {\n await this.handleSendFailure(claim, pending, error)\n return claim.messages.length\n }\n\n const oversizedIds = new Set(oversized.map((event) => event.id))\n await this.deadLetter(\n claim,\n pending.filter((row) => oversizedIds.has(row.payload.id)),\n 'oversized',\n 'Exceeds queue message size limit',\n )\n const sent = pending.filter((row) => !oversizedIds.has(row.payload.id))\n if (sent.length > 0) await this.repository.markPublished(claim, sent)\n return claim.messages.length\n }\n\n /** Drain until an empty claim or the batch limit; return the total claimed count. */\n async drain(): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- An empty claim must stop the drain before another claim starts.\n const claimed = await this.flush()\n total += claimed\n if (claimed === 0) break\n }\n return total\n }\n\n private async handleSendFailure(\n claim: OutboxClaim,\n pending: ReadonlyArray<OutboxMessage>,\n cause: unknown,\n ): Promise<void> {\n const classification = classifyFailure(cause)\n const message =\n cause instanceof Error ? cause.message : 'Publisher rejected with a non-error value'\n if (classification === 'terminal') {\n await this.deadLetter(claim, pending, 'terminal', message, cause)\n return\n }\n const exhausted = pending.filter((row) => row.attempts >= this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', message, cause)\n const retry = pending.filter((row) => row.attempts < this.options.maxAttempts)\n if (retry.length > 0) await this.repository.releaseClaim(claim, retry)\n }\n\n private async deadLetter(\n claim: OutboxClaim,\n messages: ReadonlyArray<OutboxMessage>,\n reason: DeadLetterReason,\n errorMessage: string,\n cause?: unknown,\n ): Promise<void> {\n if (messages.length === 0) return\n await this.repository.deadLetter(claim, messages, reason, errorMessage)\n logger.error('outbox_messages_dead_lettered', {\n error: cause,\n details: { claimToken: claim.token, count: messages.length, reason },\n })\n }\n}\n","import type { IOutboxRetentionRepository } from './outbox-repository.ts'\n\n/** Typist's retention defaults; receipt retention must cover the application's supported replay period. */\nexport type OutboxRetentionOptions = {\n readonly publishedRetentionMs?: number\n readonly failedRetentionMs?: number\n readonly receiptRetentionMs?: number\n readonly batchSize?: number\n readonly maxBatches?: number\n}\n\n/** Deleted records per category during one bounded sweep. */\nexport type OutboxRetentionResult = {\n readonly published: number\n readonly failed: number\n readonly receipts: number\n}\n\n/** Bounded cleanup ported from Typist's message retention handler. The application schedules each sweep. */\nexport class OutboxRetention {\n private readonly options: Required<OutboxRetentionOptions>\n\n constructor(\n private readonly repository: IOutboxRetentionRepository,\n options: OutboxRetentionOptions = {},\n ) {\n this.options = {\n publishedRetentionMs: options.publishedRetentionMs ?? 86_400_000,\n failedRetentionMs: options.failedRetentionMs ?? 30 * 86_400_000,\n receiptRetentionMs: options.receiptRetentionMs ?? 7 * 86_400_000,\n batchSize: options.batchSize ?? 1_000,\n maxBatches: options.maxBatches ?? 10,\n }\n }\n\n /** Calculate all cutoffs from one supplied time; propagate repository failures to the calling boundary. */\n async sweep(at: Date): Promise<OutboxRetentionResult> {\n const { publishedRetentionMs, failedRetentionMs, receiptRetentionMs } = this.options\n const published = await this.deleteBatches((size) =>\n this.repository.deletePublishedBefore(new Date(at.getTime() - publishedRetentionMs), size),\n )\n const failed = await this.deleteBatches((size) =>\n this.repository.deleteFailedBefore(new Date(at.getTime() - failedRetentionMs), size),\n )\n const receipts = await this.deleteBatches((size) =>\n this.repository.deleteReceiptsBefore(new Date(at.getTime() - receiptRetentionMs), size),\n )\n return { published, failed, receipts }\n }\n\n private async deleteBatches(deleteBatch: (size: number) => Promise<number>): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- The delete count decides whether another batch is needed.\n const deleted = await deleteBatch(this.options.batchSize)\n total += deleted\n if (deleted < this.options.batchSize) break\n }\n return total\n }\n}\n","import type { MessageId } from '@/core'\n\nimport type { IEventCollector } from './event-collector.ts'\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { IMessageStore } from './message-store.ts'\nimport type { IOutboxRelay } from './outbox-relay.ts'\nimport type { ITransaction } from './transaction.ts'\n\n/**\n * Commits the processed-message record, repository writes, and emitted events together before resolving.\n * An existing record rejects with `MessageAlreadyProcessedError`; external effects must run through the outbox after commit.\n * Nested calls reject with `UnitOfWorkAlreadyActiveError`; independent concurrent calls are allowed.\n */\nexport interface IUnitOfWork<Repos> {\n run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T>\n}\n\nexport type UnitOfWorkDeps<Tx, Repos> = {\n readonly transaction: ITransaction<Tx>\n /** The processed-messages and outbox repository for this transaction. */\n readonly messageStore: (tx: Tx) => IMessageStore\n /** Repositories participate in the current transaction. */\n readonly createRepositories: (tx: Tx) => Repos\n readonly eventCollector: IEventCollector\n readonly relay: IOutboxRelay\n}\n\n/** The unit of work: the boundary, the repositories, the events. Every database call is a port. */\nexport class UnitOfWork<Tx, Repos> implements IUnitOfWork<Repos> {\n constructor(private readonly deps: UnitOfWorkDeps<Tx, Repos>) {}\n\n async run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T> {\n const { transaction, messageStore, createRepositories, eventCollector, relay } = this.deps\n let written = 0\n\n let value: T\n try {\n value = await transaction.transaction(async (tx) => {\n const store = messageStore(tx)\n await store.claim(messageId)\n const repos = createRepositories(tx)\n const result = await work(repos)\n const pending = eventCollector.collect()\n await store.persistEvents(pending)\n written = pending.length\n return result\n })\n } catch (error) {\n throw MessageAlreadyProcessedError.from(error, messageId) ?? error\n }\n\n if (written > 0) relay.wake()\n return value\n }\n}\n","import { AppError } from '@/core'\n\n/** A boundary was opened inside another. One message, one atomic scope. */\nexport class UnitOfWorkAlreadyActiveError extends AppError {\n readonly _tag = 'UnitOfWorkAlreadyActiveError'\n readonly classification = 'terminal'\n\n constructor() {\n super('a unit of work is already active')\n }\n}\n"],"mappings":";;;;;AAeA,MAAa,iBAAmC;CAC9C,gBAAgB,CAAC;CACjB,aAAa,CAAC;CACd,aAAa,CAAC;CACd,sBAAsB,CAAC;AACzB;;;;;ACGA,MAAa,uBAAuC;CAClD,aAAa,CAAC;CACd,aAAa,CAAC;CACd,iBAAiB,CAAC;AACpB;;;;;ACoBA,IAAa,wBAAb,MAA4D;;CAE1D,AAAS,OAAwB,CAAC;;CAGlC,MAAM,UAAU,OAA8C;EAC5D,KAAK,KAAK,KAAK,KAAK;EACpB,OAAO,EAAE,YAAY,YAAY,KAAK,KAAK,SAAS;CACtD;AACF;;;;;;;;ACtBA,eAAsB,iBACpB,SACA,MACe;CACf,MAAM,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAO,EAAE,0BAA0B;EAChE,KAAK,MAAM,WAAW,QAAQ,YAC5B,IAAI,QAAQ,MAAM,SAAS,WAEzB,MAAM,oBAAoB,aAAa,SAAS;GAC9C,MAAM,QAAQ,MAAM;GACpB,SAAS,QAAQ,M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AG,QAAQ,KAAK,QAAQ,YAAY,SAAS,GAAG;GAE/D,MAAM,UAAU,MAAM,YAAY,KAAK,QAAQ,SAAS;GACxD,SAAS;GACT,IAAI,UAAU,KAAK,QAAQ,WAAW;EACxC;EACA,OAAO;CACT;AACF;;;;;AChCA,IAAa,aAAb,MAAiE;CAClC;CAA7B,YAAY,AAAiB,MAAiC;EAAjC;CAAkC;CAE/D,MAAM,IAAO,WAAsB,MAAgD;EACjF,MAAM,EAAE,aAAa,cAAc,oBAAoB,gBAAgB,UAAU,KAAK;EACtF,IAAI,UAAU;EAEd,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,YAAY,YAAY,OAAO,OAAO;IAClD,MAAM,QAAQ,aAAa,EAAE;IAC7B,MAAM,MAAM,MAAM,SAAS;IAE3B,MAAM,SAAS,MAAM,KADP,mBAAmB,EACH,CAAC;IAC/B,MAAM,UAAU,eAAe,QAAQ;IACvC,MAAM,MAAM,cAAc,OAAO;IACjC,UAAU,QAAQ;IAClB,OAAO;GACT,CAAC;EACH,SAAS,OAAO;GACd,MAAM,6BAA6B,KAAK,OAAO,SAAS,KAAK;EAC/D;EAEA,IAAI,UAAU,GAAG,MAAM,KAAK;EAC5B,OAAO;CACT;AACF;;;;;ACnDA,IAAa,+BAAb,cAAkD,SAAS;CACzD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,kCAAkC;CAC1C;AACF"}
1
+ {"version":3,"file":"application-Cf9SER-i.js","names":["logger"],"sources":["../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/email-service.ts","../src/application/record-email-event.ts","../src/application/message-already-processed.error.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/outbox-retention.ts","../src/application/unit-of-work.ts","../src/application/unit-of-work.errors.ts"],"sourcesContent":["import type { AnalyticsEventIdentity, AnalyticsEventInput, AnalyticsProperties } from '@/core'\n\n/** Product analytics without an SDK dependency, ported from Typist and Porte. */\nexport interface AnalyticsService<TEvent extends AnalyticsEventInput = AnalyticsEventInput> {\n /** Attach traits to one person. */\n identify(distinctId: string, properties?: AnalyticsProperties): void\n /** Merge a previous ID into this person; the application must establish that both identify the same person. */\n alias(distinctId: string, previousDistinctId: string): void\n /** Schedule an event for a person; returning does not confirm remote acceptance. */\n track(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n /** Schedule an event without creating a person profile for its distinct ID. */\n trackAnonymous(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n}\n\n/** Reports to nobody. The composition root selects this service when analytics is disabled. */\nexport const NULL_ANALYTICS: AnalyticsService = {\n identify: () => {},\n alias: () => {},\n track: () => {},\n trackAnonymous: () => {},\n}\n","/** A metric dimension; use a small, bounded value set and never user or request IDs. */\nexport type MetricAttributeValue = string | number | boolean\n\n/** Dimensions shared by observations in one time series. */\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>\n\n/** Unit and dimensions for an operational measurement. */\nexport interface MetricOptions {\n readonly attributes?: MetricAttributes\n readonly unit?: string\n}\n\n/** Operational measurements, ported from Typist's metrics-service.ts; applications own metric names. */\nexport interface MetricsService<TName extends string = string> {\n /** Add a nonnegative value to a total; the default increment is one. */\n count(name: TName, value?: number, options?: MetricOptions): void\n /** Record a current value. */\n gauge(name: TName, value: number, options?: MetricOptions): void\n /** Record one observation in a distribution. */\n histogram(name: TName, value: number, options?: MetricOptions): void\n}\n\n/** Records nothing when the composition root disables metrics. */\nexport const NULL_METRICS_SERVICE: MetricsService = {\n count: () => {},\n gauge: () => {},\n histogram: () => {},\n}\n","import type { EmailIdempotencyKey } from '@/core'\n\n/** A media type such as `application/pdf`. */\nexport type MimeType = `${string}/${string}`\n\n/** A file to attach. Binary content is bytes; the adapter encodes it for the provider. */\nexport type EmailAttachment = {\n readonly filename: string\n readonly content: string | Uint8Array\n /** Optional MIME metadata; Resend accepts filename and content without it. */\n readonly contentType?: MimeType\n}\n\n/**\n * One transactional email. Resend accepts 50 recipients, 75 tags with ASCII names and values,\n * and 40 MB of attachments after base64. Sources: https://resend.com/docs/api-reference/emails/send-email\n * and https://resend.com/docs/dashboard/emails/tags\n */\nexport type OutboundEmail = {\n /** Override the default for this email, for example \"Display Name <address@domain.com>\". */\n readonly from?: string\n readonly to: string | readonly string[]\n readonly subject: string\n readonly html: string\n /** Optional stable identity of this send. Resend deduplicates supplied keys for 24 hours. */\n readonly idempotencyKey?: EmailIdempotencyKey\n /** Resend generates plain text from html when omitted. An empty string disables that generation. */\n readonly text?: string\n readonly replyTo?: string\n /** Labels the provider stores with the email and returns on every delivery event. */\n readonly tags?: Readonly<Record<string, string>>\n readonly attachments?: readonly EmailAttachment[]\n}\n\n/** The provider accepted the email and assigned its id. */\nexport type EmailAccepted = { readonly providerId: string }\n\n/**\n * The adapter supplies the default sender and maps provider errors. Each email can override the sender.\n * A provider rejection throws `EmailServiceError`; unexpected SDK rejections propagate unchanged.\n */\nexport interface IEmailService {\n /** Resolve after provider acceptance; this does not confirm delivery to the recipient. */\n sendEmail(email: OutboundEmail): Promise<EmailAccepted>\n}\n\n/** Records every send for a test. Provider ids count up as `recorded-1`, `recorded-2`. */\nexport class RecordingEmailService implements IEmailService {\n /** Sends in call order, including repeated idempotency keys. */\n readonly sent: OutboundEmail[] = []\n\n /** Record the send before returning its provider id. */\n async sendEmail(email: OutboundEmail): Promise<EmailAccepted> {\n this.sent.push(email)\n return { providerId: `recorded-${this.sent.length}` }\n }\n}\n","import type { BounceType, DomainCommand, EmailAddress, RecordEmailEventPayload } from '@/core'\n\nimport type { IUnitOfWork } from './unit-of-work.ts'\n\n/** What a bounce records for one address. */\nexport type EmailBounceRecord = {\n readonly type: BounceType\n readonly subType: string | null\n}\n\n/**\n * The application's deliverability state per address. An implementation keeps the higher bounce\n * severity with `shouldUpdateBounce`, and treats an unknown address as nothing to record.\n */\nexport interface IEmailDeliverabilityStore {\n /** Keep the higher severity atomically. Equal severity permits replacement; the store owns timestamp ordering. */\n recordBounce(address: EmailAddress, bounce: EmailBounceRecord): Promise<void>\n /** Record a complaint without clearing existing suppression state. */\n recordComplaint(address: EmailAddress): Promise<void>\n}\n\n/** The repositories the handler needs from the unit of work. */\nexport type RecordEmailEventRepos = { readonly emailDeliverability: IEmailDeliverabilityStore }\n\n/** The container slice the handler reads. */\nexport type RecordEmailEventDeps = { readonly uow: IUnitOfWork<RecordEmailEventRepos> }\n\n/** The command, under whatever name the application registered the payload. */\nexport type RecordEmailEventCommand = DomainCommand & RecordEmailEventPayload\n\n/**\n * Record a bounce or a complaint for every recipient inside the command's unit of work.\n * The command id is the provider's event id, so a redelivered webhook is `MessageAlreadyProcessedError`.\n */\nexport async function recordEmailEvent(\n command: RecordEmailEventCommand,\n deps: RecordEmailEventDeps,\n): Promise<void> {\n await deps.uow.run(command.id, async ({ emailDeliverability }) => {\n for (const address of command.recipients) {\n if (command.event.type === 'bounced') {\n // oxlint-disable-next-line no-await-in-loop -- Finish each transaction write before starting another; a failure must leave no pending writes.\n await emailDeliverability.recordBounce(address, {\n type: command.event.bounceType,\n subType: command.event.bounceSubType,\n })\n } else {\n // oxlint-disable-next-line no-await-in-loop -- A rejected write must stop the transaction before another write starts.\n await emailDeliverability.recordComplaint(address)\n }\n }\n })\n}\n","import { AppError, DatabaseError, type MessageId } from '@/core'\n\n/** The message's effects already committed. A caller can skip duplicate delivery without repeating those effects. */\nexport class MessageAlreadyProcessedError extends AppError {\n readonly _tag = 'MessageAlreadyProcessedError'\n readonly classification = 'terminal'\n\n constructor(\n readonly messageId: MessageId,\n options?: { readonly cause: unknown },\n ) {\n super(`message ${messageId} already processed`, options)\n }\n\n /** Recognize only the processed-message primary key; preserve other failures unchanged at the call site. */\n static from(cause: unknown, messageId: MessageId): MessageAlreadyProcessedError | undefined {\n if (cause instanceof MessageAlreadyProcessedError) return cause\n if (!(cause instanceof DatabaseError)) return undefined\n const details = cause.details\n const duplicate =\n details.database === 'd1'\n ? details.kind === 'unique' &&\n details.table === 'processed_messages' &&\n details.column === 'message_id'\n : details.code === '23505' &&\n details.table_name === 'processed_messages' &&\n details.constraint_name === 'processed_messages_pkey'\n if (!duplicate) return undefined\n return new MessageAlreadyProcessedError(messageId, { cause })\n }\n}\n","import { panic } from 'better-result'\n\nimport {\n createLogger,\n unreachable,\n type DomainCommand,\n type DomainEvent,\n type DomainMessage,\n type DomainQuery,\n} from '@/core'\n\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { Handlers, MessageResult, RegistryMessage } from './registry.ts'\n\nconst logger = createLogger('message-bus')\n\n/** The port an entrypoint dispatches through. `AppDeps` names this as `IMessageBus<typeof registry>`. */\nexport interface IMessageBus<TRegistry extends Handlers<never>> {\n handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>>\n}\n\n/**\n * Routes one message to its slot. The bus opens no transaction and keeps no outbox:\n * a handler that writes opens the unit of work itself.\n */\nexport class MessageBus<Deps, TRegistry extends Handlers<Deps>> implements IMessageBus<TRegistry> {\n constructor(\n private readonly deps: Deps,\n private readonly registry: TRegistry,\n ) {}\n\n /** Resolves to the handler's own value for a command or query, and to void for an event. */\n async handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>> {\n // SAFETY: the slot for this name is what `MessageResult` names, and dispatch returns its value.\n return (await this.dispatch(message)) as MessageResult<TMessage, TRegistry>\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- one table holds every slot's value; `handle` names it.\n private dispatch(message: DomainMessage): Promise<unknown> {\n if (message.type === 'command') return this.handleCommand(message)\n if (message.type === 'query') return this.handleQuery(message)\n if (message.type === 'event') return this.handleEvent(message)\n // A message parsed at a boundary cannot reach here; one that does must not resolve silently.\n return unreachable(message)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleCommand(command: DomainCommand): Promise<unknown> {\n // `satisfies` proved the registry complete, so a missing slot is a broken registry object.\n const handler = this.registry.commands[command.name]\n if (handler === undefined) return panic(`No handler for command ${command.name}`)\n logger.debug('handling_command', { name: command.name, id: command.id })\n return handler(command, this.deps)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleQuery(query: DomainQuery): Promise<unknown> {\n const handler = this.registry.queries[query.name]\n if (handler === undefined) return panic(`No handler for query ${query.name}`)\n return handler(query, this.deps)\n }\n\n /**\n * Every subscriber runs to completion. One failure is rethrown as is. Several are thrown as\n * one `AggregateError`. A `MessageAlreadyProcessedError` means that subscriber already committed on\n * an earlier delivery, so it counts as delivered.\n */\n private async handleEvent(event: DomainEvent): Promise<void> {\n const subscriptions = this.registry.events[event.name] ?? []\n const outcomes = await Promise.allSettled(\n subscriptions.map((subscription) => subscription(event, this.deps)),\n )\n const failures: unknown[] = []\n for (const [subscriber, outcome] of outcomes.entries()) {\n if (outcome.status === 'fulfilled') continue\n if (outcome.reason instanceof MessageAlreadyProcessedError) {\n // The bus swallows this error, so this line is the only record that the skip happened.\n logger.info('duplicate_subscriber_ignored', { event: event.name, id: event.id, subscriber })\n continue\n }\n failures.push(outcome.reason)\n }\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${event.name}: ${failures.length} subscribers failed`)\n }\n }\n}\n","import { classifyFailure, createLogger, type DomainEvent } from '@/core'\n\nimport type {\n DeadLetterReason,\n IOutboxRepository,\n OutboxClaim,\n OutboxMessage,\n} from './outbox-repository.ts'\n\n/**\n * Delivers committed outbox rows. The unit of work only wakes it after a commit that wrote\n * events; the app decides what a wake is: `waitUntil`, a Durable Object alarm, nothing.\n * The sweep is the source of truth, so a lost wake loses no events.\n */\nexport interface IOutboxRelay {\n wake(): void\n}\n\n/** The publisher sends valid events and returns oversized events. QueueClient satisfies this port directly. */\nexport interface IOutboxPublisher {\n /** Resolves after queue acceptance; a rejected batch may already have sent some events. */\n sendBatchPartial(messages: ReadonlyArray<DomainEvent>): Promise<ReadonlyArray<DomainEvent>>\n}\n\n/** Optional limits for one relay; durable attempts exclude the publisher's immediate retries. */\nexport type OutboxRelayOptions = {\n readonly batchSize?: number\n readonly maxBatches?: number\n readonly maxAttempts?: number\n}\n\nconst logger = createLogger('outbox-relay')\n\n/**\n * Publishes committed events with bounded durable retries. Ported from Typist's relay with per-row exhaustion.\n * Send failures are recorded; repository failures propagate to the wake or scheduled boundary.\n */\nexport class OutboxRelay {\n private readonly options: Required<OutboxRelayOptions>\n\n constructor(\n private readonly publisher: IOutboxPublisher,\n private readonly repository: IOutboxRepository,\n options: OutboxRelayOptions = {},\n ) {\n this.options = {\n batchSize: options.batchSize ?? 50,\n maxBatches: options.maxBatches ?? 10,\n maxAttempts: options.maxAttempts ?? 10,\n }\n }\n\n /** Return the claimed count, including released and dead-lettered rows. Zero means no due rows. */\n async flush(): Promise<number> {\n const claim = await this.repository.claimPending(this.options.batchSize)\n const exhausted = claim.messages.filter((row) => row.attempts > this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', 'Claim attempt limit exceeded')\n const pending = claim.messages.filter((row) => row.attempts <= this.options.maxAttempts)\n if (pending.length === 0) return claim.messages.length\n\n let oversized: ReadonlyArray<DomainEvent>\n try {\n oversized = await this.publisher.sendBatchPartial(pending.map((row) => row.payload))\n } catch (error) {\n await this.handleSendFailure(claim, pending, error)\n return claim.messages.length\n }\n\n const oversizedIds = new Set(oversized.map((event) => event.id))\n await this.deadLetter(\n claim,\n pending.filter((row) => oversizedIds.has(row.payload.id)),\n 'oversized',\n 'Exceeds queue message size limit',\n )\n const sent = pending.filter((row) => !oversizedIds.has(row.payload.id))\n if (sent.length > 0) await this.repository.markPublished(claim, sent)\n return claim.messages.length\n }\n\n /** Drain until an empty claim or the batch limit; return the total claimed count. */\n async drain(): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- An empty claim must stop the drain before another claim starts.\n const claimed = await this.flush()\n total += claimed\n if (claimed === 0) break\n }\n return total\n }\n\n private async handleSendFailure(\n claim: OutboxClaim,\n pending: ReadonlyArray<OutboxMessage>,\n cause: unknown,\n ): Promise<void> {\n const classification = classifyFailure(cause)\n const message =\n cause instanceof Error ? cause.message : 'Publisher rejected with a non-error value'\n if (classification === 'terminal') {\n await this.deadLetter(claim, pending, 'terminal', message, cause)\n return\n }\n const exhausted = pending.filter((row) => row.attempts >= this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', message, cause)\n const retry = pending.filter((row) => row.attempts < this.options.maxAttempts)\n if (retry.length > 0) await this.repository.releaseClaim(claim, retry)\n }\n\n private async deadLetter(\n claim: OutboxClaim,\n messages: ReadonlyArray<OutboxMessage>,\n reason: DeadLetterReason,\n errorMessage: string,\n cause?: unknown,\n ): Promise<void> {\n if (messages.length === 0) return\n await this.repository.deadLetter(claim, messages, reason, errorMessage)\n logger.error('outbox_messages_dead_lettered', {\n error: cause,\n details: { claimToken: claim.token, count: messages.length, reason },\n })\n }\n}\n","import type { IOutboxRetentionRepository } from './outbox-repository.ts'\n\n/** Typist's retention defaults; receipt retention must cover the application's supported replay period. */\nexport type OutboxRetentionOptions = {\n readonly publishedRetentionMs?: number\n readonly failedRetentionMs?: number\n readonly receiptRetentionMs?: number\n readonly batchSize?: number\n readonly maxBatches?: number\n}\n\n/** Deleted records per category during one bounded sweep. */\nexport type OutboxRetentionResult = {\n readonly published: number\n readonly failed: number\n readonly receipts: number\n}\n\n/** Bounded cleanup ported from Typist's message retention handler. The application schedules each sweep. */\nexport class OutboxRetention {\n private readonly options: Required<OutboxRetentionOptions>\n\n constructor(\n private readonly repository: IOutboxRetentionRepository,\n options: OutboxRetentionOptions = {},\n ) {\n this.options = {\n publishedRetentionMs: options.publishedRetentionMs ?? 86_400_000,\n failedRetentionMs: options.failedRetentionMs ?? 30 * 86_400_000,\n receiptRetentionMs: options.receiptRetentionMs ?? 7 * 86_400_000,\n batchSize: options.batchSize ?? 1_000,\n maxBatches: options.maxBatches ?? 10,\n }\n }\n\n /** Calculate all cutoffs from one supplied time; propagate repository failures to the calling boundary. */\n async sweep(at: Date): Promise<OutboxRetentionResult> {\n const { publishedRetentionMs, failedRetentionMs, receiptRetentionMs } = this.options\n const published = await this.deleteBatches((size) =>\n this.repository.deletePublishedBefore(new Date(at.getTime() - publishedRetentionMs), size),\n )\n const failed = await this.deleteBatches((size) =>\n this.repository.deleteFailedBefore(new Date(at.getTime() - failedRetentionMs), size),\n )\n const receipts = await this.deleteBatches((size) =>\n this.repository.deleteReceiptsBefore(new Date(at.getTime() - receiptRetentionMs), size),\n )\n return { published, failed, receipts }\n }\n\n private async deleteBatches(deleteBatch: (size: number) => Promise<number>): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- The delete count decides whether another batch is needed.\n const deleted = await deleteBatch(this.options.batchSize)\n total += deleted\n if (deleted < this.options.batchSize) break\n }\n return total\n }\n}\n","import type { MessageId } from '@/core'\n\nimport type { IEventCollector } from './event-collector.ts'\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { IMessageStore } from './message-store.ts'\nimport type { IOutboxRelay } from './outbox-relay.ts'\nimport type { ITransaction } from './transaction.ts'\n\n/**\n * Commits the processed-message record, repository writes, and emitted events together before resolving.\n * An existing record rejects with `MessageAlreadyProcessedError`; external effects must run through the outbox after commit.\n * Nested calls reject with `UnitOfWorkAlreadyActiveError`; independent concurrent calls are allowed.\n */\nexport interface IUnitOfWork<Repos> {\n run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T>\n}\n\nexport type UnitOfWorkDeps<Tx, Repos> = {\n readonly transaction: ITransaction<Tx>\n /** The processed-messages and outbox repository for this transaction. */\n readonly messageStore: (tx: Tx) => IMessageStore\n /** Repositories participate in the current transaction. */\n readonly createRepositories: (tx: Tx) => Repos\n readonly eventCollector: IEventCollector\n readonly relay: IOutboxRelay\n}\n\n/** The unit of work: the boundary, the repositories, the events. Every database call is a port. */\nexport class UnitOfWork<Tx, Repos> implements IUnitOfWork<Repos> {\n constructor(private readonly deps: UnitOfWorkDeps<Tx, Repos>) {}\n\n async run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T> {\n const { transaction, messageStore, createRepositories, eventCollector, relay } = this.deps\n let written = 0\n\n let value: T\n try {\n value = await transaction.transaction(async (tx) => {\n const store = messageStore(tx)\n await store.claim(messageId)\n const repos = createRepositories(tx)\n const result = await work(repos)\n const pending = eventCollector.collect()\n await store.persistEvents(pending)\n written = pending.length\n return result\n })\n } catch (error) {\n throw MessageAlreadyProcessedError.from(error, messageId) ?? error\n }\n\n if (written > 0) relay.wake()\n return value\n }\n}\n","import { AppError } from '@/core'\n\n/** A boundary was opened inside another. One message, one atomic scope. */\nexport class UnitOfWorkAlreadyActiveError extends AppError {\n readonly _tag = 'UnitOfWorkAlreadyActiveError'\n readonly classification = 'terminal'\n\n constructor() {\n super('a unit of work is already active')\n }\n}\n"],"mappings":";;;;;AAeA,MAAa,iBAAmC;CAC9C,gBAAgB,CAAC;CACjB,aAAa,CAAC;CACd,aAAa,CAAC;CACd,sBAAsB,CAAC;AACzB;;;;;ACGA,MAAa,uBAAuC;CAClD,aAAa,CAAC;CACd,aAAa,CAAC;CACd,iBAAiB,CAAC;AACpB;;;;;ACoBA,IAAa,wBAAb,MAA4D;;CAE1D,AAAS,OAAwB,CAAC;;CAGlC,MAAM,UAAU,OAA8C;EAC5D,KAAK,KAAK,KAAK,KAAK;EACpB,OAAO,EAAE,YAAY,YAAY,KAAK,KAAK,SAAS;CACtD;AACF;;;;;;;;ACtBA,eAAsB,iBACpB,SACA,MACe;CACf,MAAM,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAO,EAAE,0BAA0B;EAChE,KAAK,MAAM,WAAW,QAAQ,YAC5B,IAAI,QAAQ,MAAM,SAAS,WAEzB,MAAM,oBAAoB,aAAa,SAAS;GAC9C,MAAM,QAAQ,MAAM;GACpB,SAAS,QA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Q,GAAG,QAAQ,KAAK,QAAQ,YAAY,SAAS,GAAG;GAE/D,MAAM,UAAU,MAAM,YAAY,KAAK,QAAQ,SAAS;GACxD,SAAS;GACT,IAAI,UAAU,KAAK,QAAQ,WAAW;EACxC;EACA,OAAO;CACT;AACF;;;;;AChCA,IAAa,aAAb,MAAiE;CAClC;CAA7B,YAAY,AAAiB,MAAiC;EAAjC;CAAkC;CAE/D,MAAM,IAAO,WAAsB,MAAgD;EACjF,MAAM,EAAE,aAAa,cAAc,oBAAoB,gBAAgB,UAAU,KAAK;EACtF,IAAI,UAAU;EAEd,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,YAAY,YAAY,OAAO,OAAO;IAClD,MAAM,QAAQ,aAAa,EAAE;IAC7B,MAAM,MAAM,MAAM,SAAS;IAE3B,MAAM,SAAS,MAAM,KADP,mBAAmB,EACH,CAAC;IAC/B,MAAM,UAAU,eAAe,QAAQ;IACvC,MAAM,MAAM,cAAc,OAAO;IACjC,UAAU,QAAQ;IAClB,OAAO;GACT,CAAC;EACH,SAAS,OAAO;GACd,MAAM,6BAA6B,KAAK,OAAO,SAAS,KAAK;EAC/D;EAEA,IAAI,UAAU,GAAG,MAAM,KAAK;EAC5B,OAAO;CACT;AACF;;;;;ACnDA,IAAa,+BAAb,cAAkD,SAAS;CACzD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,kCAAkC;CAC1C;AACF"}
@@ -1,3 +1,3 @@
1
- import { G as DomainEvent, J as MessageId, K as DomainMessage, W as DomainCommand, q as DomainQuery } from "./index-G1QG0P5g.js";
2
- import { $ as EventHandler, A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, G as MetricAttributeValue, H as ObservabilityScope, I as EmailAccepted, J as MetricsService, K as MetricAttributes, L as EmailAttachment, M as OutboxClaim, N as OutboxMessage, O as OutboxRelayOptions, P as IMessageStore, Q as CommandHandler, R as IEmailService, S as UnitOfWork, T as IOutboxPublisher, U as ObservabilityService, V as RecordingEmailService, W as ObservabilityUser, X as AnalyticsService, Y as NULL_METRICS_SERVICE, Z as NULL_ANALYTICS, _ as RecordEmailEventCommand, a as OutboxRetentionResult, b as recordEmailEvent, c as CommandRegistry, d as MessageRegistry, et as QueryHandler, f as MessageResult, g as IEmailDeliverabilityStore, h as EmailBounceRecord, i as OutboxRetentionOptions, j as IOutboxRetentionRepository, k as DeadLetterReason, l as EventRegistry, m as RegistryMessage, n as MessageAlreadyProcessedError, o as IMessageBus, p as QueryRegistry, q as MetricOptions, r as OutboxRetention, s as MessageBus, t as UnitOfWorkAlreadyActiveError, u as Handlers, v as RecordEmailEventDeps, w as ITransaction, x as IUnitOfWork, y as RecordEmailEventRepos, z as MimeType } from "./index-B45Dr5gs.js";
1
+ import { J as DomainMessage, K as DomainCommand, X as MessageId, Y as DomainQuery, q as DomainEvent } from "./index-DvJUcSW1.js";
2
+ import { $ as EventHandler, A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, G as MetricAttributeValue, H as ObservabilityScope, I as EmailAccepted, J as MetricsService, K as MetricAttributes, L as EmailAttachment, M as OutboxClaim, N as OutboxMessage, O as OutboxRelayOptions, P as IMessageStore, Q as CommandHandler, R as IEmailService, S as UnitOfWork, T as IOutboxPublisher, U as ObservabilityService, V as RecordingEmailService, W as ObservabilityUser, X as AnalyticsService, Y as NULL_METRICS_SERVICE, Z as NULL_ANALYTICS, _ as RecordEmailEventCommand, a as OutboxRetentionResult, b as recordEmailEvent, c as CommandRegistry, d as MessageRegistry, et as QueryHandler, f as MessageResult, g as IEmailDeliverabilityStore, h as EmailBounceRecord, i as OutboxRetentionOptions, j as IOutboxRetentionRepository, k as DeadLetterReason, l as EventRegistry, m as RegistryMessage, n as MessageAlreadyProcessedError, o as IMessageBus, p as QueryRegistry, q as MetricOptions, r as OutboxRetention, s as MessageBus, t as UnitOfWorkAlreadyActiveError, u as Handlers, v as RecordEmailEventDeps, w as ITransaction, x as IUnitOfWork, y as RecordEmailEventRepos, z as MimeType } from "./index-Cchdg2aQ.js";
3
3
  export { type AnalyticsService, type CommandHandler, type CommandRegistry, type DeadLetterReason, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAccepted, type EmailAttachment, type EmailBounceRecord, type EventHandler, type EventRegistry, type Handlers, type IEmailDeliverabilityStore, type IEmailService, type IEventCollector, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRelay, type IOutboxRepository, type IOutboxRetentionRepository, type ITransaction, type IUnitOfWork, MessageAlreadyProcessedError, MessageBus, type MessageId, type MessageRegistry, type MessageResult, type MetricAttributeValue, type MetricAttributes, type MetricOptions, type MetricsService, type MimeType, NULL_ANALYTICS, NULL_METRICS_SERVICE, type ObservabilityScope, type ObservabilityService, type ObservabilityUser, type OutboundEmail, type OutboxClaim, type OutboxMessage, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type QueryHandler, type QueryRegistry, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, recordEmailEvent };
@@ -1,3 +1,3 @@
1
- import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-C4JOf71r.js";
1
+ import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-Cf9SER-i.js";
2
2
 
3
3
  export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, recordEmailEvent };
@@ -1,4 +1,4 @@
1
- import { Zt as AppError } from "../index-G1QG0P5g.js";
1
+ import { $t as AppError } from "../index-DvJUcSW1.js";
2
2
  //#region src/infrastructure/better-auth/apple-client-secret.d.ts
3
3
  /**
4
4
  * Apple's issuer and OAuth callback origin, and the `aud` claim of the client secret. Include it in
@@ -1,4 +1,4 @@
1
- import { a as createLogger, tt as AppError } from "../core-hdaNiCOU.js";
1
+ import { a as createLogger, rt as AppError } from "../core-ClSP5-V9.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { createPrivateKey, sign } from "node:crypto";
4
4
 
@@ -1,4 +1,4 @@
1
- import { H as RateLimitError } from "../core-hdaNiCOU.js";
1
+ import { W as RateLimitError } from "../core-ClSP5-V9.js";
2
2
  import { createAuthClient } from "better-auth/client";
3
3
 
4
4
  //#region src/infrastructure/better-auth/auth-client.ts
@@ -1,4 +1,4 @@
1
- import { Zt as AppError } from "../index-G1QG0P5g.js";
1
+ import { $t as AppError } from "../index-DvJUcSW1.js";
2
2
  import { BetterAuthOptions, BetterAuthRateLimitStorage } from "better-auth";
3
3
  //#region src/infrastructure/better-auth/rate-limit.d.ts
4
4
  /** A rule Better Auth passes to storage: a window in seconds and the requests it allows. */
@@ -1,4 +1,4 @@
1
- import { a as createLogger, tt as AppError } from "../core-hdaNiCOU.js";
1
+ import { a as createLogger, rt as AppError } from "../core-ClSP5-V9.js";
2
2
 
3
3
  //#region src/infrastructure/better-auth/rate-limit.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { a as createLogger } from "./core-hdaNiCOU.js";
1
+ import { a as createLogger } from "./core-ClSP5-V9.js";
2
2
  import { v7 } from "uuid";
3
3
  import { isAPIError } from "better-auth/api";
4
4
  import { anonymous, bearer, captcha, deviceAuthorization, emailOTP, lastLoginMethod, magicLink, openAPI } from "better-auth/plugins";
@@ -1,4 +1,4 @@
1
- import { Zt as AppError } from "../index-G1QG0P5g.js";
1
+ import { $t as AppError } from "../index-DvJUcSW1.js";
2
2
  import { DurableObject } from "cloudflare:workers";
3
3
  //#region src/infrastructure/cloudflare/auth-secondary-storage.d.ts
4
4
  /** The supplied TTL cannot produce a valid expiry timestamp. Retrying the same input cannot fix it. */
@@ -1,4 +1,4 @@
1
- import { tt as AppError } from "../core-hdaNiCOU.js";
1
+ import { rt as AppError } from "../core-ClSP5-V9.js";
2
2
  import { DurableObject } from "cloudflare:workers";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/auth-secondary-storage.ts
@@ -1,4 +1,4 @@
1
- import { x as shouldRetryFailure, y as isAbortError } from "../core-hdaNiCOU.js";
1
+ import { x as shouldRetryFailure, y as isAbortError } from "../core-ClSP5-V9.js";
2
2
  import { DurableObjectCallError, classifyDurableObjectError, isClassifiedDurableObjectError } from "./durable-object-errors.js";
3
3
  import { Result } from "better-result";
4
4
 
@@ -1,4 +1,4 @@
1
- import { Qt as FailureClassification, Zt as AppError } from "../index-G1QG0P5g.js";
1
+ import { $t as AppError, en as FailureClassification } from "../index-DvJUcSW1.js";
2
2
  import { z } from "zod";
3
3
  //#region src/infrastructure/cloudflare/durable-object-errors.d.ts
4
4
  /** Stable tag for a failed Durable Object call. */
@@ -1,4 +1,4 @@
1
- import { _ as isCloudflareRetryableError, b as isTransientTransportError, g as isCloudflareOverloadedError, tt as AppError, v as isTransientCloudflareRuntimeError, y as isAbortError } from "../core-hdaNiCOU.js";
1
+ import { _ as isCloudflareRetryableError, b as isTransientTransportError, g as isCloudflareOverloadedError, rt as AppError, v as isTransientCloudflareRuntimeError, y as isAbortError } from "../core-ClSP5-V9.js";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/durable-object-errors.ts
@@ -0,0 +1,31 @@
1
+ //#region src/infrastructure/cloudflare/kv-client.d.ts
2
+ /** Text storage bridge with the same TTL behavior as KVClient. */
3
+ export type KVSecondaryStorage = {
4
+ get: (key: string) => Promise<string | null>;
5
+ set: (key: string, value: string, ttl?: number) => Promise<void>;
6
+ delete: (key: string) => Promise<void>;
7
+ };
8
+ /** KV access with Typist's automatic transient retries and final KVError conversion. */
9
+ export declare class KVClient {
10
+ private readonly kv;
11
+ constructor(kv: KVNamespace);
12
+ /** Read text, or return null when the key does not exist. */
13
+ get(key: string): Promise<string | null>;
14
+ /** Read JSON without schema validation; the caller supplies its stored type. */
15
+ getJson<T>(key: string): Promise<T | null>;
16
+ /** Write text; positive TTL values pass to KV in seconds, and other TTL values omit expiration. */
17
+ put(key: string, value: string, options?: {
18
+ ttl?: number | undefined;
19
+ }): Promise<void>;
20
+ /** Serialize once before writing; serialization failures retain their original error. */
21
+ putJson(key: string, value: unknown, options?: {
22
+ ttl?: number | undefined;
23
+ }): Promise<void>;
24
+ /** Delete a key; a missing key succeeds, and transient failures retry automatically. */
25
+ delete(key: string): Promise<void>;
26
+ /** Expose Typist's three-method secondary storage bridge without changing KV semantics. */
27
+ asSecondaryStorage(): KVSecondaryStorage;
28
+ private run;
29
+ }
30
+ //#endregion
31
+ //# sourceMappingURL=kv-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-client.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/kv-client.ts"],"mappings":";;YAOY;EACV,MAAM,gBAAgB;EACtB,MAAM,aAAa,eAAe,iBAAiB;EACnD,SAAS,gBAAgB;;;qBAMd;mBACkB;EAA7B,YAA6B,IAAI;;EAG3B,IAAI,cAAc;;EAKlB,QAAQ,GAAG,cAAc,QAAQ;;EAKjC,IAAI,aAAa,eAAe;IAAY;MAA6B;;EASzE,QACJ,aAEA,gBACA;IAAY;MACX;;EAKG,OAAO,cAAc;;EAK3B,sBAAsB;UAQR"}
@@ -0,0 +1,62 @@
1
+ import { c as exponentialDelayCapMs, u as spreadJitterMs } from "../core-ClSP5-V9.js";
2
+ import { KVError, decideKVRetry, isKVPutRateLimitError } from "./kv-errors.js";
3
+ import { Result } from "better-result";
4
+
5
+ //#region src/infrastructure/cloudflare/kv-client.ts
6
+ /** KV access with Typist's automatic transient retries and final KVError conversion. */
7
+ var KVClient = class {
8
+ kv;
9
+ constructor(kv) {
10
+ this.kv = kv;
11
+ }
12
+ /** Read text, or return null when the key does not exist. */
13
+ async get(key) {
14
+ return await this.run("get", key, async () => this.kv.get(key));
15
+ }
16
+ /** Read JSON without schema validation; the caller supplies its stored type. */
17
+ async getJson(key) {
18
+ return await this.run("get", key, async () => this.kv.get(key, "json"));
19
+ }
20
+ /** Write text; positive TTL values pass to KV in seconds, and other TTL values omit expiration. */
21
+ async put(key, value, options) {
22
+ const kvOptions = {};
23
+ if (options?.ttl !== void 0 && options.ttl > 0) kvOptions.expirationTtl = options.ttl;
24
+ await this.run("put", key, async () => this.kv.put(key, value, kvOptions));
25
+ }
26
+ /** Serialize once before writing; serialization failures retain their original error. */
27
+ async putJson(key, value, options) {
28
+ await this.put(key, JSON.stringify(value), options);
29
+ }
30
+ /** Delete a key; a missing key succeeds, and transient failures retry automatically. */
31
+ async delete(key) {
32
+ await this.run("delete", key, async () => this.kv.delete(key));
33
+ }
34
+ /** Expose Typist's three-method secondary storage bridge without changing KV semantics. */
35
+ asSecondaryStorage() {
36
+ return {
37
+ get: (key) => this.get(key),
38
+ set: (key, value, ttl) => this.put(key, value, { ttl }),
39
+ delete: (key) => this.delete(key)
40
+ };
41
+ }
42
+ async run(operation, key, work) {
43
+ const result = await Result.tryPromise({
44
+ try: work,
45
+ catch: (cause) => cause
46
+ }, { retry: {
47
+ times: 2,
48
+ shouldRetry: (cause) => decideKVRetry(cause).retry,
49
+ delayMs: (cause, { attempt }) => (isKVPutRateLimitError(cause) ? 1e3 : 0) + spreadJitterMs(exponentialDelayCapMs(25, 3e3, attempt))
50
+ } });
51
+ if (result.isOk()) return result.value;
52
+ throw new KVError({
53
+ operation,
54
+ key,
55
+ cause: result.error
56
+ });
57
+ }
58
+ };
59
+
60
+ //#endregion
61
+ export { KVClient };
62
+ //# sourceMappingURL=kv-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-client.js","names":[],"sources":["../../src/infrastructure/cloudflare/kv-client.ts"],"sourcesContent":["import { Result } from 'better-result'\n\nimport { exponentialDelayCapMs, spreadJitterMs } from '@/core'\n\nimport { decideKVRetry, isKVPutRateLimitError, KVError } from './kv-errors.ts'\n\n/** Text storage bridge with the same TTL behavior as KVClient. */\nexport type KVSecondaryStorage = {\n get: (key: string) => Promise<string | null>\n set: (key: string, value: string, ttl?: number) => Promise<void>\n delete: (key: string) => Promise<void>\n}\n\ntype KVOperation = 'get' | 'put' | 'delete'\n\n/** KV access with Typist's automatic transient retries and final KVError conversion. */\nexport class KVClient {\n constructor(private readonly kv: KVNamespace) {}\n\n /** Read text, or return null when the key does not exist. */\n async get(key: string): Promise<string | null> {\n return await this.run('get', key, async () => this.kv.get(key))\n }\n\n /** Read JSON without schema validation; the caller supplies its stored type. */\n async getJson<T>(key: string): Promise<T | null> {\n return await this.run('get', key, async () => this.kv.get<T>(key, 'json'))\n }\n\n /** Write text; positive TTL values pass to KV in seconds, and other TTL values omit expiration. */\n async put(key: string, value: string, options?: { ttl?: number | undefined }): Promise<void> {\n const kvOptions: KVNamespacePutOptions = {}\n if (options?.ttl !== undefined && options.ttl > 0) {\n kvOptions.expirationTtl = options.ttl\n }\n await this.run('put', key, async () => this.kv.put(key, value, kvOptions))\n }\n\n /** Serialize once before writing; serialization failures retain their original error. */\n async putJson(\n key: string,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Preserve the approved JSON serialization boundary and Typist's public signature.\n value: unknown,\n options?: { ttl?: number | undefined },\n ): Promise<void> {\n await this.put(key, JSON.stringify(value), options)\n }\n\n /** Delete a key; a missing key succeeds, and transient failures retry automatically. */\n async delete(key: string): Promise<void> {\n await this.run('delete', key, async () => this.kv.delete(key))\n }\n\n /** Expose Typist's three-method secondary storage bridge without changing KV semantics. */\n asSecondaryStorage(): KVSecondaryStorage {\n return {\n get: (key) => this.get(key),\n set: (key, value, ttl) => this.put(key, value, { ttl }),\n delete: (key) => this.delete(key),\n }\n }\n\n private async run<T>(operation: KVOperation, key: string, work: () => Promise<T>): Promise<T> {\n const result = await Result.tryPromise(\n { try: work, catch: (cause) => cause },\n {\n retry: {\n times: 2,\n shouldRetry: (cause) => decideKVRetry(cause).retry,\n delayMs: (cause, { attempt }) =>\n (isKVPutRateLimitError(cause) ? 1_000 : 0) +\n spreadJitterMs(exponentialDelayCapMs(25, 3_000, attempt)),\n },\n },\n )\n if (result.isOk()) return result.value\n throw new KVError({ operation, key, cause: result.error })\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAa,WAAb,MAAsB;CACS;CAA7B,YAAY,AAAiB,IAAiB;EAAjB;CAAkB;;CAG/C,MAAM,IAAI,KAAqC;EAC7C,OAAO,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAI,GAAG,CAAC;CAChE;;CAGA,MAAM,QAAW,KAAgC;EAC/C,OAAO,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAO,KAAK,MAAM,CAAC;CAC3E;;CAGA,MAAM,IAAI,KAAa,OAAe,SAAuD;EAC3F,MAAM,YAAmC,CAAC;EAC1C,IAAI,SAAS,QAAQ,UAAa,QAAQ,MAAM,GAC9C,UAAU,gBAAgB,QAAQ;EAEpC,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAI,KAAK,OAAO,SAAS,CAAC;CAC3E;;CAGA,MAAM,QACJ,KAEA,OACA,SACe;EACf,MAAM,KAAK,IAAI,KAAK,KAAK,UAAU,KAAK,GAAG,OAAO;CACpD;;CAGA,MAAM,OAAO,KAA4B;EACvC,MAAM,KAAK,IAAI,UAAU,KAAK,YAAY,KAAK,GAAG,OAAO,GAAG,CAAC;CAC/D;;CAGA,qBAAyC;EACvC,OAAO;GACL,MAAM,QAAQ,KAAK,IAAI,GAAG;GAC1B,MAAM,KAAK,OAAO,QAAQ,KAAK,IAAI,KAAK,OAAO,EAAE,IAAI,CAAC;GACtD,SAAS,QAAQ,KAAK,OAAO,GAAG;EAClC;CACF;CAEA,MAAc,IAAO,WAAwB,KAAa,MAAoC;EAC5F,MAAM,SAAS,MAAM,OAAO,WAC1B;GAAE,KAAK;GAAM,QAAQ,UAAU;EAAM,GACrC,EACE,OAAO;GACL,OAAO;GACP,cAAc,UAAU,cAAc,KAAK,CAAC,CAAC;GAC7C,UAAU,OAAO,EAAE,eAChB,sBAAsB,KAAK,IAAI,MAAQ,KACxC,eAAe,sBAAsB,IAAI,KAAO,OAAO,CAAC;EAC5D,EACF,CACF;EACA,IAAI,OAAO,KAAK,GAAG,OAAO,OAAO;EACjC,MAAM,IAAI,QAAQ;GAAE;GAAW;GAAK,OAAO,OAAO;EAAM,CAAC;CAC3D;AACF"}
@@ -0,0 +1,52 @@
1
+ import { $t as AppError, en as FailureClassification } from "../index-DvJUcSW1.js";
2
+ //#region src/infrastructure/cloudflare/kv-errors.d.ts
3
+ /** KV operations recognized in binding error messages. */
4
+ export type KVOperation = 'get' | 'put' | 'delete' | 'list';
5
+ /** KV failure kinds retained from Typist's binding tests. */
6
+ export type KVErrorKind = 'invalid_key' | 'key_too_large' | 'invalid_expiration_ttl' | 'invalid_expiration' | 'invalid_cache_ttl' | 'invalid_list_limit' | 'value_too_large' | 'client_error' | 'rate_limited' | 'server_error';
7
+ /** Evidence extracted from a KV error and its causes. */
8
+ export interface KVErrorMeta {
9
+ kind: KVErrorKind;
10
+ message: string;
11
+ status?: number | undefined;
12
+ operation?: Uppercase<KVOperation> | undefined;
13
+ }
14
+ /** Extract Typist's verified KV message formats, including nested causes. */
15
+ export declare function extractKVMeta(cause: unknown): KVErrorMeta | undefined;
16
+ /** Identify recognized KV failures that another attempt cannot resolve. */
17
+ export declare function isTerminalKVError(cause: unknown): boolean;
18
+ /** Identify a PUT rate limit that requires at least one second before retrying. */
19
+ export declare function isKVPutRateLimitError(cause: unknown): boolean;
20
+ /** Identify PUT rate limits, server failures, and request timeouts. */
21
+ export declare function isTransientKVError(cause: unknown): boolean;
22
+ /** Apply Typist's KV, overload, platform, and transport checks in their original order. */
23
+ export declare function isRetryableKVError(cause: unknown): boolean;
24
+ /** Return the existing retry decision and minimum delay in milliseconds. */
25
+ export declare function decideKVRetry(cause: unknown): {
26
+ retry: false;
27
+ } | {
28
+ retry: true;
29
+ retryAfterMs: number;
30
+ };
31
+ /** A final KV failure with Typist's diagnostics and Better Ship's error classification. */
32
+ export declare class KVError extends AppError {
33
+ readonly _tag = "KVError";
34
+ readonly classification: FailureClassification;
35
+ retryable: boolean;
36
+ readonly operation: KVOperation;
37
+ readonly key?: string | undefined;
38
+ readonly cause: unknown;
39
+ readonly kv?: KVErrorMeta | undefined;
40
+ readonly context: {
41
+ operation: KVOperation;
42
+ key?: string | undefined;
43
+ kv?: KVErrorMeta | undefined;
44
+ };
45
+ constructor(args: {
46
+ operation: KVOperation;
47
+ key?: string | undefined;
48
+ cause: unknown;
49
+ });
50
+ }
51
+ //#endregion
52
+ //# sourceMappingURL=kv-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-errors.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/kv-errors.ts"],"mappings":";;;YASY;;YAGA;;iBAaK;EACf,MAAM;EACN;EACA;EACA,YAAY,UAAU;;;wBAIR,cAAc,iBAAiB;;wBAwC/B,kBAAkB;;wBASlB,sBAAsB;;wBAMtB,mBAAmB;;wBAOnB,mBAAmB;;wBAQnB,cACd;EACG;;EAAmB;EAAa;;;qBAMxB,gBAAgB;WAClB;WACA,gBAAgB;EACzB;WACS,WAAW;WACX;WACS;WACT,KAAK;WACL;IACP,WAAW;IACX;IACA,KAAK;;EAGP,YAAY;IAAQ,WAAW;IAAa;IAA0B"}
@@ -0,0 +1,144 @@
1
+ import { _ as isCloudflareRetryableError, b as isTransientTransportError, g as isCloudflareOverloadedError, rt as AppError } from "../core-ClSP5-V9.js";
2
+
3
+ //#region src/infrastructure/cloudflare/kv-errors.ts
4
+ /** Extract Typist's verified KV message formats, including nested causes. */
5
+ function extractKVMeta(cause) {
6
+ const message = getDeepErrorMessage(cause);
7
+ if (!message) return void 0;
8
+ const statusMatch = message.match(/\bKV\s+(GET|PUT|DELETE|LIST)\s+failed:\s+(\d{3})\b/);
9
+ const operation = statusMatch?.[1];
10
+ const status = statusMatch ? Number(statusMatch[2]) : void 0;
11
+ if (/Key name cannot be empty/i.test(message)) return {
12
+ kind: "invalid_key",
13
+ message,
14
+ status,
15
+ operation
16
+ };
17
+ if (/exceeds key length limit/i.test(message)) return {
18
+ kind: "key_too_large",
19
+ message,
20
+ status,
21
+ operation
22
+ };
23
+ if (/Invalid expiration_ttl/i.test(message)) return {
24
+ kind: "invalid_expiration_ttl",
25
+ message,
26
+ status,
27
+ operation
28
+ };
29
+ if (/Invalid expiration of/i.test(message)) return {
30
+ kind: "invalid_expiration",
31
+ message,
32
+ status,
33
+ operation
34
+ };
35
+ if (/Invalid cache_ttl/i.test(message)) return {
36
+ kind: "invalid_cache_ttl",
37
+ message,
38
+ status,
39
+ operation
40
+ };
41
+ if (/Invalid key_count_limit/i.test(message)) return {
42
+ kind: "invalid_list_limit",
43
+ message,
44
+ status,
45
+ operation
46
+ };
47
+ if (/value.*(too large|exceeds)|exceeds.*value/i.test(message)) return {
48
+ kind: "value_too_large",
49
+ message,
50
+ status,
51
+ operation
52
+ };
53
+ if (status === 429) return {
54
+ kind: "rate_limited",
55
+ message,
56
+ status,
57
+ operation
58
+ };
59
+ if (status !== void 0 && status >= 500) return {
60
+ kind: "server_error",
61
+ message,
62
+ status,
63
+ operation
64
+ };
65
+ if (status !== void 0 && status >= 400) return {
66
+ kind: "client_error",
67
+ message,
68
+ status,
69
+ operation
70
+ };
71
+ }
72
+ /** Identify recognized KV failures that another attempt cannot resolve. */
73
+ function isTerminalKVError(cause) {
74
+ const meta = extractKVMeta(cause);
75
+ if (!meta) return false;
76
+ if (meta.kind === "rate_limited" || meta.kind === "server_error") return false;
77
+ if (meta.status === 408) return false;
78
+ return true;
79
+ }
80
+ /** Identify a PUT rate limit that requires at least one second before retrying. */
81
+ function isKVPutRateLimitError(cause) {
82
+ const meta = extractKVMeta(cause);
83
+ return meta?.operation === "PUT" && meta.kind === "rate_limited";
84
+ }
85
+ /** Identify PUT rate limits, server failures, and request timeouts. */
86
+ function isTransientKVError(cause) {
87
+ const meta = extractKVMeta(cause);
88
+ if (!meta) return false;
89
+ return isKVPutRateLimitError(cause) || meta.kind === "server_error" || meta.status === 408;
90
+ }
91
+ /** Apply Typist's KV, overload, platform, and transport checks in their original order. */
92
+ function isRetryableKVError(cause) {
93
+ if (isTerminalKVError(cause)) return false;
94
+ if (isTransientKVError(cause)) return true;
95
+ if (isCloudflareOverloadedError(cause)) return false;
96
+ return isCloudflareRetryableError(cause) || isTransientTransportError(cause);
97
+ }
98
+ /** Return the existing retry decision and minimum delay in milliseconds. */
99
+ function decideKVRetry(cause) {
100
+ if (!isRetryableKVError(cause)) return { retry: false };
101
+ return {
102
+ retry: true,
103
+ retryAfterMs: isKVPutRateLimitError(cause) ? 1e3 : 0
104
+ };
105
+ }
106
+ /** A final KV failure with Typist's diagnostics and Better Ship's error classification. */
107
+ var KVError = class extends AppError {
108
+ _tag = "KVError";
109
+ classification;
110
+ retryable;
111
+ operation;
112
+ key;
113
+ cause;
114
+ kv;
115
+ context;
116
+ constructor(args) {
117
+ const kv = extractKVMeta(args.cause);
118
+ const causeMessage = getDeepErrorMessage(args.cause) || String(args.cause);
119
+ const keyContext = args.key === void 0 ? "" : ` for key "${args.key}"`;
120
+ super(`KV ${args.operation} failed${keyContext}: ${causeMessage}`, { cause: args.cause });
121
+ this.operation = args.operation;
122
+ this.key = args.key;
123
+ this.cause = args.cause;
124
+ this.kv = kv;
125
+ this.context = {
126
+ operation: args.operation,
127
+ key: args.key,
128
+ kv
129
+ };
130
+ this.retryable = isRetryableKVError(args.cause);
131
+ this.classification = isTerminalKVError(args.cause) ? "terminal" : this.retryable ? "transient" : "unknown";
132
+ }
133
+ };
134
+ function getDeepErrorMessage(cause) {
135
+ if (typeof cause === "string") return cause;
136
+ if (cause === null || cause === void 0) return "";
137
+ if (typeof cause === "number" || typeof cause === "boolean" || typeof cause === "bigint") return String(cause);
138
+ if (typeof cause !== "object") return "";
139
+ return `${"message" in cause && typeof cause.message === "string" ? cause.message : ""} ${"cause" in cause ? getDeepErrorMessage(cause.cause) : ""}`.trim();
140
+ }
141
+
142
+ //#endregion
143
+ export { KVError, decideKVRetry, extractKVMeta, isKVPutRateLimitError, isRetryableKVError, isTerminalKVError, isTransientKVError };
144
+ //# sourceMappingURL=kv-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-errors.js","names":[],"sources":["../../src/infrastructure/cloudflare/kv-errors.ts"],"sourcesContent":["import {\n AppError,\n isCloudflareOverloadedError,\n isCloudflareRetryableError,\n isTransientTransportError,\n type FailureClassification,\n} from '@/core'\n\n/** KV operations recognized in binding error messages. */\nexport type KVOperation = 'get' | 'put' | 'delete' | 'list'\n\n/** KV failure kinds retained from Typist's binding tests. */\nexport type KVErrorKind =\n | 'invalid_key'\n | 'key_too_large'\n | 'invalid_expiration_ttl'\n | 'invalid_expiration'\n | 'invalid_cache_ttl'\n | 'invalid_list_limit'\n | 'value_too_large'\n | 'client_error'\n | 'rate_limited'\n | 'server_error'\n\n/** Evidence extracted from a KV error and its causes. */\nexport interface KVErrorMeta {\n kind: KVErrorKind\n message: string\n status?: number | undefined\n operation?: Uppercase<KVOperation> | undefined\n}\n\n/** Extract Typist's verified KV message formats, including nested causes. */\nexport function extractKVMeta(cause: unknown): KVErrorMeta | undefined {\n const message = getDeepErrorMessage(cause)\n if (!message) return undefined\n const statusMatch = message.match(/\\bKV\\s+(GET|PUT|DELETE|LIST)\\s+failed:\\s+(\\d{3})\\b/)\n // SAFETY: The regular expression permits only uppercase KV operation names in this capture.\n const operation = statusMatch?.[1] as Uppercase<KVOperation> | undefined\n const status = statusMatch ? Number(statusMatch[2]) : undefined\n\n if (/Key name cannot be empty/i.test(message)) {\n return { kind: 'invalid_key', message, status, operation }\n }\n if (/exceeds key length limit/i.test(message)) {\n return { kind: 'key_too_large', message, status, operation }\n }\n if (/Invalid expiration_ttl/i.test(message)) {\n return { kind: 'invalid_expiration_ttl', message, status, operation }\n }\n if (/Invalid expiration of/i.test(message)) {\n return { kind: 'invalid_expiration', message, status, operation }\n }\n if (/Invalid cache_ttl/i.test(message)) {\n return { kind: 'invalid_cache_ttl', message, status, operation }\n }\n if (/Invalid key_count_limit/i.test(message)) {\n return { kind: 'invalid_list_limit', message, status, operation }\n }\n if (/value.*(too large|exceeds)|exceeds.*value/i.test(message)) {\n return { kind: 'value_too_large', message, status, operation }\n }\n if (status === 429) return { kind: 'rate_limited', message, status, operation }\n if (status !== undefined && status >= 500) {\n return { kind: 'server_error', message, status, operation }\n }\n if (status !== undefined && status >= 400) {\n return { kind: 'client_error', message, status, operation }\n }\n return undefined\n}\n\n/** Identify recognized KV failures that another attempt cannot resolve. */\nexport function isTerminalKVError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n if (!meta) return false\n if (meta.kind === 'rate_limited' || meta.kind === 'server_error') return false\n if (meta.status === 408) return false\n return true\n}\n\n/** Identify a PUT rate limit that requires at least one second before retrying. */\nexport function isKVPutRateLimitError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n return meta?.operation === 'PUT' && meta.kind === 'rate_limited'\n}\n\n/** Identify PUT rate limits, server failures, and request timeouts. */\nexport function isTransientKVError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n if (!meta) return false\n return isKVPutRateLimitError(cause) || meta.kind === 'server_error' || meta.status === 408\n}\n\n/** Apply Typist's KV, overload, platform, and transport checks in their original order. */\nexport function isRetryableKVError(cause: unknown): boolean {\n if (isTerminalKVError(cause)) return false\n if (isTransientKVError(cause)) return true\n if (isCloudflareOverloadedError(cause)) return false\n return isCloudflareRetryableError(cause) || isTransientTransportError(cause)\n}\n\n/** Return the existing retry decision and minimum delay in milliseconds. */\nexport function decideKVRetry(\n cause: unknown,\n): { retry: false } | { retry: true; retryAfterMs: number } {\n if (!isRetryableKVError(cause)) return { retry: false }\n return { retry: true, retryAfterMs: isKVPutRateLimitError(cause) ? 1_000 : 0 }\n}\n\n/** A final KV failure with Typist's diagnostics and Better Ship's error classification. */\nexport class KVError extends AppError {\n readonly _tag = 'KVError'\n readonly classification: FailureClassification\n retryable: boolean\n readonly operation: KVOperation\n readonly key?: string | undefined\n override readonly cause: unknown\n readonly kv?: KVErrorMeta | undefined\n readonly context: {\n operation: KVOperation\n key?: string | undefined\n kv?: KVErrorMeta | undefined\n }\n\n constructor(args: { operation: KVOperation; key?: string | undefined; cause: unknown }) {\n const kv = extractKVMeta(args.cause)\n const causeMessage = getDeepErrorMessage(args.cause) || String(args.cause)\n const keyContext = args.key === undefined ? '' : ` for key \"${args.key}\"`\n super(`KV ${args.operation} failed${keyContext}: ${causeMessage}`, { cause: args.cause })\n this.operation = args.operation\n this.key = args.key\n this.cause = args.cause\n this.kv = kv\n this.context = { operation: args.operation, key: args.key, kv }\n this.retryable = isRetryableKVError(args.cause)\n this.classification = isTerminalKVError(args.cause)\n ? 'terminal'\n : this.retryable\n ? 'transient'\n : 'unknown'\n }\n}\n\n// oxlint-disable anti-slop/no-runtime-typeof -- Preserve Typist's primitive messages and nested causes at the raw binding boundary.\nfunction getDeepErrorMessage(cause: unknown): string {\n if (typeof cause === 'string') return cause\n if (cause === null || cause === undefined) return ''\n if (typeof cause === 'number' || typeof cause === 'boolean' || typeof cause === 'bigint') {\n return String(cause)\n }\n if (typeof cause !== 'object') return ''\n const message = 'message' in cause && typeof cause.message === 'string' ? cause.message : ''\n const causeMessage = 'cause' in cause ? getDeepErrorMessage(cause.cause) : ''\n return `${message} ${causeMessage}`.trim()\n}\n// oxlint-enable anti-slop/no-runtime-typeof\n"],"mappings":";;;;AAiCA,SAAgB,cAAc,OAAyC;CACrE,MAAM,UAAU,oBAAo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,KAAK,YACH,cACA;CACR;AACF;AAGA,SAAS,oBAAoB,OAAwB;CACnD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,UAAU,QAAQ,UAAU,QAAW,OAAO;CAClD,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAC9E,OAAO,OAAO,KAAK;CAErB,IAAI,OAAO,UAAU,UAAU,OAAO;CAGtC,OAAO,GAFS,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU,GAExE,GADG,WAAW,QAAQ,oBAAoB,MAAM,KAAK,IAAI,KACvC,KAAK;AAC3C"}
@@ -1,5 +1,5 @@
1
- import { G as DomainEvent, Qt as FailureClassification, W as DomainCommand, Zt as AppError } from "../index-G1QG0P5g.js";
2
- import { D as OutboxRelay, E as IOutboxRelay } from "../index-B45Dr5gs.js";
1
+ import { $t as AppError, K as DomainCommand, en as FailureClassification, q as DomainEvent } from "../index-DvJUcSW1.js";
2
+ import { D as OutboxRelay, E as IOutboxRelay } from "../index-Cchdg2aQ.js";
3
3
  import { z } from "zod";
4
4
  //#region src/infrastructure/cloudflare/queue/queue-message.d.ts
5
5
  /** A message a queue carries: a command from outside the request, or an event from the outbox. */
@@ -1,5 +1,5 @@
1
- import { a as createLogger, d as classifyBoundaryError, f as classifyFailure, l as exponentialEqualJitterMs, p as retryAfterSecondsOf, tt as AppError, u as spreadJitterMs, x as shouldRetryFailure } from "../core-hdaNiCOU.js";
2
- import { o as MessageAlreadyProcessedError } from "../application-C4JOf71r.js";
1
+ import { a as createLogger, d as classifyBoundaryError, f as classifyFailure, l as exponentialEqualJitterMs, p as retryAfterSecondsOf, rt as AppError, u as spreadJitterMs, x as shouldRetryFailure } from "../core-ClSP5-V9.js";
2
+ import { o as MessageAlreadyProcessedError } from "../application-Cf9SER-i.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/queue/queue-limits.ts
@@ -1,4 +1,4 @@
1
- import { J as MessageId } from "../index-G1QG0P5g.js";
1
+ import { X as MessageId } from "../index-DvJUcSW1.js";
2
2
  import { z } from "zod";
3
3
  //#region src/infrastructure/cloudflare/scheduled/scheduled-handler.d.ts
4
4
  /** The work one schedule runs. Nothing returns to the platform, so each run reports its own outcome. */