better-ship 0.32.0 → 0.34.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.
@@ -1,21 +1,3 @@
1
- //#region src/infrastructure/cloudflare/tracing.ts
2
- /** Add attributes to the active span. That span is the invocation root unless `withSpan` encloses the call. */
3
- function annotateSpan(tracing, attributes) {
4
- tracing.getActiveSpan()?.setAttributes(attributes);
5
- }
6
- /**
7
- * Run `operation` in a child span.
8
- * Use it when one invocation runs several units of work, such as each message in a queue batch.
9
- * This helper does not record an exception. A failure reaches Issues as the uncaught error or `logger.error`.
10
- * An expected throw, such as a duplicate message, is not an exception record.
11
- */
12
- function withSpan(tracing, name, attributes, operation) {
13
- return tracing.enterSpan(name, (span) => {
14
- span.setAttributes(attributes);
15
- return operation();
16
- });
17
- }
1
+ import { n as withSpan, t as annotateSpan } from "../tracing-C_7B_odV.js";
18
2
 
19
- //#endregion
20
- export { annotateSpan, withSpan };
21
- //# sourceMappingURL=tracing.js.map
3
+ export { annotateSpan, withSpan };
@@ -11,6 +11,27 @@ export type SentryClientOptions = Sentry.BrowserOptions & {
11
11
  export declare function createSentryClientOptions(options: SentryClientOptions): Sentry.BrowserOptions;
12
12
  /** Forward logged browser errors once, excluding TanStack navigation control flow. */
13
13
  export declare function createSentryLoggerErrorHook(): LoggerErrorHook;
14
+ /** The error value as Sentry's React handler receives it. */
15
+ type ReactRootError = Parameters<ReturnType<typeof Sentry.reactErrorHandler>>[0];
16
+ /** The details React passes to a root error option; React may omit the component stack. */
17
+ export type ReactRootErrorInfo = {
18
+ readonly componentStack?: string | undefined;
19
+ };
20
+ /** A `hydrateRoot` error option in React's own shape. */
21
+ type ReactRootErrorHandler = (error: ReactRootError, errorInfo: ReactRootErrorInfo) => void;
22
+ /** The `hydrateRoot` error options; each one replaces React's console default. */
23
+ export type SentryReactRootOptions = {
24
+ readonly onCaughtError: ReactRootErrorHandler;
25
+ readonly onUncaughtError: ReactRootErrorHandler;
26
+ readonly onRecoverableError: ReactRootErrorHandler;
27
+ };
28
+ /**
29
+ * Report React errors to Sentry from `hydrateRoot`, as Sentry's React 19 setup does.
30
+ * Covers errors that a boundary catches, errors that no boundary catches, and hydration
31
+ * errors that React recovers from. TanStack redirects and not-found control flow are not
32
+ * reported. Each error still goes to the console, as with React's defaults.
33
+ */
34
+ export declare function createSentryReactRootOptions(): SentryReactRootOptions;
14
35
  /** Initialize once in the browser entrypoint before hydration; server imports have no side effects. */
15
36
  export declare function initializeSentry(options: SentryClientOptions): ReturnType<typeof Sentry.init>;
16
37
  /** Attach tracing once after creating the browser router, as Porte does in getRouter. */
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/infrastructure/sentry/client.ts"],"mappings":";;;;YAMY,sBAAsB,OAAO;WAC9B;WACA;WACA;;;wBAIK,0BAA0B,SAAS,sBAAsB,OAAO;;wBAWhE,+BAA+B;;wBAY/B,iBAAiB,SAAS,sBAAsB,kBAAkB,OAAO;;wBAOzE,uBACd,QAAQ,kBAAkB,OAAO;;qBAOtB,sBAAsB,OAAO"}
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/infrastructure/sentry/client.ts"],"mappings":";;;;YAMY,sBAAsB,OAAO;WAC9B;WACA;WACA;;;wBAIK,0BAA0B,SAAS,sBAAsB,OAAO;;wBAWhE,+BAA+B;;KAY1C,iBAAiB,WAAW,kBAAkB,OAAO;;YAG9C;WAAgC;;;KAGvC,yBAAyB,OAAO,gBAAgB,WAAW;;YAGpD;WACD,eAAe;WACf,iBAAiB;WACjB,oBAAoB;;;;;;;;wBASf,gCAAgC;;wBAoBhC,iBAAiB,SAAS,sBAAsB,kBAAkB,OAAO;;wBAOzE,uBACd,QAAQ,kBAAkB,OAAO;;qBAOtB,sBAAsB,OAAO"}
@@ -24,6 +24,28 @@ function createSentryLoggerErrorHook() {
24
24
  Sentry.captureException(error, { extra: attributes });
25
25
  };
26
26
  }
27
+ /**
28
+ * Report React errors to Sentry from `hydrateRoot`, as Sentry's React 19 setup does.
29
+ * Covers errors that a boundary catches, errors that no boundary catches, and hydration
30
+ * errors that React recovers from. TanStack redirects and not-found control flow are not
31
+ * reported. Each error still goes to the console, as with React's defaults.
32
+ */
33
+ function createSentryReactRootOptions() {
34
+ const handler = Sentry.reactErrorHandler((error, errorInfo) => {
35
+ console.error(error, errorInfo.componentStack);
36
+ });
37
+ const report = (error, { componentStack }) => {
38
+ handler(error, { componentStack: componentStack ?? null });
39
+ };
40
+ return {
41
+ onCaughtError: (error, errorInfo) => {
42
+ if (isNotFound(error) || isRedirect(error)) return;
43
+ report(error, errorInfo);
44
+ },
45
+ onUncaughtError: report,
46
+ onRecoverableError: report
47
+ };
48
+ }
27
49
  /** Initialize once in the browser entrypoint before hydration; server imports have no side effects. */
28
50
  function initializeSentry(options) {
29
51
  const client = Sentry.init(createSentryClientOptions(options));
@@ -39,5 +61,5 @@ function instrumentSentryRouter(router) {
39
61
  const ErrorBoundary = Sentry.ErrorBoundary;
40
62
 
41
63
  //#endregion
42
- export { ErrorBoundary, Sentry, createSentryClientOptions, createSentryLoggerErrorHook, initializeSentry, instrumentSentryRouter };
64
+ export { ErrorBoundary, Sentry, createSentryClientOptions, createSentryLoggerErrorHook, createSentryReactRootOptions, initializeSentry, instrumentSentryRouter };
43
65
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../src/infrastructure/sentry/client.ts"],"sourcesContent":["import * as Sentry from '@sentry/tanstackstart-react'\nimport { isNotFound, isRedirect } from '@tanstack/react-router'\n\nimport { setLoggerErrorHook, type LoggerErrorHook } from '@/core'\n\n/** Application settings use Sentry's names; enablement and environment belong to the application. */\nexport type SentryClientOptions = Sentry.BrowserOptions & {\n readonly dsn: string\n readonly environment: string\n readonly enabled: boolean\n}\n\n/** Filter known DOM errors and use SDK collection defaults; application options take precedence. */\nexport function createSentryClientOptions(options: SentryClientOptions): Sentry.BrowserOptions {\n return {\n ignoreErrors: [\n /^NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node\\.$/,\n /^NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node\\.$/,\n ],\n ...options,\n }\n}\n\n/** Forward logged browser errors once, excluding TanStack navigation control flow. */\nexport function createSentryLoggerErrorHook(): LoggerErrorHook {\n return ({ error, userId, attributes }) => {\n if (isNotFound(error) || isRedirect(error)) return\n if (userId !== undefined) {\n Sentry.captureException(error, { extra: attributes, user: { id: userId } })\n return\n }\n Sentry.captureException(error, { extra: attributes })\n }\n}\n\n/** Initialize once in the browser entrypoint before hydration; server imports have no side effects. */\nexport function initializeSentry(options: SentryClientOptions): ReturnType<typeof Sentry.init> {\n const client = Sentry.init(createSentryClientOptions(options))\n setLoggerErrorHook(createSentryLoggerErrorHook())\n return client\n}\n\n/** Attach tracing once after creating the browser router, as Porte does in getRouter. */\nexport function instrumentSentryRouter(\n router: Parameters<typeof Sentry.tanstackRouterBrowserTracingIntegration>[0],\n): void {\n if (router.isServer) return\n Sentry.addIntegration(Sentry.tanstackRouterBrowserTracingIntegration(router))\n}\n\n/** The SDK error boundary; the application supplies its fallback component. */\nexport const ErrorBoundary: typeof Sentry.ErrorBoundary = Sentry.ErrorBoundary\n\nexport { Sentry }\n"],"mappings":";;;;;;AAaA,SAAgB,0BAA0B,SAAqD;CAC7F,OAAO;EACL,cAAc,CACZ,oHACA,iJACF;EACA,GAAG;CACL;AACF;;AAGA,SAAgB,8BAA+C;CAC7D,QAAQ,EAAE,OAAO,QAAQ,iBAAiB;EACxC,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG;EAC5C,IAAI,WAAW,QAAW;GACxB,OAAO,iBAAiB,OAAO;IAAE,OAAO;IAAY,MAAM,EAAE,IAAI,OAAO;GAAE,CAAC;GAC1E;EACF;EACA,OAAO,iBAAiB,OAAO,EAAE,OAAO,WAAW,CAAC;CACtD;AACF;;AAGA,SAAgB,iBAAiB,SAA8D;CAC7F,MAAM,SAAS,OAAO,KAAK,0BAA0B,OAAO,CAAC;CAC7D,mBAAmB,4BAA4B,CAAC;CAChD,OAAO;AACT;;AAGA,SAAgB,uBACd,QACM;CACN,IAAI,OAAO,UAAU;CACrB,OAAO,eAAe,OAAO,wCAAwC,MAAM,CAAC;AAC9E;;AAGA,MAAa,gBAA6C,OAAO"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/infrastructure/sentry/client.ts"],"sourcesContent":["import * as Sentry from '@sentry/tanstackstart-react'\nimport { isNotFound, isRedirect } from '@tanstack/react-router'\n\nimport { setLoggerErrorHook, type LoggerErrorHook } from '@/core'\n\n/** Application settings use Sentry's names; enablement and environment belong to the application. */\nexport type SentryClientOptions = Sentry.BrowserOptions & {\n readonly dsn: string\n readonly environment: string\n readonly enabled: boolean\n}\n\n/** Filter known DOM errors and use SDK collection defaults; application options take precedence. */\nexport function createSentryClientOptions(options: SentryClientOptions): Sentry.BrowserOptions {\n return {\n ignoreErrors: [\n /^NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node\\.$/,\n /^NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node\\.$/,\n ],\n ...options,\n }\n}\n\n/** Forward logged browser errors once, excluding TanStack navigation control flow. */\nexport function createSentryLoggerErrorHook(): LoggerErrorHook {\n return ({ error, userId, attributes }) => {\n if (isNotFound(error) || isRedirect(error)) return\n if (userId !== undefined) {\n Sentry.captureException(error, { extra: attributes, user: { id: userId } })\n return\n }\n Sentry.captureException(error, { extra: attributes })\n }\n}\n\n/** The error value as Sentry's React handler receives it. */\ntype ReactRootError = Parameters<ReturnType<typeof Sentry.reactErrorHandler>>[0]\n\n/** The details React passes to a root error option; React may omit the component stack. */\nexport type ReactRootErrorInfo = { readonly componentStack?: string | undefined }\n\n/** A `hydrateRoot` error option in React's own shape. */\ntype ReactRootErrorHandler = (error: ReactRootError, errorInfo: ReactRootErrorInfo) => void\n\n/** The `hydrateRoot` error options; each one replaces React's console default. */\nexport type SentryReactRootOptions = {\n readonly onCaughtError: ReactRootErrorHandler\n readonly onUncaughtError: ReactRootErrorHandler\n readonly onRecoverableError: ReactRootErrorHandler\n}\n\n/**\n * Report React errors to Sentry from `hydrateRoot`, as Sentry's React 19 setup does.\n * Covers errors that a boundary catches, errors that no boundary catches, and hydration\n * errors that React recovers from. TanStack redirects and not-found control flow are not\n * reported. Each error still goes to the console, as with React's defaults.\n */\nexport function createSentryReactRootOptions(): SentryReactRootOptions {\n const handler = Sentry.reactErrorHandler((error, errorInfo) => {\n console.error(error, errorInfo.componentStack)\n })\n // Sentry's handler takes `null` for a missing component stack.\n const report: ReactRootErrorHandler = (error, { componentStack }) => {\n handler(error, { componentStack: componentStack ?? null })\n }\n return {\n // TanStack Router renders not-found through a React error boundary, so each 404 arrives here.\n onCaughtError: (error, errorInfo) => {\n if (isNotFound(error) || isRedirect(error)) return\n report(error, errorInfo)\n },\n onUncaughtError: report,\n onRecoverableError: report,\n }\n}\n\n/** Initialize once in the browser entrypoint before hydration; server imports have no side effects. */\nexport function initializeSentry(options: SentryClientOptions): ReturnType<typeof Sentry.init> {\n const client = Sentry.init(createSentryClientOptions(options))\n setLoggerErrorHook(createSentryLoggerErrorHook())\n return client\n}\n\n/** Attach tracing once after creating the browser router, as Porte does in getRouter. */\nexport function instrumentSentryRouter(\n router: Parameters<typeof Sentry.tanstackRouterBrowserTracingIntegration>[0],\n): void {\n if (router.isServer) return\n Sentry.addIntegration(Sentry.tanstackRouterBrowserTracingIntegration(router))\n}\n\n/** The SDK error boundary; the application supplies its fallback component. */\nexport const ErrorBoundary: typeof Sentry.ErrorBoundary = Sentry.ErrorBoundary\n\nexport { Sentry }\n"],"mappings":";;;;;;AAaA,SAAgB,0BAA0B,SAAqD;CAC7F,OAAO;EACL,cAAc,CACZ,oHACA,iJACF;EACA,GAAG;CACL;AACF;;AAGA,SAAgB,8BAA+C;CAC7D,QAAQ,EAAE,OAAO,QAAQ,iBAAiB;EACxC,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG;EAC5C,IAAI,WAAW,QAAW;GACxB,OAAO,iBAAiB,OAAO;IAAE,OAAO;IAAY,MAAM,EAAE,IAAI,OAAO;GAAE,CAAC;GAC1E;EACF;EACA,OAAO,iBAAiB,OAAO,EAAE,OAAO,WAAW,CAAC;CACtD;AACF;;;;;;;AAwBA,SAAgB,+BAAuD;CACrE,MAAM,UAAU,OAAO,mBAAmB,OAAO,cAAc;EAC7D,QAAQ,MAAM,OAAO,UAAU,cAAc;CAC/C,CAAC;CAED,MAAM,UAAiC,OAAO,EAAE,qBAAqB;EACnE,QAAQ,OAAO,EAAE,gBAAgB,kBAAkB,KAAK,CAAC;CAC3D;CACA,OAAO;EAEL,gBAAgB,OAAO,cAAc;GACnC,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG;GAC5C,OAAO,OAAO,SAAS;EACzB;EACA,iBAAiB;EACjB,oBAAoB;CACtB;AACF;;AAGA,SAAgB,iBAAiB,SAA8D;CAC7F,MAAM,SAAS,OAAO,KAAK,0BAA0B,OAAO,CAAC;CAC7D,mBAAmB,4BAA4B,CAAC;CAChD,OAAO;AACT;;AAGA,SAAgB,uBACd,QACM;CACN,IAAI,OAAO,UAAU;CACrB,OAAO,eAAe,OAAO,wCAAwC,MAAM,CAAC;AAC9E;;AAGA,MAAa,gBAA6C,OAAO"}
@@ -97,5 +97,13 @@ export declare function createErrorMiddleware<Entries>(options: ErrorMiddlewareO
97
97
  toHttpErrorResponse: (cause: unknown) => Response;
98
98
  };
99
99
  //#endregion
100
+ //#region src/infrastructure/tanstack/function-tracing.middleware.d.ts
101
+ /**
102
+ * Run one server function call in a child span named for that function.
103
+ * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.
104
+ * A handler rejection is not a span exception, and this middleware does not log.
105
+ */
106
+ export declare function createFunctionTracingMiddleware(getTracing: (context: RequestContext) => Tracing): import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, undefined, undefined, undefined, undefined>;
107
+ //#endregion
100
108
  export type { AuthContext, AuthCookieSource, AuthMiddlewareOptions, AuthSession, AuthenticatedContext, ErrorMiddlewareOptions, RequiredAuthContext };
101
109
  //# sourceMappingURL=tanstack.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack.d.ts","names":[],"sources":["../src/infrastructure/tanstack/request-context.ts","../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/error.middleware.ts"],"mappings":";;;;;;;;;;KAQY,iBAAiB;EAAmB;IAAU,sBAAsB;;IAC5E;;;;KCCQ;WACD;aAAiB;;WACjB;aAAoB;;;;KAInB,oBAAoB,gBAAgB;WACrC,MAAM;WACN,SAAS;;;KAIR,YAAY,gBAAgB,eACpC,oBAAoB;WAET;WACA;;;KAIH,qBAAqB,gBAAgB;WACtC,MAAM;WACN,SAAS;WACT,gBAAgB;;;KAIf,sBAAsB,gBAAgB;WACvC,UAAU,SAAS;aACjB;eACE,aAAa;QAAW,SAAS;YAAc,QAAQ;;;;WAI3D,mBAAmB,SAAS,qBAAqB;;;;;;;wBAc5C,qBAAqB,gBAAgB,aACnD,SAAS,sBAAsB;;;;;;;;KC/CrB;WACD,UAAU;aAAmB,aAAa;;;;KAIzC,uBAAuB;WACxB,QAAQ,WAAW;;WAEnB;;WAEA,UAAU,SAAS,mBAAmB;;;;;;wBAOjC,sBAAsB,SAAS,SAAS,uBAAuB"}
1
+ {"version":3,"file":"tanstack.d.ts","names":[],"sources":["../src/infrastructure/tanstack/request-context.ts","../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/function-tracing.middleware.ts"],"mappings":";;;;;;;;;;KAQY,iBAAiB;EAAmB;IAAU,sBAAsB;;IAC5E;;;;KCCQ;WACD;aAAiB;;WACjB;aAAoB;;;;KAInB,oBAAoB,gBAAgB;WACrC,MAAM;WACN,SAAS;;;KAIR,YAAY,gBAAgB,eACpC,oBAAoB;WAET;WACA;;;KAIH,qBAAqB,gBAAgB;WACtC,MAAM;WACN,SAAS;WACT,gBAAgB;;;KAIf,sBAAsB,gBAAgB;WACvC,UAAU,SAAS;aACjB;eACE,aAAa;QAAW,SAAS;YAAc,QAAQ;;;;WAI3D,mBAAmB,SAAS,qBAAqB;;;;;;;wBAc5C,qBAAqB,gBAAgB,aACnD,SAAS,sBAAsB;;;;;;;;KC/CrB;WACD,UAAU;aAAmB,aAAa;;;;KAIzC,uBAAuB;WACxB,QAAQ,WAAW;;WAEnB;;WAEA,UAAU,SAAS,mBAAmB;;;;;;wBAOjC,sBAAsB,SAAS,SAAS,uBAAuB;;;;;;;;;;;;;;;;;;;;;wBCnB/D,gCAAgC,aAAa,SAAS,mBAAmB,0CAAO"}
package/dist/tanstack.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { H as StaleSessionError, R as ValidationError, W as AuthenticationError, nt as AppError, r as createLogger } from "./core-BiN6S_cm.js";
2
+ import { n as withSpan } from "./tracing-C_7B_odV.js";
2
3
  import { z } from "zod";
3
4
  import { getReasonPhrase } from "http-status-codes";
4
5
  import { isNotFound, isRedirect, redirect } from "@tanstack/react-router";
@@ -229,5 +230,19 @@ function createErrorMiddleware(options) {
229
230
  }
230
231
 
231
232
  //#endregion
232
- export { createAuthMiddleware, createErrorMiddleware };
233
+ //#region src/infrastructure/tanstack/function-tracing.middleware.ts
234
+ /**
235
+ * Run one server function call in a child span named for that function.
236
+ * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.
237
+ * A handler rejection is not a span exception, and this middleware does not log.
238
+ */
239
+ function createFunctionTracingMiddleware(getTracing) {
240
+ return createMiddleware({ type: "function" }).server(({ context, serverFnMeta, next }) => withSpan(getTracing(context), `server_fn ${serverFnMeta.name}`, {
241
+ "code.function.name": serverFnMeta.name,
242
+ "code.file.path": serverFnMeta.filename
243
+ }, () => next()));
244
+ }
245
+
246
+ //#endregion
247
+ export { createAuthMiddleware, createErrorMiddleware, createFunctionTracingMiddleware };
233
248
  //# sourceMappingURL=tanstack.js.map
@@ -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/** A resolved session and the request context that produced it. */\nexport type AuthenticatedContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n readonly requestContext: RequestContext\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 /** Runs after a session resolves and before the handler. A guest or a failed lookup does not call it. */\n readonly onAuthenticated?: (context: AuthenticatedContext<Session>) => void\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 * `onAuthenticated` runs after a session resolves and before the rest of the chain.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n function notifyAuthenticated(requestContext: RequestContext, resolved: Session): void {\n options.onAuthenticated?.({\n user: resolved.user,\n session: resolved.session,\n requestContext,\n })\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 notifyAuthenticated(context, resolved)\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 notifyAuthenticated(context, resolved)\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 notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { z } from 'zod'\n\nimport {\n AppError,\n ValidationError,\n createLogger,\n type ErrorTable,\n type ResolvedError,\n} from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\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\n// A live ZodError keeps `.issues`. TanStack leaves only JSON in `Error.message`.\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (cause instanceof z.ZodError) return ValidationError.fromZod(cause)\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 * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * A thrown ZodError, or issues serialized into an error message, becomes a ValidationError first.\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 failure = reconstructValidationError(cause) ?? cause\n const resolved = table.resolve(failure)\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 = failure instanceof AppError ? failure.classification : 'unknown'\n logger.error('unexpected_error', { error: failure, classification })\n return table.fallback(failure)\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 type { ErrorPayloadOf, ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\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, 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;AAyC7C,MAAM,iBAAiB,YAAY;CACjC,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,kBAAkB;AAC3B;;;;;;AAOA,SAAgB,qBACd,SACA;CACA,SAAS,oBAAoB,gBAAgC,UAAyB;EACpF,QAAQ,kBAAkB;GACxB,MAAM,SAAS;GACf,SAAS,SAAS;GAClB;EACF,CAAC;CACH;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,CAAC,IAAI,WAAW,EAAE,QAAQ,CAAC;EACtE,SAAS,OAAO;GACd,SAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC;GAC5C,WAAW;EACb;EACA,IAAI,aAAa,MACf,OAAO,KAA2B,EAAE,SAAS;GAAE,MAAM;GAAW,SAAS;EAAU,EAAE,CAAC;EACxF,oBAAoB,SAAS,QAAQ;EACrC,OAAO,KAA2B,EAChC,SAAS;GAAE,MAAM,SAAS;GAAM,SAAS,SAAS;EAAQ,EAC5D,CAAC;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AClD,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","../src/infrastructure/tanstack/function-tracing.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/** A resolved session and the request context that produced it. */\nexport type AuthenticatedContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n readonly requestContext: RequestContext\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 /** Runs after a session resolves and before the handler. A guest or a failed lookup does not call it. */\n readonly onAuthenticated?: (context: AuthenticatedContext<Session>) => void\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 * `onAuthenticated` runs after a session resolves and before the rest of the chain.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n function notifyAuthenticated(requestContext: RequestContext, resolved: Session): void {\n options.onAuthenticated?.({\n user: resolved.user,\n session: resolved.session,\n requestContext,\n })\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 notifyAuthenticated(context, resolved)\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 notifyAuthenticated(context, resolved)\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 notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { z } from 'zod'\n\nimport {\n AppError,\n ValidationError,\n createLogger,\n type ErrorTable,\n type ResolvedError,\n} from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\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\n// A live ZodError keeps `.issues`. TanStack leaves only JSON in `Error.message`.\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (cause instanceof z.ZodError) return ValidationError.fromZod(cause)\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 * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * A thrown ZodError, or issues serialized into an error message, becomes a ValidationError first.\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 failure = reconstructValidationError(cause) ?? cause\n const resolved = table.resolve(failure)\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 = failure instanceof AppError ? failure.classification : 'unknown'\n logger.error('unexpected_error', { error: failure, classification })\n return table.fallback(failure)\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 type { ErrorPayloadOf, ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\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, 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","import { createMiddleware } from '@tanstack/react-start'\n\nimport { withSpan } from '../cloudflare/tracing.ts'\nimport type { RequestContext } from './request-context.ts'\n\n/**\n * Run one server function call in a child span named for that function.\n * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.\n * A handler rejection is not a span exception, and this middleware does not log.\n */\nexport function createFunctionTracingMiddleware(getTracing: (context: RequestContext) => Tracing) {\n return createMiddleware({ type: 'function' }).server(({ context, serverFnMeta, next }) =>\n withSpan(\n getTracing(context),\n `server_fn ${serverFnMeta.name}`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,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;;;;;;;;;ACrEA,SAAgB,gCAAgC,YAAkD;CAChG,OAAO,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,cAAc,WAC7E,SACE,WAAW,OAAO,GAClB,aAAa,aAAa,QAC1B;EACE,sBAAsB,aAAa;EACnC,kBAAkB,aAAa;CACjC,SACM,KAAK,CACb,CACF;AACF"}
@@ -0,0 +1,21 @@
1
+ //#region src/infrastructure/cloudflare/tracing.ts
2
+ /** Add attributes to the active span. That span is the invocation root unless `withSpan` encloses the call. */
3
+ function annotateSpan(tracing, attributes) {
4
+ tracing.getActiveSpan()?.setAttributes(attributes);
5
+ }
6
+ /**
7
+ * Run `operation` in a child span.
8
+ * Use it when one invocation runs several units of work, such as each message in a queue batch.
9
+ * This helper does not record an exception. A failure reaches Issues as the uncaught error or `logger.error`.
10
+ * An expected throw, such as a duplicate message, is not an exception record.
11
+ */
12
+ function withSpan(tracing, name, attributes, operation) {
13
+ return tracing.enterSpan(name, (span) => {
14
+ span.setAttributes(attributes);
15
+ return operation();
16
+ });
17
+ }
18
+
19
+ //#endregion
20
+ export { withSpan as n, annotateSpan as t };
21
+ //# sourceMappingURL=tracing-C_7B_odV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing-C_7B_odV.js","names":[],"sources":["../src/infrastructure/cloudflare/tracing.ts"],"sourcesContent":["/**\n * Workers tracing for Workers Issues.\n *\n * Ported from Suparelay `apps/web/src/server/infrastructure/tracing/span.ts`.\n * Pass `tracing` in. This file does not import `cloudflare:workers`.\n * A client bundle can import a server module that uses these helpers.\n *\n * Issues shows the active span's attributes beside a failure. Put identifiers on the span.\n * Outside an invocation there is no active span, and a missing span records nothing.\n */\n\n/** Attribute values a Workers span accepts. `undefined` leaves that attribute unset. */\nexport type SpanAttributes = Record<string, string | number | boolean | undefined>\n\n/** Add attributes to the active span. That span is the invocation root unless `withSpan` encloses the call. */\nexport function annotateSpan(tracing: Tracing, attributes: SpanAttributes): void {\n tracing.getActiveSpan()?.setAttributes(attributes)\n}\n\n/**\n * Run `operation` in a child span.\n * Use it when one invocation runs several units of work, such as each message in a queue batch.\n * This helper does not record an exception. A failure reaches Issues as the uncaught error or `logger.error`.\n * An expected throw, such as a duplicate message, is not an exception record.\n */\nexport function withSpan<T>(\n tracing: Tracing,\n name: string,\n attributes: SpanAttributes,\n operation: () => Promise<T>,\n): Promise<T> {\n return tracing.enterSpan(name, (span) => {\n span.setAttributes(attributes)\n return operation()\n })\n}\n"],"mappings":";;AAeA,SAAgB,aAAa,SAAkB,YAAkC;CAC/E,QAAQ,cAAc,CAAC,EAAE,cAAc,UAAU;AACnD;;;;;;;AAQA,SAAgB,SACd,SACA,MACA,YACA,WACY;CACZ,OAAO,QAAQ,UAAU,OAAO,SAAS;EACvC,KAAK,cAAc,UAAU;EAC7B,OAAO,UAAU;CACnB,CAAC;AACH"}
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.32.0",
4
+ "version": "0.34.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": {
@@ -33,6 +33,47 @@ export function createSentryLoggerErrorHook(): LoggerErrorHook {
33
33
  }
34
34
  }
35
35
 
36
+ /** The error value as Sentry's React handler receives it. */
37
+ type ReactRootError = Parameters<ReturnType<typeof Sentry.reactErrorHandler>>[0]
38
+
39
+ /** The details React passes to a root error option; React may omit the component stack. */
40
+ export type ReactRootErrorInfo = { readonly componentStack?: string | undefined }
41
+
42
+ /** A `hydrateRoot` error option in React's own shape. */
43
+ type ReactRootErrorHandler = (error: ReactRootError, errorInfo: ReactRootErrorInfo) => void
44
+
45
+ /** The `hydrateRoot` error options; each one replaces React's console default. */
46
+ export type SentryReactRootOptions = {
47
+ readonly onCaughtError: ReactRootErrorHandler
48
+ readonly onUncaughtError: ReactRootErrorHandler
49
+ readonly onRecoverableError: ReactRootErrorHandler
50
+ }
51
+
52
+ /**
53
+ * Report React errors to Sentry from `hydrateRoot`, as Sentry's React 19 setup does.
54
+ * Covers errors that a boundary catches, errors that no boundary catches, and hydration
55
+ * errors that React recovers from. TanStack redirects and not-found control flow are not
56
+ * reported. Each error still goes to the console, as with React's defaults.
57
+ */
58
+ export function createSentryReactRootOptions(): SentryReactRootOptions {
59
+ const handler = Sentry.reactErrorHandler((error, errorInfo) => {
60
+ console.error(error, errorInfo.componentStack)
61
+ })
62
+ // Sentry's handler takes `null` for a missing component stack.
63
+ const report: ReactRootErrorHandler = (error, { componentStack }) => {
64
+ handler(error, { componentStack: componentStack ?? null })
65
+ }
66
+ return {
67
+ // TanStack Router renders not-found through a React error boundary, so each 404 arrives here.
68
+ onCaughtError: (error, errorInfo) => {
69
+ if (isNotFound(error) || isRedirect(error)) return
70
+ report(error, errorInfo)
71
+ },
72
+ onUncaughtError: report,
73
+ onRecoverableError: report,
74
+ }
75
+ }
76
+
36
77
  /** Initialize once in the browser entrypoint before hydration; server imports have no side effects. */
37
78
  export function initializeSentry(options: SentryClientOptions): ReturnType<typeof Sentry.init> {
38
79
  const client = Sentry.init(createSentryClientOptions(options))
@@ -0,0 +1,23 @@
1
+ import { createMiddleware } from '@tanstack/react-start'
2
+
3
+ import { withSpan } from '../cloudflare/tracing.ts'
4
+ import type { RequestContext } from './request-context.ts'
5
+
6
+ /**
7
+ * Run one server function call in a child span named for that function.
8
+ * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.
9
+ * A handler rejection is not a span exception, and this middleware does not log.
10
+ */
11
+ export function createFunctionTracingMiddleware(getTracing: (context: RequestContext) => Tracing) {
12
+ return createMiddleware({ type: 'function' }).server(({ context, serverFnMeta, next }) =>
13
+ withSpan(
14
+ getTracing(context),
15
+ `server_fn ${serverFnMeta.name}`,
16
+ {
17
+ 'code.function.name': serverFnMeta.name,
18
+ 'code.file.path': serverFnMeta.filename,
19
+ },
20
+ () => next(),
21
+ ),
22
+ )
23
+ }
@@ -11,3 +11,4 @@ export {
11
11
  type AuthCookieSource,
12
12
  type ErrorMiddlewareOptions,
13
13
  } from './error.middleware.ts'
14
+ export { createFunctionTracingMiddleware } from './function-tracing.middleware.ts'
@@ -1 +0,0 @@
1
- {"version":3,"file":"tracing.js","names":[],"sources":["../../src/infrastructure/cloudflare/tracing.ts"],"sourcesContent":["/**\n * Workers tracing for Workers Issues.\n *\n * Ported from Suparelay `apps/web/src/server/infrastructure/tracing/span.ts`.\n * Pass `tracing` in. This file does not import `cloudflare:workers`.\n * A client bundle can import a server module that uses these helpers.\n *\n * Issues shows the active span's attributes beside a failure. Put identifiers on the span.\n * Outside an invocation there is no active span, and a missing span records nothing.\n */\n\n/** Attribute values a Workers span accepts. `undefined` leaves that attribute unset. */\nexport type SpanAttributes = Record<string, string | number | boolean | undefined>\n\n/** Add attributes to the active span. That span is the invocation root unless `withSpan` encloses the call. */\nexport function annotateSpan(tracing: Tracing, attributes: SpanAttributes): void {\n tracing.getActiveSpan()?.setAttributes(attributes)\n}\n\n/**\n * Run `operation` in a child span.\n * Use it when one invocation runs several units of work, such as each message in a queue batch.\n * This helper does not record an exception. A failure reaches Issues as the uncaught error or `logger.error`.\n * An expected throw, such as a duplicate message, is not an exception record.\n */\nexport function withSpan<T>(\n tracing: Tracing,\n name: string,\n attributes: SpanAttributes,\n operation: () => Promise<T>,\n): Promise<T> {\n return tracing.enterSpan(name, (span) => {\n span.setAttributes(attributes)\n return operation()\n })\n}\n"],"mappings":";;AAeA,SAAgB,aAAa,SAAkB,YAAkC;CAC/E,QAAQ,cAAc,CAAC,EAAE,cAAc,UAAU;AACnD;;;;;;;AAQA,SAAgB,SACd,SACA,MACA,YACA,WACY;CACZ,OAAO,QAAQ,UAAU,OAAO,SAAS;EACvC,KAAK,cAAc,UAAU;EAC7B,OAAO,UAAU;CACnB,CAAC;AACH"}