tempo-sdk 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,279 @@
1
+ # tempo-sdk
2
+
3
+ Tempo's JSX-annotation plugins for Vite and Next.js. At build time, every JSX
4
+ element in your codebase gets `data-tempo-*` attributes that map the rendered
5
+ DOM back to the exact source-file location that produced it. Tempo's design
6
+ surface uses these attributes to navigate from a clicked element to its source.
7
+
8
+ This package ships two plugins from one workspace:
9
+
10
+ - **`tempo-sdk`** — Vite plugin (`tempoVitePlugin`)
11
+ - **`tempo-sdk/nextjs`** — Next.js plugin (`tempoNextjsPlugin`)
12
+ - **`tempo-sdk/nextjs/plugin`** — default-exported Next.js plugin for ESM config files
13
+
14
+ Both produce byte-identical `data-tempo-*` output, so downstream consumers
15
+ (`source-editor.ts`, `frame-preload.ts`) work the same regardless of which
16
+ framework the user's project is on.
17
+
18
+ ---
19
+
20
+ ## Next.js usage
21
+
22
+ ### 1. Install
23
+
24
+ In a workspace package:
25
+
26
+ ```jsonc
27
+ {
28
+ "dependencies": { "tempo-sdk": "workspace:*" }
29
+ }
30
+ ```
31
+
32
+ In an external project: `pnpm add tempo-sdk` (or your package manager's equivalent).
33
+
34
+ ### 2. Wrap `next.config`
35
+
36
+ CommonJS (`next.config.js`):
37
+
38
+ ```js
39
+ const tempoNextjsPlugin = require("tempo-sdk/nextjs");
40
+
41
+ module.exports = tempoNextjsPlugin()({
42
+ reactStrictMode: true,
43
+ // ...rest of your existing config
44
+ });
45
+ ```
46
+
47
+ ESM (`next.config.mjs` / `next.config.ts`):
48
+
49
+ ```ts
50
+ import tempoNextjsPlugin from "tempo-sdk/nextjs/plugin";
51
+
52
+ export default tempoNextjsPlugin()({
53
+ reactStrictMode: true,
54
+ });
55
+ ```
56
+
57
+ You can also use the named export from `tempo-sdk/nextjs`:
58
+
59
+ ```ts
60
+ import { tempoNextjsPlugin } from "tempo-sdk/nextjs";
61
+ ```
62
+
63
+ ### 3. Set the `TEMPO` env var when launching dev
64
+
65
+ ```bash
66
+ TEMPO=true next dev # Turbopack (Next.js 16+ default)
67
+ TEMPO=true next dev --webpack # Webpack mode
68
+ ```
69
+
70
+ Without `TEMPO` set, the plugin is a complete no-op. You can leave
71
+ `tempoNextjsPlugin()` in `next.config.js` permanently — there is zero overhead
72
+ in normal dev. Tempo's start script sets `TEMPO=true` automatically when
73
+ launching the project under Tempo.
74
+
75
+ ### 4. App Router — that's it
76
+
77
+ The loader auto-injects `<meta name="tempo-project-root">` into the first JSX
78
+ `<head>` it sees (typically `app/layout.tsx`). Every JSX element in your project
79
+ gets `data-tempo-filepath`, `data-tempo-position`, `data-tempo-modifiedts`, and
80
+ `data-tempo-supports-*` attributes baked into the SWC-compiled output.
81
+
82
+ Example rendered HTML:
83
+
84
+ ```html
85
+ <button
86
+ data-tempo-filepath="components/Button.tsx"
87
+ data-tempo-position="142"
88
+ data-tempo-modifiedts="1708900000000"
89
+ data-tempo-supports-children="true"
90
+ >
91
+ Click me
92
+ </button>
93
+
94
+ <head>
95
+ <meta name="tempo-project-root" content="/abs/path/to/project" />
96
+ </head>
97
+ ```
98
+
99
+ ### 5. Pages Router — one extra line in `_document.tsx`
100
+
101
+ `<Head>` from `next/document` is a **custom** React component (capital H), not
102
+ intrinsic JSX `<head>` (lowercase), so auto-inject doesn't fire there. Add the
103
+ project-root meta manually:
104
+
105
+ ```tsx
106
+ // pages/_document.tsx
107
+ import { Html, Head, Main, NextScript } from "next/document";
108
+ import { tempoProjectRoot } from "tempo-sdk/nextjs";
109
+
110
+ export default function Document() {
111
+ return (
112
+ <Html>
113
+ <Head>
114
+ <meta name="tempo-project-root" content={tempoProjectRoot()} />
115
+ </Head>
116
+ <body>
117
+ <Main />
118
+ <NextScript />
119
+ </body>
120
+ </Html>
121
+ );
122
+ }
123
+ ```
124
+
125
+ `tempoProjectRoot()` returns the same canonical root the loader uses for
126
+ `data-tempo-filepath`, so paths reconstruct correctly.
127
+
128
+ ### Options
129
+
130
+ All optional:
131
+
132
+ ```js
133
+ tempoNextjsPlugin({
134
+ autoInjectRootMeta: false, // disable head meta auto-inject
135
+ productionBuild: true, // run in `next build` too (rare)
136
+ computeAnnotatedPropsModule: "./tempo-strategy.js", // custom prop-computation
137
+ })(nextConfig);
138
+ ```
139
+
140
+ `computeAnnotatedPropsModule` is a path (not a function) because Turbopack
141
+ requires loader options to be JSON-serializable. The module's default export
142
+ must be a function `(info, filepath, modifiedtsMs) => Record<string, PropValue>`.
143
+
144
+ ### Composing with other wrappers (`@next/mdx`, etc.)
145
+
146
+ `tempoNextjsPlugin` follows the `@next/mdx` higher-order-config pattern, so it
147
+ composes naturally:
148
+
149
+ ```js
150
+ const tempoNextjsPlugin = require("tempo-sdk/nextjs");
151
+ const withMDX = require("@next/mdx")();
152
+
153
+ module.exports = tempoNextjsPlugin()(
154
+ withMDX({ reactStrictMode: true })
155
+ );
156
+ ```
157
+
158
+ `tempoNextjsPlugin` should be the **outermost** wrapper so its webpack/turbopack
159
+ chaining sees the inner wrappers' contributions.
160
+
161
+ ### Supported Next.js versions
162
+
163
+ | Next.js | Webpack | Turbopack | Notes |
164
+ |---|---|---|---|
165
+ | 16.x | `--webpack` flag | default | Validated end-to-end |
166
+ | 15.3 – 15.x | default | `--turbo` flag | Wrapper writes to `turbopack.*` |
167
+ | 13.0 – 15.2 | default | `--turbo` flag | Wrapper writes to `experimental.turbo.*` |
168
+ | 12.x | default | n/a | Webpack only; turbopack field omitted |
169
+ | < 12 | n/a | n/a | Out of scope |
170
+
171
+ The wrapper detects the version via `next/package.json` and writes to the
172
+ correct field automatically.
173
+
174
+ ---
175
+
176
+ ## Vite usage
177
+
178
+ ```ts
179
+ // vite.config.ts
180
+ import { defineConfig } from "vite";
181
+ import react from "@vitejs/plugin-react";
182
+ import { tempoVitePlugin } from "tempo-sdk";
183
+
184
+ export default defineConfig({
185
+ plugins: [tempoVitePlugin(), react()],
186
+ });
187
+ ```
188
+
189
+ Same `TEMPO` env-var gating, same `data-tempo-*` output as the Next.js plugin.
190
+ The Vite plugin additionally exposes an `/__tempo/errors` SSE endpoint for
191
+ streaming compile errors to the design surface — see `SPEC.md` for the full
192
+ design.
193
+
194
+ ---
195
+
196
+ ## How it works
197
+
198
+ The Next.js plugin is a webpack-compatible loader (`nextjs-loader.cjs`) plus a
199
+ higher-order config wrapper (`tempoNextjsPlugin`) that registers the loader for
200
+ both Webpack and Turbopack from a single user-facing entrypoint.
201
+
202
+ The flow per source file:
203
+
204
+ 1. Resource gating — `.tsx`/`.jsx` only, exclude `node_modules`, require
205
+ `process.env.TEMPO`.
206
+ 2. Read mtime via `fs.statSync`.
207
+ 3. Compute project-relative filepath via `path.relative(rootContext, …)`.
208
+ 4. Call `annotateFile` from `@modules/annotation` with a callback that returns
209
+ the `data-tempo-*` props for each JSX element. The walker visits every
210
+ `JSXElement`, fragments are skipped, and props are inserted as JSX
211
+ attribute strings at the end of each opening tag.
212
+ 5. If the file contains an intrinsic JSX `<head>`, splice
213
+ `<meta name="tempo-project-root" content="…" />` into the post-annotation
214
+ source. The injected meta does not itself carry `data-tempo-*` attrs (it has
215
+ no source location), which keeps every other element's `data-tempo-position`
216
+ pointing at the byte offset of `<` in the on-disk source file.
217
+ 6. Return the annotated source. Errors at any step cause the loader to return
218
+ the original source unchanged — `correct or untouched, always`.
219
+
220
+ The `tempoNextjsPlugin` wrapper:
221
+
222
+ - Adds an `enforce: "pre"` rule under `config.module.rules` for Webpack
223
+ (`/.(tsx|jsx)$/`).
224
+ - Adds a `*.{tsx,jsx}` rule under `nextConfig.turbopack.rules` for Turbopack
225
+ with `condition: { all: [{ not: "foreign" }, "development"] }` (excludes
226
+ node_modules / Next internals AND production builds).
227
+ - Chains an existing user-supplied `webpack(config, options)` function and
228
+ merges with any existing `turbopack.rules` so other plugins are preserved.
229
+ - No-ops entirely when `process.env.TEMPO` is not set.
230
+
231
+ See `SPEC_NEXTJS.md` for the complete design specification.
232
+
233
+ ---
234
+
235
+ ## Demo
236
+
237
+ ```bash
238
+ pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev # Turbopack on :3477
239
+ pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev:webpack # Webpack on :3478
240
+ ```
241
+
242
+ Then:
243
+
244
+ ```bash
245
+ curl -s localhost:3477/ | grep -oE 'data-tempo-filepath="[^"]+"' | sort -u
246
+ ```
247
+
248
+ Should print one line per source file rendered on the home page.
249
+
250
+ ---
251
+
252
+ ## Tests
253
+
254
+ ```bash
255
+ pnpm test # all 308 tests across both plugins
256
+ pnpm test:nextjs # 175 Next.js tests (~24s)
257
+ pnpm test:nextjs:unit # fast unit tests, no servers
258
+ pnpm test:nextjs:integration # live `next dev` against demo (Turbopack + Webpack)
259
+ pnpm test:nextjs:production # `next build` correctness (no annotations in prod)
260
+ ```
261
+
262
+ Test layers:
263
+
264
+ | File | Tests | Coverage |
265
+ |---|---|---|
266
+ | `nextjs-loader.test.ts` | 41 | Loader function — file filtering, default strategy, auto-inject, error handling |
267
+ | `nextjs-wrapper.test.ts` | 26 | `tempoNextjsPlugin` — webpack chaining, turbopack merging, version detection, options |
268
+ | `nextjs-fixtures.test.ts` | 40 | Project shapes — App/Pages Router, server/client components, all routing types |
269
+ | `nextjs-published.test.ts` | 14 | Built `dist/*.cjs` and `dist/*.js` — CJS callable, ESM imports, parity |
270
+ | `nextjs-production.test.ts` | 6 | `next build` produces zero `data-tempo-*` attributes |
271
+ | `nextjs-e2e-correctness.test.ts` | — | Live `next dev` against demo (both bundlers); every recorded `data-tempo-position` actually points at `<` in the on-disk source file |
272
+
273
+ ---
274
+
275
+ ## Related docs
276
+
277
+ - `SPEC.md` — Vite plugin specification
278
+ - `SPEC_NEXTJS.md` — Next.js plugin specification
279
+ - `SPEC_TSC.md` — TypeScript type-analyzer (used by both plugins for `data-tempo-supports-*`)
@@ -0,0 +1,173 @@
1
+ // nextjs.ts
2
+ import { existsSync, realpathSync } from "fs";
3
+ import { createRequire } from "module";
4
+ import { dirname, resolve } from "path";
5
+ var TURBOPACK_RULE_KEY = "*.{tsx,jsx}";
6
+ var requireFromHere = createRequire(
7
+ typeof import.meta.url === "string" && import.meta.url.length > 0 ? import.meta.url : __filename
8
+ );
9
+ function resolveLoaderPath() {
10
+ for (const candidate of ["./nextjs-loader.cjs", "./dist/nextjs-loader.cjs"]) {
11
+ try {
12
+ return requireFromHere.resolve(candidate);
13
+ } catch {
14
+ }
15
+ }
16
+ throw new Error(
17
+ "tempo-sdk/nextjs: could not resolve nextjs-loader.cjs. Run `pnpm build` in the tempo-sdk package to produce the dist/ output."
18
+ );
19
+ }
20
+ function detectNextVersion() {
21
+ try {
22
+ const pkg = requireFromHere("next/package.json");
23
+ const m = /^(\d+)\.(\d+)/.exec(pkg.version);
24
+ if (!m) return null;
25
+ return { major: Number(m[1]), minor: Number(m[2]) };
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ function useExperimentalTurbo(version) {
31
+ if (!version) return false;
32
+ if (version.major < 15) return true;
33
+ if (version.major === 15 && version.minor < 3) return true;
34
+ return false;
35
+ }
36
+ function shouldOmitTurbopack(version) {
37
+ if (!version) return false;
38
+ return version.major < 13;
39
+ }
40
+ function buildTurbopackRule(loaderPath, options) {
41
+ const loaderOptions = {};
42
+ if (options.computeAnnotatedPropsModule !== void 0) {
43
+ loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;
44
+ }
45
+ if (options.autoInjectRootMeta !== void 0) {
46
+ loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;
47
+ }
48
+ const condition = options.productionBuild ? { not: "foreign" } : { all: [{ not: "foreign" }, "development"] };
49
+ return {
50
+ condition,
51
+ loaders: [{ loader: loaderPath, options: loaderOptions }]
52
+ };
53
+ }
54
+ function mergeTurbopackRules(existing, newRule) {
55
+ const existingRule = existing?.rules?.[TURBOPACK_RULE_KEY];
56
+ let mergedRule;
57
+ if (!existingRule) {
58
+ mergedRule = newRule;
59
+ } else if (Array.isArray(existingRule)) {
60
+ mergedRule = [...existingRule, newRule];
61
+ } else {
62
+ mergedRule = [existingRule, newRule];
63
+ }
64
+ return {
65
+ ...existing,
66
+ rules: {
67
+ ...existing?.rules,
68
+ [TURBOPACK_RULE_KEY]: mergedRule
69
+ }
70
+ };
71
+ }
72
+ function buildWebpackHook(loaderPath, options, userWebpack) {
73
+ const loaderOptions = {};
74
+ if (options.computeAnnotatedPropsModule !== void 0) {
75
+ loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;
76
+ }
77
+ if (options.autoInjectRootMeta !== void 0) {
78
+ loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;
79
+ }
80
+ const allowProduction = options.productionBuild === true;
81
+ return (configIn, context) => {
82
+ var _a;
83
+ const config = configIn;
84
+ const ctx = context;
85
+ if (ctx.dev || allowProduction) {
86
+ config.module ?? (config.module = {});
87
+ (_a = config.module).rules ?? (_a.rules = []);
88
+ config.module.rules.push({
89
+ test: /\.(tsx|jsx)$/,
90
+ exclude: /node_modules/,
91
+ enforce: "pre",
92
+ use: [{ loader: loaderPath, options: loaderOptions }]
93
+ });
94
+ }
95
+ if (typeof userWebpack === "function") {
96
+ return userWebpack(config, context);
97
+ }
98
+ return config;
99
+ };
100
+ }
101
+ var cachedTempoProjectRoot = null;
102
+ function tempoProjectRoot() {
103
+ if (cachedTempoProjectRoot !== null) return cachedTempoProjectRoot;
104
+ let dir = process.cwd();
105
+ while (true) {
106
+ if (existsSync(resolve(dir, "package.json"))) break;
107
+ const parent = dirname(dir);
108
+ if (parent === dir) break;
109
+ dir = parent;
110
+ }
111
+ let canonical = dir;
112
+ try {
113
+ canonical = realpathSync.native(dir);
114
+ } catch {
115
+ }
116
+ cachedTempoProjectRoot = canonical;
117
+ return canonical;
118
+ }
119
+ function _resetTempoProjectRoot() {
120
+ cachedTempoProjectRoot = null;
121
+ }
122
+ function tempoNextjsPlugin(pluginOptions = {}) {
123
+ return (inputConfigArg) => {
124
+ const inputConfig = inputConfigArg ?? {};
125
+ if (!process.env.TEMPO) return inputConfig;
126
+ const loaderPath = _internal.resolveLoaderPath();
127
+ const version = _internal.detectNextVersion();
128
+ const omitTurbopack = _internal.shouldOmitTurbopack(version);
129
+ const useExperimental = _internal.useExperimentalTurbo(version);
130
+ const newRule = buildTurbopackRule(loaderPath, pluginOptions);
131
+ const existingTurbo = useExperimental ? inputConfig.experimental?.turbo : inputConfig.turbopack;
132
+ const mergedTurbo = mergeTurbopackRules(existingTurbo, newRule);
133
+ const webpackHook = buildWebpackHook(
134
+ loaderPath,
135
+ pluginOptions,
136
+ inputConfig.webpack ?? null
137
+ );
138
+ const next = {
139
+ ...inputConfig,
140
+ webpack: webpackHook
141
+ };
142
+ if (!omitTurbopack) {
143
+ if (useExperimental) {
144
+ next.experimental = {
145
+ ...inputConfig.experimental,
146
+ turbo: mergedTurbo
147
+ };
148
+ } else {
149
+ next.turbopack = mergedTurbo;
150
+ }
151
+ }
152
+ return next;
153
+ };
154
+ }
155
+ var nextjs_default = tempoNextjsPlugin;
156
+ var _internal = {
157
+ buildTurbopackRule,
158
+ mergeTurbopackRules,
159
+ buildWebpackHook,
160
+ detectNextVersion,
161
+ useExperimentalTurbo,
162
+ shouldOmitTurbopack,
163
+ resolveLoaderPath
164
+ };
165
+
166
+ export {
167
+ tempoProjectRoot,
168
+ _resetTempoProjectRoot,
169
+ tempoNextjsPlugin,
170
+ nextjs_default,
171
+ _internal
172
+ };
173
+ //# sourceMappingURL=chunk-BRNAFXET.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../nextjs.ts"],"sourcesContent":["/**\n * Next.js plugin that registers the tempo-annotate loader for Webpack and\n * Turbopack. Mirrors the user-facing pattern of `@next/mdx`: a higher-order\n * function that takes plugin options, returns a function that takes the user's\n * `next.config`, and returns a new config with the plugin's loader rules\n * merged in.\n *\n * See SPEC_NEXTJS.md (in this directory) for the full design rationale.\n *\n * @example\n * ```js\n * // next.config.js\n * const tempoNextjsPlugin = require(\"tempo-sdk/nextjs\");\n * module.exports = tempoNextjsPlugin()({ reactStrictMode: true });\n * ```\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\n\nimport type { ElementInfo, PropValue } from \"@modules/annotation\";\n\n// ---------------------------------------------------------------------------\n// Types. We keep these minimal and self-contained rather than depending on\n// Next.js types — the plugin file is loaded by `next.config.js` evaluation,\n// before `next` itself is fully resolved in some environments.\n// ---------------------------------------------------------------------------\n\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoNextjsOptions {\n /** Path to a JS/TS module that default-exports a `ComputeAnnotatedProps`\n * function. Resolved relative to the project root (CWD where the user\n * invokes `next dev` / `next build`). Turbopack does not allow function-\n * valued loader options, so this must be a path. */\n computeAnnotatedPropsModule?: string;\n\n /** File patterns to include. Default: `[\"**\\/*.tsx\", \"**\\/*.jsx\"]`. */\n include?: string | RegExp | Array<string | RegExp>;\n\n /** File patterns to exclude. Default: `[\"**\\/node_modules\\/**\"]`. */\n exclude?: string | RegExp | Array<string | RegExp>;\n\n /** Auto-inject `<meta name=\"tempo-project-root\">` into JSX `<head>`.\n * Default: `true`. */\n autoInjectRootMeta?: boolean;\n\n /** Run the loader during production builds too. Default: `false`. */\n productionBuild?: boolean;\n}\n\ninterface TurbopackRule {\n condition?: unknown;\n loaders?: Array<{ loader: string; options?: unknown } | string>;\n}\n\ninterface TurbopackConfig {\n rules?: Record<string, TurbopackRule | TurbopackRule[]>;\n [key: string]: unknown;\n}\n\ninterface NextConfigLike {\n webpack?: ((config: unknown, context: { dev: boolean; [k: string]: unknown }) => unknown) | null;\n turbopack?: TurbopackConfig;\n experimental?: { turbo?: TurbopackConfig; [k: string]: unknown };\n [key: string]: unknown;\n}\n\ntype NextConfigInput = NextConfigLike | undefined;\n\ninterface WebpackHookContext {\n dev: boolean;\n [key: string]: unknown;\n}\n\ninterface WebpackConfigLike {\n module?: { rules?: unknown[] };\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst TURBOPACK_RULE_KEY = \"*.{tsx,jsx}\";\n\nconst requireFromHere = createRequire(\n typeof import.meta.url === \"string\" && import.meta.url.length > 0\n ? import.meta.url\n : __filename,\n);\n\nfunction resolveLoaderPath(): string {\n // Production: dist/nextjs.{js,cjs} sits next to dist/nextjs-loader.cjs.\n // Development: source nextjs.ts sits at <pkg>/nextjs.ts; the built\n // loader is at <pkg>/dist/nextjs-loader.cjs. Try both so unit tests\n // running directly against the .ts source file still find the loader.\n for (const candidate of [\"./nextjs-loader.cjs\", \"./dist/nextjs-loader.cjs\"]) {\n try {\n return requireFromHere.resolve(candidate);\n } catch {\n // try next candidate\n }\n }\n throw new Error(\n \"tempo-sdk/nextjs: could not resolve nextjs-loader.cjs. \" +\n \"Run `pnpm build` in the tempo-sdk package to produce the dist/ output.\",\n );\n}\n\ninterface NextVersionInfo {\n major: number;\n minor: number;\n}\n\nfunction detectNextVersion(): NextVersionInfo | null {\n try {\n const pkg = requireFromHere(\"next/package.json\") as { version: string };\n const m = /^(\\d+)\\.(\\d+)/.exec(pkg.version);\n if (!m) return null;\n return { major: Number(m[1]), minor: Number(m[2]) };\n } catch {\n return null;\n }\n}\n\n/** Should the wrapper write to `experimental.turbo` instead of `turbopack`? */\nfunction useExperimentalTurbo(version: NextVersionInfo | null): boolean {\n if (!version) return false;\n if (version.major < 15) return true;\n if (version.major === 15 && version.minor < 3) return true;\n return false;\n}\n\n/** Should the wrapper omit Turbopack registration entirely? Some pre-13 versions\n * error on unknown config keys. */\nfunction shouldOmitTurbopack(version: NextVersionInfo | null): boolean {\n if (!version) return false;\n return version.major < 13;\n}\n\nfunction buildTurbopackRule(\n loaderPath: string,\n options: TempoNextjsOptions,\n): TurbopackRule {\n const loaderOptions: Record<string, unknown> = {};\n if (options.computeAnnotatedPropsModule !== undefined) {\n loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;\n }\n if (options.autoInjectRootMeta !== undefined) {\n loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;\n }\n\n // {all: [{not: \"foreign\"}, \"development\"]} — exclude node_modules / Next\n // internals AND only run during `next dev`. The \"development\" condition is\n // a Turbopack built-in; it matches both `next dev` and `next build` in dev\n // mode but is inert during a production `next build`.\n const condition = options.productionBuild\n ? { not: \"foreign\" }\n : { all: [{ not: \"foreign\" }, \"development\"] };\n\n return {\n condition,\n loaders: [{ loader: loaderPath, options: loaderOptions }],\n };\n}\n\nfunction mergeTurbopackRules(\n existing: TurbopackConfig | undefined,\n newRule: TurbopackRule,\n): TurbopackConfig {\n const existingRule = existing?.rules?.[TURBOPACK_RULE_KEY];\n let mergedRule: TurbopackRule | TurbopackRule[];\n if (!existingRule) {\n mergedRule = newRule;\n } else if (Array.isArray(existingRule)) {\n mergedRule = [...existingRule, newRule];\n } else {\n mergedRule = [existingRule, newRule];\n }\n return {\n ...existing,\n rules: {\n ...existing?.rules,\n [TURBOPACK_RULE_KEY]: mergedRule,\n },\n };\n}\n\nfunction buildWebpackHook(\n loaderPath: string,\n options: TempoNextjsOptions,\n userWebpack: NextConfigLike[\"webpack\"],\n): NonNullable<NextConfigLike[\"webpack\"]> {\n const loaderOptions: Record<string, unknown> = {};\n if (options.computeAnnotatedPropsModule !== undefined) {\n loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;\n }\n if (options.autoInjectRootMeta !== undefined) {\n loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;\n }\n\n const allowProduction = options.productionBuild === true;\n\n return (configIn, context) => {\n const config = configIn as WebpackConfigLike;\n const ctx = context as WebpackHookContext;\n if (ctx.dev || allowProduction) {\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: /\\.(tsx|jsx)$/,\n exclude: /node_modules/,\n enforce: \"pre\",\n use: [{ loader: loaderPath, options: loaderOptions }],\n });\n }\n if (typeof userWebpack === \"function\") {\n return userWebpack(config, context);\n }\n return config;\n };\n}\n\n// ---------------------------------------------------------------------------\n// tempoProjectRoot — sync helper for Pages Router users (Section 6.4)\n// ---------------------------------------------------------------------------\n\nlet cachedTempoProjectRoot: string | null = null;\n\n/**\n * Returns the canonical project root that the Tempo loader uses to compute\n * `data-tempo-filepath` values. Use this in `pages/_document.tsx` to set the\n * content of `<meta name=\"tempo-project-root\">`, ensuring the manual meta tag\n * value matches what the loader produces.\n */\nexport function tempoProjectRoot(): string {\n if (cachedTempoProjectRoot !== null) return cachedTempoProjectRoot;\n\n // Walk upward from CWD looking for the nearest package.json. CWD is what\n // Next.js itself uses as the project root when the user invokes\n // `next dev` / `next build` — the loader's `rootContext` matches.\n let dir = process.cwd();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (existsSync(resolve(dir, \"package.json\"))) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n let canonical = dir;\n try {\n canonical = realpathSync.native(dir);\n } catch {\n // Keep `dir` as fallback.\n }\n cachedTempoProjectRoot = canonical;\n return canonical;\n}\n\n/** Reset the cached project root. For tests only. */\nexport function _resetTempoProjectRoot(): void {\n cachedTempoProjectRoot = null;\n}\n\n// ---------------------------------------------------------------------------\n// tempoNextjsPlugin — the wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Higher-order function that wraps a Next.js config to register the\n * tempo-annotate loader with both Webpack and Turbopack. No-op when\n * `process.env.TEMPO` is not set.\n *\n * @example\n * ```js\n * // next.config.js\n * const tempoNextjsPlugin = require(\"tempo-sdk/nextjs\");\n * module.exports = tempoNextjsPlugin()({ reactStrictMode: true });\n * ```\n */\nexport function tempoNextjsPlugin(\n pluginOptions: TempoNextjsOptions = {},\n): (inputConfig?: NextConfigLike) => NextConfigLike {\n return (inputConfigArg?: NextConfigLike): NextConfigLike => {\n const inputConfig: NextConfigLike = inputConfigArg ?? {};\n\n if (!process.env.TEMPO) return inputConfig;\n\n // Routed through `_internal.*` so unit tests can spy on these helpers\n // without rewiring the imports.\n const loaderPath = _internal.resolveLoaderPath();\n const version = _internal.detectNextVersion();\n const omitTurbopack = _internal.shouldOmitTurbopack(version);\n const useExperimental = _internal.useExperimentalTurbo(version);\n\n const newRule = buildTurbopackRule(loaderPath, pluginOptions);\n\n const existingTurbo = useExperimental\n ? inputConfig.experimental?.turbo\n : inputConfig.turbopack;\n const mergedTurbo = mergeTurbopackRules(existingTurbo, newRule);\n\n const webpackHook = buildWebpackHook(\n loaderPath,\n pluginOptions,\n inputConfig.webpack ?? null,\n );\n\n const next: NextConfigLike = {\n ...inputConfig,\n webpack: webpackHook,\n };\n\n if (!omitTurbopack) {\n if (useExperimental) {\n next.experimental = {\n ...inputConfig.experimental,\n turbo: mergedTurbo,\n };\n } else {\n next.turbopack = mergedTurbo;\n }\n }\n\n return next;\n };\n}\n\nexport default tempoNextjsPlugin;\n\n// ---------------------------------------------------------------------------\n// Type re-exports for users writing custom strategies.\n// ---------------------------------------------------------------------------\n\nexport type { ElementInfo, PropValue } from \"@modules/annotation\";\n\n// Internal exports used by tests.\nexport const _internal = {\n buildTurbopackRule,\n mergeTurbopackRules,\n buildWebpackHook,\n detectNextVersion,\n useExperimentalTurbo,\n shouldOmitTurbopack,\n resolveLoaderPath,\n};\n"],"mappings":";AAiBA,SAAS,YAAY,oBAAoB;AACzC,SAAS,qBAAqB;AAC9B,SAAS,SAAS,eAAe;AAsEjC,IAAM,qBAAqB;AAE3B,IAAM,kBAAkB;AAAA,EACtB,OAAO,YAAY,QAAQ,YAAY,YAAY,IAAI,SAAS,IAC5D,YAAY,MACZ;AACN;AAEA,SAAS,oBAA4B;AAKnC,aAAW,aAAa,CAAC,uBAAuB,0BAA0B,GAAG;AAC3E,QAAI;AACF,aAAO,gBAAgB,QAAQ,SAAS;AAAA,IAC1C,QAAQ;AAAA,IAER;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;AACF;AAOA,SAAS,oBAA4C;AACn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AoC,CAAC,GACa;AAClD,SAAO,CAAC,mBAAoD;AAC1D,UAAM,cAA8B,kBAAkB,CAAC;AAEvD,QAAI,CAAC,QAAQ,IAAI,MAAO,QAAO;AAI/B,UAAM,aAAa,UAAU,kBAAkB;AAC/C,UAAM,UAAU,UAAU,kBAAkB;AAC5C,UAAM,gBAAgB,UAAU,oBAAoB,OAAO;AAC3D,UAAM,kBAAkB,UAAU,qBAAqB,OAAO;AAE9D,UAAM,UAAU,mBAAmB,YAAY,aAAa;AAE5D,UAAM,gBAAgB,kBAClB,YAAY,cAAc,QAC1B,YAAY;AAChB,UAAM,cAAc,oBAAoB,eAAe,OAAO;AAE9D,UAAM,cAAc;AAAA,MAClB;AAAA,MACA;AAAA,MACA,YAAY,WAAW;AAAA,IACzB;AAEA,UAAM,OAAuB;AAAA,MAC3B,GAAG;AAAA,MACH,SAAS;AAAA,IACX;AAEA,QAAI,CAAC,eAAe;AAClB,UAAI,iBAAiB;AACnB,aAAK,eAAe;AAAA,UAClB,GAAG,YAAY;AAAA,UACf,OAAO;AAAA,QACT;AAAA,MACF,OAAO;AACL,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,iBAAQ;AASR,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -0,0 +1,171 @@
1
+ // nextjs.ts
2
+ import { existsSync, realpathSync } from "fs";
3
+ import { createRequire } from "module";
4
+ import { dirname, resolve } from "path";
5
+ var TURBOPACK_RULE_KEY = "*.{tsx,jsx}";
6
+ var requireFromHere = createRequire(import.meta.url);
7
+ function resolveLoaderPath() {
8
+ for (const candidate of ["./nextjs-loader.cjs", "./dist/nextjs-loader.cjs"]) {
9
+ try {
10
+ return requireFromHere.resolve(candidate);
11
+ } catch {
12
+ }
13
+ }
14
+ throw new Error(
15
+ "tempo-sdk/nextjs: could not resolve nextjs-loader.cjs. Run `pnpm build` in the tempo-sdk package to produce the dist/ output."
16
+ );
17
+ }
18
+ function detectNextVersion() {
19
+ try {
20
+ const pkg = requireFromHere("next/package.json");
21
+ const m = /^(\d+)\.(\d+)/.exec(pkg.version);
22
+ if (!m) return null;
23
+ return { major: Number(m[1]), minor: Number(m[2]) };
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function useExperimentalTurbo(version) {
29
+ if (!version) return false;
30
+ if (version.major < 15) return true;
31
+ if (version.major === 15 && version.minor < 3) return true;
32
+ return false;
33
+ }
34
+ function shouldOmitTurbopack(version) {
35
+ if (!version) return false;
36
+ return version.major < 13;
37
+ }
38
+ function buildTurbopackRule(loaderPath, options) {
39
+ const loaderOptions = {};
40
+ if (options.computeAnnotatedPropsModule !== void 0) {
41
+ loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;
42
+ }
43
+ if (options.autoInjectRootMeta !== void 0) {
44
+ loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;
45
+ }
46
+ const condition = options.productionBuild ? { not: "foreign" } : { all: [{ not: "foreign" }, "development"] };
47
+ return {
48
+ condition,
49
+ loaders: [{ loader: loaderPath, options: loaderOptions }]
50
+ };
51
+ }
52
+ function mergeTurbopackRules(existing, newRule) {
53
+ const existingRule = existing?.rules?.[TURBOPACK_RULE_KEY];
54
+ let mergedRule;
55
+ if (!existingRule) {
56
+ mergedRule = newRule;
57
+ } else if (Array.isArray(existingRule)) {
58
+ mergedRule = [...existingRule, newRule];
59
+ } else {
60
+ mergedRule = [existingRule, newRule];
61
+ }
62
+ return {
63
+ ...existing,
64
+ rules: {
65
+ ...existing?.rules,
66
+ [TURBOPACK_RULE_KEY]: mergedRule
67
+ }
68
+ };
69
+ }
70
+ function buildWebpackHook(loaderPath, options, userWebpack) {
71
+ const loaderOptions = {};
72
+ if (options.computeAnnotatedPropsModule !== void 0) {
73
+ loaderOptions.computeAnnotatedPropsModule = options.computeAnnotatedPropsModule;
74
+ }
75
+ if (options.autoInjectRootMeta !== void 0) {
76
+ loaderOptions.autoInjectRootMeta = options.autoInjectRootMeta;
77
+ }
78
+ const allowProduction = options.productionBuild === true;
79
+ return (configIn, context) => {
80
+ var _a;
81
+ const config = configIn;
82
+ const ctx = context;
83
+ if (ctx.dev || allowProduction) {
84
+ config.module ?? (config.module = {});
85
+ (_a = config.module).rules ?? (_a.rules = []);
86
+ config.module.rules.push({
87
+ test: /\.(tsx|jsx)$/,
88
+ exclude: /node_modules/,
89
+ enforce: "pre",
90
+ use: [{ loader: loaderPath, options: loaderOptions }]
91
+ });
92
+ }
93
+ if (typeof userWebpack === "function") {
94
+ return userWebpack(config, context);
95
+ }
96
+ return config;
97
+ };
98
+ }
99
+ var cachedTempoProjectRoot = null;
100
+ function tempoProjectRoot() {
101
+ if (cachedTempoProjectRoot !== null) return cachedTempoProjectRoot;
102
+ let dir = process.cwd();
103
+ while (true) {
104
+ if (existsSync(resolve(dir, "package.json"))) break;
105
+ const parent = dirname(dir);
106
+ if (parent === dir) break;
107
+ dir = parent;
108
+ }
109
+ let canonical = dir;
110
+ try {
111
+ canonical = realpathSync.native(dir);
112
+ } catch {
113
+ }
114
+ cachedTempoProjectRoot = canonical;
115
+ return canonical;
116
+ }
117
+ function _resetTempoProjectRoot() {
118
+ cachedTempoProjectRoot = null;
119
+ }
120
+ function tempoNextjsPlugin(pluginOptions = {}) {
121
+ return (inputConfigArg) => {
122
+ const inputConfig = inputConfigArg ?? {};
123
+ if (!process.env.TEMPO) return inputConfig;
124
+ const loaderPath = _internal.resolveLoaderPath();
125
+ const version = _internal.detectNextVersion();
126
+ const omitTurbopack = _internal.shouldOmitTurbopack(version);
127
+ const useExperimental = _internal.useExperimentalTurbo(version);
128
+ const newRule = buildTurbopackRule(loaderPath, pluginOptions);
129
+ const existingTurbo = useExperimental ? inputConfig.experimental?.turbo : inputConfig.turbopack;
130
+ const mergedTurbo = mergeTurbopackRules(existingTurbo, newRule);
131
+ const webpackHook = buildWebpackHook(
132
+ loaderPath,
133
+ pluginOptions,
134
+ inputConfig.webpack ?? null
135
+ );
136
+ const next = {
137
+ ...inputConfig,
138
+ webpack: webpackHook
139
+ };
140
+ if (!omitTurbopack) {
141
+ if (useExperimental) {
142
+ next.experimental = {
143
+ ...inputConfig.experimental,
144
+ turbo: mergedTurbo
145
+ };
146
+ } else {
147
+ next.turbopack = mergedTurbo;
148
+ }
149
+ }
150
+ return next;
151
+ };
152
+ }
153
+ var nextjs_default = tempoNextjsPlugin;
154
+ var _internal = {
155
+ buildTurbopackRule,
156
+ mergeTurbopackRules,
157
+ buildWebpackHook,
158
+ detectNextVersion,
159
+ useExperimentalTurbo,
160
+ shouldOmitTurbopack,
161
+ resolveLoaderPath
162
+ };
163
+
164
+ export {
165
+ tempoProjectRoot,
166
+ _resetTempoProjectRoot,
167
+ tempoNextjsPlugin,
168
+ nextjs_default,
169
+ _internal
170
+ };
171
+ //# sourceMappingURL=chunk-FIAAEHXK.js.map