better-ship 0.13.0 → 0.14.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.
- package/dist/{application-DnlgWcOZ.js → application-C4JOf71r.js} +22 -3
- package/dist/application-C4JOf71r.js.map +1 -0
- package/dist/application.d.ts +3 -3
- package/dist/application.js +2 -2
- package/dist/better-auth/apple-client-secret.d.ts +1 -1
- package/dist/better-auth/apple-client-secret.js +1 -1
- package/dist/better-auth/auth-client.js +1 -1
- package/dist/better-auth/rate-limit.d.ts +1 -1
- package/dist/better-auth/rate-limit.js +1 -1
- package/dist/better-auth.js +1 -1
- package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
- package/dist/cloudflare/auth-secondary-storage.js +1 -1
- package/dist/cloudflare/queue.d.ts +2 -2
- package/dist/cloudflare/queue.js +2 -2
- package/dist/cloudflare/scheduled.d.ts +1 -1
- package/dist/cloudflare/scheduled.js +1 -1
- package/dist/cloudflare.d.ts +3 -3
- package/dist/cloudflare.js +3 -3
- package/dist/{core-BiqdOMwU.js → core-hdaNiCOU.js} +21 -2
- package/dist/core-hdaNiCOU.js.map +1 -0
- package/dist/core.d.ts +2 -2
- package/dist/core.js +2 -2
- package/dist/http.d.ts +2 -2
- package/dist/http.js +2 -2
- package/dist/{index-DG4jkwad.d.ts → index-C28HgVfY.d.ts} +56 -3
- package/dist/index-C28HgVfY.d.ts.map +1 -0
- package/dist/{index-B5O6mNjZ.d.ts → index-G1QG0P5g.d.ts} +34 -2
- package/dist/index-G1QG0P5g.d.ts.map +1 -0
- package/dist/{outbox-repository-options-BiilQf4_.d.ts → outbox-repository-options-BZjfDqGf.d.ts} +3 -3
- package/dist/{outbox-repository-options-BiilQf4_.d.ts.map → outbox-repository-options-BZjfDqGf.d.ts.map} +1 -1
- package/dist/{outbox-repository-options-BI75j7b7.js → outbox-repository-options-DOTpJH-e.js} +2 -2
- package/dist/{outbox-repository-options-BI75j7b7.js.map → outbox-repository-options-DOTpJH-e.js.map} +1 -1
- package/dist/postgres.d.ts +3 -3
- package/dist/postgres.js +3 -3
- package/dist/posthog/client.d.ts +22 -0
- package/dist/posthog/client.d.ts.map +1 -0
- package/dist/posthog/client.js +34 -0
- package/dist/posthog/client.js.map +1 -0
- package/dist/posthog/metrics.d.ts +18 -0
- package/dist/posthog/metrics.d.ts.map +1 -0
- package/dist/posthog/metrics.js +30 -0
- package/dist/posthog/metrics.js.map +1 -0
- package/dist/posthog/proxy.d.ts +17 -0
- package/dist/posthog/proxy.d.ts.map +1 -0
- package/dist/posthog/proxy.js +34 -0
- package/dist/posthog/proxy.js.map +1 -0
- package/dist/posthog/server.d.ts +37 -0
- package/dist/posthog/server.d.ts.map +1 -0
- package/dist/posthog/server.js +81 -0
- package/dist/posthog/server.js.map +1 -0
- package/dist/resend.d.ts +3 -3
- package/dist/resend.js +2 -2
- package/dist/sentry/client.d.ts +22 -0
- package/dist/sentry/client.d.ts.map +1 -0
- package/dist/sentry/client.js +48 -0
- package/dist/sentry/client.js.map +1 -0
- package/dist/sentry/server.d.ts +24 -0
- package/dist/sentry/server.d.ts.map +1 -0
- package/dist/sentry/server.js +48 -0
- package/dist/sentry/server.js.map +1 -0
- package/dist/sentry/vite.d.ts +11 -0
- package/dist/sentry/vite.d.ts.map +1 -0
- package/dist/sentry/vite.js +17 -0
- package/dist/sentry/vite.js.map +1 -0
- package/dist/tanstack.d.ts +1 -1
- package/dist/tanstack.js +2 -2
- package/dist/testing/outbox-repository.d.ts +2 -2
- package/dist/{webhook-verification-CyBoERFz.d.ts → webhook-verification-D7DIhH6C.d.ts} +2 -2
- package/dist/{webhook-verification-CyBoERFz.d.ts.map → webhook-verification-D7DIhH6C.d.ts.map} +1 -1
- package/dist/{webhook-verification-CeXUJXVP.js → webhook-verification-trEgyz7I.js} +2 -2
- package/dist/{webhook-verification-CeXUJXVP.js.map → webhook-verification-trEgyz7I.js.map} +1 -1
- package/package.json +9 -2
- package/src/application/analytics-service.ts +21 -0
- package/src/application/index.ts +13 -0
- package/src/application/metrics-service.ts +28 -0
- package/src/application/observability-service.ts +16 -0
- package/src/core/analytics-event.ts +37 -0
- package/src/core/index.ts +9 -0
- package/src/core/missing-configuration.error.ts +12 -0
- package/src/infrastructure/posthog/client.ts +41 -0
- package/src/infrastructure/posthog/metrics.ts +30 -0
- package/src/infrastructure/posthog/proxy.ts +47 -0
- package/src/infrastructure/posthog/server.ts +107 -0
- package/src/infrastructure/sentry/client.ts +55 -0
- package/src/infrastructure/sentry/server.ts +51 -0
- package/src/infrastructure/sentry/vite.ts +17 -0
- package/dist/application-DnlgWcOZ.js.map +0 -1
- package/dist/core-BiqdOMwU.js.map +0 -1
- package/dist/index-B5O6mNjZ.d.ts.map +0 -1
- package/dist/index-DG4jkwad.d.ts.map +0 -1
|
@@ -1,6 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as DatabaseError, E as unreachable, a as createLogger, f as classifyFailure, tt as AppError } from "./core-hdaNiCOU.js";
|
|
2
2
|
import { panic } from "better-result";
|
|
3
3
|
|
|
4
|
+
//#region src/application/analytics-service.ts
|
|
5
|
+
/** Reports to nobody. The composition root selects this service when analytics is disabled. */
|
|
6
|
+
const NULL_ANALYTICS = {
|
|
7
|
+
identify: () => {},
|
|
8
|
+
alias: () => {},
|
|
9
|
+
track: () => {},
|
|
10
|
+
trackAnonymous: () => {}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/application/metrics-service.ts
|
|
15
|
+
/** Records nothing when the composition root disables metrics. */
|
|
16
|
+
const NULL_METRICS_SERVICE = {
|
|
17
|
+
count: () => {},
|
|
18
|
+
gauge: () => {},
|
|
19
|
+
histogram: () => {}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
4
23
|
//#region src/application/email-service.ts
|
|
5
24
|
/** Records every send for a test. Provider ids count up as `recorded-1`, `recorded-2`. */
|
|
6
25
|
var RecordingEmailService = class {
|
|
@@ -268,5 +287,5 @@ var UnitOfWorkAlreadyActiveError = class extends AppError {
|
|
|
268
287
|
};
|
|
269
288
|
|
|
270
289
|
//#endregion
|
|
271
|
-
export { MessageBus as a, RecordingEmailService as c, OutboxRelay as i, UnitOfWork as n, MessageAlreadyProcessedError as o, OutboxRetention as r, recordEmailEvent as s, UnitOfWorkAlreadyActiveError as t };
|
|
272
|
-
//# sourceMappingURL=application-
|
|
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
|
|
@@ -0,0 +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 /** The stable identity of this send. Resend deduplicates it 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,MAAM;EACzB,CAAC;OAGD,MAAM,oBAAoB,gBAAgB,OAAO;CAGvD,CAAC;AACH;;;;;ACjDA,IAAa,+BAAb,MAAa,qCAAqC,SAAS;CAK9C;CAJX,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,YACE,AAAS,WACT,SACA;EACA,MAAM,WAAW,UAAU,qBAAqB,OAAO;EAH9C;CAIX;;CAGA,OAAO,KAAK,OAAgB,WAAgE;EAC1F,IAAI,iBAAiB,8BAA8B,OAAO;EAC1D,IAAI,EAAE,iBAAiB,gBAAgB,OAAO;EAC9C,MAAM,UAAU,MAAM;EAStB,IAAI,EAPF,QAAQ,a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,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"}
|
package/dist/application.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { G as DomainEvent, J as MessageId, K as DomainMessage, W as DomainCommand, q as DomainQuery } from "./index-
|
|
2
|
-
import { A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, H as
|
|
3
|
-
export { 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 MimeType, 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
|
+
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-C28HgVfY.js";
|
|
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 };
|
package/dist/application.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError } from "./application-
|
|
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";
|
|
2
2
|
|
|
3
|
-
export { MessageAlreadyProcessedError, MessageBus, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, recordEmailEvent };
|
|
3
|
+
export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, recordEmailEvent };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Zt as AppError } from "../index-G1QG0P5g.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 {
|
|
1
|
+
import { Zt as AppError } from "../index-G1QG0P5g.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. */
|
package/dist/better-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as createLogger } from "./core-
|
|
1
|
+
import { a as createLogger } from "./core-hdaNiCOU.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 {
|
|
1
|
+
import { Zt as AppError } from "../index-G1QG0P5g.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,5 +1,5 @@
|
|
|
1
|
-
import { G as DomainEvent,
|
|
2
|
-
import { D as OutboxRelay, E as IOutboxRelay } from "../index-
|
|
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-C28HgVfY.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. */
|
package/dist/cloudflare/queue.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { o as MessageAlreadyProcessedError } from "../application-
|
|
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";
|
|
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-
|
|
1
|
+
import { J as MessageId } from "../index-G1QG0P5g.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. */
|
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { G as DomainEvent, J as MessageId, nt as DatabaseError, rt as DatabaseFailure, tt as D1ConstraintKind } from "./index-
|
|
2
|
-
import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-
|
|
3
|
-
import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-
|
|
1
|
+
import { G as DomainEvent, J as MessageId, nt as DatabaseError, rt as DatabaseFailure, tt as D1ConstraintKind } from "./index-G1QG0P5g.js";
|
|
2
|
+
import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-C28HgVfY.js";
|
|
3
|
+
import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-BZjfDqGf.js";
|
|
4
4
|
import { BatchItem } from "drizzle-orm/batch";
|
|
5
5
|
import { AnyD1Database, DrizzleD1Database } from "drizzle-orm/d1";
|
|
6
6
|
//#region src/infrastructure/cloudflare/d1-database-types.d.ts
|
package/dist/cloudflare.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { o as MessageAlreadyProcessedError } from "./application-
|
|
3
|
-
import { a as stageD1Statement, i as runWithUnitOfWorkContext, n as collectD1Statements, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-
|
|
1
|
+
import { D as DatabaseError, c as exponentialDelayCapMs, tt as AppError } from "./core-hdaNiCOU.js";
|
|
2
|
+
import { o as MessageAlreadyProcessedError } from "./application-C4JOf71r.js";
|
|
3
|
+
import { a as stageD1Statement, i as runWithUnitOfWorkContext, n as collectD1Statements, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-DOTpJH-e.js";
|
|
4
4
|
import { DrizzleQueryError } from "drizzle-orm/errors";
|
|
5
5
|
import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
|
|
6
6
|
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
@@ -17,6 +17,25 @@ var AppError = class extends Error {
|
|
|
17
17
|
}
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/core/missing-configuration.error.ts
|
|
22
|
+
/** Required configuration is absent. Ported from Porte's configuration.errors.ts. */
|
|
23
|
+
var MissingConfigurationError = class extends AppError {
|
|
24
|
+
key;
|
|
25
|
+
_tag = "MissingConfigurationError";
|
|
26
|
+
classification = "terminal";
|
|
27
|
+
/** Name the missing setting without including its value. */
|
|
28
|
+
constructor(key) {
|
|
29
|
+
super(`${key} is required`);
|
|
30
|
+
this.key = key;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/core/analytics-event.ts
|
|
36
|
+
/** Parse a persisted analytics event UUID; the SDK generates ordinary event UUIDs itself. */
|
|
37
|
+
const AnalyticsEventIdSchema = z.uuid().brand();
|
|
38
|
+
|
|
20
39
|
//#endregion
|
|
21
40
|
//#region src/core/email-address.ts
|
|
22
41
|
/** A parsed email address for message payloads and webhook recipients. Ported from Typist's `EmailSchema`. */
|
|
@@ -904,5 +923,5 @@ function createLogger(module, config) {
|
|
|
904
923
|
}
|
|
905
924
|
|
|
906
925
|
//#endregion
|
|
907
|
-
export {
|
|
908
|
-
//# sourceMappingURL=core-
|
|
926
|
+
export { AnalyticsEventIdSchema as $, ProblemDetailsSchema as A, NotAuthorizedError as B, defineMessages as C, DatabaseError as D, unreachable as E, ResourceNotFoundError as F, BounceTypeSchema as G, RateLimitError as H, UpgradeRequiredError as I, shouldUpdateBounce as J, isEmailDeliverable as K, ValidationError as L, ValidationProblemErrorSchema as M, MalformedRequestError as N, defineErrors as O, RequestTimeoutError as P, EmailAddressSchema as Q, InternalServerError as R, Entity as S, notImplemented as T, AuthenticationError as U, StaleSessionError as V, RecordEmailEventPayloadSchema as W, InvalidEmailIdempotencyKeyError as X, EmailServiceError as Y, emailIdempotencyKey as Z, isCloudflareRetryableError as _, createLogger as a, isTransientTransportError as b, exponentialDelayCapMs as c, classifyBoundaryError as d, MissingConfigurationError as et, classifyFailure as f, isCloudflareOverloadedError as g, isCloudflareObjectResetError as h, consoleSink as i, ValidationProblemDetailsSchema as j, sharedErrors as k, exponentialEqualJitterMs as l, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS as m, Logger as n, setLogSink as o, retryAfterSecondsOf as p, parseBounceType as q, configureLogger as r, setLoggerErrorHook as s, LogLevel as t, AppError as tt, spreadJitterMs as u, isTransientCloudflareRuntimeError as v, defineId as w, shouldRetryFailure as x, isAbortError as y, ServiceUnavailableError as z };
|
|
927
|
+
//# sourceMappingURL=core-hdaNiCOU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-hdaNiCOU.js","names":["uuidv7","uuidv7"],"sources":["../src/core/app-error.ts","../src/core/missing-configuration.error.ts","../src/core/analytics-event.ts","../src/core/email-address.ts","../src/core/email-idempotency-key.ts","../src/core/email-service.error.ts","../src/core/email-deliverability.ts","../src/core/record-email-event.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/request.errors.ts","../src/core/problem-details.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/failure-classification.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/logger.ts"],"sourcesContent":["import type { FailureClassification } from './failure-classification.ts'\n\n/**\n * The base of every expected failure. A subclass declares its tag and its classification,\n * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from\n * raw throws with `instanceof AppError`; a value that fails it was never judged.\n *\n * A `readonly` field with a literal initializer keeps the literal type, so\n * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.\n */\nexport abstract class AppError extends Error {\n abstract readonly _tag: string\n abstract readonly classification: FailureClassification\n\n override get name(): string {\n return this._tag\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Required configuration is absent. Ported from Porte's configuration.errors.ts. */\nexport class MissingConfigurationError extends AppError {\n readonly _tag = 'MissingConfigurationError'\n readonly classification = 'terminal'\n\n /** Name the missing setting without including its value. */\n constructor(readonly key: string) {\n super(`${key} is required`)\n }\n}\n","import { z } from 'zod'\n\n/** An event name and its application-owned properties, ported from Typist's analytics/types.ts. */\nexport interface AnalyticsEventInput<\n TName extends string = string,\n TProperties extends object = object,\n> {\n readonly name: TName\n readonly properties: TProperties\n}\n\n/** A value supported by analytics person properties. */\nexport type AnalyticsProperty =\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly AnalyticsProperty[]\n | AnalyticsProperties\n\n/** Person properties supplied by the application. */\nexport interface AnalyticsProperties {\n readonly [name: string]: AnalyticsProperty\n}\n\n/** Parse a persisted analytics event UUID; the SDK generates ordinary event UUIDs itself. */\nexport const AnalyticsEventIdSchema = z.uuid().brand<'AnalyticsEventId'>()\n\n/** The identity of one analytics event across repeated application deliveries. */\nexport type AnalyticsEventId = z.infer<typeof AnalyticsEventIdSchema>\n\n/** Supply both original values when replaying one event; never share them across different occurrences. */\nexport interface AnalyticsEventIdentity {\n readonly uuid: AnalyticsEventId\n readonly timestamp: Date\n}\n","import { z } from 'zod'\n\n/** A parsed email address for message payloads and webhook recipients. Ported from Typist's `EmailSchema`. */\nexport const EmailAddressSchema = z.email().brand<'EmailAddress'>()\n\n/** An address the schema accepted. */\nexport type EmailAddress = z.infer<typeof EmailAddressSchema>\n","import type { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\n\n/** A key only `emailIdempotencyKey` mints, so every send carries one built by its rules. */\nexport type EmailIdempotencyKey = string & z.core.$brand<'EmailIdempotencyKey'>\n\n// Resend accepts 1 to 256 characters. Source: https://resend.com/docs/dashboard/emails/idempotency-keys\nconst MAX_KEY_LENGTH = 256\n\n/** A key outside 1 to 256 characters. Keys come from stable ids, so this is a defect, not a retry. */\nexport class InvalidEmailIdempotencyKeyError extends AppError {\n readonly _tag = 'InvalidEmailIdempotencyKeyError'\n readonly classification = 'terminal'\n\n constructor(readonly length: number) {\n super(`Email idempotency key must have 1 to ${MAX_KEY_LENGTH} characters`)\n }\n}\n\n/**\n * `<scope>/<id>` for one logical send. Resend deduplicates it for 24 hours.\n * Derive `id` from a stable identity: a message id, a job id, a user id with a template name.\n * The same key must map to an identical payload; a changed body is rejected as terminal.\n * A random `id` means every request is a deliberate new send, as a sign-in code resend is.\n * Source: https://resend.com/docs/dashboard/emails/idempotency-keys\n */\nexport function emailIdempotencyKey(scope: string, id: string): EmailIdempotencyKey {\n const key = `${scope}/${id}`\n if (scope.length === 0 || id.length === 0 || key.length > MAX_KEY_LENGTH)\n throw new InvalidEmailIdempotencyKeyError(key.length)\n // SAFETY: the brand is a compile-time mark; the checks above are the whole rule.\n return key as EmailIdempotencyKey\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** Why the provider rejected a send. The reason owns the classification, so the two never disagree. */\nexport type EmailSendFailureReason =\n | 'rate_limited'\n | 'idempotency_conflict'\n | 'provider_error'\n | 'quota_exceeded'\n | 'invalid_request'\n | 'configuration'\n\nconst CLASSIFICATION_BY_REASON = {\n rate_limited: 'transient',\n idempotency_conflict: 'transient',\n provider_error: 'transient',\n quota_exceeded: 'terminal',\n invalid_request: 'terminal',\n configuration: 'terminal',\n} satisfies Record<EmailSendFailureReason, FailureClassification>\n\n/**\n * The provider rejected a send. The boundary that awaited the send logs once; the adapter never does.\n * `retryAfter` is the server's delay in seconds when it sent one, so `retryAfterSecondsOf` reads it.\n */\nexport class EmailServiceError extends AppError {\n readonly _tag = 'EmailServiceError'\n readonly classification: FailureClassification\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n\n constructor(args: {\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n readonly cause: unknown\n }) {\n super(`Email send failed: ${args.provider} ${args.providerCode}`, { cause: args.cause })\n this.reason = args.reason\n this.classification = CLASSIFICATION_BY_REASON[args.reason]\n this.provider = args.provider\n this.providerCode = args.providerCode\n this.statusCode = args.statusCode\n this.retryAfter = args.retryAfter\n }\n}\n","import { z } from 'zod'\n\n/** The bounce classes Resend reports, ported from Typist's comm-eligibility.ts. */\nexport const BounceTypeSchema = z.enum(['Permanent', 'Transient', 'Undetermined'])\n\n/** One bounce class. */\nexport type BounceType = z.infer<typeof BounceTypeSchema>\n\n/** Parse a provider's bounce type. An unknown value is `Undetermined`, which suppresses. */\nexport function parseBounceType(value: string | undefined): BounceType {\n const parsed = BounceTypeSchema.safeParse(value)\n return parsed.success ? parsed.data : 'Undetermined'\n}\n\nconst BOUNCE_SEVERITY = {\n Transient: 1,\n Undetermined: 2,\n Permanent: 3,\n} satisfies Record<BounceType, number>\n\n/** Keep the higher severity. Equal severity permits replacement; callers own timestamp ordering. */\nexport function shouldUpdateBounce(incoming: BounceType, current: BounceType | null): boolean {\n if (current === null) return true\n return BOUNCE_SEVERITY[incoming] >= BOUNCE_SEVERITY[current]\n}\n\n/** Typist's send policy: no complaint, and either no bounce or a transient one. Delivery is not guaranteed. */\nexport function isEmailDeliverable(bounceType: BounceType | null, complained: boolean): boolean {\n if (complained) return false\n return bounceType === null || bounceType === 'Transient'\n}\n","import { z } from 'zod'\n\nimport { EmailAddressSchema } from './email-address.ts'\nimport { BounceTypeSchema } from './email-deliverability.ts'\n\n/**\n * The payload of the command an application registers to record a bounce or a complaint.\n * Register it under a name of the application's choice in `defineMessages`; `recordEmailEvent` handles it.\n */\nexport const RecordEmailEventPayloadSchema = z.object({\n recipients: z.array(EmailAddressSchema).min(1),\n event: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('bounced'),\n bounceType: BounceTypeSchema,\n bounceSubType: z.string().nullable(),\n }),\n z.object({ type: z.literal('complained') }),\n ]),\n})\n\n/** A parsed payload. */\nexport type RecordEmailEventPayload = z.infer<typeof RecordEmailEventPayloadSchema>\n","import { AppError } from './app-error.ts'\n\n/** A protected operation requires a session that the caller did not provide. */\nexport class AuthenticationError extends AppError {\n readonly _tag = 'AuthenticationError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Authentication required')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** HTTP 429 with a retry delay in seconds. A null delay means the response supplies no valid duration. */\nexport class RateLimitError extends AppError {\n readonly _tag = 'RateLimitError'\n readonly classification = 'transient'\n readonly status = 429\n\n constructor(readonly retryAfter: number | null) {\n super('Too many requests')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** A presented session cookie no longer resolves; the application owns cleanup and redirect policy. */\nexport class StaleSessionError extends AppError {\n readonly _tag = 'StaleSessionError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Session is no longer valid. Sign in again.')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** The authenticated caller cannot perform this operation. Ported from Porte's auth.errors.ts. */\nexport class NotAuthorizedError extends AppError {\n readonly _tag = 'NotAuthorizedError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Not allowed')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Safe public replacement for an unknown failure, ported from Porte's internal.errors.ts. */\nexport class InternalServerError extends AppError {\n readonly _tag = 'InternalServerError'\n readonly classification = 'unknown'\n\n constructor() {\n super('Something went wrong')\n }\n}\n\n/** Safe public replacement for a classified transient failure. */\nexport class ServiceUnavailableError extends AppError {\n readonly _tag = 'ServiceUnavailableError'\n readonly classification = 'transient'\n\n constructor() {\n super('Try again shortly')\n }\n}\n","import { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport type { ValidationProblemError } from './problem-details.ts'\n\n/** One invalid value as a validator reports it: a message and a path of keys. */\nexport type ValidationIssue = {\n readonly message: string\n readonly path: readonly PropertyKey[]\n}\n\n/** Invalid user input, one entry per invalid value in the RFC 9457 shape. Technical failures use another error. */\nexport class ValidationError extends AppError {\n readonly _tag = 'ValidationError'\n readonly classification = 'terminal'\n\n constructor(\n readonly errors: readonly ValidationProblemError[],\n message = 'The request was not valid',\n ) {\n super(message)\n }\n\n /** Convert a Zod error. Each issue path becomes a JSON Pointer. */\n static fromZod(error: z.ZodError, message?: string): ValidationError {\n return ValidationError.fromIssues(error.issues, message)\n }\n\n /** Convert issues from any validator, such as issues TanStack serialized into an error message. */\n static fromIssues(issues: readonly ValidationIssue[], message?: string): ValidationError {\n return new ValidationError(\n issues.map((issue) => ({ detail: issue.message, pointer: jsonPointer(issue.path) })),\n message,\n )\n }\n}\n\n/** The server cannot parse the request syntax. */\nexport class MalformedRequestError extends AppError {\n readonly _tag = 'MalformedRequestError'\n readonly classification = 'terminal'\n\n constructor(args: { cause: unknown }) {\n super('The request was malformed', args)\n }\n}\n\n/** No resource matches the requested HTTP path. */\nexport class ResourceNotFoundError extends AppError {\n readonly _tag = 'ResourceNotFoundError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Resource not found')\n }\n}\n\n/** A WebSocket route received a request without an upgrade. */\nexport class UpgradeRequiredError extends AppError {\n readonly _tag = 'UpgradeRequiredError'\n readonly classification = 'terminal'\n\n constructor() {\n super('WebSocket upgrade required')\n }\n}\n\n/** The requested operation did not answer before its deadline. */\nexport class RequestTimeoutError extends AppError {\n readonly _tag = 'RequestTimeoutError'\n readonly classification = 'transient'\n\n constructor() {\n super('The request timed out')\n }\n}\n\nconst readablePathSchema = z.array(z.union([z.string(), z.number()]))\n\n// A symbol step cannot be shown, so the pointer keeps only the steps a person can read.\nfunction jsonPointer(path: readonly PropertyKey[]): string {\n const parsed = readablePathSchema.safeParse(path)\n const steps = parsed.success ? parsed.data : []\n if (steps.length === 0) return '#'\n return `#/${steps.map((step) => String(step).replaceAll('~', '~0').replaceAll('/', '~1')).join('/')}`\n}\n","import { z } from 'zod'\n\n/**\n * The standard RFC 9457 body for a failed HTTP response.\n * The HTTP response status remains authoritative; extensions may add problem-specific data.\n * @see https://http.dev/problem-details\n */\nexport const ProblemDetailsSchema = z.looseObject({\n /**\n * Stable URI for the problem type; use `about:blank` when the HTTP status is sufficient.\n * @example \"about:blank\"\n */\n type: z.string(),\n /**\n * Stable human-readable name for the problem type.\n * @example \"Service Unavailable\"\n */\n title: z.string(),\n /**\n * Safe human-readable explanation for this occurrence; clients must not parse it.\n * @example \"The service is unavailable.\"\n */\n detail: z.string().optional(),\n /**\n * URI reference for this occurrence; omit it when no correlation resource exists.\n * @example \"/problems/occurrences/01K5F6Y7\"\n */\n instance: z.string().optional(),\n})\n\n/** An RFC 9457 problem body for a failed HTTP response. */\nexport type ProblemDetails = z.infer<typeof ProblemDetailsSchema>\n\n/** One invalid value in a `422` validation problem. */\nexport const ValidationProblemErrorSchema = z.object({\n /**\n * Safe explanation of why this value is invalid.\n * @example \"Must be a positive integer.\"\n */\n detail: z.string(),\n /**\n * RFC 6901 JSON Pointer fragment for the invalid value.\n * @example \"#/age\"\n */\n pointer: z.string().regex(/^#(?:\\/(?:[^~]|~[01])*)*$/u),\n})\n\n/** One invalid value in a `422` validation problem. */\nexport type ValidationProblemError = z.infer<typeof ValidationProblemErrorSchema>\n\n/** An RFC 9457 validation problem with one or more invalid content values. */\nexport const ValidationProblemDetailsSchema = ProblemDetailsSchema.extend({\n errors: z.array(ValidationProblemErrorSchema).min(1),\n})\n\n/** An RFC 9457 validation problem with one or more invalid content values. */\nexport type ValidationProblemDetails = z.infer<typeof ValidationProblemDetailsSchema>\n","import { panic } from 'better-result'\nimport { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport { AuthenticationError } from './authentication.error.ts'\nimport { InternalServerError, ServiceUnavailableError } from './internal.errors.ts'\nimport { NotAuthorizedError } from './not-authorized.error.ts'\nimport { ValidationProblemErrorSchema } from './problem-details.ts'\nimport { RateLimitError } from './rate-limit.error.ts'\nimport {\n MalformedRequestError,\n RequestTimeoutError,\n ResourceNotFoundError,\n UpgradeRequiredError,\n ValidationError,\n} from './request.errors.ts'\nimport { StaleSessionError } from './stale-session.error.ts'\n\ntype PublicFields = z.ZodObject\n\n/**\n * One public error: its class, its HTTP status, and the extra properties a client may read.\n * `fields` strips the thrown error on the server and parses the payload in the browser.\n */\nexport type ErrorEntry<Tag extends string, Fields extends PublicFields = PublicFields> = {\n readonly error: abstract new (...args: never[]) => AppError & { readonly _tag: Tag }\n readonly status: number\n readonly fields?: Fields\n}\n\ntype AnyErrorEntry = ErrorEntry<string>\n\n/** Entries keyed by tag. The compiler rejects a key that differs from the class's `_tag`. */\nexport type ErrorEntries<Entries> = {\n readonly [Tag in keyof Entries & string]: ErrorEntry<Tag>\n}\n\ntype EntryPayload<Tag extends string, Entry> = Entry extends {\n readonly fields: infer Fields extends z.ZodType\n}\n ? { readonly _tag: Tag; readonly message: string } & z.output<Fields>\n : { readonly _tag: Tag; readonly message: string }\n\ntype PayloadOfEntries<Entries> = {\n [Tag in keyof Entries & string]: EntryPayload<Tag, Entries[Tag]>\n}[keyof Entries & string]\n\n/** The HTTP status and public payload for one resolved failure. */\nexport type ResolvedError<Payload> = {\n readonly status: number\n readonly payload: Payload\n}\n\n/**\n * One application's public errors, shared by every transport boundary and the browser.\n * `resolve` and `fallback` serve boundaries. `parse` and `generic` serve screens.\n */\nexport type ErrorTable<Entries> = {\n readonly entries: Entries\n /** The discriminated union of every entry's `_tag`, `message`, and fields. */\n readonly payloadSchema: z.ZodType<PayloadOfEntries<Entries>>\n /** The `InternalServerError` payload, for screens that must show something. */\n readonly generic: PayloadOfEntries<Entries>\n /** Read a rejection value. Null means no known tag, so the request never reached the Worker. */\n parse(cause: unknown): PayloadOfEntries<Entries> | null\n /** Narrow a rejection value to one tag's payload, for a caller that acts on that one error. */\n is<Tag extends keyof Entries & string>(\n cause: unknown,\n tag: Tag,\n ): cause is Extract<PayloadOfEntries<Entries>, { readonly _tag: Tag }>\n /** Match a local instance or a remote error by tag. Null means the failure is not public. */\n resolve(cause: unknown): ResolvedError<PayloadOfEntries<Entries>> | null\n /** The replacement for an unmapped failure: 503 when it declared itself transient, else 500. */\n fallback(cause: unknown): ResolvedError<PayloadOfEntries<Entries>>\n}\n\n/** The union of payloads a table can produce. */\nexport type ErrorPayloadOf<Table> =\n Table extends ErrorTable<infer Entries> ? PayloadOfEntries<Entries> : never\n\n/** The union of tags a table contains. */\nexport type ErrorTagOf<Table> =\n Table extends ErrorTable<infer Entries> ? keyof Entries & string : never\n\nfunction entriesOf<const Entries extends ErrorEntries<Entries>>(entries: Entries): Entries {\n return entries\n}\n\nconst ValidationFields = z.object({ errors: z.array(ValidationProblemErrorSchema) })\nconst RateLimitFields = z.object({ retryAfter: z.number().nullable() })\n\n/** The errors every application can throw, with their statuses. `defineErrors` includes them. */\nexport const sharedErrors = entriesOf({\n MalformedRequestError: { error: MalformedRequestError, status: 400 },\n AuthenticationError: { error: AuthenticationError, status: 401 },\n StaleSessionError: { error: StaleSessionError, status: 401 },\n NotAuthorizedError: { error: NotAuthorizedError, status: 403 },\n ResourceNotFoundError: { error: ResourceNotFoundError, status: 404 },\n ValidationError: { error: ValidationError, status: 422, fields: ValidationFields },\n UpgradeRequiredError: { error: UpgradeRequiredError, status: 426 },\n RateLimitError: { error: RateLimitError, status: 429, fields: RateLimitFields },\n InternalServerError: { error: InternalServerError, status: 500 },\n ServiceUnavailableError: { error: ServiceUnavailableError, status: 503 },\n RequestTimeoutError: { error: RequestTimeoutError, status: 504 },\n})\n\ntype MergedEntries<Entries> = Omit<typeof sharedErrors, keyof Entries> & Entries\n\n// Workers RPC drops the prototype but keeps own properties and marks the error as remote.\nconst RemoteErrorSchema = z.object({\n _tag: z.string(),\n message: z.string(),\n remote: z.literal(true),\n})\n\ntype Match = { readonly tag: string; readonly entry: AnyErrorEntry; readonly error: Error }\n\nfunction match(byTag: ReadonlyMap<string, AnyErrorEntry>, cause: unknown): Match | null {\n if (cause instanceof AppError) {\n const entry = byTag.get(cause._tag)\n if (entry === undefined || !(cause instanceof entry.error)) return null\n return { tag: cause._tag, entry, error: cause }\n }\n if (!(cause instanceof Error)) return null\n const remote = RemoteErrorSchema.safeParse(cause)\n if (!remote.success) return null\n const entry = byTag.get(remote.data._tag)\n return entry === undefined ? null : { tag: remote.data._tag, entry, error: cause }\n}\n\n/**\n * Build the application's error table. The shared entries are always included;\n * an entry with the same key replaces the shared one.\n */\nexport function defineErrors<const Entries extends ErrorEntries<Entries>>(\n entries: Entries,\n): ErrorTable<MergedEntries<Entries>> {\n type Payload = PayloadOfEntries<MergedEntries<Entries>>\n const merged = { ...sharedErrors, ...entries }\n const byTag: ReadonlyMap<string, AnyErrorEntry> = new Map(Object.entries<AnyErrorEntry>(merged))\n\n const resolve = (cause: unknown): ResolvedError<Payload> | null => {\n const found = match(byTag, cause)\n if (found === null) return null\n const fields = found.entry.fields?.safeParse(found.error)\n if (fields !== undefined && !fields.success) return null\n // SAFETY: The entry's own `fields` schema produced these properties, so the payload has the shape declared for this tag.\n const payload = { _tag: found.tag, message: found.error.message, ...fields?.data } as Payload\n return { status: found.entry.status, payload }\n }\n\n const resolveShared = (error: AppError): ResolvedError<Payload> =>\n resolve(error) ?? panic(`Error table cannot resolve shared error ${error._tag}`)\n const generic = resolveShared(new InternalServerError())\n const unavailable = resolveShared(new ServiceUnavailableError())\n\n const variants = [...byTag].map(([tag, entry]) =>\n // oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- Zod names an object schema's property map `shape`.\n z.strictObject({ _tag: z.literal(tag), message: z.string(), ...entry.fields?.shape }),\n )\n const [first, ...rest] = variants\n if (first === undefined) return panic('Error table has no entries')\n // Each variant is one entry's `_tag`, `message`, and fields, which is the union `PayloadOfEntries` describes.\n const payloadSchema = z.discriminatedUnion('_tag', [first, ...rest]).pipe(z.custom<Payload>())\n\n // No return annotation: TypeScript resolves the deferred payload union differently in that position.\n const parse = (cause: unknown) => {\n const parsed = payloadSchema.safeParse(cause)\n return parsed.success ? parsed.data : null\n }\n\n return {\n entries: merged,\n payloadSchema,\n generic: generic.payload,\n parse,\n is<Tag extends keyof MergedEntries<Entries> & string>(\n cause: unknown,\n tag: Tag,\n ): cause is Extract<Payload, { readonly _tag: Tag }> {\n const parsed = parse(cause)\n return parsed !== null && parsed._tag === tag\n },\n resolve,\n fallback: (cause) =>\n cause instanceof AppError && cause.classification === 'transient' ? unavailable : generic,\n }\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** SQLite reports these constraint categories through D1. */\nexport type D1ConstraintKind = 'unique' | 'not_null' | 'foreign_key' | 'check'\n\n/** Database evidence for callers that interpret a specific code or constraint. */\nexport type DatabaseFailure =\n | {\n readonly database: 'd1'\n readonly code: string | undefined\n readonly kind: D1ConstraintKind | undefined\n readonly table: string | undefined\n readonly column: string | undefined\n readonly constraintName: string | undefined\n }\n | {\n readonly database: 'postgres'\n readonly code: string | undefined\n readonly table_name: string | undefined\n readonly column_name: string | undefined\n readonly constraint_name: string | undefined\n }\n\n/** Classification describes the failure; callers must separately establish whether repetition is safe. */\nexport class DatabaseError extends AppError {\n readonly _tag = 'DatabaseError'\n\n constructor(\n readonly operation: string,\n readonly classification: FailureClassification,\n readonly details: DatabaseFailure,\n options: { readonly cause: unknown },\n ) {\n super(`Database operation failed: ${operation}`, options)\n }\n}\n","import { panic } from 'better-result'\n\n/**\n * Mark a line the types say cannot run. A union member without a branch stops compilation here.\n *\n * @throws Panic when a value outside the union arrives at runtime.\n */\nexport function unreachable(value: never): never {\n return panic(`Unreachable: ${String(value)}`)\n}\n\n/**\n * Mark a body that is not written yet. A defect, not an expected failure.\n *\n * @param what - The behavior the body will provide, such as `invoice export`.\n * @throws Panic always.\n */\nexport function notImplemented(what: string): never {\n return panic(`Not implemented: ${what}`)\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\n/** A string only `create()` or `schema.parse()` of the same kind can produce. */\nexport type Id<Brand extends string> = string & z.core.$brand<Brand>\n\n/** One id kind the application mints. `schema` parses untrusted input; `create` mints a uuid v7. */\nexport type IdDefinition<Brand extends string> = {\n readonly schema: z.core.$ZodBranded<z.ZodUUID, Brand>\n /** Mint a new time-ordered id. No parse: we produced it, so it is valid by construction. */\n create(): Id<Brand>\n}\n\n/** The id type of a definition: `type CallId = IdOf<typeof CallId>`. */\nexport type IdOf<Definition extends IdDefinition<string>> = z.output<Definition['schema']>\n\n/**\n * Define an id kind the application mints: `export const CallId = defineId('CallId')`.\n * An id another system mints, such as a provider's call id, stays a plain branded schema.\n */\nexport function defineId<const Brand extends string>(brand: Brand): IdDefinition<Brand> {\n const schema = z.uuidv7({ error: `Invalid ${brand}` })\n return {\n // SAFETY: `brand()` is type-only and returns a conditional TypeScript cannot reduce for a generic brand; for every literal it is this branded schema.\n schema: schema.brand<Brand>() as z.core.$ZodBranded<z.ZodUUID, Brand>,\n // SAFETY: uuidv7() always yields a valid v7 uuid, and the brand is a compile-time mark only.\n create: () => uuidv7() as Id<Brand>,\n }\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\nimport type { DomainCommand, DomainEvent, DomainQuery, MessageId } from './messages.ts'\n\n/** Payload schemas keyed by message name. A payload never carries `type`, `name`, or `id`. */\nexport type PayloadSchemas = Readonly<Record<string, z.ZodType<object>>>\n\n/** An application's messages: one list of payload schemas per kind. */\nexport type MessageDefinition = {\n readonly commands: PayloadSchemas\n readonly events: PayloadSchemas\n readonly queries: PayloadSchemas\n}\n\ntype AnyMessages = { readonly definition: MessageDefinition }\ntype Def<Messages extends AnyMessages> = Messages['definition']\ntype Payload<Schemas extends PayloadSchemas, Name extends keyof Schemas> = z.output<Schemas[Name]>\n\n/** Every command of an application: `CommandOf<typeof messages>`. */\nexport type CommandOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['commands'] & string]: DomainCommand<Name> &\n Payload<Def<Messages>['commands'], Name>\n}[keyof Def<Messages>['commands'] & string]\n\n/** Every event of an application: `EventOf<typeof messages>`. */\nexport type EventOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['events'] & string]: DomainEvent<Name> &\n Payload<Def<Messages>['events'], Name>\n}[keyof Def<Messages>['events'] & string]\n\n/** Every query of an application: `QueryOf<typeof messages>`. */\nexport type QueryOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['queries'] & string]: DomainQuery<Name> &\n Payload<Def<Messages>['queries'], Name>\n}[keyof Def<Messages>['queries'] & string]\n\n/** Every message of an application: what the registry and the bus are typed with. */\nexport type MessageOf<Messages extends AnyMessages> =\n | CommandOf<Messages>\n | EventOf<Messages>\n | QueryOf<Messages>\n\n/**\n * What `defineMessages` returns. The factories build messages for in-process dispatch without\n * parsing; the data is already typed. The schemas parse untrusted input at a boundary.\n */\nexport type AppMessages<Definition extends MessageDefinition> = {\n readonly definition: Definition\n /** Build a command. `id` defaults to a uuid v7; a webhook passes the provider's key, `stripe:event:evt_123`. */\n createCommand<Name extends keyof Definition['commands'] & string>(\n name: Name,\n payload: Payload<Definition['commands'], Name>,\n id?: MessageId,\n ): DomainCommand<Name> & Payload<Definition['commands'], Name>\n /** Build an event. `id` defaults to a uuid v7, which also orders it in time. */\n createEvent<Name extends keyof Definition['events'] & string>(\n name: Name,\n payload: Payload<Definition['events'], Name>,\n id?: MessageId,\n ): DomainEvent<Name> & Payload<Definition['events'], Name>\n /** Build a query. No id: nothing claims a read. */\n createQuery<Name extends keyof Definition['queries'] & string>(\n name: Name,\n payload: Payload<Definition['queries'], Name>,\n ): DomainQuery<Name> & Payload<Definition['queries'], Name>\n readonly commandSchema: z.ZodType<CommandOf<AppMessages<Definition>>>\n readonly eventSchema: z.ZodType<EventOf<AppMessages<Definition>>>\n readonly querySchema: z.ZodType<QueryOf<AppMessages<Definition>>>\n /** What a queue body may be: a command or an event. Queries never cross a queue. */\n readonly queueSchema: z.ZodType<\n CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>\n >\n}\n\ntype RoutingField = 'type' | 'name' | 'id'\n\n/** A payload that declares a routing field maps to `never`, so `defineMessages` rejects it. */\ntype WithoutRoutingFields<Schemas extends PayloadSchemas> = {\n readonly [Name in keyof Schemas]: keyof z.output<Schemas[Name]> & RoutingField extends never\n ? Schemas[Name]\n : never\n}\n\n/** The compile-time rule: no payload of any kind declares `type`, `name`, or `id`. */\ntype ValidDefinition<Definition extends MessageDefinition> = {\n readonly commands: WithoutRoutingFields<Definition['commands']>\n readonly events: WithoutRoutingFields<Definition['events']>\n readonly queries: WithoutRoutingFields<Definition['queries']>\n}\n\nconst MessageIdSchema = z.string().min(1)\n\n/** One full message schema: the routing fields joined to the payload. */\nfunction messageSchema(\n type: 'command' | 'event' | 'query',\n name: string,\n payload: z.ZodType<object>,\n) {\n const routing =\n type === 'query'\n ? z.object({ type: z.literal(type), name: z.literal(name) })\n : z.object({ type: z.literal(type), name: z.literal(name), id: MessageIdSchema })\n return routing.and(payload)\n}\n\n/** A union over every message of one kind. Empty when the application has none of that kind. */\nfunction unionOf(type: 'command' | 'event' | 'query', schemas: PayloadSchemas) {\n return z.union(\n Object.entries(schemas).map(([name, payload]) => messageSchema(type, name, payload)),\n )\n}\n\n/**\n * Define an application's messages once. The key is the name; the factories add the routing\n * fields `type`, `name`, and `id`. A payload that declares one of them is a compile error.\n */\nexport function defineMessages<const Definition extends MessageDefinition>(\n definition: Definition & ValidDefinition<Definition>,\n): AppMessages<Definition> {\n const commandSchema = unionOf('command', definition.commands)\n const eventSchema = unionOf('event', definition.events)\n const querySchema = unionOf('query', definition.queries)\n return {\n definition,\n createCommand: (name, payload, id = uuidv7()) => ({ ...payload, type: 'command', name, id }),\n createEvent: (name, payload, id = uuidv7()) => ({ ...payload, type: 'event', name, id }),\n createQuery: (name, payload) => ({ ...payload, type: 'query', name }),\n commandSchema: commandSchema.pipe(z.custom<CommandOf<AppMessages<Definition>>>()),\n eventSchema: eventSchema.pipe(z.custom<EventOf<AppMessages<Definition>>>()),\n querySchema: querySchema.pipe(z.custom<QueryOf<AppMessages<Definition>>>()),\n queueSchema: z\n .union([commandSchema, eventSchema])\n .pipe(z.custom<CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>>()),\n }\n}\n","import type { DomainEvent } from './messages.ts'\n\n/** What an aggregate's plain data must have: an identity. A branded id keeps its brand. */\nexport type EntityData = { readonly id: string }\n\n/**\n * The base of an aggregate: its identity, the events it raised, and the plain data a repository\n * stores. The subclass keeps its constructor private and declares `static restore(data: Data)`,\n * the one door a repository rebuilds it through. A repository drains the events after `save`.\n */\nexport abstract class Entity<Data extends EntityData, TEvent extends DomainEvent = DomainEvent> {\n private events: TEvent[] = []\n\n abstract readonly id: Data['id']\n\n /** Record one event with the state change that caused it. The unit of work commits both. */\n protected addEvent(event: TEvent): void {\n this.events.push(event)\n }\n\n /** A copy of the events raised since the last `clearEvents`. */\n collectEvents(): ReadonlyArray<TEvent> {\n return [...this.events]\n }\n\n /** Forget the raised events once the boundary has taken them. */\n clearEvents(): void {\n this.events = []\n }\n\n /** Plain data for the repository. The subclass's `restore(data)` accepts exactly this. */\n abstract toPlainObject(): Data\n}\n","/**\n * What one failure is, before any policy decides what to do about it.\n *\n * `transient`: the world may differ on the next attempt. `terminal`: repeating gives the\n * same answer. `unknown`: nobody judged this error, so it came from outside unwrapped.\n */\nexport type FailureClassification = 'transient' | 'terminal' | 'unknown'\n\n/**\n * Who is asking to repeat the work.\n *\n * An immediate owner holds a caller and a socket open. A durable owner already stored the\n * work, so it can afford to try again on a failure nobody classified.\n */\nexport type RetryOwner = 'immediate' | 'durable'\n\n/** Decide whether one retry owner may repeat a failed operation. */\nexport function shouldRetryFailure(args: {\n readonly classification: FailureClassification\n readonly repeatSafe: boolean\n readonly owner: RetryOwner\n}): boolean {\n if (!args.repeatSafe) return false\n if (args.classification === 'transient') return true\n if (args.classification === 'terminal') return false\n return args.owner === 'durable'\n}\n","/**\n * Messages that the platform-neutral transports raise for a failure that may pass.\n *\n * A boundary that knows its own runtime adds its own patterns before these.\n */\nconst TRANSIENT_TRANSPORT_PATTERNS = [\n /network/,\n /fetch failed/,\n /timeout/,\n /timed?\\s*out/,\n /connection.*(lost|reset|refused|closed|aborted)/,\n /econnreset/,\n /econnrefused/,\n /etimedout/,\n /eai_again/,\n]\n\n/** Cancellation is a decision, not a failure to repeat. */\nexport function isAbortError(cause: unknown): boolean {\n return cause instanceof Error && cause.name === 'AbortError'\n}\n\n/** Match known transient transport messages while excluding explicit cancellation. */\nexport function isTransientTransportError(cause: unknown): boolean {\n if (!(cause instanceof Error) || isAbortError(cause)) return false\n const message = cause.message.toLowerCase()\n return TRANSIENT_TRANSPORT_PATTERNS.some((pattern) => pattern.test(message))\n}\n","import { z } from 'zod'\n\n/** Stable Cloudflare messages that mean the runtime failed, not our code, and a repeat may pass. */\nexport const CLOUDFLARE_TRANSIENT_ERROR_PATTERNS = {\n networkConnectionLost: /network connection lost/,\n objectReset: /caused object to be reset/,\n codeUpdateReset: /reset because its code was updated/,\n objectMoved: /object has moved to a different machine/,\n internalWorkflows: /internal workflows error/,\n} as const\n\nconst TRANSIENT_PLATFORM_PATTERNS = [\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectReset,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.codeUpdateReset,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectMoved,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.internalWorkflows,\n]\n\n// workerd stamps these flags as own properties on the error it throws across a binding.\nconst RetryableFlagSchema = z.object({ retryable: z.literal(true) })\nconst OverloadedFlagSchema = z.object({ overloaded: z.literal(true) })\nconst ObjectResetFlagSchema = z.object({ durableObjectReset: z.literal(true) })\n\n/** workerd stamps `retryable` on a failure it judged safe to repeat. */\nexport function isCloudflareRetryableError(cause: unknown): boolean {\n return RetryableFlagSchema.validate(cause)\n}\n\n/** workerd stamps `overloaded` when the target could not take the call. */\nexport function isCloudflareOverloadedError(cause: unknown): boolean {\n return OverloadedFlagSchema.validate(cause)\n}\n\n/** workerd stamps `durableObjectReset` when the object restarted during the call. */\nexport function isCloudflareObjectResetError(cause: unknown): boolean {\n return ObjectResetFlagSchema.validate(cause)\n}\n\n/** Match transient Cloudflare runtime evidence without the general transport patterns. */\nexport function isTransientCloudflareRuntimeError(cause: unknown): boolean {\n if (isCloudflareObjectResetError(cause)) return true\n if (!(cause instanceof Error)) return false\n const message = cause.message.toLowerCase()\n return TRANSIENT_PLATFORM_PATTERNS.some((pattern) => pattern.test(message))\n}\n","import { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport {\n isCloudflareOverloadedError,\n isCloudflareRetryableError,\n isTransientCloudflareRuntimeError,\n} from './cloudflare-classification.ts'\nimport type { FailureClassification } from './failure-classification.ts'\nimport { isAbortError, isTransientTransportError } from './transport-classification.ts'\n\n/** A boundary's own rule for its raw errors. `undefined` means the boundary has no opinion. */\nexport type BoundaryErrorClassifier = (cause: unknown) => FailureClassification | undefined\n\n/**\n * Classify one raw external error: the boundary's own rule first, then Cloudflare's signals,\n * then the transport patterns. Cancellation is terminal even when Cloudflare marks it retryable.\n */\nexport function classifyBoundaryError(args: {\n readonly cause: unknown\n readonly classifyBoundary: BoundaryErrorClassifier\n readonly includeCloudflare: boolean\n}): FailureClassification {\n const boundary = args.classifyBoundary(args.cause)\n if (boundary !== undefined) return boundary\n\n if (isAbortError(args.cause)) return 'terminal'\n\n if (\n args.includeCloudflare &&\n (isCloudflareOverloadedError(args.cause) ||\n isCloudflareRetryableError(args.cause) ||\n isTransientCloudflareRuntimeError(args.cause))\n ) {\n return 'transient'\n }\n\n if (isTransientTransportError(args.cause)) return 'transient'\n\n return 'unknown'\n}\n\n/**\n * Judge a final failure for its durable retry owner. An `AppError` carries its own answer.\n * A raw throw nobody judged is unknown, so an immediate owner stops and a durable one may repeat.\n */\nexport function classifyFailure(cause: unknown): FailureClassification {\n if (cause instanceof AppError) return cause.classification\n if (isAbortError(cause)) return 'terminal'\n if (isTransientCloudflareRuntimeError(cause)) return 'transient'\n return 'unknown'\n}\n\nconst RetryAfterSchema = z.object({ retryAfter: z.number().positive() })\n\n/** Read a positive server-advertised retry delay in seconds, such as `RateLimitError.retryAfter`. */\nexport function retryAfterSecondsOf(cause: unknown): number | null {\n const result = RetryAfterSchema.safeParse(cause)\n return result.success ? result.data.retryAfter : null\n}\n","import { panic } from 'better-result'\n\n/** Uniform jitter within one fixed window. */\nexport function spreadJitterMs(spreadMs: number): number {\n if (!Number.isFinite(spreadMs) || spreadMs < 0) {\n return panic('spreadMs must be a non-negative number')\n }\n return Math.floor(Math.random() * spreadMs)\n}\n\n/**\n * Half the capped exponential delay, plus jitter over the other half. Decorrelates concurrent\n * repeats like full jitter, but keeps a floor: use it when few attempts remain before work is dropped.\n */\nexport function exponentialEqualJitterMs(\n baseDelayMs: number,\n maxDelayMs: number,\n attempt: number,\n): number {\n const halfCapMs = exponentialDelayCapMs(baseDelayMs, maxDelayMs, attempt) / 2\n return Math.floor(halfCapMs) + spreadJitterMs(halfCapMs)\n}\n\n/** Capped exponential delay for a durable retry recorded in storage. */\nexport function exponentialDelayCapMs(\n baseDelayMs: number,\n maxDelayMs: number,\n attempt: number,\n): number {\n if (!Number.isSafeInteger(attempt) || attempt < 1) {\n return panic('attempt must be a positive integer')\n }\n return Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs)\n}\n","/**\n * Module-scoped logging for every host.\n *\n * A logger emits one plain-data entry per log. The default sink hands it to `console` as an\n * entry object for a log service or as a colored line for a person, selected at startup.\n */\n\n/** A value a log entry may carry. Errors enter only through `Logger.error`. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ReadonlyArray<LogValue>\n | LogFields\n\n/** Named log values. */\nexport type LogFields = { readonly [key: string]: LogValue }\n\n/**\n * The supported log severity levels, in ascending order.\n *\n * A const object, not an enum, so a parsed environment value typed `'INFO'` is a `LogLevel`.\n */\nexport const LogLevel = {\n DEBUG: 'DEBUG',\n INFO: 'INFO',\n WARN: 'WARN',\n ERROR: 'ERROR',\n} as const\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]\n\n/** An error as plain data, including diagnostics, causes, and aggregate members. */\nexport type SerializedError = {\n readonly name: string\n readonly message: string\n readonly stack?: string\n readonly fields?: LogFields\n readonly cause?: SerializedError\n readonly errors?: ReadonlyArray<SerializedError>\n}\n\n/** One log, as the sink receives it. Plain data, safe to stringify. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly message: string\n readonly details: LogFields\n readonly userId?: string\n /** Present on `Logger.error` entries that carried an error. */\n readonly error?: SerializedError\n}\n\n/** The context an error log carries. */\nexport type ErrorLogContext = {\n readonly error?: unknown\n readonly userId?: string\n readonly details?: LogFields\n}\n\n/** What a logger lets through: a level and everything above it, or nothing. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Overrides the application settings for one logger. */\nexport interface LoggerConfig {\n readonly level?: LogThreshold\n}\n\n/** `json` writes the entry object. `pretty` writes one readable line for a person. */\nexport type LogFormat = 'json' | 'pretty'\n\n/**\n * The application settings, set once at the composition root.\n *\n * An omitted field keeps its default. An explicit `undefined` is a compile error, so the root\n * parses an environment value before passing it. The logger reads no environment itself.\n */\nexport interface LoggerSettings extends LoggerConfig {\n readonly format?: LogFormat\n}\n\n// The production server setting, so a root that never configures still logs safely.\nconst DEFAULT_SETTINGS: Required<LoggerSettings> = {\n level: LogLevel.INFO,\n format: 'json',\n}\n\n// The application configures once at startup; loggers can exist before startup completes.\nlet settings = DEFAULT_SETTINGS\n\n/**\n * Set application settings, including for existing loggers. Per-logger overrides take priority.\n * Call at startup, never per request. An omitted field resets to INFO and JSON output.\n */\nexport function configureLogger(config: LoggerSettings): void {\n settings = {\n level: config.level ?? DEFAULT_SETTINGS.level,\n format: config.format ?? DEFAULT_SETTINGS.format,\n }\n}\n\n/** The error data sent to the configured error hook. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly distinctId: string | undefined\n readonly context: LogFields\n}\n\n/** A function that forwards one logged error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** Where every log entry goes. */\nexport type LogSink = (entry: LogEntry) => void\n\nlet errorHook: LoggerErrorHook | null = null\n\n/**\n * Register the function that receives each logged error.\n *\n * Set once at the process entry point. A later call replaces the earlier hook.\n */\nexport function setLoggerErrorHook(fn: LoggerErrorHook): void {\n errorHook = fn\n}\n\n// One console method per level, so a host that filters by method can tell them apart.\nconst CONSOLE_METHOD = {\n [LogLevel.DEBUG]: 'debug',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\n// Built from the code point so no raw control character sits in the source.\nconst ESC = String.fromCharCode(27)\nconst ANSI_RESET = `${ESC}[0m`\nconst ANSI_GRAY = `${ESC}[90m`\nconst ANSI_BLUE = `${ESC}[34m`\n\n// Severity reads at a glance: quiet levels stay dim, and an error is the only bold line.\nconst LEVEL_ANSI = {\n DEBUG: `${ESC}[2;36m`,\n INFO: ANSI_BLUE,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nfunction prettyLine(entry: LogEntry): string {\n // Node prints debug and info exactly like log, so the level must be in the text too.\n const level = `[${entry.level}]`\n const module = `[${entry.module}]`\n // A browser console colors by method on its own; a terminal needs ANSI to do the same.\n if ('window' in globalThis) return `${entry.timestamp} ${level} ${module} ${entry.message}`\n const timestamp = `${ANSI_GRAY}${entry.timestamp}${ANSI_RESET}`\n const coloredLevel = `${LEVEL_ANSI[entry.level]}${level}${ANSI_RESET}`\n const coloredModule = `${ANSI_BLUE}${module}${ANSI_RESET}`\n return `${timestamp} ${coloredLevel} ${coloredModule} ${entry.message}`\n}\n\n/**\n * JSON format writes the entry object. Pretty format writes one line, then the details,\n * the error, and the stack as separate console arguments.\n */\nexport const consoleSink: LogSink = (entry) => {\n // Resolved per call, so a console replaced after import still receives the output.\n const write = console[CONSOLE_METHOD[entry.level]]\n if (settings.format === 'json') {\n write(entry)\n return\n }\n const line = prettyLine(entry)\n const fields =\n entry.userId === undefined ? entry.details : { ...entry.details, userId: entry.userId }\n const details = Object.keys(fields).length === 0 ? [] : [fields]\n if (entry.error === undefined) {\n write(line, ...details)\n return\n }\n // A stack inside an object prints as one quoted string; as its own argument it prints as lines.\n const { stack, ...error } = entry.error\n if (stack === undefined) write(line, ...details, error)\n else write(line, ...details, error, `\\n${stack}`)\n}\n\nlet logSink: LogSink = consoleSink\n\n/**\n * Send every log entry somewhere other than `console`.\n *\n * Set once at the process entry point, never per module. A logger is created\n * by name and nothing else, so its destination is a fact about the process.\n */\nexport function setLogSink(fn: LogSink): void {\n logSink = fn\n}\n\nconst LOG_LEVELS = Object.values(LogLevel)\nconst MAX_ERROR_DEPTH = 3\n\n/**\n * Diagnostics worth keeping off an error, named one by one.\n *\n * An allowlist rather than every own property: an error raised by a library we\n * do not control may hang a request or a user payload off itself, and a log is\n * the wrong place to discover that. `_tag` and `classification` are what every `AppError`\n * declares. `remote` and the three flags after it are the ones workerd sets itself.\n */\nconst KEPT_ERROR_FIELDS = [\n '_tag',\n 'classification',\n 'code',\n 'operation',\n 'status',\n 'statusCode',\n 'remote',\n 'retryable',\n 'overloaded',\n 'durableObjectReset',\n] as const\n\ntype ErrorDiagnostics = Error & { readonly [K in (typeof KEPT_ERROR_FIELDS)[number]]?: LogValue }\n\ntype MutableSerializedError = { -readonly [K in keyof SerializedError]: SerializedError[K] }\n\nconst serializeError = (error: Error, depth = 0): SerializedError => {\n if (depth > MAX_ERROR_DEPTH) return { name: 'Error', message: '[error nesting truncated]' }\n\n // Every field is optional, so an `Error` is already one of these.\n const carrier: ErrorDiagnostics = error\n const kept = KEPT_ERROR_FIELDS.filter((key) => carrier[key] !== undefined)\n const serialized: MutableSerializedError = { name: error.name, message: error.message }\n if (error.stack !== undefined) serialized.stack = error.stack\n if (kept.length > 0)\n serialized.fields = Object.fromEntries(kept.map((key) => [key, carrier[key]]))\n if (error.cause instanceof Error) serialized.cause = serializeError(error.cause, depth + 1)\n else if (error.cause !== undefined)\n serialized.cause = { name: 'Error', message: '[non-error cause]' }\n if (error instanceof AggregateError) {\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- AggregateError accepts arbitrary values; instanceof Error validates each member.\n serialized.errors = error.errors.map((failure: unknown) =>\n failure instanceof Error\n ? serializeError(failure, depth + 1)\n : { name: 'NonError', message: '[non-error aggregate member]' },\n )\n }\n return serialized\n}\n\n/** Write module-scoped logs with application defaults and optional overrides. */\nexport class Logger {\n private readonly config: LoggerConfig\n\n /** Create a logger for one module. */\n constructor(\n private readonly module: string,\n overrideConfig?: LoggerConfig,\n ) {\n this.config = { ...overrideConfig }\n }\n\n private log(\n level: LogLevel,\n message: string,\n details: LogFields,\n error?: SerializedError,\n userId?: string,\n ): void {\n const threshold = this.config.level ?? settings.level\n if (threshold === 'OFF') return\n if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(threshold)) return\n\n let entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n module: this.module,\n message,\n details,\n }\n if (userId !== undefined) entry = { ...entry, userId }\n logSink(error === undefined ? entry : { ...entry, error })\n }\n\n /** Write a debug log. */\n debug(message: string, details: LogFields = {}): void {\n this.log(LogLevel.DEBUG, message, details)\n }\n\n /** Write an information log. */\n info(message: string, details: LogFields = {}): void {\n this.log(LogLevel.INFO, message, details)\n }\n\n /** Write a warning log. */\n warn(message: string, details: LogFields = {}): void {\n this.log(LogLevel.WARN, message, details)\n }\n\n /**\n * Write an error log and send the error to the configured hook.\n *\n * The details say which call this was, and the error says what went wrong\n * inside it. Both the entry and the error hook receive the supplied user ID.\n */\n error(message: string, context: ErrorLogContext = {}): void {\n const details = context.details ?? {}\n const thrown = context.error\n let error: SerializedError | undefined\n if (thrown instanceof Error) {\n error = serializeError(thrown)\n } else if (thrown !== undefined) {\n // Not an `Error`, so there is no name or stack to keep, only its JSON form.\n let json: string\n try {\n json = JSON.stringify(thrown)\n } catch {\n json = '[non-serializable error]'\n }\n error = { name: 'NonError', message: json }\n }\n this.log(LogLevel.ERROR, message, details, error, context.userId)\n\n if (errorHook !== null && thrown !== undefined) {\n errorHook({ error: thrown, distinctId: context.userId, context: details })\n }\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string, config?: LoggerConfig): Logger {\n return new Logger(module, config)\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAsB,WAAtB,cAAuC,MAAM;CAI3C,IAAa,OAAe;EAC1B,OAAO,KAAK;CACd;AACF;;;;;ACdA,IAAa,4BAAb,cAA+C,SAAS;CAKjC;CAJrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YAAY,AAAS,KAAa;EAChC,MAAM,GAAG,IAAI,aAAa;EADP;CAErB;AACF;;;;;ACgBA,MAAa,yBAAyB,EAAE,KAAK,CAAC,CAAC,MAA0B;;;;;ACxBzE,MAAa,qBAAqB,EAAE,MAAM,CAAC,CAAC,MAAsB;;;;ACKlE,MAAM,iBAAiB;;AAGvB,IAAa,kCAAb,cAAqD,SAAS;CAIvC;CAHrB,AAAS,OA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OAAO;GACT;GACA,QAAQ;IAAE,MAAM;IAAY,SAAS;GAAK;EAC5C;EACA,KAAK,IAAI,SAAS,OAAO,SAAS,SAAS,OAAO,QAAQ,MAAM;EAEhE,IAAI,cAAc,QAAQ,WAAW,QACnC,UAAU;GAAE,OAAO;GAAQ,YAAY,QAAQ;GAAQ,SAAS;EAAQ,CAAC;CAE7E;AACF;;AAGA,SAAgB,aAAa,QAAgB,QAA+B;CAC1E,OAAO,IAAI,OAAO,QAAQ,MAAM;AAClC"}
|
package/dist/core.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as notImplemented, A as isCloudflareRetryableError, At as RecordEmailEventPayload, B as MessageOf, Bt as InvalidEmailIdempotencyKeyError, C as BoundaryErrorClassifier, Ct as ValidationProblemErrorSchema, D as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, Dt as StaleSessionError, E as retryAfterSecondsOf, Et as NotAuthorizedError, F as EntityData, Ft as parseBounceType, G as DomainEvent, Gt as
|
|
2
|
-
export { AppError, type AppMessages, AuthenticationError, type BounceType, BounceTypeSchema, type BoundaryErrorClassifier, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAddress, EmailAddressSchema, type EmailIdempotencyKey, type EmailSendFailureReason, EmailServiceError, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, InvalidEmailIdempotencyKeyError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageDefinition, type MessageId, type MessageOf, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, type RecordEmailEventPayload, RecordEmailEventPayloadSchema, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
|
|
1
|
+
import { $ as notImplemented, $t as RetryOwner, A as isCloudflareRetryableError, At as RecordEmailEventPayload, B as MessageOf, Bt as InvalidEmailIdempotencyKeyError, C as BoundaryErrorClassifier, Ct as ValidationProblemErrorSchema, D as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, Dt as StaleSessionError, E as retryAfterSecondsOf, Et as NotAuthorizedError, F as EntityData, Ft as parseBounceType, G as DomainEvent, Gt as AnalyticsEventIdSchema, H as QueryOf, Ht as EmailAddress, I as AppMessages, It as shouldUpdateBounce, J as MessageId, Jt as AnalyticsProperties, K as DomainMessage, Kt as AnalyticsEventIdentity, L as CommandOf, Lt as EmailSendFailureReason, M as isAbortError, Mt as BounceType, N as isTransientTransportError, Nt as BounceTypeSchema, O as isCloudflareObjectResetError, Ot as RateLimitError, P as Entity, Pt as isEmailDeliverable, Q as defineId, Qt as FailureClassification, R as EventOf, Rt as EmailServiceError, S as spreadJitterMs, St as ValidationProblemError, T as classifyFailure, Tt as ServiceUnavailableError, U as defineMessages, Ut as EmailAddressSchema, V as PayloadSchemas, Vt as emailIdempotencyKey, W as DomainCommand, Wt as AnalyticsEventId, X as IdDefinition, Xt as MissingConfigurationError, Y as Id, Yt as AnalyticsProperty, Z as IdOf, Zt as AppError, _ as createLogger, _t as ValidationIssue, a as LogFormat, at as ErrorEntry, b as exponentialDelayCapMs, bt as ValidationProblemDetails, c as LogThreshold, ct as ErrorTagOf, d as LoggerConfig, dt as sharedErrors, en as shouldRetryFailure, et as unreachable, f as LoggerErrorHook, ft as MalformedRequestError, g as consoleSink, gt as ValidationError, h as configureLogger, ht as UpgradeRequiredError, i as LogFields, it as ErrorEntries, j as isTransientCloudflareRuntimeError, jt as RecordEmailEventPayloadSchema, k as isCloudflareOverloadedError, kt as AuthenticationError, l as LogValue, lt as ResolvedError, m as SerializedError, mt as ResourceNotFoundError, n as ErrorLogContext, nt as DatabaseError, o as LogLevel, ot as ErrorPayloadOf, p as LoggerSettings, pt as RequestTimeoutError, q as DomainQuery, qt as AnalyticsEventInput, r as LogEntry, rt as DatabaseFailure, s as LogSink, st as ErrorTable, t as ErrorCaptureEntry, tt as D1ConstraintKind, u as Logger, ut as defineErrors, v as setLogSink, vt as ProblemDetails, w as classifyBoundaryError, wt as InternalServerError, x as exponentialEqualJitterMs, xt as ValidationProblemDetailsSchema, y as setLoggerErrorHook, yt as ProblemDetailsSchema, z as MessageDefinition, zt as EmailIdempotencyKey } from "./index-G1QG0P5g.js";
|
|
2
|
+
export { type AnalyticsEventId, AnalyticsEventIdSchema, type AnalyticsEventIdentity, type AnalyticsEventInput, type AnalyticsProperties, type AnalyticsProperty, AppError, type AppMessages, AuthenticationError, type BounceType, BounceTypeSchema, type BoundaryErrorClassifier, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAddress, EmailAddressSchema, type EmailIdempotencyKey, type EmailSendFailureReason, EmailServiceError, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, InvalidEmailIdempotencyKeyError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageDefinition, type MessageId, type MessageOf, MissingConfigurationError, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, type RecordEmailEventPayload, RecordEmailEventPayloadSchema, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
|
package/dist/core.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as AnalyticsEventIdSchema, A as ProblemDetailsSchema, B as NotAuthorizedError, C as defineMessages, D as DatabaseError, E as unreachable, F as ResourceNotFoundError, G as BounceTypeSchema, H as RateLimitError, I as UpgradeRequiredError, J as shouldUpdateBounce, K as isEmailDeliverable, L as ValidationError, M as ValidationProblemErrorSchema, N as MalformedRequestError, O as defineErrors, P as RequestTimeoutError, Q as EmailAddressSchema, R as InternalServerError, S as Entity, T as notImplemented, U as AuthenticationError, V as StaleSessionError, W as RecordEmailEventPayloadSchema, X as InvalidEmailIdempotencyKeyError, Y as EmailServiceError, Z as emailIdempotencyKey, _ as isCloudflareRetryableError, a as createLogger, b as isTransientTransportError, c as exponentialDelayCapMs, d as classifyBoundaryError, et as MissingConfigurationError, f as classifyFailure, g as isCloudflareOverloadedError, h as isCloudflareObjectResetError, i as consoleSink, j as ValidationProblemDetailsSchema, k as sharedErrors, l as exponentialEqualJitterMs, m as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, n as Logger, o as setLogSink, p as retryAfterSecondsOf, q as parseBounceType, r as configureLogger, s as setLoggerErrorHook, t as LogLevel, tt as AppError, u as spreadJitterMs, v as isTransientCloudflareRuntimeError, w as defineId, x as shouldRetryFailure, y as isAbortError, z as ServiceUnavailableError } from "./core-hdaNiCOU.js";
|
|
2
2
|
|
|
3
|
-
export { AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, Logger, MalformedRequestError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RecordEmailEventPayloadSchema, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
|
|
3
|
+
export { AnalyticsEventIdSchema, AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, Logger, MalformedRequestError, MissingConfigurationError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RecordEmailEventPayloadSchema, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
|
package/dist/http.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { u as Logger } from "./index-
|
|
2
|
-
import { n as WebhookVerificationError, r as WebhookVerifier, t as WebhookVerification } from "./webhook-verification-
|
|
1
|
+
import { u as Logger } from "./index-G1QG0P5g.js";
|
|
2
|
+
import { n as WebhookVerificationError, r as WebhookVerifier, t as WebhookVerification } from "./webhook-verification-D7DIhH6C.js";
|
|
3
3
|
//#region src/infrastructure/http/webhook-handler.d.ts
|
|
4
4
|
/** Read raw webhook requests and acknowledge effects only after the callback completes. */
|
|
5
5
|
export declare class WebhookHandler<Event> {
|
package/dist/http.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as createLogger } from "./core-
|
|
2
|
-
import { t as WebhookVerificationError } from "./webhook-verification-
|
|
1
|
+
import { a as createLogger } from "./core-hdaNiCOU.js";
|
|
2
|
+
import { t as WebhookVerificationError } from "./webhook-verification-trEgyz7I.js";
|
|
3
3
|
import { StatusCodes } from "http-status-codes";
|
|
4
4
|
|
|
5
5
|
//#region src/infrastructure/http/webhook-handler.ts
|