From 87c22abb0b43e6c767e193651321732516e5625e Mon Sep 17 00:00:00 2001 From: Sagnik Ghosh Date: Sun, 15 Nov 2026 02:29:56 +0530 Subject: [PATCH] runtime-next: browser and edge builds of the root entry The root's exports had no browser or edge condition, so every bundler got the server build, which re-exports @autter/runtime-node (OpenTelemetry, require-in-the-middle, fs). A module shared by client and server code, such as an error catalog importing defineRuntimeErrors, broke the client build. - src/index.browser.ts ("browser") and src/index.edge.ts ("edge-light", "worker") export every name the server root exports, with its types: the coded-error and redaction helpers for real (bundled runtime-core; runtime-edge's classes on the edge), capture/log/context calls as no-ops that warn once in development, setup functions and server wrappers as functions that throw a "server-only" error when called. - exports["."]: types, edge-light, worker, browser, import, require. Edge conditions come before "browser" because Next's edge compiles also match "browser" and would otherwise get the browser build. - Compile-time parity check in both entries; tests for export parity (ESM and CJS), esbuild bundles for browser/edge-light/worker with no Node code, the stand-ins' behaviour, and Node resolution. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + package-lock.json | 2 + packages/runtime-next/README.md | 61 +++- packages/runtime-next/package.json | 16 +- packages/runtime-next/src/index.browser.ts | 92 ++++++ packages/runtime-next/src/index.edge.ts | 77 +++++ packages/runtime-next/src/index.ts | 12 +- packages/runtime-next/src/server-stand-ins.ts | 188 ++++++++++++ .../runtime-next/test/root-builds.test.mjs | 271 ++++++++++++++++++ packages/runtime-next/tsup.config.ts | 31 +- 10 files changed, 742 insertions(+), 12 deletions(-) create mode 100644 packages/runtime-next/src/index.browser.ts create mode 100644 packages/runtime-next/src/index.edge.ts create mode 100644 packages/runtime-next/src/server-stand-ins.ts create mode 100644 packages/runtime-next/test/root-builds.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 13281dd..5e0f1a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### runtime-next: the root is safe in modules shared with client and edge code + +- `@autter/runtime-next` has a browser build (`browser` condition) and an edge build (`edge-light` / `worker`) of its root entry. Before, every bundler got the server build, so a module that both a client component and a route handler import (an error catalog importing `defineRuntimeErrors`) pulled `@autter/runtime-node`, OpenTelemetry and `fs` into the client bundle and the build failed. The new builds export every name the server root does, with the same types: the coded-error helpers (`RuntimeError`, `defineRuntimeErrors`, `isRuntimeErrorLike`, `toClientError`, `errorAttributes`, `CODE_PATTERN`) and `redactAttributes` / `redactText` are the real ones; capture, log and context calls (`captureServerException`, `runtimeLogger`, `runtimeContext`, …) do nothing and warn once in development; setup functions and server wrappers (`registerAutter`, `withAutter`, `withRuntimeRequest`, `createAutterRelayRoute`, `withLlmCall`, …) throw a "server-only" error when called. Node.js resolves the root to the server build as before, for `import` and `require`. See the README ("Importing the root from shared modules"). + ## [1.18.0] - 2026-11-14 Packages: `otlp-ingester` 1.16.0, `runtime-node` 1.14.0, and the local `dashboard` image. Release the ingester before `runtime-node` 1.14.0 (`llm_cache_tokens`); see the upgrade notes. diff --git a/package-lock.json b/package-lock.json index d6ffd8c..2462305 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6828,7 +6828,9 @@ "@autter/runtime-node": "^1.9.0" }, "devDependencies": { + "@autter/runtime-core": "0.0.0", "@types/react": "^18.3.0", + "esbuild": "^0.28.1", "tsup": "^8.3.5", "typescript": "^5.7.0" }, diff --git a/packages/runtime-next/README.md b/packages/runtime-next/README.md index 1cc91b9..92522bf 100644 --- a/packages/runtime-next/README.md +++ b/packages/runtime-next/README.md @@ -15,8 +15,11 @@ Set `AUTTER_RUNTIME_KEY` in your environment. Then three small files, and The package has two entry points — this split is what keeps the Node OpenTelemetry SDK out of your browser bundle: -- `@autter/runtime-next` (or `@autter/runtime-next/server`) — server only: - `instrumentation.ts`, route handlers, server components. +- `@autter/runtime-next` (or `@autter/runtime-next/server`) — the server + API: `instrumentation.ts`, route handlers, server components. The root + (not `/server`) is also safe in modules that client or edge code imports, + such as an error catalog: see + [Importing the root from shared modules](#importing-the-root-from-shared-modules). - `@autter/runtime-next/client` — client components: browser tracker + error boundary. Never imports Node code. - `@autter/runtime-next/instrumentation` — `onRequestError` for @@ -184,15 +187,61 @@ Also re-exported for convenience: `captureException`, `captureMessage`, servers: `autterErrorHandler`, `autterFastifyErrors`, `autterKoa` and `captureRequestError`. -> Importing the root entry from a client component pulls the Node OTel SDK -> into the browser bundle and fails the build (`fs` cannot be resolved). -> Client code must always use `@autter/runtime-next/client`. - LLM tracing is on automatically once `registerAutter` runs: Vercel AI SDK calls with `experimental_telemetry: { isEnabled: true }` (and anything wrapped in `withLlmCall` or an `instrumentLlmClient` client) are recorded at 100% — every call, with model, tokens, latency, and cost. See the [`@autter/runtime-node` README](../runtime-node) for the API. + +## Importing the root from shared modules + +A module that both client and server code import, such as an error catalog, +can import the root. The bundler picks the root's build by export condition, +and the browser and edge builds export every name the server build does, with +the same types, so the import never fails with "export not found" and never +pulls the Node OpenTelemetry SDK (or `fs`) into a browser or edge bundle: + +```ts +// lib/errors.ts — imported by a client component and by route handlers +import { defineRuntimeErrors } from "@autter/runtime-next"; + +export const orderErrors = defineRuntimeErrors("orders", { + not_found: { status: 404, message: "No such order", expected: true }, +}); +``` + +| Bundled for | Build | What the root gives you | +| --- | --- | --- | +| Node.js server (route handlers, server components, server actions, `instrumentation.ts`) | `import` / `require` | Everything. | +| Edge runtime (`middleware.ts`, `export const runtime = "edge"`; the `edge-light` / `worker` conditions) | `dist/index.edge.js` | The coded-error helpers for real (`@autter/runtime-edge`'s, the same classes `@autter/runtime-next/edge` uses). Every other name is a stand-in, as in the browser. | +| Browser (client components; the `browser` condition) | `dist/index.browser.js` | The coded-error helpers for real: `RuntimeError`, `defineRuntimeErrors`, `isRuntimeErrorLike`, `toClientError`, `errorAttributes`, `CODE_PATTERN`, plus `redactAttributes` and `redactText`. Every other name is a stand-in (below). | + +The stand-ins in the browser and edge builds: + +- Capture, log and context calls do nothing and warn once per name in + development (silent in production): `captureServerException`, + `captureServerMessage`, `reportServerOutcome`, `captureRequestError`, + `trackLlmCall`, `addBreadcrumb`, `makeSafeCapture()`, `runtimeLogger`, + `createRuntimeLogger()`, `runtimeContext`. Wrappers still run your code: + `withRuntimeOperation`, `withProcessSpan`, `runInBackground` and + `runtimeContext.fork` call the function and return its result; + `instrumentLlmClient` returns the client unchanged. `flushRuntimeLogs` + resolves `{ ok: true, errors: [] }`. +- Config builders return inert values, so a shared config module can build + them at import time: `otlpSink`, `consoleSink`, `fileSink`, and the + `enrich*` enrichers. +- Setup functions and server wrappers throw a "server-only" error naming the + function when they are called (never at import): `registerAutter`, + `withAutter`, `withRuntimeRequest`, `createAutterRelayRoute`, + `withLlmCall`, `emitLlmSelftestTrace`, `initAutterLogging`, + `installAutterAutoFlush`, and the Express, Fastify and Koa hooks. + +So report browser errors with `captureException` from +`@autter/runtime-next/client` (a server capture called in the browser is not +forwarded to the browser tracker), and use `@autter/runtime-next/edge` for +middleware and edge routes. `@autter/runtime-next/server` has no browser or +edge build: import it from Node.js server code only. + ## Operation logging (1.4.0+) Import `withRuntimeOperation`, `runtimeLogger`, `createRuntimeLogger`, diff --git a/packages/runtime-next/package.json b/packages/runtime-next/package.json index bd83db4..ce10360 100644 --- a/packages/runtime-next/package.json +++ b/packages/runtime-next/package.json @@ -10,6 +10,18 @@ "exports": { ".": { "types": "./dist/index.d.ts", + "edge-light": { + "import": "./dist/index.edge.js", + "require": "./dist/index.edge.cjs" + }, + "worker": { + "import": "./dist/index.edge.js", + "require": "./dist/index.edge.cjs" + }, + "browser": { + "import": "./dist/index.browser.js", + "require": "./dist/index.browser.cjs" + }, "import": "./dist/index.js", "require": "./dist/index.cjs" }, @@ -51,7 +63,7 @@ "directory": "packages/runtime-next" }, "scripts": { - "build": "node ../../scripts/ensure-built.mjs runtime-node runtime-edge runtime-browser && node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup", + "build": "node ../../scripts/ensure-built.mjs runtime-core runtime-node runtime-edge runtime-browser && node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup", "test": "npm run build -w @autter/runtime-core && npm run build -w @autter/runtime-node && npm run build -w @autter/runtime-edge && npm run build -w @autter/runtime-browser && npm run build && node --test test/*.test.mjs" }, "dependencies": { @@ -63,7 +75,9 @@ "react": ">=18" }, "devDependencies": { + "@autter/runtime-core": "0.0.0", "@types/react": "^18.3.0", + "esbuild": "^0.28.1", "tsup": "^8.3.5", "typescript": "^5.7.0" }, diff --git a/packages/runtime-next/src/index.browser.ts b/packages/runtime-next/src/index.browser.ts new file mode 100644 index 0000000..2e0492b --- /dev/null +++ b/packages/runtime-next/src/index.browser.ts @@ -0,0 +1,92 @@ +/** + * Browser build of the `@autter/runtime-next` root, picked by bundlers + * through the `browser` export condition (Next.js client components, + * Turbopack and webpack client builds, Vite). + * + * It exists for modules that both client and server code import, such as an + * error catalog: + * + * // lib/errors.ts, imported by a client component and a route handler + * import { defineRuntimeErrors } from "@autter/runtime-next"; + * export const orderErrors = defineRuntimeErrors({ ... }); + * + * It exports every name the server root exports, with the same types: + * + * - the coded-error and redaction helpers are the real ones (pure code from + * @autter/runtime-core, bundled in); + * - everything else is a stand-in from `server-stand-ins.ts`: capture and + * log calls are no-ops that warn once in development, setup functions + * (`registerAutter`, `withAutter`, …) throw a "server-only" error when + * called. + * + * Never imports @autter/runtime-node, OpenTelemetry or a Node module. The + * browser tracker and React components stay in `@autter/runtime-next/client`. + */ +import { serverStandIns } from "./server-stand-ins.js"; + +export { + CODE_PATTERN, + RuntimeError, + defineRuntimeErrors, + isRuntimeErrorLike, + toClientError, + errorAttributes, + redactAttributes, + redactText, +} from "@autter/runtime-core"; + +export const { + addBreadcrumb, + autterErrorHandler, + autterErrorResponse, + autterFastify, + autterFastifyErrors, + autterKoa, + autterRequests, + captureRequestError, + captureServerException, + captureServerMessage, + consoleSink, + createAutterRelayRoute, + createRuntimeLogger, + emitLlmSelftestTrace, + enrichDeployment, + enrichEdgeGeo, + enrichRequestSize, + enrichUserAgent, + fileSink, + flushRuntimeLogs, + initAutterLogging, + installAutterAutoFlush, + instrumentLlmClient, + makeSafeCapture, + otlpSink, + registerAutter, + reportServerOutcome, + runInBackground, + runtimeContext, + runtimeLogStats, + runtimeLogger, + trackLlmCall, + withAutter, + withLlmCall, + withProcessSpan, + withRuntimeOperation, + withRuntimeRequest, +} = serverStandIns("browser"); + +// The server root's types, so this build's declarations match it name for name. +export type * from "./server.js"; + +/* + * Compile-time parity with the server root (checked by the build's + * declaration step): the same value names, each assignable to its server + * type. test/root-builds.test.mjs checks the built files too. + */ +type Root = typeof import("./index.js"); +type Self = typeof import("./index.browser.js"); +type Assert = T; +type _BrowserRootParity = [ + Assert<[keyof Root] extends [keyof Self] ? ([keyof Self] extends [keyof Root] ? true : false) : false>, + Assert ? true : false>, +]; diff --git a/packages/runtime-next/src/index.edge.ts b/packages/runtime-next/src/index.edge.ts new file mode 100644 index 0000000..bb7d365 --- /dev/null +++ b/packages/runtime-next/src/index.edge.ts @@ -0,0 +1,77 @@ +/** + * Edge build of the `@autter/runtime-next` root, picked by bundlers through + * the `edge-light` / `worker` export conditions (Next.js edge runtime: + * `middleware.ts`, `export const runtime = "edge"` routes; Workers), like + * `@autter/runtime-next/instrumentation` already is. + * + * Same contract as the browser build (`index.browser.ts`): every name the + * server root exports, with the same types. The coded-error helpers come + * from @autter/runtime-edge, so a `RuntimeError` built from a shared catalog + * is the very class `withAutter` from `@autter/runtime-next/edge` checks; + * the other server exports are stand-ins (no-ops that warn once in + * development, or a "server-only" error pointing to + * `@autter/runtime-next/edge`). Never imports @autter/runtime-node, + * OpenTelemetry or a Node module. + */ +import { serverStandIns } from "./server-stand-ins.js"; + +export { + CODE_PATTERN, + RuntimeError, + defineRuntimeErrors, + isRuntimeErrorLike, + toClientError, +} from "@autter/runtime-edge"; +export { errorAttributes, redactAttributes, redactText } from "@autter/runtime-core"; + +export const { + addBreadcrumb, + autterErrorHandler, + autterErrorResponse, + autterFastify, + autterFastifyErrors, + autterKoa, + autterRequests, + captureRequestError, + captureServerException, + captureServerMessage, + consoleSink, + createAutterRelayRoute, + createRuntimeLogger, + emitLlmSelftestTrace, + enrichDeployment, + enrichEdgeGeo, + enrichRequestSize, + enrichUserAgent, + fileSink, + flushRuntimeLogs, + initAutterLogging, + installAutterAutoFlush, + instrumentLlmClient, + makeSafeCapture, + otlpSink, + registerAutter, + reportServerOutcome, + runInBackground, + runtimeContext, + runtimeLogStats, + runtimeLogger, + trackLlmCall, + withAutter, + withLlmCall, + withProcessSpan, + withRuntimeOperation, + withRuntimeRequest, +} = serverStandIns("edge"); + +// The server root's types, so this build's declarations match it name for name. +export type * from "./server.js"; + +/* Compile-time parity with the server root; see index.browser.ts. */ +type Root = typeof import("./index.js"); +type Self = typeof import("./index.edge.js"); +type Assert = T; +type _EdgeRootParity = [ + Assert<[keyof Root] extends [keyof Self] ? ([keyof Self] extends [keyof Root] ? true : false) : false>, + Assert ? true : false>, +]; diff --git a/packages/runtime-next/src/index.ts b/packages/runtime-next/src/index.ts index 8fd16ee..f6fedaa 100644 --- a/packages/runtime-next/src/index.ts +++ b/packages/runtime-next/src/index.ts @@ -1,10 +1,14 @@ /** * @autter/runtime-next — one-command Autter Runtime for Next.js. * - * The root entry is SERVER-ONLY (`instrumentation.ts`, route handlers). - * Client components must import from `@autter/runtime-next/client` — - * importing the root from client code would pull the Node OpenTelemetry - * SDK into the browser bundle and break the build. + * This is the root's Node.js build: the server API (`instrumentation.ts`, + * route handlers, server components). Bundlers pick `index.browser.ts` for + * the `browser` condition and `index.edge.ts` for `edge-light` / `worker`: + * the same names, with the coded-error helpers for real and stand-ins for + * the server-only functions, so a module shared with client or edge code + * can import the root without pulling the Node OpenTelemetry SDK in. + * Browser reporting and the error boundary live in + * `@autter/runtime-next/client`. */ export * from "./server.js"; diff --git a/packages/runtime-next/src/server-stand-ins.ts b/packages/runtime-next/src/server-stand-ins.ts new file mode 100644 index 0000000..3b2ba41 --- /dev/null +++ b/packages/runtime-next/src/server-stand-ins.ts @@ -0,0 +1,188 @@ +/** + * Stand-ins for the server-only exports of the root entry, shared by its + * browser build (`index.browser.ts`) and its edge build (`index.edge.ts`). + * + * A module that both client and server code import (an error catalog, a + * `lib/telemetry.ts`) imports the root, and the bundler picks the root's + * build by export condition. Those builds must export every name the server + * root exports, or the shared module fails with "export not found". So each + * server-only name gets a stand-in here: + * + * - capture, log and context calls are no-ops (callbacks they wrap still + * run) that warn once per name, in development only; + * - config builders (sinks, enrichers) return inert values, because a shared + * config module may build them at import time; + * - setup and server wrappers (`registerAutter`, `withAutter`, …) throw a + * clear "server-only" error when called. + * + * Nothing here runs at import time, nothing imports Node modules or + * @autter/runtime-node: `import type` is erased from the build. + */ +import type * as Server from "./server.js"; + +export type RootBuild = "browser" | "edge"; + +/** Root exports that are real (isomorphic) in every build. */ +export type IsomorphicName = + | "CODE_PATTERN" + | "RuntimeError" + | "defineRuntimeErrors" + | "isRuntimeErrorLike" + | "toClientError" + | "errorAttributes" + | "redactAttributes" + | "redactText"; + +/** Every other root export: it needs a stand-in outside Node. */ +export type StandInName = Exclude; + +export type ServerStandIns = { [K in StandInName]: (typeof Server)[K] }; + +const WHERE: Record = { + browser: 'its browser build (the "browser" export condition)', + edge: 'its edge build (the "edge-light" / "worker" export conditions)', +}; + +const INSTEAD: Record = { + browser: + "In client components, use @autter/runtime-next/client (initAutterBrowser, captureException, AutterErrorBoundary).", + edge: "On the edge runtime (middleware, `export const runtime = \"edge\"` routes), use @autter/runtime-next/edge.", +}; + +function isDevelopment(): boolean { + try { + // Kept literal so bundlers replace it; `process` may not exist at all. + return process.env.NODE_ENV === "development"; + } catch { + return false; + } +} + +/** The message a server-only stand-in throws. */ +export function serverOnlyMessage(name: string, build: RootBuild): string { + return ( + `${name}() is server-only, but "@autter/runtime-next" resolved to ${WHERE[build]} here. ` + + `Call it from Node.js server code (instrumentation.ts, route handlers, server actions). ${INSTEAD[build]}` + ); +} + +/** + * Build the stand-ins for one build. The return type is every server-only + * root export with its server type, so a new server export fails the build + * until it has a stand-in here. + */ +export function serverStandIns(build: RootBuild): ServerStandIns { + const warned = new Set(); + const dropped = (name: string): void => { + if (warned.has(name) || !isDevelopment()) return; + warned.add(name); + try { + console.warn( + `[autter] ${name}() did nothing: "@autter/runtime-next" resolved to ${WHERE[build]}, ` + + `which has no server tracker. ${INSTEAD[build]} (Shown once, in development only.)`, + ); + } catch { + /* no console */ + } + }; + const serverOnly = + (name: string) => + // `any[]`: assignable to every server signature it stands in for. + (..._args: any[]): never => { + throw new Error(serverOnlyMessage(name, build)); + }; + const operation = (): Server.RuntimeOperation => ({ + id: "", + setContext() {}, + outcome() {}, + step: async (_name, fn) => fn(), + }); + const logger = (name: string): ReturnType => ({ + debug: () => dropped(`${name}.debug`), + info: () => dropped(`${name}.info`), + warn: () => dropped(`${name}.warn`), + error: () => dropped(`${name}.error`), + }); + const sink = (name: string) => () => ({ name, write() {} }); + const enricher = () => () => {}; + + return { + // Capture and logging: no-ops. + captureServerException: () => dropped("captureServerException"), + captureServerMessage: () => dropped("captureServerMessage"), + reportServerOutcome: () => dropped("reportServerOutcome"), + captureRequestError: () => dropped("captureRequestError"), + trackLlmCall: () => dropped("trackLlmCall"), + addBreadcrumb: () => dropped("addBreadcrumb"), + makeSafeCapture: () => ({ + captureException: () => dropped("makeSafeCapture().captureException"), + captureMessage: () => dropped("makeSafeCapture().captureMessage"), + }), + runtimeLogger: logger("runtimeLogger"), + createRuntimeLogger: () => logger("createRuntimeLogger()"), + runtimeContext: { + set: () => dropped("runtimeContext.set"), + outcome: () => dropped("runtimeContext.outcome"), + debug: () => dropped("runtimeContext.debug"), + info: () => dropped("runtimeContext.info"), + warn: () => dropped("runtimeContext.warn"), + error: () => dropped("runtimeContext.error"), + degraded: () => dropped("runtimeContext.degraded"), + id: undefined, + requestId: undefined, + fork: async (_name, fn) => { + dropped("runtimeContext.fork"); + return fn(operation()); + }, + carrier: () => undefined, + }, + flushRuntimeLogs: async () => ({ ok: true, errors: [] }), + runtimeLogStats: () => ({ buffered: 0, dropped: 0 }), + // Wrappers around the app's own work: run it, record nothing. + withRuntimeOperation: async (_name, fn) => { + dropped("withRuntimeOperation"); + return fn(operation()); + }, + runInBackground: async (name, fn) => { + dropped("runInBackground"); + // Never rejects, like the server version; the error is not reported. + try { + return await fn(operation()); + } catch (error) { + if (isDevelopment()) console.error(`[autter] runInBackground("${name}") failed:`, error); + return undefined; + } + }, + withProcessSpan: async (_name, fn) => { + dropped("withProcessSpan"); + return fn(); + }, + instrumentLlmClient: (client) => { + dropped("instrumentLlmClient"); + return client; + }, + // Config builders: inert values (only useful to initAutterLogging, which throws). + otlpSink: sink("otlp"), + consoleSink: sink("console"), + fileSink: sink("file"), + enrichUserAgent: enricher, + enrichRequestSize: enricher, + enrichEdgeGeo: enricher, + enrichDeployment: enricher, + // Setup and server wrappers: throw when called. + registerAutter: serverOnly("registerAutter"), + createAutterRelayRoute: serverOnly("createAutterRelayRoute"), + withRuntimeRequest: serverOnly("withRuntimeRequest"), + withAutter: serverOnly("withAutter"), + withLlmCall: serverOnly("withLlmCall"), + emitLlmSelftestTrace: serverOnly("emitLlmSelftestTrace"), + installAutterAutoFlush: serverOnly("installAutterAutoFlush"), + initAutterLogging: serverOnly("initAutterLogging"), + autterRequests: serverOnly("autterRequests"), + autterFastify: serverOnly("autterFastify"), + autterErrorResponse: serverOnly("autterErrorResponse"), + autterErrorHandler: serverOnly("autterErrorHandler"), + autterFastifyErrors: serverOnly("autterFastifyErrors"), + autterKoa: serverOnly("autterKoa"), + }; +} diff --git a/packages/runtime-next/test/root-builds.test.mjs b/packages/runtime-next/test/root-builds.test.mjs new file mode 100644 index 0000000..c330c46 --- /dev/null +++ b/packages/runtime-next/test/root-builds.test.mjs @@ -0,0 +1,271 @@ +// The root entry's browser and edge builds (index.browser.ts, index.edge.ts): +// a module that both client and server code import (an error catalog) can +// import "@autter/runtime-next" without pulling Node code into the client or +// edge bundle, and without hitting "export not found". +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; +import * as edgeSdk from "@autter/runtime-edge"; +import { build } from "esbuild"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const PACKAGE = join(HERE, ".."); +const require = createRequire(import.meta.url); + +const server = await import("../dist/index.js"); +const browser = await import("../dist/index.browser.js"); +const edge = await import("../dist/index.edge.js"); + +function exportDiff(expected, actual) { + const want = Object.keys(expected).filter((name) => name !== "default"); + const have = Object.keys(actual).filter((name) => name !== "default"); + return { + missing: want.filter((name) => !have.includes(name)).sort(), + extra: have.filter((name) => !want.includes(name)).sort(), + }; +} + +test("the browser and edge roots export exactly the server root's names (ESM and CJS)", () => { + const builds = { + "index.browser.js": browser, + "index.edge.js": edge, + "index.browser.cjs": require("../dist/index.browser.cjs"), + "index.edge.cjs": require("../dist/index.edge.cjs"), + }; + for (const [file, mod] of Object.entries(builds)) { + const { missing, extra } = exportDiff(server, mod); + assert.deepEqual( + { missing, extra }, + { missing: [], extra: [] }, + `dist/${file} differs from the server root: missing [${missing.join(", ")}], extra [${extra.join(", ")}]`, + ); + for (const name of Object.keys(server)) { + assert.equal(typeof mod[name], typeof server[name], `${file}: ${name} is a ${typeof mod[name]}, the server's is a ${typeof server[name]}`); + } + } + // The server root is the same with CJS. + assert.deepEqual(exportDiff(server, require("../dist/index.cjs")), { missing: [], extra: [] }); +}); + +test("Node resolves the root to the server build, for import and require", () => { + assert.ok(import.meta.resolve("@autter/runtime-next").endsWith("/packages/runtime-next/dist/index.js")); + assert.ok(require.resolve("@autter/runtime-next").endsWith(join("packages", "runtime-next", "dist", "index.cjs"))); + assert.equal(require("@autter/runtime-next").registerAutter, require("../dist/index.cjs").registerAutter); +}); + +// A module shared by a client component and a route handler. +const SHARED_MODULE = ` +import { + RuntimeError, + defineRuntimeErrors, + toClientError, + isRuntimeErrorLike, + captureServerException, + runtimeLogger, + runtimeContext, + withAutter, +} from "@autter/runtime-next"; + +export const orderErrors = defineRuntimeErrors("orders", { + not_found: { status: 404, message: "No such order", expected: true }, +}); + +export function describe(error) { + captureServerException(error); + runtimeLogger.info("described an error"); + runtimeContext.set({ described: true }); + return isRuntimeErrorLike(error) ? toClientError(error) : null; +} + +export { RuntimeError, withAutter }; +`; + +// What must never reach a browser or edge bundle. +const NODE_ONLY = [ + { what: "a node: import", pattern: /["']node:[a-z_/]+["']/ }, + { what: "fs", pattern: /(?:require\(\s*|from\s*|import\(\s*)["']fs(?:\/promises)?["']/ }, + { what: "@opentelemetry", pattern: /@opentelemetry/ }, + { what: "require-in-the-middle", pattern: /require-in-the-middle/ }, + { what: "@autter/runtime-node", pattern: /@autter\/runtime-node/ }, +]; + +async function bundle(options) { + const result = await build({ + stdin: { contents: SHARED_MODULE, resolveDir: PACKAGE, sourcefile: "shared-errors.js", loader: "js" }, + bundle: true, + write: false, + format: "esm", + metafile: true, + logLevel: "silent", + ...options, + }); + const code = result.outputFiles[0].text; + const minified = await build({ ...options, stdin: { contents: code, loader: "js" }, bundle: false, write: false, minify: true, format: "esm", logLevel: "silent" }); + return { code, inputs: Object.keys(result.metafile.inputs), bytes: code.length, minifiedBytes: minified.outputFiles[0].text.length }; +} + +function assertNodeFree(label, { code, inputs }) { + for (const { what, pattern } of NODE_ONLY) { + assert.doesNotMatch(code, pattern, `${label}: the bundle contains ${what}`); + } + const nodeInputs = inputs.filter((input) => /runtime-node|@opentelemetry|require-in-the-middle/.test(input)); + assert.deepEqual(nodeInputs, [], `${label}: the bundle read Node-only files`); +} + +const BUNDLES = [ + // Turbopack/webpack client builds, Vite: the "browser" condition. + { label: "browser", options: { platform: "browser", conditions: ["browser"] }, entry: "dist/index.browser.js" }, + // Next.js edge compiles add "edge-light" (webpack keeps its "browser" default too). + { label: "edge-light", options: { platform: "neutral", mainFields: ["module", "main"], conditions: ["edge-light"] }, entry: "dist/index.edge.js" }, + { label: "edge-light + browser (Next.js webpack edge)", options: { platform: "neutral", mainFields: ["module", "main"], conditions: ["edge-light", "browser"] }, entry: "dist/index.edge.js" }, + // Cloudflare Workers (wrangler: workerd, worker, browser). + { label: "worker", options: { platform: "neutral", mainFields: ["module", "main"], conditions: ["workerd", "worker", "browser"] }, entry: "dist/index.edge.js" }, +]; + +for (const { label, options, entry } of BUNDLES) { + test(`a shared module importing the root bundles for ${label} without Node code`, async (t) => { + const result = await bundle(options); + assert.ok( + result.inputs.some((input) => input === entry || input.endsWith(`runtime-next/${entry}`)), + `${label}: expected ${entry}, the bundle read ${result.inputs.join(", ")}`, + ); + assertNodeFree(label, result); + t.diagnostic(`${label}: ${entry}, ${result.bytes} bytes (${result.minifiedBytes} minified), inputs: ${result.inputs.join(", ")}`); + }); +} + +async function captureConsole(fn) { + const calls = { warn: [], error: [] }; + const original = { warn: console.warn, error: console.error }; + console.warn = (...args) => calls.warn.push(args.join(" ")); + console.error = (...args) => calls.error.push(args.join(" ")); + try { + await fn(); + } finally { + console.warn = original.warn; + console.error = original.error; + } + return calls; +} + +async function withNodeEnv(value, fn) { + const before = process.env.NODE_ENV; + process.env.NODE_ENV = value; + try { + return await fn(); + } finally { + if (before === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = before; + } +} + +async function useNoOps(root) { + root.captureServerException(new Error("x"), { a: 1 }); + root.captureServerMessage("m", "warning"); + root.reportServerOutcome("checkout", "declined"); + root.captureRequestError(new Error("x")); + root.trackLlmCall({ provider: "openai", model: "gpt", durationMs: 1 }); + root.addBreadcrumb({ message: "clicked" }); + root.runtimeLogger.info("hello"); + root.runtimeLogger.error(new Error("x")); + root.createRuntimeLogger({ area: "cart" }).warn("careful"); + root.runtimeContext.set({ a: 1 }); + root.runtimeContext.outcome("failed"); + root.runtimeContext.degraded(new Error("x"), "fallback"); + const safe = root.makeSafeCapture(); + safe.captureException(new Error("x")); + safe.captureMessage("m"); + assert.equal(root.runtimeContext.id, undefined); + assert.equal(root.runtimeContext.requestId, undefined); + assert.equal(root.runtimeContext.carrier(), undefined); + // Wrappers still run the app's work. + assert.equal(await root.withRuntimeOperation("op", (op) => op.step("s", () => 41 + 1)), 42); + assert.equal(await root.withProcessSpan("job", async () => "done"), "done"); + assert.equal(await root.runtimeContext.fork("child", () => "forked"), "forked"); + assert.equal(await root.runInBackground("bg", () => "ok"), "ok"); + assert.equal(await root.runInBackground("bg-fails", () => { throw new Error("boom"); }), undefined); + const client = { chat: {} }; + assert.equal(root.instrumentLlmClient(client), client); + // Plumbing and config builders. + assert.deepEqual(await root.flushRuntimeLogs(), { ok: true, errors: [] }); + assert.deepEqual(root.runtimeLogStats(), { buffered: 0, dropped: 0 }); + for (const sink of [root.otlpSink(), root.consoleSink(), root.fileSink({ path: "x.log" })]) { + assert.equal(typeof sink.name, "string"); + sink.write({}); + } + for (const enricher of [root.enrichUserAgent(), root.enrichRequestSize(), root.enrichEdgeGeo(), root.enrichDeployment({})]) { + enricher({ level: "info", message: "m", attributes: {} }, {}); + } +} + +for (const [label, root] of [["browser", browser], ["edge", edge]]) { + test(`${label} root: no-ops never throw and stay silent in production`, async () => { + const calls = await withNodeEnv("production", () => captureConsole(() => useNoOps(root))); + assert.deepEqual(calls, { warn: [], error: [] }); + }); + + test(`${label} root: no-ops warn once per name in development`, async () => { + const first = await withNodeEnv("development", () => captureConsole(() => useNoOps(root))); + const warned = first.warn.join("\n"); + for (const name of ["captureServerException", "runtimeLogger.info", "runtimeContext.set", "withRuntimeOperation", "instrumentLlmClient"]) { + assert.match(warned, new RegExp(`\\[autter\\] ${name.replace(".", "\\.")}\\(\\) did nothing`), name); + } + assert.match(warned, new RegExp(`resolved to its ${label} build`)); + assert.equal(new Set(first.warn).size, first.warn.length, "a name warned twice"); + // A failed background task is printed in development (it is not reported anywhere). + assert.equal(first.error.length, 1); + assert.match(first.error[0], /runInBackground\("bg-fails"\) failed/); + // The second time round: nothing new. + const second = await withNodeEnv("development", () => captureConsole(() => useNoOps(root))); + assert.deepEqual(second.warn, []); + }); + + test(`${label} root: setup and server wrappers throw a clear server-only error`, () => { + const where = label === "browser" ? /@autter\/runtime-next\/client/ : /@autter\/runtime-next\/edge/; + const calls = { + registerAutter: () => root.registerAutter({ apiKey: "k", service: "s" }), + createAutterRelayRoute: () => root.createAutterRelayRoute({ apiKey: "k" }), + withRuntimeRequest: () => root.withRuntimeRequest(async () => new Response("ok")), + withAutter: () => root.withAutter(async () => new Response("ok")), + withLlmCall: () => root.withLlmCall({ provider: "openai", model: "gpt" }, () => 1), + emitLlmSelftestTrace: () => root.emitLlmSelftestTrace(), + installAutterAutoFlush: () => root.installAutterAutoFlush(), + initAutterLogging: () => root.initAutterLogging({ service: "s" }), + autterRequests: () => root.autterRequests(), + autterFastify: () => root.autterFastify({ addHook() {} }, {}, () => {}), + autterErrorResponse: () => root.autterErrorResponse(), + autterErrorHandler: () => root.autterErrorHandler(), + autterFastifyErrors: () => root.autterFastifyErrors({ addHook() {} }), + autterKoa: () => root.autterKoa(), + }; + for (const [name, call] of Object.entries(calls)) { + assert.throws(call, (error) => { + assert.match(error.message, new RegExp(`^${name}\\(\\) is server-only`), name); + assert.match(error.message, new RegExp(`its ${label} build`), name); + assert.match(error.message, where, name); + return true; + }); + } + }); + + test(`${label} root: the coded-error helpers are the real ones`, () => { + const errors = root.defineRuntimeErrors("orders", { not_found: { status: 404, message: "No such order", expected: true } }); + const error = errors.not_found(); + assert.ok(error instanceof root.RuntimeError); + assert.equal(error.code, "orders.not_found"); + assert.equal(root.isRuntimeErrorLike(error), true); + assert.deepEqual(root.toClientError(error, "req-1"), { error: { message: "No such order", code: error.code, requestId: "req-1" } }); + assert.equal(root.errorAttributes(error)["exception.type"], server.errorAttributes(error)["exception.type"]); + assert.equal(root.CODE_PATTERN.source, server.CODE_PATTERN.source); + assert.deepEqual(root.redactAttributes({ password: "hunter2", plan: "pro" }), server.redactAttributes({ password: "hunter2", plan: "pro" })); + assert.equal(root.redactText("Bearer abcdefghijklmnop"), server.redactText("Bearer abcdefghijklmnop")); + }); +} + +test("edge root: RuntimeError is @autter/runtime-edge's, the class @autter/runtime-next/edge checks", () => { + assert.equal(edge.RuntimeError, edgeSdk.RuntimeError); + assert.equal(edge.defineRuntimeErrors, edgeSdk.defineRuntimeErrors); + assert.equal(edge.toClientError, edgeSdk.toClientError); +}); diff --git a/packages/runtime-next/tsup.config.ts b/packages/runtime-next/tsup.config.ts index 35c6562..cfd464d 100644 --- a/packages/runtime-next/tsup.config.ts +++ b/packages/runtime-next/tsup.config.ts @@ -6,7 +6,7 @@ export default defineConfig([ format: ["esm", "cjs"], dts: true, target: "node20", - // No `clean` here: the three configs build in parallel and a clean in + // No `clean` here: the configs build in parallel and a clean in // one would race the others' declaration output. The build script // empties dist/ first instead. // Optional, resolved at runtime (after() wiring) — never bundled. @@ -32,6 +32,35 @@ export default defineConfig([ if (format === "cjs") options.supported = { ...options.supported, "dynamic-import": false }; }, }, + { + // Browser build of the root (the "browser" export condition): the + // isomorphic error helpers and stand-ins for the server-only names. + // No Node modules, no @autter/runtime-node, no React. + entry: { "index.browser": "src/index.browser.ts" }, + format: ["esm", "cjs"], + dts: { resolve: ["@autter/runtime-core"] }, + // es2020, not the client entry's es2019: runtime-core uses BigInt + // literals (in code this entry tree-shakes away, but esbuild parses it). + target: "es2020", + platform: "browser", + // Private workspace package: inlined, like runtime-node and runtime-edge do. + noExternal: ["@autter/runtime-core"], + // esbuild's browser platform would bake in NODE_ENV=development; leave + // `process.env.NODE_ENV` for the app's bundler to replace. + esbuildOptions(options) { + options.define = { ...options.define, "process.env.NODE_ENV": "process.env.NODE_ENV" }; + }, + }, + { + // Edge build of the root ("edge-light" / "worker"): the same contract, + // error helpers from @autter/runtime-edge. + entry: { "index.edge": "src/index.edge.ts" }, + format: ["esm", "cjs"], + dts: { resolve: ["@autter/runtime-core"] }, + target: "es2022", + platform: "neutral", + noExternal: ["@autter/runtime-core"], + }, { entry: { client: "src/client.ts" }, format: ["esm", "cjs"],