better-ship 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/{application-rpZoTfzU.js → application-DjsQtpgw.js} +2 -2
  2. package/dist/application-DjsQtpgw.js.map +1 -0
  3. package/dist/application.d.ts +3 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.d.ts +21 -0
  6. package/dist/better-auth/apple-client-secret.d.ts.map +1 -0
  7. package/dist/better-auth/apple-client-secret.js +44 -0
  8. package/dist/better-auth/apple-client-secret.js.map +1 -0
  9. package/dist/better-auth/auth-client.d.ts +16 -0
  10. package/dist/better-auth/auth-client.d.ts.map +1 -0
  11. package/dist/better-auth/auth-client.js +24 -0
  12. package/dist/better-auth/auth-client.js.map +1 -0
  13. package/dist/better-auth/rate-limit.d.ts +34 -0
  14. package/dist/better-auth/rate-limit.d.ts.map +1 -0
  15. package/dist/better-auth/rate-limit.js +59 -0
  16. package/dist/better-auth/rate-limit.js.map +1 -0
  17. package/dist/better-auth/secondary-storage.d.ts +11 -0
  18. package/dist/better-auth/secondary-storage.d.ts.map +1 -0
  19. package/dist/better-auth/secondary-storage.js +18 -0
  20. package/dist/better-auth/secondary-storage.js.map +1 -0
  21. package/dist/better-auth/stripe.d.ts +9 -0
  22. package/dist/better-auth/stripe.d.ts.map +1 -0
  23. package/dist/better-auth/stripe.js +17 -0
  24. package/dist/better-auth/stripe.js.map +1 -0
  25. package/dist/better-auth.d.ts +100 -0
  26. package/dist/better-auth.d.ts.map +1 -0
  27. package/dist/better-auth.js +112 -0
  28. package/dist/better-auth.js.map +1 -0
  29. package/dist/cloudflare/auth-secondary-storage.d.ts +36 -0
  30. package/dist/cloudflare/auth-secondary-storage.d.ts.map +1 -0
  31. package/dist/cloudflare/auth-secondary-storage.js +98 -0
  32. package/dist/cloudflare/auth-secondary-storage.js.map +1 -0
  33. package/dist/cloudflare.d.ts +7 -7
  34. package/dist/cloudflare.d.ts.map +1 -1
  35. package/dist/cloudflare.js +3 -3
  36. package/dist/cloudflare.js.map +1 -1
  37. package/dist/core-Cx5SeyKV.js +709 -0
  38. package/dist/core-Cx5SeyKV.js.map +1 -0
  39. package/dist/core.d.ts +2 -2
  40. package/dist/core.js +2 -2
  41. package/dist/index-BStnggQO.d.ts +584 -0
  42. package/dist/index-BStnggQO.d.ts.map +1 -0
  43. package/dist/{index-BN_tjxME.d.ts → index-DWIRrJMP.d.ts} +21 -50
  44. package/dist/index-DWIRrJMP.d.ts.map +1 -0
  45. package/dist/postgres.d.ts +7 -7
  46. package/dist/postgres.d.ts.map +1 -1
  47. package/dist/postgres.js +3 -3
  48. package/dist/postgres.js.map +1 -1
  49. package/dist/tanstack.d.ts +88 -1
  50. package/dist/tanstack.d.ts.map +1 -0
  51. package/dist/tanstack.js +225 -0
  52. package/dist/tanstack.js.map +1 -0
  53. package/dist/{unit-of-work-context-CbUJGHlL.d.ts → unit-of-work-context-CPz9rdSS.d.ts} +3 -2
  54. package/dist/unit-of-work-context-CPz9rdSS.d.ts.map +1 -0
  55. package/dist/{unit-of-work-context-BLNj72v0.js → unit-of-work-context-DToDpAkv.js} +2 -2
  56. package/dist/unit-of-work-context-DToDpAkv.js.map +1 -0
  57. package/package.json +57 -12
  58. package/src/application/event-collector.ts +3 -3
  59. package/src/application/handlers.ts +7 -4
  60. package/src/application/index.ts +1 -1
  61. package/src/application/message-already-processed.error.ts +1 -3
  62. package/src/application/message-bus.ts +14 -8
  63. package/src/application/message-store.ts +2 -2
  64. package/src/application/registry.ts +14 -13
  65. package/src/application/unit-of-work.ts +2 -1
  66. package/src/core/authentication.error.ts +11 -0
  67. package/src/core/define-messages.ts +136 -0
  68. package/src/core/entity.ts +33 -0
  69. package/src/core/error-table.ts +188 -0
  70. package/src/core/identity.ts +29 -0
  71. package/src/core/index.ts +50 -0
  72. package/src/core/internal.errors.ts +21 -0
  73. package/src/core/logger.ts +27 -15
  74. package/src/{application → core}/messages.ts +4 -4
  75. package/src/core/not-authorized.error.ts +11 -0
  76. package/src/core/problem-details.ts +57 -0
  77. package/src/core/rate-limit.error.ts +12 -0
  78. package/src/core/request.errors.ts +86 -0
  79. package/src/core/stale-session.error.ts +11 -0
  80. package/src/infrastructure/better-auth/apple-client-secret.ts +54 -0
  81. package/src/infrastructure/better-auth/auth-client.ts +26 -0
  82. package/src/infrastructure/better-auth/options.ts +232 -0
  83. package/src/infrastructure/better-auth/rate-limit.ts +69 -0
  84. package/src/infrastructure/better-auth/secondary-storage.ts +21 -0
  85. package/src/infrastructure/better-auth/stripe.ts +11 -0
  86. package/src/infrastructure/cloudflare/auth-secondary-storage.ts +113 -0
  87. package/src/infrastructure/cloudflare/base-d1-repository.ts +2 -2
  88. package/src/infrastructure/cloudflare/d1-message-store.ts +3 -7
  89. package/src/infrastructure/cloudflare/d1-schema.ts +2 -2
  90. package/src/infrastructure/postgres/base-postgres-repository.ts +2 -2
  91. package/src/infrastructure/postgres/postgres-message-store.ts +3 -7
  92. package/src/infrastructure/postgres/postgres-schema.ts +2 -2
  93. package/src/infrastructure/tanstack/auth.middleware.ts +89 -0
  94. package/src/infrastructure/tanstack/error.middleware.ts +81 -0
  95. package/src/infrastructure/tanstack/http-error-response.ts +30 -0
  96. package/src/infrastructure/tanstack/index.ts +13 -0
  97. package/src/infrastructure/tanstack/last-login-method.ts +13 -0
  98. package/src/infrastructure/tanstack/resolve-failure.ts +24 -0
  99. package/src/infrastructure/tanstack/session-cookies.ts +36 -0
  100. package/src/infrastructure/tanstack/to-error-payload.ts +32 -0
  101. package/src/infrastructure/unit-of-work-context.ts +3 -2
  102. package/dist/application-rpZoTfzU.js.map +0 -1
  103. package/dist/core-MjwyZJ4i.js +0 -302
  104. package/dist/core-MjwyZJ4i.js.map +0 -1
  105. package/dist/index-BN_tjxME.d.ts.map +0 -1
  106. package/dist/index-ToddX0m3.d.ts +0 -213
  107. package/dist/index-ToddX0m3.d.ts.map +0 -1
  108. package/dist/unit-of-work-context-BLNj72v0.js.map +0 -1
  109. package/dist/unit-of-work-context-CbUJGHlL.d.ts.map +0 -1
@@ -0,0 +1,584 @@
1
+ import { z } from "zod";
2
+ //#region src/core/failure-classification.d.ts
3
+ /**
4
+ * What one failure is, before any policy decides what to do about it.
5
+ *
6
+ * `transient`: the world may differ on the next attempt. `terminal`: repeating gives the
7
+ * same answer. `unknown`: nobody judged this error, so it came from outside unwrapped.
8
+ */
9
+ type FailureClassification = 'transient' | 'terminal' | 'unknown';
10
+ /**
11
+ * Who is asking to repeat the work.
12
+ *
13
+ * An immediate owner holds a caller and a socket open. A durable owner already stored the
14
+ * work, so it can afford to try again on a failure nobody classified.
15
+ */
16
+ type RetryOwner = 'immediate' | 'durable';
17
+ /** Decide whether one retry owner may repeat a failed operation. */
18
+ declare function shouldRetryFailure(args: {
19
+ readonly classification: FailureClassification;
20
+ readonly repeatSafe: boolean;
21
+ readonly owner: RetryOwner;
22
+ }): boolean;
23
+ //#endregion
24
+ //#region src/core/app-error.d.ts
25
+ /**
26
+ * The base of every expected failure. A subclass declares its tag and its classification,
27
+ * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from
28
+ * raw throws with `instanceof AppError`; a value that fails it was never judged.
29
+ *
30
+ * A `readonly` field with a literal initializer keeps the literal type, so
31
+ * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.
32
+ */
33
+ declare abstract class AppError extends Error {
34
+ abstract readonly _tag: string;
35
+ abstract readonly classification: FailureClassification;
36
+ get name(): string;
37
+ }
38
+ //#endregion
39
+ //#region src/core/authentication.error.d.ts
40
+ /** A protected operation requires a session that the caller did not provide. */
41
+ declare class AuthenticationError extends AppError {
42
+ readonly _tag = "AuthenticationError";
43
+ readonly classification = "terminal";
44
+ constructor();
45
+ }
46
+ //#endregion
47
+ //#region src/core/rate-limit.error.d.ts
48
+ /** HTTP 429 with a retry delay in seconds. A null delay means the response supplies no valid duration. */
49
+ declare class RateLimitError extends AppError {
50
+ readonly retryAfter: number | null;
51
+ readonly _tag = "RateLimitError";
52
+ readonly classification = "transient";
53
+ readonly status = 429;
54
+ constructor(retryAfter: number | null);
55
+ }
56
+ //#endregion
57
+ //#region src/core/stale-session.error.d.ts
58
+ /** A presented session cookie no longer resolves; the application owns cleanup and redirect policy. */
59
+ declare class StaleSessionError extends AppError {
60
+ readonly _tag = "StaleSessionError";
61
+ readonly classification = "terminal";
62
+ constructor();
63
+ }
64
+ //#endregion
65
+ //#region src/core/not-authorized.error.d.ts
66
+ /** The authenticated caller cannot perform this operation. Ported from Porte's auth.errors.ts. */
67
+ declare class NotAuthorizedError extends AppError {
68
+ readonly _tag = "NotAuthorizedError";
69
+ readonly classification = "terminal";
70
+ constructor();
71
+ }
72
+ //#endregion
73
+ //#region src/core/internal.errors.d.ts
74
+ /** Safe public replacement for an unknown failure, ported from Porte's internal.errors.ts. */
75
+ declare class InternalServerError extends AppError {
76
+ readonly _tag = "InternalServerError";
77
+ readonly classification = "unknown";
78
+ constructor();
79
+ }
80
+ /** Safe public replacement for a classified transient failure. */
81
+ declare class ServiceUnavailableError extends AppError {
82
+ readonly _tag = "ServiceUnavailableError";
83
+ readonly classification = "transient";
84
+ constructor();
85
+ }
86
+ //#endregion
87
+ //#region src/core/problem-details.d.ts
88
+ /**
89
+ * The standard RFC 9457 body for a failed HTTP response.
90
+ * The HTTP response status remains authoritative; extensions may add problem-specific data.
91
+ * @see https://http.dev/problem-details
92
+ */
93
+ declare const ProblemDetailsSchema: z.ZodObject<{
94
+ type: z.ZodString;
95
+ title: z.ZodString;
96
+ detail: z.ZodOptional<z.ZodString>;
97
+ instance: z.ZodOptional<z.ZodString>;
98
+ }, z.core.$loose>;
99
+ /** An RFC 9457 problem body for a failed HTTP response. */
100
+ type ProblemDetails = z.infer<typeof ProblemDetailsSchema>;
101
+ /** One invalid value in a `422` validation problem. */
102
+ declare const ValidationProblemErrorSchema: z.ZodObject<{
103
+ detail: z.ZodString;
104
+ pointer: z.ZodString;
105
+ }, z.core.$strip>;
106
+ /** One invalid value in a `422` validation problem. */
107
+ type ValidationProblemError = z.infer<typeof ValidationProblemErrorSchema>;
108
+ /** An RFC 9457 validation problem with one or more invalid content values. */
109
+ declare const ValidationProblemDetailsSchema: z.ZodObject<{
110
+ type: z.ZodString;
111
+ title: z.ZodString;
112
+ detail: z.ZodOptional<z.ZodString>;
113
+ instance: z.ZodOptional<z.ZodString>;
114
+ errors: z.ZodArray<z.ZodObject<{
115
+ detail: z.ZodString;
116
+ pointer: z.ZodString;
117
+ }, z.core.$strip>>;
118
+ }, z.core.$loose>;
119
+ /** An RFC 9457 validation problem with one or more invalid content values. */
120
+ type ValidationProblemDetails = z.infer<typeof ValidationProblemDetailsSchema>;
121
+ //#endregion
122
+ //#region src/core/request.errors.d.ts
123
+ /** One invalid value as a validator reports it: a message and a path of keys. */
124
+ type ValidationIssue = {
125
+ readonly message: string;
126
+ readonly path: readonly PropertyKey[];
127
+ };
128
+ /** Invalid user input, one entry per invalid value in the RFC 9457 shape. Technical failures use another error. */
129
+ declare class ValidationError extends AppError {
130
+ readonly errors: readonly ValidationProblemError[];
131
+ readonly _tag = "ValidationError";
132
+ readonly classification = "terminal";
133
+ constructor(errors: readonly ValidationProblemError[], message?: string);
134
+ /** Convert a Zod error. Each issue path becomes a JSON Pointer. */
135
+ static fromZod(error: z.ZodError, message?: string): ValidationError;
136
+ /** Convert issues from any validator, such as issues TanStack serialized into an error message. */
137
+ static fromIssues(issues: readonly ValidationIssue[], message?: string): ValidationError;
138
+ }
139
+ /** The server cannot parse the request syntax. */
140
+ declare class MalformedRequestError extends AppError {
141
+ readonly _tag = "MalformedRequestError";
142
+ readonly classification = "terminal";
143
+ constructor(args: {
144
+ cause: unknown;
145
+ });
146
+ }
147
+ /** No resource matches the requested HTTP path. */
148
+ declare class ResourceNotFoundError extends AppError {
149
+ readonly _tag = "ResourceNotFoundError";
150
+ readonly classification = "terminal";
151
+ constructor();
152
+ }
153
+ /** A WebSocket route received a request without an upgrade. */
154
+ declare class UpgradeRequiredError extends AppError {
155
+ readonly _tag = "UpgradeRequiredError";
156
+ readonly classification = "terminal";
157
+ constructor();
158
+ }
159
+ /** The requested operation did not answer before its deadline. */
160
+ declare class RequestTimeoutError extends AppError {
161
+ readonly _tag = "RequestTimeoutError";
162
+ readonly classification = "transient";
163
+ constructor();
164
+ }
165
+ //#endregion
166
+ //#region src/core/error-table.d.ts
167
+ type PublicFields = z.ZodObject;
168
+ /**
169
+ * One public error: its class, its HTTP status, and the extra properties a client may read.
170
+ * `fields` strips the thrown error on the server and parses the payload in the browser.
171
+ */
172
+ type ErrorEntry<Tag extends string, Fields extends PublicFields = PublicFields> = {
173
+ readonly error: abstract new (...args: never[]) => AppError & {
174
+ readonly _tag: Tag;
175
+ };
176
+ readonly status: number;
177
+ readonly fields?: Fields;
178
+ };
179
+ /** Entries keyed by tag. The compiler rejects a key that differs from the class's `_tag`. */
180
+ type ErrorEntries<Entries> = { readonly [Tag in keyof Entries & string]: ErrorEntry<Tag>; };
181
+ type EntryPayload<Tag extends string, Entry> = Entry extends {
182
+ readonly fields: infer Fields extends z.ZodType;
183
+ } ? {
184
+ readonly _tag: Tag;
185
+ readonly message: string;
186
+ } & z.output<Fields> : {
187
+ readonly _tag: Tag;
188
+ readonly message: string;
189
+ };
190
+ type PayloadOfEntries<Entries> = { [Tag in keyof Entries & string]: EntryPayload<Tag, Entries[Tag]>; }[keyof Entries & string];
191
+ /** The HTTP status and public payload for one resolved failure. */
192
+ type ResolvedError<Payload> = {
193
+ readonly status: number;
194
+ readonly payload: Payload;
195
+ };
196
+ /**
197
+ * One application's public errors, shared by every transport boundary and the browser.
198
+ * `resolve` and `fallback` serve boundaries. `parse` and `generic` serve screens.
199
+ */
200
+ type ErrorTable<Entries> = {
201
+ readonly entries: Entries;
202
+ /** The discriminated union of every entry's `_tag`, `message`, and fields. */
203
+ readonly payloadSchema: z.ZodType<PayloadOfEntries<Entries>>;
204
+ /** The `InternalServerError` payload, for screens that must show something. */
205
+ readonly generic: PayloadOfEntries<Entries>;
206
+ /** Read a rejection value. Null means no known tag, so the request never reached the Worker. */
207
+ parse(cause: unknown): PayloadOfEntries<Entries> | null;
208
+ /** Narrow a rejection value to one tag's payload, for a caller that acts on that one error. */
209
+ is<Tag extends keyof Entries & string>(cause: unknown, tag: Tag): cause is Extract<PayloadOfEntries<Entries>, {
210
+ readonly _tag: Tag;
211
+ }>;
212
+ /** Match a local instance or a remote error by tag. Null means the failure is not public. */
213
+ resolve(cause: unknown): ResolvedError<PayloadOfEntries<Entries>> | null;
214
+ /** The replacement for an unmapped failure: 503 when it declared itself transient, else 500. */
215
+ fallback(cause: unknown): ResolvedError<PayloadOfEntries<Entries>>;
216
+ };
217
+ /** The union of payloads a table can produce. */
218
+ type ErrorPayloadOf<Table> = Table extends ErrorTable<infer Entries> ? PayloadOfEntries<Entries> : never;
219
+ /** The union of tags a table contains. */
220
+ type ErrorTagOf<Table> = Table extends ErrorTable<infer Entries> ? keyof Entries & string : never;
221
+ /** The errors every application can throw, with their statuses. `defineErrors` includes them. */
222
+ declare const sharedErrors: {
223
+ readonly MalformedRequestError: {
224
+ readonly error: typeof MalformedRequestError;
225
+ readonly status: 400;
226
+ };
227
+ readonly AuthenticationError: {
228
+ readonly error: typeof AuthenticationError;
229
+ readonly status: 401;
230
+ };
231
+ readonly StaleSessionError: {
232
+ readonly error: typeof StaleSessionError;
233
+ readonly status: 401;
234
+ };
235
+ readonly NotAuthorizedError: {
236
+ readonly error: typeof NotAuthorizedError;
237
+ readonly status: 403;
238
+ };
239
+ readonly ResourceNotFoundError: {
240
+ readonly error: typeof ResourceNotFoundError;
241
+ readonly status: 404;
242
+ };
243
+ readonly ValidationError: {
244
+ readonly error: typeof ValidationError;
245
+ readonly status: 422;
246
+ readonly fields: z.ZodObject<{
247
+ errors: z.ZodArray<z.ZodObject<{
248
+ detail: z.ZodString;
249
+ pointer: z.ZodString;
250
+ }, z.core.$strip>>;
251
+ }, z.core.$strip>;
252
+ };
253
+ readonly UpgradeRequiredError: {
254
+ readonly error: typeof UpgradeRequiredError;
255
+ readonly status: 426;
256
+ };
257
+ readonly RateLimitError: {
258
+ readonly error: typeof RateLimitError;
259
+ readonly status: 429;
260
+ readonly fields: z.ZodObject<{
261
+ retryAfter: z.ZodNullable<z.ZodNumber>;
262
+ }, z.core.$strip>;
263
+ };
264
+ readonly InternalServerError: {
265
+ readonly error: typeof InternalServerError;
266
+ readonly status: 500;
267
+ };
268
+ readonly ServiceUnavailableError: {
269
+ readonly error: typeof ServiceUnavailableError;
270
+ readonly status: 503;
271
+ };
272
+ readonly RequestTimeoutError: {
273
+ readonly error: typeof RequestTimeoutError;
274
+ readonly status: 504;
275
+ };
276
+ };
277
+ type MergedEntries<Entries> = Omit<typeof sharedErrors, keyof Entries> & Entries;
278
+ /**
279
+ * Build the application's error table. The shared entries are always included;
280
+ * an entry with the same key replaces the shared one.
281
+ */
282
+ declare function defineErrors<const Entries extends ErrorEntries<Entries>>(entries: Entries): ErrorTable<MergedEntries<Entries>>;
283
+ //#endregion
284
+ //#region src/core/database.error.d.ts
285
+ /** SQLite reports these constraint categories through D1. */
286
+ type D1ConstraintKind = 'unique' | 'not_null' | 'foreign_key' | 'check';
287
+ /** Database evidence for callers that interpret a specific code or constraint. */
288
+ type DatabaseFailure = {
289
+ readonly database: 'd1';
290
+ readonly code: string | undefined;
291
+ readonly kind: D1ConstraintKind | undefined;
292
+ readonly table: string | undefined;
293
+ readonly column: string | undefined;
294
+ readonly constraintName: string | undefined;
295
+ } | {
296
+ readonly database: 'postgres';
297
+ readonly code: string | undefined;
298
+ readonly table_name: string | undefined;
299
+ readonly column_name: string | undefined;
300
+ readonly constraint_name: string | undefined;
301
+ };
302
+ /** Classification describes the failure; callers must separately establish whether repetition is safe. */
303
+ declare class DatabaseError extends AppError {
304
+ readonly operation: string;
305
+ readonly classification: FailureClassification;
306
+ readonly details: DatabaseFailure;
307
+ readonly _tag = "DatabaseError";
308
+ constructor(operation: string, classification: FailureClassification, details: DatabaseFailure, options: {
309
+ readonly cause: unknown;
310
+ });
311
+ }
312
+ //#endregion
313
+ //#region src/core/defects.d.ts
314
+ /**
315
+ * Mark a line the types say cannot run. A union member without a branch stops compilation here.
316
+ *
317
+ * @throws Panic when a value outside the union arrives at runtime.
318
+ */
319
+ declare function unreachable(value: never): never;
320
+ /**
321
+ * Mark a body that is not written yet. A defect, not an expected failure.
322
+ *
323
+ * @param what - The behavior the body will provide, such as `invoice export`.
324
+ * @throws Panic always.
325
+ */
326
+ declare function notImplemented(what: string): never;
327
+ //#endregion
328
+ //#region src/core/identity.d.ts
329
+ /** A string only `create()` or `schema.parse()` of the same kind can produce. */
330
+ type Id<Brand extends string> = string & z.core.$brand<Brand>;
331
+ /** One id kind the application mints. `schema` parses untrusted input; `create` mints a uuid v7. */
332
+ type IdDefinition<Brand extends string> = {
333
+ readonly schema: z.core.$ZodBranded<z.ZodUUID, Brand>;
334
+ /** Mint a new time-ordered id. No parse: we produced it, so it is valid by construction. */
335
+ create(): Id<Brand>;
336
+ };
337
+ /** The id type of a definition: `type CallId = IdOf<typeof CallId>`. */
338
+ type IdOf<Definition extends IdDefinition<string>> = z.output<Definition['schema']>;
339
+ /**
340
+ * Define an id kind the application mints: `export const CallId = defineId('CallId')`.
341
+ * An id another system mints, such as a provider's call id, stays a plain branded schema.
342
+ */
343
+ declare function defineId<const Brand extends string>(brand: Brand): IdDefinition<Brand>;
344
+ //#endregion
345
+ //#region src/core/messages.d.ts
346
+ /**
347
+ * The identity of a command or event. Receipts and the outbox are keyed by it.
348
+ *
349
+ * Internal messages use UUID v7, so receipts sort by creation. External messages use the
350
+ * provider's own key, `stripe:event:evt_123`, so a redelivered webhook is a duplicate by
351
+ * construction. The app parses and generates ids; this package only carries them.
352
+ */
353
+ type MessageId = string;
354
+ /** An action to perform. One handler, returns a value. The product adds its payload. */
355
+ type DomainCommand<Name extends string = string> = {
356
+ readonly type: 'command';
357
+ readonly name: Name;
358
+ readonly id: MessageId;
359
+ };
360
+ /** A request for data. One handler, returns a value. No id: nothing claims a read. */
361
+ type DomainQuery<Name extends string = string> = {
362
+ readonly type: 'query';
363
+ readonly name: Name;
364
+ };
365
+ /** A fact that happened. Zero or more subscribers, returns nothing. The product adds its payload. */
366
+ type DomainEvent<Name extends string = string> = {
367
+ readonly type: 'event';
368
+ readonly name: Name;
369
+ readonly id: MessageId;
370
+ };
371
+ /** The routing fields the bus reads. `type` selects the table, `name` selects the slot. */
372
+ type DomainMessage = DomainCommand | DomainEvent | DomainQuery;
373
+ //#endregion
374
+ //#region src/core/define-messages.d.ts
375
+ /** Payload schemas keyed by message name. A payload never carries `type`, `name`, or `id`. */
376
+ type PayloadSchemas = Readonly<Record<string, z.ZodType<object>>>;
377
+ /** An application's messages: one list of payload schemas per kind. */
378
+ type MessageDefinition = {
379
+ readonly commands: PayloadSchemas;
380
+ readonly events: PayloadSchemas;
381
+ readonly queries: PayloadSchemas;
382
+ };
383
+ type AnyMessages = {
384
+ readonly definition: MessageDefinition;
385
+ };
386
+ type Def<Messages extends AnyMessages> = Messages['definition'];
387
+ type Payload<Schemas extends PayloadSchemas, Name extends keyof Schemas> = z.output<Schemas[Name]>;
388
+ /** Every command of an application: `CommandOf<typeof messages>`. */
389
+ type CommandOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['commands'] & string]: DomainCommand<Name> & Payload<Def<Messages>['commands'], Name>; }[keyof Def<Messages>['commands'] & string];
390
+ /** Every event of an application: `EventOf<typeof messages>`. */
391
+ type EventOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['events'] & string]: DomainEvent<Name> & Payload<Def<Messages>['events'], Name>; }[keyof Def<Messages>['events'] & string];
392
+ /** Every query of an application: `QueryOf<typeof messages>`. */
393
+ type QueryOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['queries'] & string]: DomainQuery<Name> & Payload<Def<Messages>['queries'], Name>; }[keyof Def<Messages>['queries'] & string];
394
+ /** Every message of an application: what the registry and the bus are typed with. */
395
+ type MessageOf<Messages extends AnyMessages> = CommandOf<Messages> | EventOf<Messages> | QueryOf<Messages>;
396
+ /**
397
+ * What `defineMessages` returns. The factories build messages for in-process dispatch without
398
+ * parsing; the data is already typed. The schemas parse untrusted input at a boundary.
399
+ */
400
+ type AppMessages<Definition extends MessageDefinition> = {
401
+ readonly definition: Definition;
402
+ /** Build a command. `id` defaults to a uuid v7; a webhook passes the provider's key, `stripe:event:evt_123`. */
403
+ createCommand<Name extends keyof Definition['commands'] & string>(name: Name, payload: Payload<Definition['commands'], Name>, id?: MessageId): DomainCommand<Name> & Payload<Definition['commands'], Name>;
404
+ /** Build an event. `id` defaults to a uuid v7, which also orders it in time. */
405
+ createEvent<Name extends keyof Definition['events'] & string>(name: Name, payload: Payload<Definition['events'], Name>, id?: MessageId): DomainEvent<Name> & Payload<Definition['events'], Name>;
406
+ /** Build a query. No id: nothing claims a read. */
407
+ createQuery<Name extends keyof Definition['queries'] & string>(name: Name, payload: Payload<Definition['queries'], Name>): DomainQuery<Name> & Payload<Definition['queries'], Name>;
408
+ readonly commandSchema: z.ZodType<CommandOf<AppMessages<Definition>>>;
409
+ readonly eventSchema: z.ZodType<EventOf<AppMessages<Definition>>>;
410
+ readonly querySchema: z.ZodType<QueryOf<AppMessages<Definition>>>;
411
+ /** What a queue body may be: a command or an event. Queries never cross a queue. */
412
+ readonly queueSchema: z.ZodType<CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>>;
413
+ };
414
+ type RoutingField = 'type' | 'name' | 'id';
415
+ /** A payload that declares a routing field maps to `never`, so `defineMessages` rejects it. */
416
+ type WithoutRoutingFields<Schemas extends PayloadSchemas> = { readonly [Name in keyof Schemas]: keyof z.output<Schemas[Name]> & RoutingField extends never ? Schemas[Name] : never; };
417
+ /** The compile-time rule: no payload of any kind declares `type`, `name`, or `id`. */
418
+ type ValidDefinition<Definition extends MessageDefinition> = {
419
+ readonly commands: WithoutRoutingFields<Definition['commands']>;
420
+ readonly events: WithoutRoutingFields<Definition['events']>;
421
+ readonly queries: WithoutRoutingFields<Definition['queries']>;
422
+ };
423
+ /**
424
+ * Define an application's messages once. The key is the name; the factories add the routing
425
+ * fields `type`, `name`, and `id`. A payload that declares one of them is a compile error.
426
+ */
427
+ declare function defineMessages<const Definition extends MessageDefinition>(definition: Definition & ValidDefinition<Definition>): AppMessages<Definition>;
428
+ //#endregion
429
+ //#region src/core/entity.d.ts
430
+ /** What an aggregate's plain data must have: an identity. A branded id keeps its brand. */
431
+ type EntityData = {
432
+ readonly id: string;
433
+ };
434
+ /**
435
+ * The base of an aggregate: its identity, the events it raised, and the plain data a repository
436
+ * stores. The subclass keeps its constructor private and declares `static restore(data: Data)`,
437
+ * the one door a repository rebuilds it through. A repository drains the events after `save`.
438
+ */
439
+ declare abstract class Entity<Data extends EntityData, TEvent extends DomainEvent = DomainEvent> {
440
+ private events;
441
+ abstract readonly id: Data['id'];
442
+ /** Record one event with the state change that caused it. The unit of work commits both. */
443
+ protected addEvent(event: TEvent): void;
444
+ /** A copy of the events raised since the last `clearEvents`. */
445
+ collectEvents(): ReadonlyArray<TEvent>;
446
+ /** Forget the raised events once the boundary has taken them. */
447
+ clearEvents(): void;
448
+ /** Plain data for the repository. The subclass's `restore(data)` accepts exactly this. */
449
+ abstract toPlainObject(): Data;
450
+ }
451
+ //#endregion
452
+ //#region src/core/transport-classification.d.ts
453
+ /** Cancellation is a decision, not a failure to repeat. */
454
+ declare function isAbortError(cause: unknown): boolean;
455
+ /** Match known transient transport messages while excluding explicit cancellation. */
456
+ declare function isTransientTransportError(cause: unknown): boolean;
457
+ //#endregion
458
+ //#region src/core/logger.d.ts
459
+ /**
460
+ * Module-scoped logging for every host.
461
+ *
462
+ * A logger emits one plain-data entry per log. The default sink hands it to `console` as an
463
+ * entry object for a log service or as a colored line for a person, selected at startup.
464
+ */
465
+ /** A value a log entry may carry. Errors enter only through `Logger.error`. */
466
+ type LogValue = string | number | boolean | null | undefined | ReadonlyArray<LogValue> | LogFields;
467
+ /** Named log values. */
468
+ type LogFields = {
469
+ readonly [key: string]: LogValue;
470
+ };
471
+ /**
472
+ * The supported log severity levels, in ascending order.
473
+ *
474
+ * A const object, not an enum, so a parsed environment value typed `'INFO'` is a `LogLevel`.
475
+ */
476
+ declare const LogLevel: {
477
+ readonly DEBUG: 'DEBUG';
478
+ readonly INFO: 'INFO';
479
+ readonly WARN: 'WARN';
480
+ readonly ERROR: 'ERROR';
481
+ };
482
+ type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];
483
+ /** An error as plain data, including diagnostics, causes, and aggregate members. */
484
+ type SerializedError = {
485
+ readonly name: string;
486
+ readonly message: string;
487
+ readonly stack?: string;
488
+ readonly fields?: LogFields;
489
+ readonly cause?: SerializedError;
490
+ readonly errors?: ReadonlyArray<SerializedError>;
491
+ };
492
+ /** One log, as the sink receives it. Plain data, safe to stringify. */
493
+ type LogEntry = {
494
+ readonly timestamp: string;
495
+ readonly level: LogLevel;
496
+ readonly module: string;
497
+ readonly message: string;
498
+ readonly details: LogFields;
499
+ readonly userId?: string;
500
+ /** Present on `Logger.error` entries that carried an error. */
501
+ readonly error?: SerializedError;
502
+ };
503
+ /** The context an error log carries. */
504
+ type ErrorLogContext = {
505
+ readonly error?: unknown;
506
+ readonly userId?: string;
507
+ readonly details?: LogFields;
508
+ };
509
+ /** What a logger lets through: a level and everything above it, or nothing. */
510
+ type LogThreshold = LogLevel | 'OFF';
511
+ /** Overrides the application settings for one logger. */
512
+ interface LoggerConfig {
513
+ readonly level?: LogThreshold;
514
+ }
515
+ /** `json` writes the entry object. `pretty` writes one readable line for a person. */
516
+ type LogFormat = 'json' | 'pretty';
517
+ /**
518
+ * The application settings, set once at the composition root.
519
+ *
520
+ * An omitted field keeps its default. An explicit `undefined` is a compile error, so the root
521
+ * parses an environment value before passing it. The logger reads no environment itself.
522
+ */
523
+ interface LoggerSettings extends LoggerConfig {
524
+ readonly format?: LogFormat;
525
+ }
526
+ /**
527
+ * Set application settings, including for existing loggers. Per-logger overrides take priority.
528
+ * Call at startup, never per request. An omitted field resets to INFO and JSON output.
529
+ */
530
+ declare function configureLogger(config: LoggerSettings): void;
531
+ /** The error data sent to the configured error hook. */
532
+ interface ErrorCaptureEntry {
533
+ readonly error: unknown;
534
+ readonly distinctId: string | undefined;
535
+ readonly context: LogFields;
536
+ }
537
+ /** A function that forwards one logged error to an error service. */
538
+ type LoggerErrorHook = (entry: ErrorCaptureEntry) => void;
539
+ /** Where every log entry goes. */
540
+ type LogSink = (entry: LogEntry) => void;
541
+ /**
542
+ * Register the function that receives each logged error.
543
+ *
544
+ * Set once at the process entry point. A later call replaces the earlier hook.
545
+ */
546
+ declare function setLoggerErrorHook(fn: LoggerErrorHook): void;
547
+ /**
548
+ * JSON format writes the entry object. Pretty format writes one line, then the details,
549
+ * the error, and the stack as separate console arguments.
550
+ */
551
+ declare const consoleSink: LogSink;
552
+ /**
553
+ * Send every log entry somewhere other than `console`.
554
+ *
555
+ * Set once at the process entry point, never per module. A logger is created
556
+ * by name and nothing else, so its destination is a fact about the process.
557
+ */
558
+ declare function setLogSink(fn: LogSink): void;
559
+ /** Write module-scoped logs with application defaults and optional overrides. */
560
+ declare class Logger {
561
+ private readonly module;
562
+ private readonly config;
563
+ /** Create a logger for one module. */
564
+ constructor(module: string, overrideConfig?: LoggerConfig);
565
+ private log;
566
+ /** Write a debug log. */
567
+ debug(message: string, details?: LogFields): void;
568
+ /** Write an information log. */
569
+ info(message: string, details?: LogFields): void;
570
+ /** Write a warning log. */
571
+ warn(message: string, details?: LogFields): void;
572
+ /**
573
+ * Write an error log and send the error to the configured hook.
574
+ *
575
+ * The details say which call this was, and the error says what went wrong
576
+ * inside it. Both the entry and the error hook receive the supplied user ID.
577
+ */
578
+ error(message: string, context?: ErrorLogContext): void;
579
+ }
580
+ /** Create a logger for one module. */
581
+ declare function createLogger(module: string, config?: LoggerConfig): Logger;
582
+ //#endregion
583
+ export { sharedErrors as $, QueryOf as A, defineId as B, EntityData as C, MessageDefinition as D, EventOf as E, DomainQuery as F, DatabaseFailure as G, unreachable as H, MessageId as I, ErrorPayloadOf as J, ErrorEntries as K, Id as L, DomainCommand as M, DomainEvent as N, MessageOf as O, DomainMessage as P, defineErrors as Q, IdDefinition as R, Entity as S, CommandOf as T, D1ConstraintKind as U, notImplemented as V, DatabaseError as W, ErrorTagOf as X, ErrorTable as Y, ResolvedError as Z, createLogger as _, AuthenticationError as _t, LogFormat as a, ValidationIssue as at, isAbortError as b, RetryOwner as bt, LogThreshold as c, ValidationProblemDetails as ct, LoggerConfig as d, ValidationProblemErrorSchema as dt, MalformedRequestError as et, LoggerErrorHook as f, InternalServerError as ft, consoleSink as g, RateLimitError as gt, configureLogger as h, StaleSessionError as ht, LogFields as i, ValidationError as it, defineMessages as j, PayloadSchemas as k, LogValue as l, ValidationProblemDetailsSchema as lt, SerializedError as m, NotAuthorizedError as mt, ErrorLogContext as n, ResourceNotFoundError as nt, LogLevel as o, ProblemDetails as ot, LoggerSettings as p, ServiceUnavailableError as pt, ErrorEntry as q, LogEntry as r, UpgradeRequiredError as rt, LogSink as s, ProblemDetailsSchema as st, ErrorCaptureEntry as t, RequestTimeoutError as tt, Logger as u, ValidationProblemError as ut, setLogSink as v, AppError as vt, AppMessages as w, isTransientTransportError as x, shouldRetryFailure as xt, setLoggerErrorHook as y, FailureClassification as yt, IdOf as z };
584
+ //# sourceMappingURL=index-BStnggQO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-BStnggQO.d.ts","names":[],"sources":["../src/core/failure-classification.ts","../src/core/app-error.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/problem-details.ts","../src/core/request.errors.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/messages.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/transport-classification.ts","../src/core/logger.ts"],"mappings":";;;;;;;;KAMY;;;;;;;KAQA;;i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