better-ship 0.17.0 → 0.18.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 (116) hide show
  1. package/dist/{application-Cf9SER-i.js → application-CNdzHIXk.js} +5 -7
  2. package/dist/{application-Cf9SER-i.js.map → application-CNdzHIXk.js.map} +1 -1
  3. package/dist/application.d.ts +2 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.d.ts +1 -1
  6. package/dist/better-auth/apple-client-secret.js +2 -2
  7. package/dist/better-auth/apple-client-secret.js.map +1 -1
  8. package/dist/better-auth/auth-client.js +1 -1
  9. package/dist/better-auth/rate-limit.d.ts +1 -1
  10. package/dist/better-auth/rate-limit.js +4 -6
  11. package/dist/better-auth/rate-limit.js.map +1 -1
  12. package/dist/better-auth.js +1 -1
  13. package/dist/billing/client.d.ts +86 -0
  14. package/dist/billing/client.d.ts.map +1 -0
  15. package/dist/billing/client.js +77 -0
  16. package/dist/billing/client.js.map +1 -0
  17. package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
  18. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  19. package/dist/cloudflare/durable-object-client.js +1 -1
  20. package/dist/cloudflare/durable-object-errors.d.ts +1 -1
  21. package/dist/cloudflare/durable-object-errors.js +1 -1
  22. package/dist/cloudflare/kv-client.js +1 -1
  23. package/dist/cloudflare/kv-errors.d.ts +1 -1
  24. package/dist/cloudflare/kv-errors.js +1 -1
  25. package/dist/cloudflare/queue.d.ts +2 -2
  26. package/dist/cloudflare/queue.d.ts.map +1 -1
  27. package/dist/cloudflare/queue.js +10 -12
  28. package/dist/cloudflare/queue.js.map +1 -1
  29. package/dist/cloudflare/r2-client.d.ts +70 -0
  30. package/dist/cloudflare/r2-client.d.ts.map +1 -0
  31. package/dist/cloudflare/r2-client.js +153 -0
  32. package/dist/cloudflare/r2-client.js.map +1 -0
  33. package/dist/cloudflare/r2-errors.d.ts +34 -0
  34. package/dist/cloudflare/r2-errors.d.ts.map +1 -0
  35. package/dist/cloudflare/r2-errors.js +90 -0
  36. package/dist/cloudflare/r2-errors.js.map +1 -0
  37. package/dist/cloudflare/scheduled.d.ts +1 -1
  38. package/dist/cloudflare/scheduled.js +2 -2
  39. package/dist/cloudflare/scheduled.js.map +1 -1
  40. package/dist/cloudflare.d.ts +3 -3
  41. package/dist/cloudflare.js +3 -3
  42. package/dist/{core-ClSP5-V9.js → core-UUW2unJd.js} +106 -195
  43. package/dist/core-UUW2unJd.js.map +1 -0
  44. package/dist/core.d.ts +2 -2
  45. package/dist/core.js +2 -2
  46. package/dist/http.d.ts +2 -2
  47. package/dist/http.js +3 -3
  48. package/dist/http.js.map +1 -1
  49. package/dist/{index-Cchdg2aQ.d.ts → index-CYHXOH08.d.ts} +2 -2
  50. package/dist/{index-Cchdg2aQ.d.ts.map → index-CYHXOH08.d.ts.map} +1 -1
  51. package/dist/{index-DvJUcSW1.d.ts → index-DUFS0SJ_.d.ts} +41 -102
  52. package/dist/index-DUFS0SJ_.d.ts.map +1 -0
  53. package/dist/{outbox-repository-options-ICOF8g2h.js → outbox-repository-options-CgdqU20T.js} +2 -2
  54. package/dist/{outbox-repository-options-ICOF8g2h.js.map → outbox-repository-options-CgdqU20T.js.map} +1 -1
  55. package/dist/{outbox-repository-options-AkihEaik.d.ts → outbox-repository-options-DjBgFhMi.d.ts} +3 -3
  56. package/dist/{outbox-repository-options-AkihEaik.d.ts.map → outbox-repository-options-DjBgFhMi.d.ts.map} +1 -1
  57. package/dist/postgres.d.ts +3 -3
  58. package/dist/postgres.js +3 -3
  59. package/dist/posthog/metrics.d.ts +1 -1
  60. package/dist/posthog/server.d.ts +2 -2
  61. package/dist/posthog/server.js +1 -1
  62. package/dist/resend.d.ts +3 -3
  63. package/dist/resend.js +2 -2
  64. package/dist/sentry/client.d.ts +1 -1
  65. package/dist/sentry/client.d.ts.map +1 -1
  66. package/dist/sentry/client.js +10 -4
  67. package/dist/sentry/client.js.map +1 -1
  68. package/dist/sentry/server.d.ts +2 -2
  69. package/dist/sentry/server.js +5 -5
  70. package/dist/sentry/server.js.map +1 -1
  71. package/dist/stripe/payment-service.d.ts +52 -0
  72. package/dist/stripe/payment-service.d.ts.map +1 -0
  73. package/dist/stripe/payment-service.error.d.ts +13 -0
  74. package/dist/stripe/payment-service.error.d.ts.map +1 -0
  75. package/dist/stripe/payment-service.error.js +30 -0
  76. package/dist/stripe/payment-service.error.js.map +1 -0
  77. package/dist/stripe/payment-service.js +72 -0
  78. package/dist/stripe/payment-service.js.map +1 -0
  79. package/dist/stripe/payment-webhook.d.ts +18 -0
  80. package/dist/stripe/payment-webhook.d.ts.map +1 -0
  81. package/dist/stripe/payment-webhook.js +47 -0
  82. package/dist/stripe/payment-webhook.js.map +1 -0
  83. package/dist/tanstack.d.ts +1 -1
  84. package/dist/tanstack.js +4 -4
  85. package/dist/tanstack.js.map +1 -1
  86. package/dist/testing/outbox-repository.d.ts +2 -2
  87. package/dist/testing/payment-service.d.ts +10 -0
  88. package/dist/testing/payment-service.d.ts.map +1 -0
  89. package/dist/testing/payment-service.js +76 -0
  90. package/dist/testing/payment-service.js.map +1 -0
  91. package/dist/{webhook-verification-D6aGQfNi.js → webhook-verification-BBmjkHgI.js} +2 -2
  92. package/dist/{webhook-verification-D6aGQfNi.js.map → webhook-verification-BBmjkHgI.js.map} +1 -1
  93. package/dist/{webhook-verification-BcQQG-vY.d.ts → webhook-verification-BuxPzdr4.d.ts} +2 -2
  94. package/dist/{webhook-verification-BcQQG-vY.d.ts.map → webhook-verification-BuxPzdr4.d.ts.map} +1 -1
  95. package/package.json +13 -6
  96. package/src/application/outbox-relay.ts +3 -1
  97. package/src/core/console-log-sink.ts +65 -0
  98. package/src/core/index.ts +1 -4
  99. package/src/core/logger.ts +80 -281
  100. package/src/infrastructure/better-auth/apple-client-secret.ts +1 -1
  101. package/src/infrastructure/better-auth/rate-limit.ts +3 -1
  102. package/src/infrastructure/billing/client.ts +173 -0
  103. package/src/infrastructure/cloudflare/queue/queue-consumer.ts +8 -9
  104. package/src/infrastructure/cloudflare/r2-client.ts +162 -0
  105. package/src/infrastructure/cloudflare/r2-errors.ts +111 -0
  106. package/src/infrastructure/cloudflare/scheduled/scheduled-handler.ts +1 -1
  107. package/src/infrastructure/http/webhook-handler.ts +1 -1
  108. package/src/infrastructure/sentry/client.ts +6 -3
  109. package/src/infrastructure/sentry/server.ts +4 -4
  110. package/src/infrastructure/stripe/payment-service.error.ts +42 -0
  111. package/src/infrastructure/stripe/payment-service.ts +129 -0
  112. package/src/infrastructure/stripe/payment-webhook.ts +49 -0
  113. package/src/infrastructure/tanstack/resolve-failure.ts +3 -2
  114. package/src/infrastructure/testing/payment-service-contract.ts +91 -0
  115. package/dist/core-ClSP5-V9.js.map +0 -1
  116. package/dist/index-DvJUcSW1.d.ts.map +0 -1
@@ -0,0 +1,72 @@
1
+ import { PaymentServiceError } from "./payment-service.error.js";
2
+ import Stripe from "stripe";
3
+
4
+ //#region src/infrastructure/stripe/payment-service.ts
5
+ /**
6
+ * Ported from Typist's StripeClient request boundary; the native SDK now owns retries.
7
+ * Each request defaults to two SDK retries. Native request options can override retries and timeout.
8
+ */
9
+ var StripePaymentService = class {
10
+ stripe;
11
+ /** Inject a native SDK instance; its transport, credentials, and API version remain caller-owned. */
12
+ constructor(stripe) {
13
+ this.stripe = stripe;
14
+ }
15
+ /** Create a customer with a stable application key and preserve the native response. */
16
+ createCustomer(input, options) {
17
+ return this.request("customers.create", () => this.stripe.customers.create(input, {
18
+ maxNetworkRetries: 2,
19
+ ...options
20
+ }));
21
+ }
22
+ /** Force payment mode after caller parameters; return the native Checkout Session. */
23
+ createCheckout(input, options) {
24
+ return this.request("checkout.sessions.create", () => this.stripe.checkout.sessions.create({
25
+ ...input,
26
+ mode: "payment"
27
+ }, {
28
+ maxNetworkRetries: 2,
29
+ ...options
30
+ }));
31
+ }
32
+ /** Force setup mode after caller parameters; this operation does not charge the customer. */
33
+ setupPaymentMethod(input, options) {
34
+ return this.request("checkout.sessions.create", () => this.stripe.checkout.sessions.create({
35
+ ...input,
36
+ mode: "setup"
37
+ }, {
38
+ maxNetworkRetries: 2,
39
+ ...options
40
+ }));
41
+ }
42
+ /** Force confirmation and off-session use; preserve native card failures for application handling. */
43
+ chargeSavedMethod(input, options) {
44
+ return this.request("paymentIntents.create", () => this.stripe.paymentIntents.create({
45
+ ...input,
46
+ confirm: true,
47
+ off_session: true
48
+ }, {
49
+ maxNetworkRetries: 2,
50
+ ...options
51
+ }));
52
+ }
53
+ /** Preserve every native status and response field when reconciling an existing payment. */
54
+ getPayment(paymentId, params, options) {
55
+ return this.request("paymentIntents.retrieve", () => this.stripe.paymentIntents.retrieve(paymentId, params, {
56
+ maxNetworkRetries: 2,
57
+ ...options
58
+ }));
59
+ }
60
+ async request(operation, work) {
61
+ try {
62
+ return await work();
63
+ } catch (cause) {
64
+ if (!(cause instanceof Stripe.errors.StripeError) || cause instanceof Stripe.errors.StripeCardError) throw cause;
65
+ throw new PaymentServiceError(operation, cause);
66
+ }
67
+ }
68
+ };
69
+
70
+ //#endregion
71
+ export { StripePaymentService };
72
+ //# sourceMappingURL=payment-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment-service.js","names":[],"sources":["../../src/infrastructure/stripe/payment-service.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport { PaymentServiceError } from './payment-service.error.ts'\n\n/** Supply the same key and parameters when repeating one durable payment attempt. */\nexport type PaymentRequestOptions = Stripe.RequestOptions &\n Required<Pick<Stripe.RequestOptions, 'idempotencyKey'>>\n\n/** Native Checkout parameters; the service selects payment or setup mode. */\nexport type CheckoutInput = Omit<Stripe.Checkout.SessionCreateParams, 'mode'>\n\n/** A saved customer method; the service confirms the payment off-session. */\nexport type SavedMethodCharge = Omit<Stripe.PaymentIntentCreateParams, 'confirm' | 'off_session'> &\n Required<Pick<Stripe.PaymentIntentCreateParams, 'customer' | 'payment_method'>>\n\n/** Native customer response, including Stripe request metadata. */\nexport type CustomerResult = Awaited<ReturnType<Stripe['customers']['create']>>\n\n/** Native Checkout response. Its URL can be null; this does not confirm payment. */\nexport type CheckoutResult = Awaited<ReturnType<Stripe['checkout']['sessions']['create']>>\n\n/** Native PaymentIntent response. Applications decide what each status permits. */\nexport type PaymentResult = Awaited<ReturnType<Stripe['paymentIntents']['create']>>\n\n/**\n * Stripe payment operations, with native types and stable keys for mutations.\n * Rejects with PaymentServiceError or native StripeCardError; unexpected defects propagate.\n */\nexport interface IPaymentService {\n /** Create a customer; the application owns persistence and reuse of the customer link. */\n createCustomer(\n input: Stripe.CustomerCreateParams,\n options: PaymentRequestOptions,\n ): Promise<CustomerResult>\n /** Create one-time payment checkout; application fulfillment requires verified payment confirmation. */\n createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>\n /** Create checkout in setup mode. The application records consent and verifies the saved method's owner. */\n setupPaymentMethod(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>\n /** Confirm a saved method off-session. Native card errors can require customer authentication. */\n chargeSavedMethod(\n input: SavedMethodCharge,\n options: PaymentRequestOptions,\n ): Promise<PaymentResult>\n /** Retrieve an existing payment without starting another payment attempt. */\n getPayment(\n paymentId: string,\n params?: Stripe.PaymentIntentRetrieveParams,\n options?: Stripe.RequestOptions,\n ): Promise<PaymentResult>\n}\n\n/**\n * Ported from Typist's StripeClient request boundary; the native SDK now owns retries.\n * Each request defaults to two SDK retries. Native request options can override retries and timeout.\n */\nexport class StripePaymentService implements IPaymentService {\n /** Inject a native SDK instance; its transport, credentials, and API version remain caller-owned. */\n constructor(private readonly stripe: Stripe) {}\n\n /** Create a customer with a stable application key and preserve the native response. */\n createCustomer(\n input: Stripe.CustomerCreateParams,\n options: PaymentRequestOptions,\n ): Promise<CustomerResult> {\n return this.request('customers.create', () =>\n this.stripe.customers.create(input, { maxNetworkRetries: 2, ...options }),\n )\n }\n\n /** Force payment mode after caller parameters; return the native Checkout Session. */\n createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult> {\n return this.request('checkout.sessions.create', () =>\n this.stripe.checkout.sessions.create(\n { ...input, mode: 'payment' },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Force setup mode after caller parameters; this operation does not charge the customer. */\n setupPaymentMethod(\n input: CheckoutInput,\n options: PaymentRequestOptions,\n ): Promise<CheckoutResult> {\n return this.request('checkout.sessions.create', () =>\n this.stripe.checkout.sessions.create(\n { ...input, mode: 'setup' },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Force confirmation and off-session use; preserve native card failures for application handling. */\n chargeSavedMethod(\n input: SavedMethodCharge,\n options: PaymentRequestOptions,\n ): Promise<PaymentResult> {\n return this.request('paymentIntents.create', () =>\n this.stripe.paymentIntents.create(\n { ...input, confirm: true, off_session: true },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Preserve every native status and response field when reconciling an existing payment. */\n getPayment(\n paymentId: string,\n params?: Stripe.PaymentIntentRetrieveParams,\n options?: Stripe.RequestOptions,\n ): Promise<PaymentResult> {\n return this.request('paymentIntents.retrieve', () =>\n this.stripe.paymentIntents.retrieve(paymentId, params, { maxNetworkRetries: 2, ...options }),\n )\n }\n\n private async request<T>(operation: string, work: () => Promise<T>): Promise<T> {\n try {\n return await work()\n } catch (cause) {\n if (\n !(cause instanceof Stripe.errors.StripeError) ||\n cause instanceof Stripe.errors.StripeCardError\n )\n throw cause\n throw new PaymentServiceError(operation, cause)\n }\n }\n}\n"],"mappings":";;;;;;;;AAuDA,IAAa,uBAAb,MAA6D;CAE9B;;CAA7B,YAAY,AAAiB,QAAgB;EAAhB;CAAiB;;CAG9C,eACE,OACA,SACyB;EACzB,OAAO,KAAK,QAAQ,0BAClB,KAAK,OAAO,UAAU,OAAO,OAAO;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CAAC,CAC1E;CACF;;CAGA,eAAe,OAAsB,SAAyD;EAC5F,OAAO,KAAK,QAAQ,kCAClB,KAAK,OAAO,SAAS,SAAS,OAC5B;GAAE,GAAG;GAAO,MAAM;EAAU,GAC5B;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,mBACE,OACA,SACyB;EACzB,OAAO,KAAK,QAAQ,kCAClB,KAAK,OAAO,SAAS,SAAS,OAC5B;GAAE,GAAG;GAAO,MAAM;EAAQ,GAC1B;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,kBACE,OACA,SACwB;EACxB,OAAO,KAAK,QAAQ,+BAClB,KAAK,OAAO,eAAe,OACzB;GAAE,GAAG;GAAO,SAAS;GAAM,aAAa;EAAK,GAC7C;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,WACE,WACA,QACA,SACwB;EACxB,OAAO,KAAK,QAAQ,iCAClB,KAAK,OAAO,eAAe,SAAS,WAAW,QAAQ;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CAAC,CAC7F;CACF;CAEA,MAAc,QAAW,WAAmB,MAAoC;EAC9E,IAAI;GACF,OAAO,MAAM,KAAK;EACpB,SAAS,OAAO;GACd,IACE,EAAE,iBAAiB,OAAO,OAAO,gBACjC,iBAAiB,OAAO,OAAO,iBAE/B,MAAM;GACR,MAAM,IAAI,oBAAoB,WAAW,KAAK;EAChD;CACF;AACF"}
@@ -0,0 +1,18 @@
1
+ import { r as WebhookVerifier, t as WebhookVerification } from "../webhook-verification-BuxPzdr4.js";
2
+ import Stripe from "stripe";
3
+ //#region src/infrastructure/stripe/payment-webhook.d.ts
4
+ /**
5
+ * Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.
6
+ * Returns native events; application conversion owns event selection and payload validation.
7
+ */
8
+ export declare class StripeWebhookVerifier implements WebhookVerifier<Stripe.Event> {
9
+ private readonly stripe;
10
+ private readonly signingSecret;
11
+ private readonly tolerance?;
12
+ /** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */
13
+ constructor(stripe: Stripe, signingSecret: string, tolerance?: number | undefined);
14
+ /** Reject signature and JSON failures. Operational failures propagate without logging. */
15
+ verify(body: string, headers: Headers): Promise<WebhookVerification<Stripe.Event>>;
16
+ }
17
+ //#endregion
18
+ //# sourceMappingURL=payment-webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment-webhook.d.ts","names":[],"sources":["../../src/infrastructure/stripe/payment-webhook.ts"],"mappings":";;;;;;;qBAYa,iCAAiC,gBAAgB,OAAO;mBAGhD;mBACA;mBACA;;EAHnB,YACmB,QAAQ,QACR,uBACA;;EAIb,OAAO,cAAc,SAAS,UAAU,QAAQ,oBAAoB,OAAO"}
@@ -0,0 +1,47 @@
1
+ import { t as WebhookVerificationError } from "../webhook-verification-BBmjkHgI.js";
2
+ import Stripe from "stripe";
3
+
4
+ //#region src/infrastructure/stripe/payment-webhook.ts
5
+ /**
6
+ * Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.
7
+ * Returns native events; application conversion owns event selection and payload validation.
8
+ */
9
+ var StripeWebhookVerifier = class {
10
+ stripe;
11
+ signingSecret;
12
+ tolerance;
13
+ /** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */
14
+ constructor(stripe, signingSecret, tolerance) {
15
+ this.stripe = stripe;
16
+ this.signingSecret = signingSecret;
17
+ this.tolerance = tolerance;
18
+ }
19
+ /** Reject signature and JSON failures. Operational failures propagate without logging. */
20
+ async verify(body, headers) {
21
+ const signature = headers.get("stripe-signature");
22
+ if (!signature) return {
23
+ outcome: "rejected",
24
+ error: new WebhookVerificationError("missing_headers")
25
+ };
26
+ try {
27
+ return {
28
+ outcome: "event",
29
+ event: await this.stripe.webhooks.constructEventAsync(body, signature, this.signingSecret, this.tolerance, Stripe.createSubtleCryptoProvider())
30
+ };
31
+ } catch (cause) {
32
+ if (cause instanceof Stripe.errors.StripeSignatureVerificationError) return {
33
+ outcome: "rejected",
34
+ error: new WebhookVerificationError("invalid_signature", cause)
35
+ };
36
+ if (cause instanceof SyntaxError) return {
37
+ outcome: "rejected",
38
+ error: new WebhookVerificationError("invalid_payload", cause)
39
+ };
40
+ throw cause;
41
+ }
42
+ }
43
+ };
44
+
45
+ //#endregion
46
+ export { StripeWebhookVerifier };
47
+ //# sourceMappingURL=payment-webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment-webhook.js","names":[],"sources":["../../src/infrastructure/stripe/payment-webhook.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport {\n WebhookVerificationError,\n type WebhookVerification,\n type WebhookVerifier,\n} from '../http/webhook-verification.ts'\n\n/**\n * Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.\n * Returns native events; application conversion owns event selection and payload validation.\n */\nexport class StripeWebhookVerifier implements WebhookVerifier<Stripe.Event> {\n /** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */\n constructor(\n private readonly stripe: Stripe,\n private readonly signingSecret: string,\n private readonly tolerance?: number,\n ) {}\n\n /** Reject signature and JSON failures. Operational failures propagate without logging. */\n async verify(body: string, headers: Headers): Promise<WebhookVerification<Stripe.Event>> {\n const signature = headers.get('stripe-signature')\n if (!signature)\n return { outcome: 'rejected', error: new WebhookVerificationError('missing_headers') }\n try {\n const event = await this.stripe.webhooks.constructEventAsync(\n body,\n signature,\n this.signingSecret,\n this.tolerance,\n Stripe.createSubtleCryptoProvider(),\n )\n return { outcome: 'event', event }\n } catch (cause) {\n if (cause instanceof Stripe.errors.StripeSignatureVerificationError)\n return {\n outcome: 'rejected',\n error: new WebhookVerificationError('invalid_signature', cause),\n }\n if (cause instanceof SyntaxError)\n return {\n outcome: 'rejected',\n error: new WebhookVerificationError('invalid_payload', cause),\n }\n throw cause\n }\n }\n}\n"],"mappings":";;;;;;;;AAYA,IAAa,wBAAb,MAA4E;CAGvD;CACA;CACA;;CAHnB,YACE,AAAiB,QACjB,AAAiB,eACjB,AAAiB,WACjB;EAHiB;EACA;EACA;CAChB;;CAGH,MAAM,OAAO,MAAc,SAA8D;EACvF,MAAM,YAAY,QAAQ,IAAI,kBAAkB;EAChD,IAAI,CAAC,WACH,OAAO;GAAE,SAAS;GAAY,OAAO,IAAI,yBAAyB,iBAAiB;EAAE;EACvF,IAAI;GAQF,OAAO;IAAE,SAAS;IAAS,aAPP,KAAK,OAAO,SAAS,oBACvC,MACA,WACA,KAAK,eACL,KAAK,WACL,OAAO,2BAA2B,CACpC;GACiC;EACnC,SAAS,OAAO;GACd,IAAI,iBAAiB,OAAO,OAAO,kCACjC,OAAO;IACL,SAAS;IACT,OAAO,IAAI,yBAAyB,qBAAqB,KAAK;GAChE;GACF,IAAI,iBAAiB,aACnB,OAAO;IACL,SAAS;IACT,OAAO,IAAI,yBAAyB,mBAAmB,KAAK;GAC9D;GACF,MAAM;EACR;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { lt as ErrorTable } from "./index-DvJUcSW1.js";
1
+ import { ot as ErrorTable } from "./index-DUFS0SJ_.js";
2
2
  import { Register } from "@tanstack/react-start";
3
3
  import { BetterAuthCookies } from "better-auth";
4
4
  //#region src/infrastructure/tanstack/request-context.d.ts
package/dist/tanstack.js CHANGED
@@ -1,4 +1,4 @@
1
- import { G as AuthenticationError, U as StaleSessionError, a as createLogger, rt as AppError, z as ValidationError } from "./core-ClSP5-V9.js";
1
+ import { H as StaleSessionError, R as ValidationError, W as AuthenticationError, nt as AppError, r as createLogger } from "./core-UUW2unJd.js";
2
2
  import { z } from "zod";
3
3
  import { getReasonPhrase } from "http-status-codes";
4
4
  import { isNotFound, isRedirect, redirect } from "@tanstack/react-router";
@@ -71,16 +71,16 @@ const logger = createLogger("error-boundary");
71
71
  function resolveFailure(table, cause) {
72
72
  const resolved = table.resolve(cause);
73
73
  if (resolved !== null) {
74
- logger.warn("handled_error", { details: {
74
+ logger.warn("handled_error", {
75
75
  tag: resolved.payload._tag,
76
76
  status: resolved.status
77
- } });
77
+ });
78
78
  return resolved;
79
79
  }
80
80
  const classification = cause instanceof AppError ? cause.classification : "unknown";
81
81
  logger.error("unexpected_error", {
82
82
  error: cause,
83
- details: { classification }
83
+ classification
84
84
  });
85
85
  return table.fallback(cause);
86
86
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack.js","names":["logger"],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/resolve-failure.ts","../src/infrastructure/tanstack/http-error-response.ts","../src/infrastructure/tanstack/session-cookies.ts","../src/infrastructure/tanstack/to-error-payload.ts","../src/infrastructure/tanstack/error.middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport type { RequestContext } from './request-context.ts'\n\nconst logger = createLogger('auth-middleware')\n\n/** The fields middleware reads; generic callers retain every additional session and user field. */\nexport type AuthSession = {\n readonly user: { readonly id: string }\n readonly session: { readonly id: string }\n}\n\n/** Authenticated context retains the application's complete user and session types. */\nexport type RequiredAuthContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n}\n\n/** Optional authentication supplies both fields together or neither field. */\nexport type AuthContext<Session extends AuthSession> =\n | RequiredAuthContext<Session>\n | {\n readonly user: undefined\n readonly session: undefined\n }\n\n/** Select the current request's Better Auth instance from TanStack's registered context. */\nexport type AuthMiddlewareOptions<Session extends AuthSession> = {\n readonly getAuth: (context: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\n}\n\n/**\n * Preserve Porte's function and request middleware contracts with application-owned services.\n * Optional lookup failures log once and continue as guests. Required lookup failures propagate.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n const extractAuth = createMiddleware({ type: 'function' }).server<AuthContext<Session>>(\n async ({ next, context }) => {\n let resolved: Session | null\n try {\n const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\n } catch (error) {\n logger.error('get_session_failed', { error })\n resolved = null\n }\n if (resolved === null)\n return next<AuthContext<Session>>({ context: { user: undefined, session: undefined } })\n return next<AuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n\n async function resolveRequiredSession(\n context: RequestContext,\n headers: Headers,\n ): Promise<Session> {\n const resolved = await options.getAuth(context).api.getSession({ headers })\n if (resolved === null) {\n if (getSessionCookie(headers)) throw new StaleSessionError()\n throw new AuthenticationError()\n }\n return resolved\n }\n\n const requireAuth = createMiddleware({ type: 'function' }).server(async ({ next, context }) => {\n const resolved = await resolveRequiredSession(context, await requestHeaders())\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n })\n const requireAuthRequest = createMiddleware({ type: 'request' }).server(\n async ({ request, next, context }) => {\n const resolved = await resolveRequiredSession(context, request.headers)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { AppError, createLogger, type ErrorTable, type ResolvedError } from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\n\n/**\n * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.\n */\nexport function resolveFailure<Entries>(\n table: ErrorTable<Entries>,\n cause: unknown,\n): ResolvedError<ErrorPayloadOf<ErrorTable<Entries>>> {\n const resolved = table.resolve(cause)\n if (resolved !== null) {\n logger.warn('handled_error', {\n details: { tag: resolved.payload._tag, status: resolved.status },\n })\n return resolved\n }\n const classification = cause instanceof AppError ? cause.classification : 'unknown'\n logger.error('unexpected_error', { error: cause, details: { classification } })\n return table.fallback(cause)\n}\n","import { getReasonPhrase } from 'http-status-codes'\nimport { z } from 'zod'\n\nimport type { ErrorTable, ProblemDetails } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// A known delay becomes the header; a null delay sends no header.\nconst RetryAfterSchema = z.object({ retryAfter: z.number() })\n\n/**\n * Build the API route converter for one error table.\n * The body is RFC 9457 problem details; public fields become extension members.\n */\nexport function createHttpErrorResponseConverter<Entries>(table: ErrorTable<Entries>) {\n return function toHttpErrorResponse(cause: unknown): Response {\n const { status, payload } = resolveFailure(table, cause)\n const { _tag, message, ...fields } = payload\n const body: ProblemDetails = {\n type: 'about:blank',\n title: getReasonPhrase(status),\n detail: message,\n ...fields,\n }\n const headers = new Headers({ 'Content-Type': 'application/problem+json' })\n const retry = RetryAfterSchema.safeParse(payload)\n if (retry.success) headers.set('Retry-After', String(retry.data.retryAfter))\n return Response.json(body, { status, headers })\n }\n}\n","import type { deleteCookie } from '@tanstack/react-start/server'\nimport type { BetterAuthCookies } from 'better-auth'\nimport { parseCookies } from 'better-auth/cookies'\n\ntype AuthCookie = BetterAuthCookies['sessionToken']\ntype DeleteCookieOptions = NonNullable<Parameters<typeof deleteCookie>[1]>\n\n/**\n * Delete the session, session cache, account cache, and remember-me cookies of one instance.\n * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.\n */\nexport async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.getRequestHeaders().get('cookie') ?? '').keys()]\n const definitions = [\n cookies.sessionToken,\n cookies.sessionData,\n cookies.accountData,\n cookies.dontRememberToken,\n ]\n for (const cookie of definitions) {\n // Better Auth names a chunk `${name}.${index}`, so a missed chunk would resurrect the value.\n const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`))\n for (const name of new Set([cookie.name, ...chunks]))\n server.deleteCookie(name, deletionOf(cookie.attributes))\n }\n}\n\nfunction deletionOf(attributes: AuthCookie['attributes']): DeleteCookieOptions {\n // Better Auth sets `/` and the secure flag at runtime; the types leave both optional.\n const options: DeleteCookieOptions = {\n path: attributes.path ?? '/',\n secure: attributes.secure ?? false,\n }\n if (attributes.domain !== undefined) options.domain = attributes.domain\n return options\n}\n","import { z } from 'zod'\n\nimport { ValidationError, type ErrorPayloadOf, type ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// TanStack serializes a validator's issues into `Error.message` as JSON.\nconst SerializedIssuesSchema = z\n .array(z.object({ message: z.string(), path: z.array(z.union([z.string(), z.number()])) }))\n .min(1)\n\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (!(cause instanceof Error)) return null\n let message: unknown\n try {\n message = JSON.parse(cause.message)\n } catch {\n return null\n }\n const parsed = SerializedIssuesSchema.safeParse(message)\n return parsed.success ? ValidationError.fromIssues(parsed.data) : null\n}\n\n/**\n * Build the server-function converter for one error table.\n * The result is a plain object, because only own data survives serialization.\n */\nexport function createErrorPayloadConverter<Entries>(table: ErrorTable<Entries>) {\n return function toErrorPayload(cause: unknown): ErrorPayloadOf<ErrorTable<Entries>> {\n return resolveFailure(table, reconstructValidationError(cause) ?? cause).payload\n }\n}\n","import { isNotFound, isRedirect, redirect } from '@tanstack/react-router'\nimport { createMiddleware } from '@tanstack/react-start'\nimport type { BetterAuthCookies } from 'better-auth'\n\nimport { StaleSessionError, type ErrorTable } from '@/core'\n\nimport { createHttpErrorResponseConverter } from './http-error-response.ts'\nimport type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\n\n/** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */\nexport type AuthCookieSource = {\n readonly $context: Promise<{ readonly authCookies: BetterAuthCookies }>\n}\n\n/** The application's error table, its stale-session redirect, and its Better Auth instance. */\nexport type ErrorMiddlewareOptions<Entries> = {\n readonly errors: ErrorTable<Entries>\n /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\n /** Select the request's Better Auth instance; its cookie definitions say what to clear. */\n readonly getAuth: (context: RequestContext) => AuthCookieSource\n}\n\n/**\n * Build both transport boundaries from one error table.\n * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.\n */\nexport function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>) {\n const toErrorPayload = createErrorPayloadConverter(options.errors)\n const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors)\n\n async function clearSession(context: RequestContext): Promise<void> {\n const { authCookies } = await options.getAuth(context).$context\n await clearStaleSessionCookies(authCookies)\n }\n\n async function handleFunctionError(cause: unknown, context: RequestContext): Promise<never> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) {\n await clearSession(context)\n // oxlint-disable-next-line typescript/only-throw-error -- Router redirects by throwing this.\n throw redirect({ href: options.signIn })\n }\n // oxlint-disable-next-line typescript/only-throw-error -- The client rejects with this and reads its tag.\n throw toErrorPayload(cause)\n }\n\n // A route answers 401 instead of a redirect because fetch would follow it into the HTML shell.\n async function handleRouteError(cause: unknown, context: RequestContext): Promise<Response> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) await clearSession(context)\n return toHttpErrorResponse(cause)\n }\n\n const functionErrorMiddleware = createMiddleware({ type: 'function' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleFunctionError(cause, context)\n }\n },\n )\n\n const routeErrorMiddleware = createMiddleware({ type: 'request' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleRouteError(cause, context)\n }\n },\n )\n\n return { functionErrorMiddleware, routeErrorMiddleware, toErrorPayload, toHttpErrorResponse }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM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F,MAAM,iBAAiB,4BAA4B,QAAQ,MAAM;CACjE,MAAM,sBAAsB,iCAAiC,QAAQ,MAAM;CAE3E,eAAe,aAAa,SAAwC;EAClE,MAAM,EAAE,gBAAgB,MAAM,QAAQ,QAAQ,OAAO,CAAC,CAAC;EACvD,MAAM,yBAAyB,WAAW;CAC5C;CAEA,eAAe,oBAAoB,OAAgB,SAAyC;EAE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB;GACtC,MAAM,aAAa,OAAO;GAE1B,MAAM,SAAS,EAAE,MAAM,QAAQ,OAAO,CAAC;EACzC;EAEA,MAAM,eAAe,KAAK;CAC5B;CAGA,eAAe,iBAAiB,OAAgB,SAA4C;EAE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB,MAAM,aAAa,OAAO;EAClE,OAAO,oBAAoB,KAAK;CAClC;CAsBA,OAAO;EAAE,yBApBuB,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACrE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,oBAAoB,OAAO,OAAO;GAC3C;EACF,CAa6B;EAAG,sBAVL,iBAAiB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OACjE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,iBAAiB,OAAO,OAAO;GACxC;EACF,CAGmD;EAAG;EAAgB;CAAoB;AAC9F"}
1
+ {"version":3,"file":"tanstack.js","names":["logger"],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/resolve-failure.ts","../src/infrastructure/tanstack/http-error-response.ts","../src/infrastructure/tanstack/session-cookies.ts","../src/infrastructure/tanstack/to-error-payload.ts","../src/infrastructure/tanstack/error.middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport type { RequestContext } from './request-context.ts'\n\nconst logger = createLogger('auth-middleware')\n\n/** The fields middleware reads; generic callers retain every additional session and user field. */\nexport type AuthSession = {\n readonly user: { readonly id: string }\n readonly session: { readonly id: string }\n}\n\n/** Authenticated context retains the application's complete user and session types. */\nexport type RequiredAuthContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n}\n\n/** Optional authentication supplies both fields together or neither field. */\nexport type AuthContext<Session extends AuthSession> =\n | RequiredAuthContext<Session>\n | {\n readonly user: undefined\n readonly session: undefined\n }\n\n/** Select the current request's Better Auth instance from TanStack's registered context. */\nexport type AuthMiddlewareOptions<Session extends AuthSession> = {\n readonly getAuth: (context: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\n}\n\n/**\n * Preserve Porte's function and request middleware contracts with application-owned services.\n * Optional lookup failures log once and continue as guests. Required lookup failures propagate.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n const extractAuth = createMiddleware({ type: 'function' }).server<AuthContext<Session>>(\n async ({ next, context }) => {\n let resolved: Session | null\n try {\n const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\n } catch (error) {\n logger.error('get_session_failed', { error })\n resolved = null\n }\n if (resolved === null)\n return next<AuthContext<Session>>({ context: { user: undefined, session: undefined } })\n return next<AuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n\n async function resolveRequiredSession(\n context: RequestContext,\n headers: Headers,\n ): Promise<Session> {\n const resolved = await options.getAuth(context).api.getSession({ headers })\n if (resolved === null) {\n if (getSessionCookie(headers)) throw new StaleSessionError()\n throw new AuthenticationError()\n }\n return resolved\n }\n\n const requireAuth = createMiddleware({ type: 'function' }).server(async ({ next, context }) => {\n const resolved = await resolveRequiredSession(context, await requestHeaders())\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n })\n const requireAuthRequest = createMiddleware({ type: 'request' }).server(\n async ({ request, next, context }) => {\n const resolved = await resolveRequiredSession(context, request.headers)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { AppError, createLogger, type ErrorTable, type ResolvedError } from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\n\n/**\n * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.\n */\nexport function resolveFailure<Entries>(\n table: ErrorTable<Entries>,\n cause: unknown,\n): ResolvedError<ErrorPayloadOf<ErrorTable<Entries>>> {\n const resolved = table.resolve(cause)\n if (resolved !== null) {\n logger.warn('handled_error', {\n tag: resolved.payload._tag,\n status: resolved.status,\n })\n return resolved\n }\n const classification = cause instanceof AppError ? cause.classification : 'unknown'\n logger.error('unexpected_error', { error: cause, classification })\n return table.fallback(cause)\n}\n","import { getReasonPhrase } from 'http-status-codes'\nimport { z } from 'zod'\n\nimport type { ErrorTable, ProblemDetails } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// A known delay becomes the header; a null delay sends no header.\nconst RetryAfterSchema = z.object({ retryAfter: z.number() })\n\n/**\n * Build the API route converter for one error table.\n * The body is RFC 9457 problem details; public fields become extension members.\n */\nexport function createHttpErrorResponseConverter<Entries>(table: ErrorTable<Entries>) {\n return function toHttpErrorResponse(cause: unknown): Response {\n const { status, payload } = resolveFailure(table, cause)\n const { _tag, message, ...fields } = payload\n const body: ProblemDetails = {\n type: 'about:blank',\n title: getReasonPhrase(status),\n detail: message,\n ...fields,\n }\n const headers = new Headers({ 'Content-Type': 'application/problem+json' })\n const retry = RetryAfterSchema.safeParse(payload)\n if (retry.success) headers.set('Retry-After', String(retry.data.retryAfter))\n return Response.json(body, { status, headers })\n }\n}\n","import type { deleteCookie } from '@tanstack/react-start/server'\nimport type { BetterAuthCookies } from 'better-auth'\nimport { parseCookies } from 'better-auth/cookies'\n\ntype AuthCookie = BetterAuthCookies['sessionToken']\ntype DeleteCookieOptions = NonNullable<Parameters<typeof deleteCookie>[1]>\n\n/**\n * Delete the session, session cache, account cache, and remember-me cookies of one instance.\n * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.\n */\nexport async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.getRequestHeaders().get('cookie') ?? '').keys()]\n const definitions = [\n cookies.sessionToken,\n cookies.sessionData,\n cookies.accountData,\n cookies.dontRememberToken,\n ]\n for (const cookie of definitions) {\n // Better Auth names a chunk `${name}.${index}`, so a missed chunk would resurrect the value.\n const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`))\n for (const name of new Set([cookie.name, ...chunks]))\n server.deleteCookie(name, deletionOf(cookie.attributes))\n }\n}\n\nfunction deletionOf(attributes: AuthCookie['attributes']): DeleteCookieOptions {\n // Better Auth sets `/` and the secure flag at runtime; the types leave both optional.\n const options: DeleteCookieOptions = {\n path: attributes.path ?? '/',\n secure: attributes.secure ?? false,\n }\n if (attributes.domain !== undefined) options.domain = attributes.domain\n return options\n}\n","import { z } from 'zod'\n\nimport { ValidationError, type ErrorPayloadOf, type ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// TanStack serializes a validator's issues into `Error.message` as JSON.\nconst SerializedIssuesSchema = z\n .array(z.object({ message: z.string(), path: z.array(z.union([z.string(), z.number()])) }))\n .min(1)\n\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (!(cause instanceof Error)) return null\n let message: unknown\n try {\n message = JSON.parse(cause.message)\n } catch {\n return null\n }\n const parsed = SerializedIssuesSchema.safeParse(message)\n return parsed.success ? ValidationError.fromIssues(parsed.data) : null\n}\n\n/**\n * Build the server-function converter for one error table.\n * The result is a plain object, because only own data survives serialization.\n */\nexport function createErrorPayloadConverter<Entries>(table: ErrorTable<Entries>) {\n return function toErrorPayload(cause: unknown): ErrorPayloadOf<ErrorTable<Entries>> {\n return resolveFailure(table, reconstructValidationError(cause) ?? cause).payload\n }\n}\n","import { isNotFound, isRedirect, redirect } from '@tanstack/react-router'\nimport { createMiddleware } from '@tanstack/react-start'\nimport type { BetterAuthCookies } from 'better-auth'\n\nimport { StaleSessionError, type ErrorTable } from '@/core'\n\nimport { createHttpErrorResponseConverter } from './http-error-response.ts'\nimport type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\n\n/** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */\nexport type AuthCookieSource = {\n readonly $context: Promise<{ readonly authCookies: BetterAuthCookies }>\n}\n\n/** The application's error table, its stale-session redirect, and its Better Auth instance. */\nexport type ErrorMiddlewareOptions<Entries> = {\n readonly errors: ErrorTable<Entries>\n /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\n /** Select the request's Better Auth instance; its cookie definitions say what to clear. */\n readonly getAuth: (context: RequestContext) => AuthCookieSource\n}\n\n/**\n * Build both transport boundaries from one error table.\n * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.\n */\nexport function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>) {\n const toErrorPayload = createErrorPayloadConverter(options.errors)\n const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors)\n\n async function clearSession(context: RequestContext): Promise<void> {\n const { authCookies } = await options.getAuth(context).$context\n await clearStaleSessionCookies(authCookies)\n }\n\n async function handleFunctionError(cause: unknown, context: RequestContext): Promise<never> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) {\n await clearSession(context)\n // oxlint-disable-next-line typescript/only-throw-error -- Router redirects by throwing this.\n throw redirect({ href: options.signIn })\n }\n // oxlint-disable-next-line typescript/only-throw-error -- The client rejects with this and reads its tag.\n throw toErrorPayload(cause)\n }\n\n // A route answers 401 instead of a redirect because fetch would follow it into the HTML shell.\n async function handleRouteError(cause: unknown, context: RequestContext): Promise<Response> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) await clearSession(context)\n return toHttpErrorResponse(cause)\n }\n\n const functionErrorMiddleware = createMiddleware({ type: 'function' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleFunctionError(cause, context)\n }\n },\n )\n\n const routeErrorMiddleware = createMiddleware({ type: 'request' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleRouteError(cause, context)\n }\n },\n )\n\n return { functionErrorMiddleware, routeErrorMiddleware, toErrorPayload, toHttpErrorResponse }\n}\n"],"mappings":";;;;;;;;AAOA,MAAMA,WAAS,aAAa,iBAAiB;AAgC7C,MAAM,iBAAiB,YAAY;CACjC,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,kBAAkB;AAC3B;;;;;AAMA,SAAgB,qBACd,SACA;CACA,MAAM,cAAc,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACzD,OAAO,EAAE,MAAM,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,MAAM,UAAU,MAAM,eAAe;GACrC,WAAW,MAAM,QAAQ,QAAQ,OAAO,CAAC,CA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M,QAAQ,OAAO,CAAC;EACzC;EAEA,MAAM,eAAe,KAAK;CAC5B;CAGA,eAAe,iBAAiB,OAAgB,SAA4C;EAE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB,MAAM,aAAa,OAAO;EAClE,OAAO,oBAAoB,KAAK;CAClC;CAsBA,OAAO;EAAE,yBApBuB,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACrE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,oBAAoB,OAAO,OAAO;GAC3C;EACF,CAa6B;EAAG,sBAVL,iBAAiB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OACjE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,iBAAiB,OAAO,OAAO;GACxC;EACF,CAGmD;EAAG;EAAgB;CAAoB;AAC9F"}
@@ -1,5 +1,5 @@
1
- import { q as DomainEvent } from "../index-DvJUcSW1.js";
2
- import { A as IOutboxRepository } from "../index-Cchdg2aQ.js";
1
+ import { W as DomainEvent } from "../index-DUFS0SJ_.js";
2
+ import { A as IOutboxRepository } from "../index-CYHXOH08.js";
3
3
  //#region src/infrastructure/testing/outbox-repository-contract.d.ts
4
4
  /** Stored fields observed by the adapter contract, independent of a database library. */
5
5
  export type OutboxContractRow = {
@@ -0,0 +1,10 @@
1
+ import { IPaymentService } from "../stripe/payment-service.js";
2
+ import Stripe from "stripe";
3
+ //#region src/infrastructure/testing/payment-service-contract.d.ts
4
+ /**
5
+ * Test a Stripe payment adapter through native fetch injection without live payments.
6
+ * Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.
7
+ */
8
+ export declare function paymentServiceContract(test: (name: string, run: () => Promise<void>) => void, create: (stripe: Stripe) => IPaymentService): void;
9
+ //#endregion
10
+ //# sourceMappingURL=payment-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment-service.d.ts","names":[],"sources":["../../src/infrastructure/testing/payment-service-contract.ts"],"mappings":";;;;;;;wBAUgB,uBACd,OAAO,cAAc,WAAW,wBAChC,SAAS,QAAQ,WAAW"}
@@ -0,0 +1,76 @@
1
+ import Stripe from "stripe";
2
+ import { deepStrictEqual, equal, rejects } from "node:assert/strict";
3
+
4
+ //#region src/infrastructure/testing/payment-service-contract.ts
5
+ /**
6
+ * Test a Stripe payment adapter through native fetch injection without live payments.
7
+ * Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.
8
+ */
9
+ function paymentServiceContract(test, create) {
10
+ test("payment checkout selects payment mode and retains the supplied key", async () => {
11
+ const fixture = paymentFixture(create);
12
+ await fixture.service.createCheckout({ customer: "cus_contract" }, { idempotencyKey: "checkout:contract" });
13
+ equal(fixture.requests[0]?.body.get("mode"), "payment");
14
+ equal(fixture.requests[0]?.headers.get("idempotency-key"), "checkout:contract");
15
+ });
16
+ test("payment method setup selects setup mode", async () => {
17
+ const fixture = paymentFixture(create);
18
+ await fixture.service.setupPaymentMethod({ customer: "cus_contract" }, { idempotencyKey: "setup:contract" });
19
+ equal(fixture.requests[0]?.body.get("mode"), "setup");
20
+ });
21
+ test("saved method payments confirm off-session", async () => {
22
+ const fixture = paymentFixture(create);
23
+ await fixture.service.chargeSavedMethod({
24
+ amount: 1e3,
25
+ currency: "usd",
26
+ customer: "cus_contract",
27
+ payment_method: "pm_contract"
28
+ }, { idempotencyKey: "charge:contract" });
29
+ equal(fixture.requests[0]?.body.get("confirm"), "true");
30
+ equal(fixture.requests[0]?.body.get("off_session"), "true");
31
+ });
32
+ test("payment reads preserve native statuses and response fields", async () => {
33
+ const payment = await paymentFixture(create).service.getPayment("pi_contract");
34
+ deepStrictEqual({
35
+ id: payment.id,
36
+ status: payment.status
37
+ }, {
38
+ id: "pi_contract",
39
+ status: "requires_capture"
40
+ });
41
+ });
42
+ test("card failures retain the native error contract", async () => {
43
+ const fixture = paymentFixture(create, Response.json({ error: {
44
+ type: "card_error",
45
+ code: "authentication_required",
46
+ message: "Authentication required"
47
+ } }, { status: 402 }));
48
+ await rejects(fixture.service.chargeSavedMethod({
49
+ amount: 1e3,
50
+ currency: "usd",
51
+ customer: "cus_contract",
52
+ payment_method: "pm_contract"
53
+ }, { idempotencyKey: "charge:contract" }), Stripe.errors.StripeCardError);
54
+ });
55
+ }
56
+ function paymentFixture(create, response = Response.json({
57
+ id: "pi_contract",
58
+ status: "requires_capture"
59
+ })) {
60
+ const requests = [];
61
+ return {
62
+ service: create(new Stripe("sk_test_contract", { httpClient: Stripe.createFetchHttpClient(async (input, init) => {
63
+ const request = new Request(input, init);
64
+ requests.push({
65
+ headers: request.headers,
66
+ body: new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer()))
67
+ });
68
+ return response.clone();
69
+ }) })),
70
+ requests
71
+ };
72
+ }
73
+
74
+ //#endregion
75
+ export { paymentServiceContract };
76
+ //# sourceMappingURL=payment-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment-service.js","names":[],"sources":["../../src/infrastructure/testing/payment-service-contract.ts"],"sourcesContent":["import { deepStrictEqual, equal, rejects } from 'node:assert/strict'\n\nimport Stripe from 'stripe'\n\nimport type { IPaymentService } from '../stripe/payment-service.ts'\n\n/**\n * Test a Stripe payment adapter through native fetch injection without live payments.\n * Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.\n */\nexport function paymentServiceContract(\n test: (name: string, run: () => Promise<void>) => void,\n create: (stripe: Stripe) => IPaymentService,\n): void {\n test('payment checkout selects payment mode and retains the supplied key', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.createCheckout(\n { customer: 'cus_contract' },\n { idempotencyKey: 'checkout:contract' },\n )\n equal(fixture.requests[0]?.body.get('mode'), 'payment')\n equal(fixture.requests[0]?.headers.get('idempotency-key'), 'checkout:contract')\n })\n\n test('payment method setup selects setup mode', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.setupPaymentMethod(\n { customer: 'cus_contract' },\n { idempotencyKey: 'setup:contract' },\n )\n equal(fixture.requests[0]?.body.get('mode'), 'setup')\n })\n\n test('saved method payments confirm off-session', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.chargeSavedMethod(\n { amount: 1000, currency: 'usd', customer: 'cus_contract', payment_method: 'pm_contract' },\n { idempotencyKey: 'charge:contract' },\n )\n equal(fixture.requests[0]?.body.get('confirm'), 'true')\n equal(fixture.requests[0]?.body.get('off_session'), 'true')\n })\n\n test('payment reads preserve native statuses and response fields', async () => {\n const fixture = paymentFixture(create)\n const payment = await fixture.service.getPayment('pi_contract')\n deepStrictEqual(\n { id: payment.id, status: payment.status },\n { id: 'pi_contract', status: 'requires_capture' },\n )\n })\n\n test('card failures retain the native error contract', async () => {\n const response = Response.json(\n {\n error: {\n type: 'card_error',\n code: 'authentication_required',\n message: 'Authentication required',\n },\n },\n { status: 402 },\n )\n const fixture = paymentFixture(create, response)\n await rejects(\n fixture.service.chargeSavedMethod(\n { amount: 1000, currency: 'usd', customer: 'cus_contract', payment_method: 'pm_contract' },\n { idempotencyKey: 'charge:contract' },\n ),\n Stripe.errors.StripeCardError,\n )\n })\n}\n\nfunction paymentFixture(\n create: (stripe: Stripe) => IPaymentService,\n response = Response.json({ id: 'pi_contract', status: 'requires_capture' }),\n) {\n const requests: { headers: Headers; body: URLSearchParams }[] = []\n const stripe = new Stripe('sk_test_contract', {\n httpClient: Stripe.createFetchHttpClient(async (input, init) => {\n const request = new Request(input, init)\n requests.push({\n headers: request.headers,\n body: new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer())),\n })\n return response.clone()\n }),\n })\n return { service: create(stripe), requests }\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,uBACd,MACA,QACM;CACN,KAAK,sEAAsE,YAAY;EACrF,MAAM,UAAU,eAAe,MAAM;EACrC,MAAM,QAAQ,QAAQ,eACpB,EAAE,UAAU,eAAe,GAC3B,E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ACA,OAAO,OAAO,eAChB;CACF,CAAC;AACH;AAEA,SAAS,eACP,QACA,WAAW,SAAS,KAAK;CAAE,IAAI;CAAe,QAAQ;AAAmB,CAAC,GAC1E;CACA,MAAM,WAA0D,CAAC;CAWjE,OAAO;EAAE,SAAS,OAAO,IAVN,OAAO,oBAAoB,EAC5C,YAAY,OAAO,sBAAsB,OAAO,OAAO,SAAS;GAC9D,MAAM,UAAU,IAAI,QAAQ,OAAO,IAAI;GACvC,SAAS,KAAK;IACZ,SAAS,QAAQ;IACjB,MAAM,IAAI,gBAAgB,IAAI,YAAY,CAAC,CAAC,OAAO,MAAM,QAAQ,YAAY,CAAC,CAAC;GACjF,CAAC;GACD,OAAO,SAAS,MAAM;EACxB,CAAC,EACH,CAC8B,CAAC;EAAG;CAAS;AAC7C"}
@@ -1,4 +1,4 @@
1
- import { rt as AppError } from "./core-ClSP5-V9.js";
1
+ import { nt as AppError } from "./core-UUW2unJd.js";
2
2
 
3
3
  //#region src/infrastructure/http/webhook-verification.ts
4
4
  /** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */
@@ -15,4 +15,4 @@ var WebhookVerificationError = class extends AppError {
15
15
 
16
16
  //#endregion
17
17
  export { WebhookVerificationError as t };
18
- //# sourceMappingURL=webhook-verification-D6aGQfNi.js.map
18
+ //# sourceMappingURL=webhook-verification-BBmjkHgI.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-verification-D6aGQfNi.js","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"sourcesContent":["import { AppError } from '@/core'\n\n/** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */\nexport class WebhookVerificationError extends AppError {\n readonly _tag = 'WebhookVerificationError'\n readonly classification = 'terminal'\n\n /** Keep secrets and payload details out of the public message. */\n constructor(\n readonly reason: 'missing_headers' | 'invalid_signature' | 'invalid_payload',\n cause?: unknown,\n ) {\n super(`Webhook rejected: ${reason}`, { cause })\n }\n}\n\n/** A verified event, an ignored event, or an invalid request. */\nexport type WebhookVerification<Event> =\n | { readonly outcome: 'event'; readonly event: Event }\n | { readonly outcome: 'ignored'; readonly type: string }\n | { readonly outcome: 'rejected'; readonly error: WebhookVerificationError }\n\n/** The provider owns signature verification, timestamp tolerance, and payload parsing. */\nexport interface WebhookVerifier<Event> {\n /** Verify the exact body before parsing it. Return invalid requests; throw operational failures. */\n verify(body: string, headers: Headers): Promise<WebhookVerification<Event>>\n}\n"],"mappings":";;;;AAGA,IAAa,2BAAb,cAA8C,SAAS;CAM1C;CALX,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YACE,AAAS,QACT,OACA;EACA,MAAM,qBAAqB,UAAU,EAAE,MAAM,CAAC;EAHrC;CAIX;AACF"}
1
+ {"version":3,"file":"webhook-verification-BBmjkHgI.js","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"sourcesContent":["import { AppError } from '@/core'\n\n/** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */\nexport class WebhookVerificationError extends AppError {\n readonly _tag = 'WebhookVerificationError'\n readonly classification = 'terminal'\n\n /** Keep secrets and payload details out of the public message. */\n constructor(\n readonly reason: 'missing_headers' | 'invalid_signature' | 'invalid_payload',\n cause?: unknown,\n ) {\n super(`Webhook rejected: ${reason}`, { cause })\n }\n}\n\n/** A verified event, an ignored event, or an invalid request. */\nexport type WebhookVerification<Event> =\n | { readonly outcome: 'event'; readonly event: Event }\n | { readonly outcome: 'ignored'; readonly type: string }\n | { readonly outcome: 'rejected'; readonly error: WebhookVerificationError }\n\n/** The provider owns signature verification, timestamp tolerance, and payload parsing. */\nexport interface WebhookVerifier<Event> {\n /** Verify the exact body before parsing it. Return invalid requests; throw operational failures. */\n verify(body: string, headers: Headers): Promise<WebhookVerification<Event>>\n}\n"],"mappings":";;;;AAGA,IAAa,2BAAb,cAA8C,SAAS;CAM1C;CALX,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YACE,AAAS,QACT,OACA;EACA,MAAM,qBAAqB,UAAU,EAAE,MAAM,CAAC;EAHrC;CAIX;AACF"}
@@ -1,4 +1,4 @@
1
- import { $t as AppError } from "./index-DvJUcSW1.js";
1
+ import { Xt as AppError } from "./index-DUFS0SJ_.js";
2
2
  //#region src/infrastructure/http/webhook-verification.d.ts
3
3
  /** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */
4
4
  declare class WebhookVerificationError extends AppError {
@@ -26,4 +26,4 @@ interface WebhookVerifier<Event> {
26
26
  }
27
27
  //#endregion
28
28
  export { WebhookVerificationError as n, WebhookVerifier as r, WebhookVerification as t };
29
- //# sourceMappingURL=webhook-verification-BcQQG-vY.d.ts.map
29
+ //# sourceMappingURL=webhook-verification-BuxPzdr4.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-verification-BcQQG-vY.d.ts","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"mappings":";;;cAGa,iCAAiC;WAMjC;WALF;WACA;;EAGT,YACW,qEACT;;;KAOQ,oBAAoB;WACjB;WAA2B,OAAO;;WAClC;WAA6B;;WAC7B;WAA8B,OAAO;;;UAGnC,gBAAgB;;EAE/B,OAAO,cAAc,SAAS,UAAU,QAAQ,oBAAoB"}
1
+ {"version":3,"file":"webhook-verification-BuxPzdr4.d.ts","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"mappings":";;;cAGa,iCAAiC;WAMjC;WALF;WACA;;EAGT,YACW,qEACT;;;KAOQ,oBAAoB;WACjB;WAA2B,OAAO;;WAClC;WAA6B;;WAC7B;WAA8B,OAAO;;;UAGnC,gBAAgB;;EAE/B,OAAO,cAAc,SAAS,UAAU,QAAQ,oBAAoB"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://www.schemastore.org/package.json",
3
3
  "name": "better-ship",
4
- "version": "0.17.0",
4
+ "version": "0.18.0",
5
5
  "description": "Foundation for applications on Cloudflare Workers: logger, errors, message bus, infrastructure adapters, and UI primitives",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -22,6 +22,7 @@
22
22
  "./better-auth/rate-limit": "./dist/better-auth/rate-limit.js",
23
23
  "./better-auth/secondary-storage": "./dist/better-auth/secondary-storage.js",
24
24
  "./better-auth/stripe": "./dist/better-auth/stripe.js",
25
+ "./billing/client": "./dist/billing/client.js",
25
26
  "./cloudflare": "./dist/cloudflare.js",
26
27
  "./cloudflare/auth-secondary-storage": "./dist/cloudflare/auth-secondary-storage.js",
27
28
  "./cloudflare/durable-object-client": "./dist/cloudflare/durable-object-client.js",
@@ -29,6 +30,8 @@
29
30
  "./cloudflare/kv-client": "./dist/cloudflare/kv-client.js",
30
31
  "./cloudflare/kv-errors": "./dist/cloudflare/kv-errors.js",
31
32
  "./cloudflare/queue": "./dist/cloudflare/queue.js",
33
+ "./cloudflare/r2-client": "./dist/cloudflare/r2-client.js",
34
+ "./cloudflare/r2-errors": "./dist/cloudflare/r2-errors.js",
32
35
  "./cloudflare/scheduled": "./dist/cloudflare/scheduled.js",
33
36
  "./core": "./dist/core.js",
34
37
  "./http": "./dist/http.js",
@@ -41,9 +44,13 @@
41
44
  "./sentry/client": "./dist/sentry/client.js",
42
45
  "./sentry/server": "./dist/sentry/server.js",
43
46
  "./sentry/vite": "./dist/sentry/vite.js",
47
+ "./stripe/payment-service": "./dist/stripe/payment-service.js",
48
+ "./stripe/payment-service.error": "./dist/stripe/payment-service.error.js",
49
+ "./stripe/payment-webhook": "./dist/stripe/payment-webhook.js",
44
50
  "./tanstack": "./dist/tanstack.js",
45
51
  "./tanstack/server": "./dist/tanstack/server.js",
46
52
  "./testing/outbox-repository": "./dist/testing/outbox-repository.js",
53
+ "./testing/payment-service": "./dist/testing/payment-service.js",
47
54
  "./ui": "./dist/ui.js",
48
55
  "./package.json": "./package.json"
49
56
  },
@@ -54,11 +61,11 @@
54
61
  "better-result": "^3.0.1",
55
62
  "http-status-codes": "^2.3.0",
56
63
  "uuid": "^14.0.2",
57
- "zod": "^4.6.2"
64
+ "zod": "^4.6.4"
58
65
  },
59
66
  "devDependencies": {
60
67
  "@better-auth/stripe": "^1.7.4",
61
- "@cloudflare/vitest-plugin": "^1.1.7",
68
+ "@cloudflare/vitest-plugin": "^1.1.8",
62
69
  "@cloudflare/workers-types": "5.20260911.1",
63
70
  "@posthog/react": "^1.10.6",
64
71
  "@sentry/cloudflare": "^10.74.0",
@@ -76,7 +83,7 @@
76
83
  "drizzle-orm": "^0.45.2",
77
84
  "playwright": "^1.63.0",
78
85
  "postgres": "^3.4.9",
79
- "posthog-js": "^1.430.2",
86
+ "posthog-js": "^1.430.3",
80
87
  "posthog-node": "^5.52.1",
81
88
  "react": "^19.3.0",
82
89
  "resend": "^6.28.0",
@@ -85,7 +92,7 @@
85
92
  "tsdown": "^0.23.0",
86
93
  "typescript": "^7.0.2",
87
94
  "vitest": "^4.1.11",
88
- "wrangler": "^4.131.0"
95
+ "wrangler": "^4.131.1"
89
96
  },
90
97
  "peerDependencies": {
91
98
  "@better-auth/stripe": "^1.7.4",
@@ -96,7 +103,7 @@
96
103
  "@tanstack/react-start": "^1.168.52",
97
104
  "better-auth": "^1.7.4",
98
105
  "drizzle-orm": "^0.45.2",
99
- "posthog-js": "^1.430.2",
106
+ "posthog-js": "^1.430.3",
100
107
  "posthog-node": "^5.52.1",
101
108
  "react": "^19.3.0",
102
109
  "resend": "^6.28.0",
@@ -119,7 +119,9 @@ export class OutboxRelay {
119
119
  await this.repository.deadLetter(claim, messages, reason, errorMessage)
120
120
  logger.error('outbox_messages_dead_lettered', {
121
121
  error: cause,
122
- details: { claimToken: claim.token, count: messages.length, reason },
122
+ claimToken: claim.token,
123
+ count: messages.length,
124
+ reason,
123
125
  })
124
126
  }
125
127
  }
@@ -0,0 +1,65 @@
1
+ import type { LogEntry, LogFields, LogFormat, LogLevel, LogSink } from './logger.ts'
2
+
3
+ const METHOD = {
4
+ DEBUG: 'debug',
5
+ INFO: 'info',
6
+ WARN: 'warn',
7
+ ERROR: 'error',
8
+ } as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>
9
+
10
+ const ESC = String.fromCharCode(27)
11
+ const RESET = `${ESC}[0m`
12
+ const LEVEL_COLOR = {
13
+ DEBUG: `${ESC}[2;36m`,
14
+ INFO: `${ESC}[34m`,
15
+ WARN: `${ESC}[33m`,
16
+ ERROR: `${ESC}[1;31m`,
17
+ } satisfies Record<LogLevel, string>
18
+
19
+ let format: LogFormat = 'json'
20
+
21
+ export function setConsoleLogFormat(value: LogFormat): void {
22
+ format = value
23
+ }
24
+
25
+ function contextOf(entry: LogEntry): LogFields | undefined {
26
+ const context = { ...entry.attributes }
27
+ if (entry.userId !== undefined) context.userId = entry.userId
28
+ return Object.keys(context).length === 0 ? undefined : context
29
+ }
30
+
31
+ function jsonEntry(entry: LogEntry): LogEntry {
32
+ if (!(entry.error instanceof Error)) return entry
33
+ const error = { name: entry.error.name, message: entry.error.message, stack: entry.error.stack }
34
+ return { ...entry, error }
35
+ }
36
+
37
+ /** Write one structured record or one readable development entry to `console`. */
38
+ export const consoleSink: LogSink = (entry) => {
39
+ const write = console[METHOD[entry.level]]
40
+ if (format === 'json') {
41
+ write(jsonEntry(entry))
42
+ return
43
+ }
44
+
45
+ const context = contextOf(entry)
46
+ const values = context === undefined ? [] : [context]
47
+ const errors = entry.error === undefined ? [] : [entry.error]
48
+ if (format === 'pretty-browser') {
49
+ write(
50
+ `%c${entry.timestamp}%c [${entry.level}] %c[${entry.module}]%c ${entry.event}`,
51
+ 'color: #737373',
52
+ '',
53
+ 'color: #2563eb',
54
+ '',
55
+ ...values,
56
+ ...errors,
57
+ )
58
+ return
59
+ }
60
+ write(
61
+ `${ESC}[90m${entry.timestamp}${RESET} ${LEVEL_COLOR[entry.level]}[${entry.level}]${RESET} ${ESC}[34m[${entry.module}]${RESET} ${entry.event}`,
62
+ ...values,
63
+ ...errors,
64
+ )
65
+ }
package/src/core/index.ts CHANGED
@@ -104,20 +104,17 @@ export {
104
104
  configureLogger,
105
105
  consoleSink,
106
106
  createLogger,
107
- Logger,
108
107
  LogLevel,
109
108
  setLoggerErrorHook,
110
109
  setLogSink,
111
110
  type ErrorCaptureEntry,
112
- type ErrorLogContext,
113
111
  type LogEntry,
114
112
  type LogFields,
115
113
  type LogFormat,
116
- type LoggerConfig,
114
+ type Logger,
117
115
  type LoggerErrorHook,
118
116
  type LoggerSettings,
119
117
  type LogSink,
120
118
  type LogThreshold,
121
119
  type LogValue,
122
- type SerializedError,
123
120
  } from './logger.ts'