better-ship 0.40.0 → 0.42.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 (126) hide show
  1. package/dist/{application-xXTCe8o0.js → application-BwevrnLI.js} +75 -10
  2. package/dist/application-BwevrnLI.js.map +1 -0
  3. package/dist/application.d.ts +3 -3
  4. package/dist/application.js +2 -2
  5. package/dist/{auth-secondary-storage-CcNkkEk0.d.ts → auth-secondary-storage-DlzjamBm.d.ts} +2 -2
  6. package/dist/{auth-secondary-storage-CcNkkEk0.d.ts.map → auth-secondary-storage-DlzjamBm.d.ts.map} +1 -1
  7. package/dist/better-auth/apple-client-secret.d.ts +1 -1
  8. package/dist/better-auth/apple-client-secret.js +1 -1
  9. package/dist/better-auth/auth-client.js +1 -1
  10. package/dist/better-auth/rate-limit.d.ts +1 -1
  11. package/dist/better-auth/rate-limit.js +1 -1
  12. package/dist/better-auth/secondary-storage.d.ts +1 -1
  13. package/dist/better-auth.js +1 -1
  14. package/dist/billing/client.d.ts +1 -1
  15. package/dist/billing/client.js +1 -1
  16. package/dist/browser-support/floor.d.ts +1 -1
  17. package/dist/browser-support/floor.js +1 -1
  18. package/dist/browser-support/oxlint.js +1 -1
  19. package/dist/client-BZgpmuSp.js +27 -0
  20. package/dist/client-BZgpmuSp.js.map +1 -0
  21. package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
  22. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  23. package/dist/cloudflare/durable-object-client.js +2 -2
  24. package/dist/cloudflare/durable-object-errors.d.ts +1 -1
  25. package/dist/cloudflare/durable-object-errors.js +1 -1
  26. package/dist/cloudflare/kv-client.js +2 -2
  27. package/dist/cloudflare/kv-errors.d.ts +1 -1
  28. package/dist/cloudflare/kv-errors.js +1 -1
  29. package/dist/cloudflare/queue.d.ts +3 -21
  30. package/dist/cloudflare/queue.d.ts.map +1 -1
  31. package/dist/cloudflare/queue.js +11 -52
  32. package/dist/cloudflare/queue.js.map +1 -1
  33. package/dist/cloudflare/r2-client.js +2 -2
  34. package/dist/cloudflare/r2-errors.d.ts +1 -1
  35. package/dist/cloudflare/r2-errors.js +1 -1
  36. package/dist/cloudflare/rate-limiter.d.ts +1 -1
  37. package/dist/cloudflare/rate-limiter.js +1 -1
  38. package/dist/cloudflare/scheduled.d.ts +1 -1
  39. package/dist/cloudflare/scheduled.js +1 -1
  40. package/dist/cloudflare/turnstile.d.ts +1 -1
  41. package/dist/cloudflare/turnstile.js +1 -1
  42. package/dist/cloudflare.d.ts +3 -3
  43. package/dist/cloudflare.d.ts.map +1 -1
  44. package/dist/cloudflare.js +6 -5
  45. package/dist/cloudflare.js.map +1 -1
  46. package/dist/{core-DOBZeYSX.js → core-CV8SQv01.js} +65 -4
  47. package/dist/core-CV8SQv01.js.map +1 -0
  48. package/dist/core.d.ts +2 -2
  49. package/dist/core.js +2 -2
  50. package/dist/{durable-object-errors-CcfTu0PQ.js → durable-object-errors-C7e7essH.js} +2 -2
  51. package/dist/{durable-object-errors-CcfTu0PQ.js.map → durable-object-errors-C7e7essH.js.map} +1 -1
  52. package/dist/{floor-BTBtPI9_.js → floor-BdRTO_LO.js} +2 -2
  53. package/dist/{floor-BTBtPI9_.js.map → floor-BdRTO_LO.js.map} +1 -1
  54. package/dist/http.d.ts +2 -2
  55. package/dist/http.js +2 -2
  56. package/dist/{index-Db2GV9ZP.d.ts → index-DIHLfC-p.d.ts} +44 -4
  57. package/dist/index-DIHLfC-p.d.ts.map +1 -0
  58. package/dist/{index-CtIdbnEZ.d.ts → index-tJzJUgTh.d.ts} +30 -4
  59. package/dist/index-tJzJUgTh.d.ts.map +1 -0
  60. package/dist/{kv-errors-B2k_2lyY.js → kv-errors-DXbnO7cB.js} +2 -2
  61. package/dist/{kv-errors-B2k_2lyY.js.map → kv-errors-DXbnO7cB.js.map} +1 -1
  62. package/dist/{metrics-DRCoGBNF.d.ts → metrics-CdpccKGI.d.ts} +2 -2
  63. package/dist/{metrics-DRCoGBNF.d.ts.map → metrics-CdpccKGI.d.ts.map} +1 -1
  64. package/dist/{outbox-repository-options-Dd-s5SxA.js → outbox-repository-options-BKapMX7X.js} +2 -2
  65. package/dist/{outbox-repository-options-Dd-s5SxA.js.map → outbox-repository-options-BKapMX7X.js.map} +1 -1
  66. package/dist/{outbox-repository-options-Cmf0vbBQ.d.ts → outbox-repository-options-BtAq0nAG.d.ts} +3 -3
  67. package/dist/{outbox-repository-options-Cmf0vbBQ.d.ts.map → outbox-repository-options-BtAq0nAG.d.ts.map} +1 -1
  68. package/dist/{payment-service.error-BR10zqxk.js → payment-service.error-oW2bKAfU.js} +2 -2
  69. package/dist/{payment-service.error-BR10zqxk.js.map → payment-service.error-oW2bKAfU.js.map} +1 -1
  70. package/dist/postgres.d.ts +3 -3
  71. package/dist/postgres.d.ts.map +1 -1
  72. package/dist/postgres.js +6 -5
  73. package/dist/postgres.js.map +1 -1
  74. package/dist/posthog/metrics.d.ts +1 -1
  75. package/dist/posthog/server.d.ts +3 -3
  76. package/dist/posthog/server.js +1 -1
  77. package/dist/{r2-errors-BF49eqU_.js → r2-errors-DzpOvciV.js} +2 -2
  78. package/dist/{r2-errors-BF49eqU_.js.map → r2-errors-DzpOvciV.js.map} +1 -1
  79. package/dist/{request-BYQodKDU.js → request-C5k8ME_7.js} +2 -2
  80. package/dist/{request-BYQodKDU.js.map → request-C5k8ME_7.js.map} +1 -1
  81. package/dist/resend.d.ts +3 -3
  82. package/dist/resend.js +2 -2
  83. package/dist/sentry/client.d.ts +1 -1
  84. package/dist/sentry/client.js +1 -1
  85. package/dist/sentry/server.d.ts +2 -2
  86. package/dist/sentry/tanstack.d.ts +1 -1
  87. package/dist/stripe/client.d.ts +7 -2
  88. package/dist/stripe/client.d.ts.map +1 -1
  89. package/dist/stripe/client.js +1 -1
  90. package/dist/stripe/payment-service.error.d.ts +1 -1
  91. package/dist/stripe/payment-service.error.js +1 -1
  92. package/dist/stripe/payment-service.js +1 -1
  93. package/dist/stripe/payment-webhook.d.ts +1 -1
  94. package/dist/stripe/payment-webhook.js +1 -1
  95. package/dist/stripe/request.js +1 -1
  96. package/dist/{stripe-fixture-yFUknTJO.js → stripe-fixture-11EmnD6F.js} +2 -2
  97. package/dist/{stripe-fixture-yFUknTJO.js.map → stripe-fixture-11EmnD6F.js.map} +1 -1
  98. package/dist/tanstack.d.ts +1 -1
  99. package/dist/tanstack.js +1 -1
  100. package/dist/testing/outbox-repository.d.ts +2 -2
  101. package/dist/testing/payment-service.js +2 -2
  102. package/dist/testing/stripe.js +1 -1
  103. package/dist/{webhook-verification-C4R6OO7f.js → webhook-verification-B8v3-LQ2.js} +2 -2
  104. package/dist/{webhook-verification-C4R6OO7f.js.map → webhook-verification-B8v3-LQ2.js.map} +1 -1
  105. package/dist/{webhook-verification-DL4L3zbu.d.ts → webhook-verification-Cy4Z5djk.d.ts} +2 -2
  106. package/dist/{webhook-verification-DL4L3zbu.d.ts.map → webhook-verification-Cy4Z5djk.d.ts.map} +1 -1
  107. package/package.json +1 -1
  108. package/src/application/index.ts +6 -0
  109. package/src/application/outbox-relay.ts +35 -13
  110. package/src/application/outbox-repository.ts +2 -0
  111. package/src/application/queue-or-rpc-publisher.ts +70 -0
  112. package/src/core/classify-failure.ts +12 -2
  113. package/src/core/index.ts +6 -0
  114. package/src/core/redelivery-policy.ts +66 -0
  115. package/src/infrastructure/cloudflare/d1-outbox-repository.ts +4 -1
  116. package/src/infrastructure/cloudflare/queue/index.ts +0 -1
  117. package/src/infrastructure/cloudflare/queue/queue-consumer.ts +11 -4
  118. package/src/infrastructure/postgres/postgres-outbox-repository.ts +4 -1
  119. package/src/infrastructure/stripe/client.ts +7 -3
  120. package/dist/application-xXTCe8o0.js.map +0 -1
  121. package/dist/client-Dv1Ch7yY.js +0 -20
  122. package/dist/client-Dv1Ch7yY.js.map +0 -1
  123. package/dist/core-DOBZeYSX.js.map +0 -1
  124. package/dist/index-CtIdbnEZ.d.ts.map +0 -1
  125. package/dist/index-Db2GV9ZP.d.ts.map +0 -1
  126. package/src/infrastructure/cloudflare/queue/redelivery-policy.ts +0 -64
@@ -1,4 +1,4 @@
1
- import { D as unreachable, O as DatabaseError, d as classifyFailure, r as createLogger, s as exponentialDelayCapMs, tt as AppError } from "./core-DOBZeYSX.js";
1
+ import { A as DatabaseError, c as decideRedelivery, k as unreachable, r as createLogger, rt as AppError } from "./core-CV8SQv01.js";
2
2
  import { panic } from "better-result";
3
3
 
4
4
  //#region src/application/analytics-service.ts
@@ -173,8 +173,15 @@ var OutboxRelay = class {
173
173
  }
174
174
  /** Sends the rows' events, marks the delivered rows published, and fails or retries the rest by their error. */
175
175
  async publishDueRows(claimToken, dueRows) {
176
+ const publishedAt = this.now().getTime();
176
177
  const rejectedEvents = await this.publishEvents(dueRows);
177
178
  const rejectedEventIds = new Set(rejectedEvents.map(({ message: event }) => event.id));
179
+ for (const row of dueRows) logger.info("outbox_event_timing", {
180
+ name: row.payload.name,
181
+ attempt: row.attempts,
182
+ waitMs: publishedAt - row.createdAt.getTime(),
183
+ outcome: rejectedEventIds.has(row.payload.id) ? "rejected" : "delivered"
184
+ });
178
185
  const deliveredRows = dueRows.filter((row) => !rejectedEventIds.has(row.payload.id));
179
186
  if (deliveredRows.length > 0) await this.outboxRepo.markPublished(claimToken, deliveredRows);
180
187
  for (const [error, rows] of rowsByError(rejectedEvents, dueRows)) await this.failOrRetry(claimToken, rows, error);
@@ -209,25 +216,44 @@ var OutboxRelay = class {
209
216
  * was rejected. Marks them failed on a terminal error or a last attempt; releases the rest for retry.
210
217
  */
211
218
  async failOrRetry(claimToken, rows, cause) {
212
- const classification = classifyFailure(cause);
213
219
  const errorMessage = cause instanceof Error ? cause.message : "Publisher rejected with a non-error value";
214
- if (classification === "terminal") {
220
+ if (decideRedelivery(cause, 1, this.delays).action === "ack") {
215
221
  await this.markFailed(claimToken, rows, "terminal", errorMessage, cause);
216
222
  return;
217
223
  }
218
224
  const { exhaustedRows, retryRows } = this.splitByLastAttempt(rows);
219
225
  await this.markFailed(claimToken, exhaustedRows, "exhausted", errorMessage, cause);
220
- await this.releaseForRetry(claimToken, retryRows);
226
+ await this.releaseForRetry(claimToken, retryRows, cause);
221
227
  }
222
228
  /** Releases rows for another attempt. Each row waits longer the more attempts it has used. */
223
- async releaseForRetry(claimToken, rows) {
229
+ async releaseForRetry(claimToken, rows, cause) {
224
230
  const now = this.now().getTime();
225
231
  for (const attempts of new Set(rows.map((row) => row.attempts))) {
226
- const delayMs = exponentialDelayCapMs(this.options.retryBaseDelayMs, this.options.retryMaxDelayMs, attempts);
227
- const rowsWithSameDelay = rows.filter((row) => row.attempts === attempts);
228
- await this.outboxRepo.releaseClaim(claimToken, rowsWithSameDelay, new Date(now + delayMs));
232
+ const decision = decideRedelivery(cause, attempts, this.delays);
233
+ const delayMs = decision.action === "retry" ? decision.delayMs : 0;
234
+ const rowsWithSameAttempts = rows.filter((row) => row.attempts === attempts);
235
+ const context = {
236
+ attempt: attempts,
237
+ count: rowsWithSameAttempts.length,
238
+ delayMs
239
+ };
240
+ if (decision.action === "retry" && decision.classification === "unknown" && attempts === 1) logger.error("outbox_unknown_failure", {
241
+ error: cause,
242
+ ...context
243
+ });
244
+ else logger.debug("outbox_retry_scheduled", {
245
+ error: cause,
246
+ ...context
247
+ });
248
+ await this.outboxRepo.releaseClaim(claimToken, rowsWithSameAttempts, new Date(now + delayMs));
229
249
  }
230
250
  }
251
+ get delays() {
252
+ return {
253
+ baseDelayMs: this.options.retryBaseDelayMs,
254
+ maxDelayMs: this.options.retryMaxDelayMs
255
+ };
256
+ }
231
257
  /** Splits claimed rows: rows whose last run crashed with no attempt left, and rows that may run now. */
232
258
  splitByAttemptsLeft(rows) {
233
259
  return {
@@ -276,6 +302,45 @@ function rowsByError(rejectedEvents, rows) {
276
302
  return groups;
277
303
  }
278
304
 
305
+ //#endregion
306
+ //#region src/application/queue-or-rpc-publisher.ts
307
+ const DEFAULT_CALLS_PER_REQUEST = 25;
308
+ /**
309
+ * Publishes each event over RPC or to the queue. Events that the rule picks are consumed over RPC,
310
+ * in parallel, until the request's call budget is used; every other event goes to the queue.
311
+ * Build one per request, so the budget counts that request's calls. A failed call or queue send
312
+ * rejects only its own events.
313
+ */
314
+ var QueueOrRpcPublisher = class {
315
+ options;
316
+ callsLeft;
317
+ constructor(options) {
318
+ this.options = options;
319
+ this.callsLeft = options.callsPerRequest ?? DEFAULT_CALLS_PER_REQUEST;
320
+ }
321
+ async publish(events) {
322
+ const rpcEvents = [];
323
+ const queuedEvents = [];
324
+ for (const event of events) if (this.options.usesRpc(event) && this.callsLeft > 0) {
325
+ rpcEvents.push(event);
326
+ this.callsLeft -= 1;
327
+ } else queuedEvents.push(event);
328
+ const [queueResult, ...callResults] = await Promise.allSettled([queuedEvents.length > 0 ? this.options.queue.publish(queuedEvents) : Promise.resolve([]), ...rpcEvents.map((event) => this.options.consumer.consume(event))]);
329
+ const queueRejected = queueResult?.status === "fulfilled" ? queueResult.value : queuedEvents.map((event) => ({
330
+ message: event,
331
+ error: queueResult?.reason
332
+ }));
333
+ const callRejected = rpcEvents.flatMap((event, index) => {
334
+ const result = callResults[index];
335
+ return result?.status === "rejected" ? [{
336
+ message: event,
337
+ error: result.reason
338
+ }] : [];
339
+ });
340
+ return [...queueRejected, ...callRejected];
341
+ }
342
+ };
343
+
279
344
  //#endregion
280
345
  //#region src/application/outbox-retention.ts
281
346
  /** Bounded cleanup ported from Typist's message retention handler. The application schedules each sweep. */
@@ -354,5 +419,5 @@ var UnitOfWorkAlreadyActiveError = class extends AppError {
354
419
  };
355
420
 
356
421
  //#endregion
357
- 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 };
358
- //# sourceMappingURL=application-xXTCe8o0.js.map
422
+ export { OutboxRelay as a, recordEmailEvent as c, NULL_ANALYTICS as d, QueueOrRpcPublisher as i, RecordingEmailService as l, UnitOfWork as n, MessageBus as o, OutboxRetention as r, MessageAlreadyProcessedError as s, UnitOfWorkAlreadyActiveError as t, NULL_METRICS_SERVICE as u };
423
+ //# sourceMappingURL=application-BwevrnLI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-BwevrnLI.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/queue-or-rpc-publisher.ts","../src/application/outbox-retention.ts","../src/application/unit-of-work.ts","../src/application/unit-of-work.errors.ts"],"sourcesContent":["import type { AnalyticsEventInput, AnalyticsProperties, AnalyticsTarget } from '@/core'\n\n/** The properties of one event name; an untyped service accepts any properties. */\nexport type AnalyticsPropertiesOf<\n TEvent extends AnalyticsEventInput,\n TName extends TEvent['name'],\n> = string extends TEvent['name']\n ? TEvent['properties']\n : Extract<TEvent, { readonly name: TName }>['properties']\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<TName extends TEvent['name']>(\n name: TName,\n properties: AnalyticsPropertiesOf<TEvent, TName>,\n target: AnalyticsTarget,\n ): void\n /** Schedule an event without creating a person profile for its distinct ID. */\n trackAnonymous<TName extends TEvent['name']>(\n name: TName,\n properties: AnalyticsPropertiesOf<TEvent, TName>,\n target: AnalyticsTarget,\n ): void\n}\n\n/**\n * Reports to nobody. The composition root selects this service when analytics is disabled.\n * `satisfies` keeps its own type, so it serves an `AnalyticsService` of any event map.\n */\nexport const NULL_ANALYTICS = {\n identify: () => {},\n alias: () => {},\n track: (\n _name: string,\n _properties: AnalyticsEventInput['properties'],\n _target: AnalyticsTarget,\n ) => {},\n trackAnonymous: (\n _name: string,\n _properties: AnalyticsEventInput['properties'],\n _target: AnalyticsTarget,\n ) => {},\n} satisfies AnalyticsService\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/** Received email headers, without the body or attachments. */\nexport type ReceivedEmail = { readonly headers: Readonly<Record<string, string>> }\n\n/** One attachment of a received email. `downloadUrl` is a signed link that stops working at `expiresAt`. */\nexport type ReceivedAttachment = {\n readonly filename: string | null\n readonly contentType: string\n readonly size: number\n readonly downloadUrl: string\n readonly expiresAt: string\n}\n\n/** A received email's sender, plain text body, and attachments, for an application that reads mail it receives. */\nexport type ReceivedContent = {\n /** The sender as the email states it, for example \"Display Name <address@domain.com>\". */\n readonly from: string\n readonly text: string | null\n readonly attachments: readonly ReceivedAttachment[]\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 * Subscribers run one after another, so one unit of work finishes before the next starts.\n * Every subscriber still runs. One failure is rethrown as is. Several are thrown as one `AggregateError`.\n * A `MessageAlreadyProcessedError` means that subscriber already committed on 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 failures: unknown[] = []\n for (const [subscriber, subscription] of subscriptions.entries()) {\n try {\n await subscription(event, this.deps)\n } catch (reason) {\n if (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', {\n event: event.name,\n id: event.id,\n subscriber,\n })\n continue\n }\n failures.push(reason)\n }\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 { createLogger, decideRedelivery, type DomainEvent, type RedeliveryDelays } from '@/core'\n\nimport type { IOutboxPublisher, RejectedMessage } from './outbox-publisher.ts'\nimport type { IOutboxRepository, OutboxFailureReason, OutboxRow } from './outbox-repository.ts'\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 /** The longest wait before the first retry; each later retry doubles it. Jitter picks between half and all of it. */\n readonly retryBaseDelayMs?: number\n /** The longest wait before a retry. */\n readonly retryMaxDelayMs?: number\n}\n\nconst logger = createLogger('outbox-relay')\n\n/**\n * Moves committed events out of the outbox: claims due rows, sends their events through the publisher,\n * and records each result on its row. A repository failure propagates to the caller.\n */\nexport class OutboxRelay {\n private readonly options: Required<OutboxRelayOptions>\n\n constructor(\n private readonly publisher: IOutboxPublisher,\n private readonly outboxRepo: IOutboxRepository,\n options: OutboxRelayOptions = {},\n private readonly now: () => Date = () => new Date(),\n ) {\n this.options = {\n batchSize: options.batchSize ?? 50,\n maxBatches: options.maxBatches ?? 10,\n maxAttempts: options.maxAttempts ?? 10,\n retryBaseDelayMs: options.retryBaseDelayMs ?? 1_000,\n retryMaxDelayMs: options.retryMaxDelayMs ?? 60_000,\n }\n }\n\n /**\n * Runs one batch: claims due rows, marks rows with no attempt left failed, and publishes the rest.\n * Called by `drain()`. Returns the claimed count; zero means no row was due.\n */\n async flush(): Promise<number> {\n const batch = await this.outboxRepo.claimDueRows(this.options.batchSize)\n const { exhaustedRows, dueRows } = this.splitByAttemptsLeft(batch.rows)\n await this.markFailed(batch.token, exhaustedRows, 'exhausted', 'Claim attempt limit exceeded')\n if (dueRows.length > 0) await this.publishDueRows(batch.token, dueRows)\n // drain() keeps going while a claim finds rows, even if every row was exhausted.\n return batch.rows.length\n }\n\n /** Sends the rows' events, marks the delivered rows published, and fails or retries the rest by their error. */\n private async publishDueRows(\n claimToken: string,\n dueRows: ReadonlyArray<OutboxRow>,\n ): Promise<void> {\n const publishedAt = this.now().getTime()\n const rejectedEvents = await this.publishEvents(dueRows)\n const rejectedEventIds = new Set(rejectedEvents.map(({ message: event }) => event.id))\n for (const row of dueRows) {\n // The wait from the commit to the delivery start: the latency a priority event exists to avoid.\n logger.info('outbox_event_timing', {\n name: row.payload.name,\n attempt: row.attempts,\n waitMs: publishedAt - row.createdAt.getTime(),\n outcome: rejectedEventIds.has(row.payload.id) ? 'rejected' : 'delivered',\n })\n }\n const deliveredRows = dueRows.filter((row) => !rejectedEventIds.has(row.payload.id))\n if (deliveredRows.length > 0) await this.outboxRepo.markPublished(claimToken, deliveredRows)\n for (const [error, rows] of rowsByError(rejectedEvents, dueRows)) {\n // oxlint-disable-next-line no-await-in-loop -- Each error decides fail or retry for its own rows.\n await this.failOrRetry(claimToken, rows, error)\n }\n }\n\n /** Publishes the rows' events. A thrown publish counts as every event rejected with that error. */\n private async publishEvents(\n rows: ReadonlyArray<OutboxRow>,\n ): Promise<readonly RejectedMessage<DomainEvent>[]> {\n const events = rows.map((row) => row.payload)\n try {\n return await this.publisher.publish(events)\n } catch (error) {\n return events.map((event) => ({ message: event, error }))\n }\n }\n\n /**\n * Runs batches until no row is due: at most `maxBatches` × `batchSize` rows, 500 by default. Called\n * after a commit through `waitUntilWake`, and by the app's cron sweep. Returns the total claimed count.\n */\n async drain(): Promise<number> {\n let total = 0\n for (let batchCount = 0; batchCount < this.options.maxBatches; batchCount += 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 /**\n * Decides fail or retry for rows whose events were not delivered: the whole send failed, or one event\n * was rejected. Marks them failed on a terminal error or a last attempt; releases the rest for retry.\n */\n private async failOrRetry(\n claimToken: string,\n rows: ReadonlyArray<OutboxRow>,\n cause: unknown,\n ): Promise<void> {\n const errorMessage =\n cause instanceof Error ? cause.message : 'Publisher rejected with a non-error value'\n if (decideRedelivery(cause, 1, this.delays).action === 'ack') {\n await this.markFailed(claimToken, rows, 'terminal', errorMessage, cause)\n return\n }\n const { exhaustedRows, retryRows } = this.splitByLastAttempt(rows)\n await this.markFailed(claimToken, exhaustedRows, 'exhausted', errorMessage, cause)\n await this.releaseForRetry(claimToken, retryRows, cause)\n }\n\n /** Releases rows for another attempt. Each row waits longer the more attempts it has used. */\n private async releaseForRetry(\n claimToken: string,\n rows: ReadonlyArray<OutboxRow>,\n cause: unknown,\n ): Promise<void> {\n const now = this.now().getTime()\n for (const attempts of new Set(rows.map((row) => row.attempts))) {\n const decision = decideRedelivery(cause, attempts, this.delays)\n // An ack here means a member error changed between calls; the row then retries at once.\n const delayMs = decision.action === 'retry' ? decision.delayMs : 0\n const rowsWithSameAttempts = rows.filter((row) => row.attempts === attempts)\n // As the queue consumer does: an unknown failure is an error once, on its first attempt.\n const context = { attempt: attempts, count: rowsWithSameAttempts.length, delayMs }\n if (decision.action === 'retry' && decision.classification === 'unknown' && attempts === 1) {\n logger.error('outbox_unknown_failure', { error: cause, ...context })\n } else {\n logger.debug('outbox_retry_scheduled', { error: cause, ...context })\n }\n // oxlint-disable-next-line no-await-in-loop -- Stop releasing rows on the first database failure.\n await this.outboxRepo.releaseClaim(claimToken, rowsWithSameAttempts, new Date(now + delayMs))\n }\n }\n\n private get delays(): RedeliveryDelays {\n return { baseDelayMs: this.options.retryBaseDelayMs, maxDelayMs: this.options.retryMaxDelayMs }\n }\n\n /** Splits claimed rows: rows whose last run crashed with no attempt left, and rows that may run now. */\n private splitByAttemptsLeft(rows: ReadonlyArray<OutboxRow>) {\n return {\n exhaustedRows: rows.filter((row) => this.hasNoAttemptLeft(row)),\n dueRows: rows.filter((row) => !this.hasNoAttemptLeft(row)),\n }\n }\n\n /** Splits failed rows: rows that just used their last attempt, and rows that may retry. */\n private splitByLastAttempt(rows: ReadonlyArray<OutboxRow>) {\n return {\n exhaustedRows: rows.filter((row) => this.isLastAttempt(row)),\n retryRows: rows.filter((row) => !this.isLastAttempt(row)),\n }\n }\n\n /** True when the row used every attempt before this claim: its last run crashed, so it must not run again. */\n private hasNoAttemptLeft(row: OutboxRow): boolean {\n // The claim already counted this run, so a row on its last allowed run equals the limit.\n return row.attempts > this.options.maxAttempts\n }\n\n /** True when the run that just failed was the row's last allowed attempt, so it must not be retried. */\n private isLastAttempt(row: OutboxRow): boolean {\n return row.attempts >= this.options.maxAttempts\n }\n\n /** Calls `outboxRepo.markFailed`, then logs one error. Does nothing for an empty list. */\n private async markFailed(\n claimToken: string,\n rows: ReadonlyArray<OutboxRow>,\n reason: OutboxFailureReason,\n errorMessage: string,\n cause?: unknown,\n ): Promise<void> {\n if (rows.length === 0) return\n await this.outboxRepo.markFailed(claimToken, rows, reason, errorMessage)\n logger.error('outbox_rows_failed', {\n error: cause,\n claimToken,\n count: rows.length,\n reason,\n })\n }\n}\n\n/** Groups the rejected events' rows by error object, so one error decides fail or retry for all its rows at once. */\nfunction rowsByError(\n rejectedEvents: readonly RejectedMessage<DomainEvent>[],\n rows: ReadonlyArray<OutboxRow>,\n): Map<unknown, OutboxRow[]> {\n const rowByEventId = new Map(rows.map((row) => [row.payload.id, row]))\n const groups = new Map<unknown, OutboxRow[]>()\n for (const { message: event, error } of rejectedEvents) {\n const row = rowByEventId.get(event.id)\n if (row === undefined) continue\n const group = groups.get(error) ?? []\n group.push(row)\n groups.set(error, group)\n }\n return groups\n}\n","import type { DomainEvent } from '@/core'\n\nimport type { IOutboxPublisher, RejectedMessage } from './outbox-publisher.ts'\n\n/** A client for a consumer that runs one event when called over RPC; it rejects when the event fails. */\nexport interface IEventConsumerClient {\n consume(event: DomainEvent): Promise<void>\n}\n\n/**\n * What an RPC event consumer returns. It returns a failure instead of throwing it: the outbox owns\n * the retries, and a throw from an RPC method is reported to Sentry on every attempt.\n */\nexport type ConsumeResult = { readonly ok: true } | { readonly ok: false; readonly error: unknown }\n\n/** The two clients, the app's rule for choosing between them, and the RPC budget. */\nexport type QueueOrRpcPublisherOptions = {\n readonly queue: IOutboxPublisher\n readonly consumer: IEventConsumerClient\n /** The app's rule: which events go over RPC. */\n readonly usesRpc: (event: DomainEvent) => boolean\n /** RPC calls in one request. Cloudflare allows 32 Worker invocations per request. */\n readonly callsPerRequest?: number\n}\n\nconst DEFAULT_CALLS_PER_REQUEST = 25\n\n/**\n * Publishes each event over RPC or to the queue. Events that the rule picks are consumed over RPC,\n * in parallel, until the request's call budget is used; every other event goes to the queue.\n * Build one per request, so the budget counts that request's calls. A failed call or queue send\n * rejects only its own events.\n */\nexport class QueueOrRpcPublisher implements IOutboxPublisher {\n private callsLeft: number\n\n constructor(private readonly options: QueueOrRpcPublisherOptions) {\n this.callsLeft = options.callsPerRequest ?? DEFAULT_CALLS_PER_REQUEST\n }\n\n async publish(\n events: ReadonlyArray<DomainEvent>,\n ): Promise<readonly RejectedMessage<DomainEvent>[]> {\n const rpcEvents: DomainEvent[] = []\n const queuedEvents: DomainEvent[] = []\n for (const event of events) {\n if (this.options.usesRpc(event) && this.callsLeft > 0) {\n rpcEvents.push(event)\n this.callsLeft -= 1\n } else {\n queuedEvents.push(event)\n }\n }\n\n const [queueResult, ...callResults] = await Promise.allSettled([\n queuedEvents.length > 0 ? this.options.queue.publish(queuedEvents) : Promise.resolve([]),\n ...rpcEvents.map((event) => this.options.consumer.consume(event)),\n ])\n\n const queueRejected =\n queueResult?.status === 'fulfilled'\n ? queueResult.value\n : queuedEvents.map((event) => ({ message: event, error: queueResult?.reason }))\n const callRejected = rpcEvents.flatMap((event, index) => {\n const result = callResults[index]\n return result?.status === 'rejected' ? [{ message: event, error: result.reason }] : []\n })\n return [...queueRejected, ...callRejected]\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 { IOutboxWake } from './outbox-wake.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`.\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: IOutboxWake\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":";;;;;;;;AAkCA,MAAa,iBAAiB;CAC5B,gBAAgB,CAAC;CACjB,aAAa,CAAC;CACd,QACE,OACA,aACA,YACG,CAAC;CACN,iBACE,OACA,aACA,YACG,CAAC;AACR;;;;;ACxBA,MAAa,uBAAuC;CAClD,aAAa,CAAC;CACd,aAAa,CAAC;CACd,iBAAiB,CAAC;AACpB;;;;;ACwCA,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;;;;;;;;AC1CA,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,QA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,MAAM,kCAAkC;CAC1C;AACF"}
@@ -1,3 +1,3 @@
1
- import { G as DomainMessage, K as DomainQuery, U as DomainCommand, W as DomainEvent, q as MessageId } from "./index-CtIdbnEZ.js";
2
- import { $ as MetricOptions, A as IUnitOfWork, B as MimeType, C as RegistryMessage, D as RecordEmailEventDeps, E as RecordEmailEventCommand, F as IMessageStore, G as RecordingEmailService, H as ReceivedAttachment, I as IEventCollector, J as ObservabilityScope, K as applyObservabilityUser, L as EmailAccepted, M as UnitOfWorkDeps, N as ITransaction, O as RecordEmailEventRepos, P as IOutboxWake, Q as MetricAttributes, R as EmailAttachment, S as QueryRegistry, T as IEmailDeliverabilityStore, U as ReceivedContent, V as OutboundEmail, W as ReceivedEmail, X as ObservabilityUser, Y as ObservabilityService, Z as MetricAttributeValue, _ as CommandRegistry, a as OutboxRetentionResult, at as CommandHandler, b as MessageRegistry, c as IOutboxRepository, d as OutboxFailureReason, et as MetricsService, f as OutboxRow, g as MessageBus, h as IMessageBus, i as OutboxRetentionOptions, it as NULL_ANALYTICS, j as UnitOfWork, k as recordEmailEvent, l as IOutboxRetentionRepository, m as RejectedMessage, n as MessageAlreadyProcessedError, nt as AnalyticsPropertiesOf, o as OutboxRelay, ot as EventHandler, p as IOutboxPublisher, q as setObservabilityUserHook, r as OutboxRetention, rt as AnalyticsService, s as OutboxRelayOptions, st as QueryHandler, t as UnitOfWorkAlreadyActiveError, tt as NULL_METRICS_SERVICE, u as OutboxBatch, v as EventRegistry, w as EmailBounceRecord, x as MessageResult, y as Handlers, z as IEmailService } from "./index-Db2GV9ZP.js";
3
- export { type AnalyticsPropertiesOf, type AnalyticsService, type CommandHandler, type CommandRegistry, 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 IOutboxRepository, type IOutboxRetentionRepository, type IOutboxWake, 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 OutboxBatch, type OutboxFailureReason, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type OutboxRow, type QueryHandler, type QueryRegistry, type ReceivedAttachment, type ReceivedContent, type ReceivedEmail, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, type RejectedMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
1
+ import { J as DomainEvent, X as DomainQuery, Y as DomainMessage, Z as MessageId, q as DomainCommand } from "./index-tJzJUgTh.js";
2
+ import { $ as ObservabilityService, A as RecordEmailEventCommand, B as IEventCollector, C as Handlers, D as RegistryMessage, E as QueryRegistry, F as UnitOfWork, G as OutboundEmail, H as EmailAttachment, I as UnitOfWorkDeps, J as ReceivedEmail, K as ReceivedAttachment, L as ITransaction, M as RecordEmailEventRepos, N as recordEmailEvent, O as EmailBounceRecord, P as IUnitOfWork, Q as ObservabilityScope, R as IOutboxWake, S as EventRegistry, T as MessageResult, U as IEmailService, V as EmailAccepted, W as MimeType, X as applyObservabilityUser, Y as RecordingEmailService, Z as setObservabilityUserHook, _ as IOutboxPublisher, a as OutboxRetentionResult, at as NULL_METRICS_SERVICE, b as MessageBus, c as QueueOrRpcPublisher, ct as NULL_ANALYTICS, d as OutboxRelayOptions, dt as QueryHandler, et as ObservabilityUser, f as IOutboxRepository, g as OutboxRow, h as OutboxFailureReason, i as OutboxRetentionOptions, it as MetricsService, j as RecordEmailEventDeps, k as IEmailDeliverabilityStore, l as QueueOrRpcPublisherOptions, lt as CommandHandler, m as OutboxBatch, n as MessageAlreadyProcessedError, nt as MetricAttributes, o as ConsumeResult, ot as AnalyticsPropertiesOf, p as IOutboxRetentionRepository, q as ReceivedContent, r as OutboxRetention, rt as MetricOptions, s as IEventConsumerClient, st as AnalyticsService, t as UnitOfWorkAlreadyActiveError, tt as MetricAttributeValue, u as OutboxRelay, ut as EventHandler, v as RejectedMessage, w as MessageRegistry, x as CommandRegistry, y as IMessageBus, z as IMessageStore } from "./index-DIHLfC-p.js";
3
+ export { type AnalyticsPropertiesOf, type AnalyticsService, type CommandHandler, type CommandRegistry, type ConsumeResult, 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 IEventConsumerClient, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRepository, type IOutboxRetentionRepository, type IOutboxWake, 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 OutboxBatch, type OutboxFailureReason, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type OutboxRow, type QueryHandler, type QueryRegistry, QueueOrRpcPublisher, type QueueOrRpcPublisherOptions, type ReceivedAttachment, type ReceivedContent, type ReceivedEmail, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, type RejectedMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
@@ -1,4 +1,4 @@
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-xXTCe8o0.js";
1
+ import { a as OutboxRelay, c as recordEmailEvent, d as NULL_ANALYTICS, i as QueueOrRpcPublisher, l as RecordingEmailService, n as UnitOfWork, o as MessageBus, r as OutboxRetention, s as MessageAlreadyProcessedError, t as UnitOfWorkAlreadyActiveError, u as NULL_METRICS_SERVICE } from "./application-BwevrnLI.js";
2
2
  import { n as setObservabilityUserHook, t as applyObservabilityUser } from "./request-user-B4rh1c2-.js";
3
3
 
4
- export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
4
+ export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, QueueOrRpcPublisher, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
@@ -1,4 +1,4 @@
1
- import { Jt as AppError } from "./index-CtIdbnEZ.js";
1
+ import { Qt as AppError } from "./index-tJzJUgTh.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. */
@@ -34,4 +34,4 @@ declare class AuthSecondaryStorage extends DurableObject {
34
34
  }
35
35
  //#endregion
36
36
  export { InvalidCounterError as n, InvalidTtlError as r, AuthSecondaryStorage as t };
37
- //# sourceMappingURL=auth-secondary-storage-CcNkkEk0.d.ts.map
37
+ //# sourceMappingURL=auth-secondary-storage-DlzjamBm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-secondary-storage-CcNkkEk0.d.ts","names":[],"sources":["../src/infrastructure/cloudflare/auth-secondary-storage.ts"],"mappings":";;;;cAWa,wBAAwB;WAC1B;WACA;EAET;;;cAMW,4BAA4B;WAC9B;WACA;EAET;;;;;;;cAUW,6BAA6B;;EAElC,OAAO;;EAMP,IAAI,eAAe,eAAe;;EAUlC,UAAU;;EAKV,gBAAgB;;EAQhB,UAAU,cAAc;;EAef,SAAS"}
1
+ {"version":3,"file":"auth-secondary-storage-DlzjamBm.d.ts","names":[],"sources":["../src/infrastructure/cloudflare/auth-secondary-storage.ts"],"mappings":";;;;cAWa,wBAAwB;WAC1B;WACA;EAET;;;cAMW,4BAA4B;WAC9B;WACA;EAET;;;;;;;cAUW,6BAA6B;;EAElC,OAAO;;EAMP,IAAI,eAAe,eAAe;;EAUlC,UAAU;;EAKV,gBAAgB;;EAQhB,UAAU,cAAc;;EAef,SAAS"}
@@ -1,4 +1,4 @@
1
- import { Jt as AppError } from "../index-CtIdbnEZ.js";
1
+ import { Qt as AppError } from "../index-tJzJUgTh.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 { r as createLogger, tt as AppError } from "../core-DOBZeYSX.js";
1
+ import { r as createLogger, rt as AppError } from "../core-CV8SQv01.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { createPrivateKey, sign } from "node:crypto";
4
4
 
@@ -1,4 +1,4 @@
1
- import { U as RateLimitError } from "../core-DOBZeYSX.js";
1
+ import { G as RateLimitError } from "../core-CV8SQv01.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 { Jt as AppError } from "../index-CtIdbnEZ.js";
1
+ import { Qt as AppError } from "../index-tJzJUgTh.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 { r as createLogger, tt as AppError } from "../core-DOBZeYSX.js";
1
+ import { r as createLogger, rt as AppError } from "../core-CV8SQv01.js";
2
2
 
3
3
  //#region src/infrastructure/better-auth/rate-limit.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as AuthSecondaryStorage } from "../auth-secondary-storage-CcNkkEk0.js";
1
+ import { t as AuthSecondaryStorage } from "../auth-secondary-storage-DlzjamBm.js";
2
2
  import { BetterAuthOptions } from "better-auth";
3
3
  //#region src/infrastructure/better-auth/secondary-storage.d.ts
4
4
  type SecondaryStorage = NonNullable<BetterAuthOptions['secondaryStorage']>;
@@ -1,4 +1,4 @@
1
- import { r as createLogger } from "./core-DOBZeYSX.js";
1
+ import { r as createLogger } from "./core-CV8SQv01.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 { Jt as AppError, Yt as FailureClassification } from "../index-CtIdbnEZ.js";
1
+ import { $t as FailureClassification, Qt as AppError } from "../index-tJzJUgTh.js";
2
2
  import { createAuthClient } from "better-auth/client";
3
3
  import { stripeClient } from "@better-auth/stripe/client";
4
4
  //#region src/infrastructure/billing/client.d.ts
@@ -1,4 +1,4 @@
1
- import { tt as AppError } from "../core-DOBZeYSX.js";
1
+ import { rt as AppError } from "../core-CV8SQv01.js";
2
2
 
3
3
  //#region src/infrastructure/billing/client.ts
4
4
  /** A Better Auth billing endpoint rejected the request. The browser boundary owns reporting. */
@@ -1,4 +1,4 @@
1
- import { Jt as AppError } from "../index-CtIdbnEZ.js";
1
+ import { Qt as AppError } from "../index-tJzJUgTh.js";
2
2
  //#region src/infrastructure/browser-support/browser-floor.error.d.ts
3
3
  /** The browserslist file is missing, empty, or not a query browserslist can resolve. */
4
4
  export declare class BrowserFloorError extends AppError {
@@ -1,3 +1,3 @@
1
- import { i as BrowserFloorError, n as buildTargets, r as updateScreenCopy, t as browserFloor } from "../floor-BTBtPI9_.js";
1
+ import { i as BrowserFloorError, n as buildTargets, r as updateScreenCopy, t as browserFloor } from "../floor-BdRTO_LO.js";
2
2
 
3
3
  export { BrowserFloorError, browserFloor, buildTargets, updateScreenCopy };
@@ -1,4 +1,4 @@
1
- import { i as BrowserFloorError, t as browserFloor } from "../floor-BTBtPI9_.js";
1
+ import { i as BrowserFloorError, t as browserFloor } from "../floor-BdRTO_LO.js";
2
2
  import { t as POLYFILLED_APIS } from "../polyfills-DEQFkqRI.js";
3
3
  import { defineRule, eslintCompatPlugin } from "@oxlint/plugins";
4
4
  import bcd from "@mdn/browser-compat-data/forLegacyNode";
@@ -0,0 +1,27 @@
1
+ import Stripe from "stripe";
2
+
3
+ //#region src/infrastructure/stripe/client.ts
4
+ /**
5
+ * Default SDK retries and per-request timeout; client configuration and individual requests can
6
+ * override them. Three tries of 8 s plus the SDK's short waits stay under a Worker's 30 s `waitUntil`
7
+ * limit and the outbox's 60 s lease. The SDK's own timeout is 80 s.
8
+ */
9
+ const STRIPE_REQUEST_OPTIONS = Object.freeze({
10
+ maxNetworkRetries: 2,
11
+ timeout: 8e3
12
+ });
13
+ /**
14
+ * Construct a native Stripe client with fetch transport, two SDK retries and an 8 s timeout by default.
15
+ * Native configuration overrides these defaults. Inject the client into application services.
16
+ */
17
+ function createStripeClient(secretKey, options = {}) {
18
+ return new Stripe(secretKey, {
19
+ httpClient: Stripe.createFetchHttpClient(),
20
+ ...STRIPE_REQUEST_OPTIONS,
21
+ ...options
22
+ });
23
+ }
24
+
25
+ //#endregion
26
+ export { createStripeClient as n, STRIPE_REQUEST_OPTIONS as t };
27
+ //# sourceMappingURL=client-BZgpmuSp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-BZgpmuSp.js","names":[],"sources":["../src/infrastructure/stripe/client.ts"],"sourcesContent":["import Stripe from 'stripe'\n\n/**\n * Default SDK retries and per-request timeout; client configuration and individual requests can\n * override them. Three tries of 8 s plus the SDK's short waits stay under a Worker's 30 s `waitUntil`\n * limit and the outbox's 60 s lease. The SDK's own timeout is 80 s.\n */\nexport const STRIPE_REQUEST_OPTIONS = Object.freeze({ maxNetworkRetries: 2, timeout: 8_000 })\n\n/**\n * Construct a native Stripe client with fetch transport, two SDK retries and an 8 s timeout by default.\n * Native configuration overrides these defaults. Inject the client into application services.\n */\nexport function createStripeClient(secretKey: string, options: Stripe.StripeConfig = {}): Stripe {\n return new Stripe(secretKey, {\n httpClient: Stripe.createFetchHttpClient(),\n ...STRIPE_REQUEST_OPTIONS,\n ...options,\n })\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,yBAAyB,OAAO,OAAO;CAAE,mBAAmB;CAAG,SAAS;AAAM,CAAC;;;;;AAM5F,SAAgB,mBAAmB,WAAmB,UAA+B,CAAC,GAAW;CAC/F,OAAO,IAAI,OAAO,WAAW;EAC3B,YAAY,OAAO,sBAAsB;EACzC,GAAG;EACH,GAAG;CACL,CAAC;AACH"}
@@ -1,2 +1,2 @@
1
- import { n as InvalidCounterError, r as InvalidTtlError, t as AuthSecondaryStorage } from "../auth-secondary-storage-CcNkkEk0.js";
1
+ import { n as InvalidCounterError, r as InvalidTtlError, t as AuthSecondaryStorage } from "../auth-secondary-storage-DlzjamBm.js";
2
2
  export { AuthSecondaryStorage, InvalidCounterError, InvalidTtlError };
@@ -1,4 +1,4 @@
1
- import { tt as AppError } from "../core-DOBZeYSX.js";
1
+ import { rt as AppError } from "../core-CV8SQv01.js";
2
2
  import { DurableObject } from "cloudflare:workers";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/auth-secondary-storage.ts
@@ -1,5 +1,5 @@
1
- import { b as shouldRetryFailure, v as isAbortError } from "../core-DOBZeYSX.js";
2
- import { i as isClassifiedDurableObjectError, n as DurableObjectCallError, r as classifyDurableObjectError } from "../durable-object-errors-CcfTu0PQ.js";
1
+ import { S as shouldRetryFailure, b as isAbortError } from "../core-CV8SQv01.js";
2
+ import { i as isClassifiedDurableObjectError, n as DurableObjectCallError, r as classifyDurableObjectError } from "../durable-object-errors-C7e7essH.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/durable-object-client.ts
@@ -1,4 +1,4 @@
1
- import { Jt as AppError, Yt as FailureClassification } from "../index-CtIdbnEZ.js";
1
+ import { $t as FailureClassification, Qt as AppError } from "../index-tJzJUgTh.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,3 +1,3 @@
1
- import { a as isDurableObjectCallError, i as isClassifiedDurableObjectError, n as DurableObjectCallError, r as classifyDurableObjectError, t as DURABLE_OBJECT_CALL_ERROR } from "../durable-object-errors-CcfTu0PQ.js";
1
+ import { a as isDurableObjectCallError, i as isClassifiedDurableObjectError, n as DurableObjectCallError, r as classifyDurableObjectError, t as DURABLE_OBJECT_CALL_ERROR } from "../durable-object-errors-C7e7essH.js";
2
2
 
3
3
  export { DURABLE_OBJECT_CALL_ERROR, DurableObjectCallError, classifyDurableObjectError, isClassifiedDurableObjectError, isDurableObjectCallError };
@@ -1,5 +1,5 @@
1
- import { l as spreadJitterMs, s as exponentialDelayCapMs } from "../core-DOBZeYSX.js";
2
- import { i as isKVPutRateLimitError, n as decideKVRetry, t as KVError } from "../kv-errors-B2k_2lyY.js";
1
+ import { d as spreadJitterMs, l as exponentialDelayCapMs } from "../core-CV8SQv01.js";
2
+ import { i as isKVPutRateLimitError, n as decideKVRetry, t as KVError } from "../kv-errors-DXbnO7cB.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/kv-client.ts
@@ -1,4 +1,4 @@
1
- import { Jt as AppError, Yt as FailureClassification } from "../index-CtIdbnEZ.js";
1
+ import { $t as FailureClassification, Qt as AppError } from "../index-tJzJUgTh.js";
2
2
  //#region src/infrastructure/cloudflare/kv-errors.d.ts
3
3
  /** KV operations recognized in binding error messages. */
4
4
  export type KVOperation = 'get' | 'put' | 'delete' | 'list';
@@ -1,3 +1,3 @@
1
- import { a as isRetryableKVError, i as isKVPutRateLimitError, n as decideKVRetry, o as isTerminalKVError, r as extractKVMeta, s as isTransientKVError, t as KVError } from "../kv-errors-B2k_2lyY.js";
1
+ import { a as isRetryableKVError, i as isKVPutRateLimitError, n as decideKVRetry, o as isTerminalKVError, r as extractKVMeta, s as isTransientKVError, t as KVError } from "../kv-errors-DXbnO7cB.js";
2
2
 
3
3
  export { KVError, decideKVRetry, extractKVMeta, isKVPutRateLimitError, isRetryableKVError, isTerminalKVError, isTransientKVError };
@@ -1,5 +1,5 @@
1
- import { Jt as AppError, U as DomainCommand, W as DomainEvent, Yt as FailureClassification } from "../index-CtIdbnEZ.js";
2
- import { P as IOutboxWake, m as RejectedMessage, o as OutboxRelay } from "../index-Db2GV9ZP.js";
1
+ import { $t as FailureClassification, J as DomainEvent, Qt as AppError, q as DomainCommand } from "../index-tJzJUgTh.js";
2
+ import { R as IOutboxWake, u as OutboxRelay, v as RejectedMessage } from "../index-DIHLfC-p.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. */
@@ -161,27 +161,9 @@ export declare function isOversized(sized: SizedMessage<QueueMessage>): boolean;
161
161
  /** Split a batch at the message-count and byte limits, keeping the order. */
162
162
  export declare function chunkByLimits<TMessage>(sized: ReadonlyArray<SizedMessage<TMessage>>): TMessage[][];
163
163
  //#endregion
164
- //#region src/infrastructure/cloudflare/queue/redelivery-policy.d.ts
165
- /** How the consumer settles one failed message: acknowledge it, or have Cloudflare redeliver it after a delay. */
166
- type RedeliveryDecision = {
167
- readonly action: 'ack';
168
- readonly classification: 'terminal';
169
- } | {
170
- readonly action: 'retry';
171
- readonly classification: Exclude<FailureClassification, 'terminal'>;
172
- readonly delaySeconds: number;
173
- };
174
- /**
175
- * Decide whether the consumer acknowledges a failed message or asks Cloudflare to redeliver it.
176
- * A terminal failure acknowledges. Transient and unknown failures redeliver: after the advertised
177
- * wait plus a spread when the error carries one, else with exponential equal-jitter backoff.
178
- * An `AggregateError` from event delivery redelivers when any member does, after the longest wait.
179
- */
180
- export declare function decideRedelivery(cause: unknown, attempt: number): RedeliveryDecision;
181
- //#endregion
182
164
  //#region src/infrastructure/cloudflare/queue/wait-until-wake.d.ts
183
165
  /** Register delivery after commit; log a failed drain once and leave recovery to the scheduled sweep. */
184
166
  export declare function waitUntilWake(context: Pick<ExecutionContext, 'waitUntil'>, relay: Pick<OutboxRelay, 'drain'>): IOutboxWake;
185
167
  //#endregion
186
- export type { DispatchBus, DispatchWrapper, IQueueClient, QueueBinding, QueueClientOptions, QueueMessage, QueueOperation, QueueSendOptions, RedeliveryDecision, SizedMessage };
168
+ export type { DispatchBus, DispatchWrapper, IQueueClient, QueueBinding, QueueClientOptions, QueueMessage, QueueOperation, QueueSendOptions, SizedMessage };
187
169
  //# sourceMappingURL=queue.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"mappings":";;;;;KAGY,eAAe,gBAAgB;;;;KCA/B;;wBA4CI,mBAAmB,iBAAiB;;qBASvC,uBAAuB;WACzB;WACA,gBAAgB;WAChB,WAAW;EAEpB,YAAY;aAAiB,WAAW;aAAyB;;;;;;;qBAWtD,8BAA8B;WAChC;WACA;WACA;WACA;WACA;EAET,YAAY;aACD;aACA;aACA;;;;;;;qBAeA,mCAAmC;WACrC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c,aAAa,aACjC;;;;KCpBS;WACG;WAAwB;;WAExB;WACA,gBAAgB,QAAQ;WACxB;;;;;;;;wBASC,iBAAiB,gBAAgB,kBAAkB;;;;wBCxBnD,cACd,SAAS,KAAK,gCACd,OAAO,KAAK,wBACX"}
1
+ {"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"mappings":";;;;;KAGY,eAAe,gBAAgB;;;;KCA/B;;wBA4CI,mBAAmB,iBAAiB;;qBASvC,uBAAuB;WACzB;WACA,gBAAgB;WAChB,WAAW;EAEpB,YAAY;aAAiB,WAAW;aAAyB;;;;;;;qBAWtD,8BAA8B;WAChC;WACA;WACA;WACA;WACA;EAET,YAAY;aACD;aACA;aACA;;;;;;;qBAeA,mCAAmC;WACrC;WACA;EAET,YAAY;;;;;KCpFF;WAA8B;;;KAG9B,aAAa,QAAQ,KAAK,MAAM;;;;;KAMhC,mBAAmB,iBAAiB,cAAc;WACnD,QAAQ,SAAS,OAAO,MAAM,aAAa;;WAE3C,YAAY,KAAK;WACjB,SAAS,SAAS,aAAa;;;UAIzB,aAAa,iBAAiB;EAC7C,KAAK,SAAS,UAAU,UAAU,mBAAmB;EACrD,UAAU,UAAU,cAAc,YAAY;;;;;;EAM9C,QAAQ,aAAa,UACnB,UAAU,cAAc,QACvB,QAAQ,cAAc,gBAAgB,MAAM,wBAAwB;;EAEvE,UAAU,SAAS,UAAU;;;;;;qBA8BlB,YACX,iBAAiB,cACjB,gCACW,aAAa;mBACK;EAA7B,YAA6B,SAAS,mBAAmB,UAAU;;EAG7D,KAAK,SAAS,UAAU,UAAU,mBAAmB;;EA4BrD,UAAU,UAAU,cAAc,YAAY;EAQ9C,QAAQ,aAAa,UACzB,UAAU,cAAc,QACvB,QAAQ,cAAc,gBAAgB,MAAM,wBAAwB;EASjE,UAAU,SAAS,UAAU;;;;;UAWrB;UAkCN;UAIM;;;;;KChKJ,gBAAgB,iBAAiB,iBAC3C,SAAS,UACT,iBACA,WAAW,kBACR;;KAGO,YAAY,iBAAiB;EAEvC,OAAO,SAAS,WAAW;;;;;;;qBAQhB,cAAc,iBAAiB;mBAQvB;mBACA;mBACA;mBACA;;;;;;;EAJnB,YACmB,KAAK,YAAY,WACjB,aAAa,KAAK,aAAa,yBAC/B,QAAQ,EAAE,QAAQ,WAClB,eAAc,gBAAgB;;EAI3C,aAAa,OAAO,eAAe;UAc3B;;UA+CA;;UAMA;;;;;UAaN;;;;;;;;;qBC5HG;WACX;WACA;WACA;;;wBAIc,kBAAkB,SAAS;;KAK/B,aAAa;WAAuB,SAAS;WAAmB;;;wBAG5D,aAAa,iBAAiB,cAC5C,UAAU,cAAc,YACvB,aAAa;;wBAKA,YAAY,OAAO,aAAa;;wBAKhC,cAAc,UAC5B,OAAO,cAAc,aAAa,aACjC;;;;wBC9Ba,cACd,SAAS,KAAK,gCACd,OAAO,KAAK,wBACX"}
@@ -1,5 +1,5 @@
1
- import { b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, r as createLogger, tt as AppError, u as classifyBoundaryError } from "../core-DOBZeYSX.js";
2
- import { o as MessageAlreadyProcessedError } from "../application-xXTCe8o0.js";
1
+ import { S as shouldRetryFailure, c as decideRedelivery, f as classifyBoundaryError, r as createLogger, rt as AppError } from "../core-CV8SQv01.js";
2
+ import { s as MessageAlreadyProcessedError } from "../application-BwevrnLI.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/queue/queue-limits.ts
@@ -268,56 +268,14 @@ var QueueClient = class {
268
268
  };
269
269
 
270
270
  //#endregion
271
- //#region src/infrastructure/cloudflare/queue/redelivery-policy.ts
272
- const BASE_RETRY_DELAY_MS = 5e3;
273
- const MAX_RETRY_DELAY_MS = 12e4;
274
- const RETRY_AFTER_SPREAD_MS = 5e3;
271
+ //#region src/infrastructure/cloudflare/queue/queue-consumer.ts
272
+ const logger$1 = createLogger("queue-consumer");
275
273
  /** Cloudflare Queues accept a redelivery delay of at most one day. */
276
274
  const MAX_QUEUE_DELAY_SECONDS = 86400;
277
- /**
278
- * Decide whether the consumer acknowledges a failed message or asks Cloudflare to redeliver it.
279
- * A terminal failure acknowledges. Transient and unknown failures redeliver: after the advertised
280
- * wait plus a spread when the error carries one, else with exponential equal-jitter backoff.
281
- * An `AggregateError` from event delivery redelivers when any member does, after the longest wait.
282
- */
283
- function decideRedelivery(cause, attempt) {
284
- if (cause instanceof AggregateError && cause.errors.length > 0) {
285
- const retries = cause.errors.map((member) => decideRedelivery(member, attempt)).filter((decision) => decision.action === "retry");
286
- if (retries.length === 0) return {
287
- action: "ack",
288
- classification: "terminal"
289
- };
290
- return {
291
- action: "retry",
292
- classification: retries.some((decision) => decision.classification === "unknown") ? "unknown" : "transient",
293
- delaySeconds: Math.max(...retries.map((decision) => decision.delaySeconds))
294
- };
295
- }
296
- const classification = classifyFailure(cause);
297
- if (classification === "terminal") return {
298
- action: "ack",
299
- classification
300
- };
301
- if (!shouldRetryFailure({
302
- classification,
303
- repeatSafe: true,
304
- owner: "durable"
305
- })) return {
306
- action: "ack",
307
- classification: "terminal"
308
- };
309
- const retryAfterSeconds = retryAfterSecondsOf(cause);
310
- const delayMs = retryAfterSeconds === null ? exponentialEqualJitterMs(BASE_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, attempt) : retryAfterSeconds * 1e3 + spreadJitterMs(RETRY_AFTER_SPREAD_MS);
311
- return {
312
- action: "retry",
313
- classification,
314
- delaySeconds: Math.min(MAX_QUEUE_DELAY_SECONDS, Math.max(1, Math.ceil(delayMs / 1e3)))
315
- };
275
+ /** Whole seconds, at least 1, at most Cloudflare's one-day limit. */
276
+ function toQueueDelaySeconds(delayMs) {
277
+ return Math.min(MAX_QUEUE_DELAY_SECONDS, Math.max(1, Math.ceil(delayMs / 1e3)));
316
278
  }
317
-
318
- //#endregion
319
- //#region src/infrastructure/cloudflare/queue/queue-consumer.ts
320
- const logger$1 = createLogger("queue-consumer");
321
279
  /**
322
280
  * Parses and dispatches each queue message, then selects acknowledgement or retry.
323
281
  * Cloudflare owns the retry limit and sends exhausted messages to the configured dead letter.
@@ -425,20 +383,21 @@ var QueueConsumer = class {
425
383
  message.ack();
426
384
  return;
427
385
  }
386
+ const delaySeconds = toQueueDelaySeconds(decision.delayMs);
428
387
  const context = {
429
388
  name: parsed?.name,
430
389
  messageId: parsed?.id,
431
390
  queueMessageId: message.id,
432
391
  attempt: message.attempts,
433
392
  classification: decision.classification,
434
- delaySeconds: decision.delaySeconds
393
+ delaySeconds
435
394
  };
436
395
  if (decision.classification === "unknown" && message.attempts === 1) logger$1.error("queue_unknown_failure", {
437
396
  error: cause,
438
397
  ...context
439
398
  });
440
399
  else logger$1.debug("redelivery_requested", context);
441
- message.retry({ delaySeconds: decision.delaySeconds });
400
+ message.retry({ delaySeconds });
442
401
  }
443
402
  };
444
403
 
@@ -453,5 +412,5 @@ function waitUntilWake(context, relay) {
453
412
  }
454
413
 
455
414
  //#endregion
456
- export { DeadLetterUnavailableError, OversizedMessageError, QUEUE_LIMITS, QueueClient, QueueConsumer, QueueSendError, chunkByLimits, classifyQueueError, decideRedelivery, isOversized, messageByteLength, sizeMessages, waitUntilWake };
415
+ export { DeadLetterUnavailableError, OversizedMessageError, QUEUE_LIMITS, QueueClient, QueueConsumer, QueueSendError, chunkByLimits, classifyQueueError, isOversized, messageByteLength, sizeMessages, waitUntilWake };
457
416
  //# sourceMappingURL=queue.js.map