@decocms/tanstack 8.0.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +86 -31
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -44
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/cms/kvBlockSource.test.ts +0 -82
  109. package/src/cms/kvBlockSource.ts +0 -68
  110. package/src/daemon/auth.ts +0 -204
  111. package/src/daemon/fs.ts +0 -238
  112. package/src/daemon/index.ts +0 -8
  113. package/src/daemon/middleware.ts +0 -156
  114. package/src/daemon/tunnel.ts +0 -129
  115. package/src/daemon/volumes.ts +0 -366
  116. package/src/daemon/watch.ts +0 -272
  117. package/src/hooks/DecoPageRenderer.tsx +0 -688
  118. package/src/hooks/DecoRootLayout.tsx +0 -111
  119. package/src/hooks/NavigationProgress.tsx +0 -21
  120. package/src/hooks/PreviewProviders.tsx +0 -26
  121. package/src/hooks/StableOutlet.tsx +0 -30
  122. package/src/hooks/index.ts +0 -9
  123. package/src/routes/adminRoutes.test.ts +0 -99
  124. package/src/routes/adminRoutes.ts +0 -153
  125. package/src/routes/cmsRoute.test.ts +0 -100
  126. package/src/routes/cmsRoute.ts +0 -944
  127. package/src/routes/components.tsx +0 -57
  128. package/src/routes/index.ts +0 -24
  129. package/src/routes/pageUrl.test.ts +0 -70
  130. package/src/routes/pageUrl.ts +0 -54
  131. package/src/routes/withSiteGlobals.test.ts +0 -206
  132. package/src/routes/withSiteGlobals.ts +0 -222
  133. package/src/sdk/cookiePassthrough.ts +0 -58
  134. package/src/sdk/createInvoke.ts +0 -77
  135. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  136. package/src/sdk/deferredSectionLoader.ts +0 -46
  137. package/src/sdk/kvHydration.test.ts +0 -215
  138. package/src/sdk/kvHydration.ts +0 -193
  139. package/src/sdk/outboundHeaders.test.ts +0 -113
  140. package/src/sdk/outboundHeaders.ts +0 -81
  141. package/src/sdk/router.ts +0 -92
  142. package/src/sdk/useHydrated.ts +0 -19
  143. package/src/sdk/workerEntry.test.ts +0 -495
  144. package/src/sdk/workerEntry.ts +0 -2307
  145. package/src/setupFastDeploy.ts +0 -13
  146. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  147. package/src/vite/plugin.js +0 -850
  148. package/src/vite/plugin.test.js +0 -113
  149. package/src/vite/plugin.test.ts +0 -52
  150. package/tsconfig.json +0 -7
@@ -1,850 +0,0 @@
1
- /**
2
- * Deco Vite plugin — server-only stubs for TanStack Start storefronts.
3
- *
4
- * Replaces server-only modules with lightweight client stubs so they
5
- * are eliminated from the browser bundle. This consolidates stubs that
6
- * every Deco site previously had to copy into its own vite.config.ts.
7
- *
8
- * blocks.gen.ts handling:
9
- * The CMS block registry can be 10MB+. Inlining it as a JS object literal
10
- * causes Vite's SSR module runner to hang on dynamic imports (transport
11
- * serialization bottleneck) and is slow to parse even with static imports
12
- * (V8 full JS parser). Instead, generate-blocks.ts writes a .json data
13
- * file, and this plugin intercepts the .ts import to return JSON.parse(...)
14
- * — V8's JSON parser is 2-10x faster than the JS parser for large data.
15
- *
16
- * meta.gen handling:
17
- * The admin schema bundle (`.deco/meta.gen.json`) is server-only;
18
- * the client receives pre-resolved blocks via the SSR payload. Stubbing
19
- * it on the client cuts a typically-large module out of the browser bundle.
20
- * Match is done by substring on the import id, so any path style works.
21
- *
22
- * loaders.gen.ts handling:
23
- * The site invoke registry (`export const siteLoaders`) registers every site
24
- * loader/action behind a dynamic `import()`. It is reachable from the client
25
- * entry (router -> setup -> commerce-loaders -> loaders.gen), so without a stub
26
- * Vite emits each loader/action module as a public client chunk — leaking the
27
- * module source (including any hardcoded credential) into the browser assets.
28
- * Invoke runs server-side only, so the client never needs it. Stubbed to an
29
- * empty object on the client; SSR keeps the real module.
30
- *
31
- * manualChunks:
32
- * `@decocms/tanstack` and `@decocms/apps` are intentionally NOT split
33
- * into their own chunks. They have circular re-exports that produce a
34
- * load-order crash when chunked separately. Rollup's default bundling
35
- * (group with importer or vendor catch-all) avoids that.
36
- *
37
- * Usage:
38
- * ```ts
39
- * import { decoVitePlugin } from "@decocms/tanstack/vite";
40
- * export default defineConfig({ plugins: [decoVitePlugin(), ...] });
41
- * ```
42
- */
43
- import { exec, execFileSync } from "node:child_process";
44
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
45
- import path from "node:path";
46
-
47
- /**
48
- * Resolve a per-build identifier for cache-key versioning.
49
- *
50
- * The returned string is injected into the worker bundle as the
51
- * `__DECO_BUILD_HASH__` global via Vite `define`. `createDecoWorkerEntry`
52
- * appends it (or `env.BUILD_HASH` if explicitly set) as `__v=<hash>` on
53
- * every Cache API key, so each new deploy gets its own cache namespace
54
- * — old edge-cached HTML referencing dead asset filenames stops being
55
- * served the moment the new worker is live.
56
- *
57
- * Resolution order:
58
- * 1. WORKERS_CI_COMMIT_SHA — Cloudflare Workers Builds default env var
59
- * (the production deploy path-of-record). Sliced to 12 chars.
60
- * 2. `git rev-parse --short=12 HEAD` — local `wrangler deploy` from a
61
- * developer laptop. Try/catch so missing git or shallow clones don't
62
- * fail the build.
63
- * 3. `Date.now().toString(36)` — last-resort fallback so the cache-bust
64
- * invariant never silently regresses to "always the same key".
65
- *
66
- * For dev (`command !== "build"`), the value is the literal `"dev"`.
67
- *
68
- * @returns {string}
69
- */
70
- function resolveBuildHash() {
71
- const ciSha = process.env.WORKERS_CI_COMMIT_SHA;
72
- if (ciSha?.trim()) return ciSha.trim().slice(0, 12);
73
-
74
- try {
75
- const sha = execFileSync("git", ["rev-parse", "--short=12", "HEAD"], {
76
- encoding: "utf-8",
77
- stdio: ["ignore", "pipe", "ignore"],
78
- }).trim();
79
- if (sha) return sha;
80
- } catch {
81
- // git absent, not a repo, or shallow clone w/o history — fall through.
82
- }
83
-
84
- return Date.now().toString(36);
85
- }
86
-
87
- // Bare-specifier stubs resolved by ID before Vite touches them.
88
- /** @type {Record<string, string>} */
89
- const CLIENT_STUBS = {
90
- "react-dom/server": "\0stub:react-dom-server",
91
- "react-dom/server.browser": "\0stub:react-dom-server",
92
- "node:stream": "\0stub:node-stream",
93
- "node:stream/web": "\0stub:node-stream-web",
94
- "node:async_hooks": "\0stub:node-async-hooks",
95
- "tanstack-start-injected-head-scripts:v": "\0stub:tanstack-head-scripts",
96
- };
97
-
98
- // SSR-only stubs. Same mechanism as CLIENT_STUBS but applied to the worker
99
- // SSR build instead of the browser build.
100
- /** @type {Record<string, string>} */
101
- const SSR_STUBS = {
102
- // `@opentelemetry/resources` (transitively pulled in by sdk-logs /
103
- // sdk-metrics / exporter-* OTel packages — five copies in node_modules due
104
- // to OTel monorepo peer-dep version pinning) statically imports bare `fs`
105
- // inside its node-platform machine-id detectors. We never call those
106
- // detectors — `instrumentWorker` builds the OTel Resource from explicit
107
- // attributes only — but Vite's CF Workers SSR resolver still walks the
108
- // re-export barrel and chokes on the bare `fs` specifier (workerd's
109
- // `nodejs_compat` only exposes the prefixed `node:fs`, not the legacy
110
- // bare form). Stub it; the static import resolves and the unreachable
111
- // detector code is never executed.
112
- fs: "\0stub:bare-fs",
113
- };
114
-
115
- // Minimal stub source for each virtual module.
116
- /** @type {Record<string, string>} */
117
- const STUB_SOURCE = {
118
- "\0stub:react-dom-server": [
119
- "const noop = () => '';",
120
- "export const renderToString = noop;",
121
- "export const renderToStaticMarkup = noop;",
122
- "export const renderToReadableStream = noop;",
123
- "export const resume = noop;",
124
- "export const version = '19.0.0';",
125
- "export default { renderToString: noop, renderToStaticMarkup: noop, renderToReadableStream: noop, resume: noop, version: '19.0.0' };",
126
- ].join("\n"),
127
-
128
- "\0stub:node-stream":
129
- "export class PassThrough {}; export class Readable {}; export class Writable {}; export default { PassThrough, Readable, Writable };",
130
-
131
- "\0stub:node-stream-web":
132
- "export const ReadableStream = globalThis.ReadableStream; export const WritableStream = globalThis.WritableStream; export const TransformStream = globalThis.TransformStream; export default { ReadableStream, WritableStream, TransformStream };",
133
-
134
- "\0stub:node-async-hooks": [
135
- "class _ALS { getStore() { return undefined; } run(_store, fn, ...args) { return fn(...args); } enterWith() {} disable() {} }",
136
- "export const AsyncLocalStorage = _ALS;",
137
- "export const AsyncResource = class {};",
138
- "export function executionAsyncId() { return 0; }",
139
- "export function createHook() { return { enable() {}, disable() {} }; }",
140
- "export default { AsyncLocalStorage: _ALS, AsyncResource, executionAsyncId, createHook };",
141
- ].join("\n"),
142
-
143
- "\0stub:tanstack-head-scripts": "export const injectedHeadScripts = undefined;",
144
-
145
- // The admin schema bundle is server-only — the client receives pre-resolved
146
- // blocks via the SSR payload. Stubbing it on the client cuts a large module
147
- // (typically 0.5-5 MB) out of the browser bundle.
148
- "\0stub:meta-gen": "export default {};",
149
-
150
- // Bare `fs` shim — see SSR_STUBS comment above for the rationale. Surfaces
151
- // just enough of `import { promises as fs } from 'fs'` to satisfy static
152
- // module resolution; method calls would throw, but the OTel detector code
153
- // path is unreachable from `instrumentWorker`.
154
- "\0stub:bare-fs": "export const promises = {}; export default { promises };",
155
- };
156
-
157
- /** @returns {import("vite").PluginOption} */
158
- export function decoVitePlugin() {
159
- /** @type {import("vite").Plugin} */
160
- const plugin = {
161
- name: "deco-server-only-stubs",
162
- enforce: "pre",
163
-
164
- resolveId(id, importer, options) {
165
- // SSR-only stubs — must be checked first since the client guard below
166
- // returns undefined for everything that hasn't matched yet on SSR.
167
- if (options?.ssr && SSR_STUBS[id]) return SSR_STUBS[id];
168
- // Server builds keep the real modules.
169
- if (options?.ssr) return undefined;
170
- // Bare-specifier exact-match stubs (react-dom/server, node:stream, etc.).
171
- if (CLIENT_STUBS[id]) return CLIENT_STUBS[id];
172
- // meta.gen.{json,ts} — the admin schema bundle. Server-only; client
173
- // receives pre-resolved blocks. Matches both file extensions so the
174
- // plugin works whether `setup.ts` imports the .json directly (current)
175
- // or a future variant routes through a generated .ts wrapper.
176
- // Requires `importer` so we don't accidentally stub the entry module.
177
- if (importer && (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))) {
178
- return "\0stub:meta-gen";
179
- }
180
- return undefined;
181
- },
182
-
183
- load(id, options) {
184
- // blocks.gen.ts — the CMS block registry (can be 10MB+).
185
- if (id.endsWith("blocks.gen.ts")) {
186
- // Client: stub — the browser receives pre-resolved sections.
187
- if (!options?.ssr) {
188
- return "export const blocks = {};";
189
- }
190
-
191
- // SSR: read .json sibling and emit JSON.parse(...) wrapper.
192
- // This avoids the Vite SSR module runner hanging on large dynamic
193
- // imports and lets V8 use its fast JSON parser (~2-10x vs object literal).
194
- const jsonPath = id.replace(/\.ts$/, ".json");
195
- if (existsSync(jsonPath)) {
196
- const raw = readFileSync(jsonPath, "utf-8");
197
- return `export const blocks = JSON.parse(${JSON.stringify(raw)});`;
198
- }
199
-
200
- // Fallback: if .json doesn't exist yet (pre-generate-blocks), let
201
- // Vite load the .ts file normally (may contain inline data for
202
- // backward-compatible sites that haven't regenerated).
203
- }
204
-
205
- // loaders.gen.ts — the site's invoke registry (`export const siteLoaders`).
206
- // It registers every site loader/action behind a dynamic `import()`, so if
207
- // it stays in the CLIENT module graph (it's reachable via
208
- // router -> setup -> commerce-loaders -> loaders.gen) Vite emits each
209
- // loader/action module as a public client chunk. That leaks the module's
210
- // source — including any hardcoded credential in it — into the browser
211
- // assets. The invoke handler runs server-side only (`/deco/invoke` ->
212
- // handleInvoke reads the registry via getRegisteredLoaders()), and client
213
- // components reach loaders/actions exclusively through the HTTP `invoke`
214
- // proxy (which imports no modules). So the client never needs `siteLoaders`.
215
- // Stub it to an empty object on the client, mirroring blocks.gen.ts above;
216
- // SSR keeps the real module.
217
- if (id.endsWith("loaders.gen.ts") && !options?.ssr) {
218
- return "export const siteLoaders = {};";
219
- }
220
-
221
- // Virtual module stubs.
222
- return STUB_SOURCE[id];
223
- },
224
-
225
- configureServer(server) {
226
- // Watch `.deco/blocks/**/*.json` and regenerate `blocks.gen.json` when
227
- // CMS content changes (manual edit, sync-decofile, daemon PATCH).
228
- // After regen, we POST the new blocks to the dev server's own
229
- // /.decofile endpoint — this calls setBlocks() inside the workerd SSR
230
- // runtime without any module invalidation (which breaks TanStack
231
- // Start/Router state).
232
- //
233
- // NOTE: @decocms/nextjs takes the opposite approach — a generated
234
- // static-import manifest (blocks-cli's generate-blocks-manifest.ts,
235
- // wired as `createNextSetup({ blocks, blocksDir: false })`) that makes
236
- // the bundler's own module-graph invalidation the content-reload
237
- // mechanism. That design is deliberately NOT used here: a spike on
238
- // TanStack Start 1.166 × @cloudflare/vite-plugin showed ANY SSR module
239
- // invalidation bricks the router (the pre-existing upstream bug called
240
- // out above), so this plugin's no-invalidation delta machinery below
241
- // stays the TanStack dev-reload path until that's fixed upstream.
242
- //
243
- // Generator is loaded lazily via tsImport (same pattern as the daemon
244
- // below) so we don't depend on the consumer's TS loader.
245
- const cwd = process.cwd();
246
- const blocksDir = path.resolve(cwd, ".deco/blocks");
247
- const outFile = path.resolve(cwd, ".deco/blocks.gen.ts");
248
- const jsonFile = outFile.replace(/\.ts$/, ".json");
249
-
250
- // Lazily load the block generator module (generateBlocks for the cold-start
251
- // bootstrap, readBlockDelta for live edits). Same tsImport pattern as the
252
- // daemon loader below — keeps `tsx` scoped to this single import instead of
253
- // registering a global hook.
254
- let genModule;
255
- const loadGenModule = () => {
256
- if (genModule) return Promise.resolve(genModule);
257
- return import("tsx/esm/api")
258
- .then(({ tsImport }) =>
259
- tsImport("@decocms/blocks-cli/generate-blocks", import.meta.url),
260
- )
261
- .then((mod) => {
262
- if (typeof mod.generateBlocks !== "function") {
263
- // tsx 4.22.0–4.22.4 has a loader-hook state bug (fixed upstream
264
- // in 4.22.5, "isolate hook state per async module.register()
265
- // registration"): inside a Vite dev-server process, tsImport
266
- // resolves correctly but returns an EMPTY module namespace —
267
- // no rejection, no missing-module error. blocks-cli floors its
268
- // tsx dependency at ^4.22.5, but a site's own lockfile can pin
269
- // a broken copy that hoists above it. Fail with an actionable
270
- // message instead of the bare "generateBlocks is not a
271
- // function" this used to surface as.
272
- throw new Error(
273
- "tsImport(@decocms/blocks-cli/generate-blocks) returned an empty module namespace. " +
274
- "This is the tsx 4.22.0–4.22.4 loader-hook bug — check `node -e \"console.log(require('tsx/package.json').version)\"` " +
275
- "and upgrade tsx to >=4.22.5 (e.g. `bun update tsx` or pin a newer tsx in devDependencies).",
276
- );
277
- }
278
- genModule = mod;
279
- return mod;
280
- });
281
- };
282
-
283
- // In-memory copy of the merged decofile, seeded once from the full
284
- // generator run and patched with cheap deltas thereafter. Lets us keep
285
- // `blocks.gen.json` on disk fresh WITHOUT re-reading + re-parsing all
286
- // ~hundreds of `.deco/blocks/*.json` files on every edit (that whole-dir
287
- // re-read is what pegged the event loop for seconds and tripped the
288
- // Studio liveness probe).
289
- /** @type {Record<string, unknown> | null} */
290
- let mergedBlocks = null;
291
- const ensureMerged = async () => {
292
- if (mergedBlocks) return { merged: mergedBlocks, result: null };
293
- const { generateBlocks } = await loadGenModule();
294
- const result = await generateBlocks({ blocksDir, outFile, silent: true });
295
- mergedBlocks = result.empty ? {} : result.blocks;
296
- return { merged: mergedBlocks, result };
297
- };
298
-
299
- // Live block edits are applied as a DELTA. The Studio daemon (or a manual
300
- // edit) writes a single `.deco/blocks/*.json` file; re-reading and
301
- // re-merging the whole directory on every write blocks the Node/Vite event
302
- // loop for seconds. Instead we read only the changed file(s) and:
303
- // 1. patch the in-memory merged map and rewrite `blocks.gen.json` — this
304
- // keeps the on-disk snapshot authoritative, because Vite's
305
- // `full-reload` re-evaluates the SSR entry, which re-seeds
306
- // setBlocks() from `blocks.gen.json`. A stale file here renders stale
307
- // content on the auto-reload (only a later manual refresh, which does
308
- // NOT re-evaluate, would show the edit).
309
- // 2. POST a delta envelope to `/.decofile` so the live isolate's
310
- // in-memory snapshot is updated too (covers reloads that don't
311
- // re-evaluate) — merged via applyDelta(), no module invalidation.
312
- let regenTimer = null;
313
- let regenInFlight = false;
314
- let regenQueued = false;
315
- /** @type {Map<string, boolean>} block filename -> isDelete (last event wins). */
316
- let pendingBlocks = new Map();
317
- const runDelta = async () => {
318
- if (regenInFlight) {
319
- regenQueued = true;
320
- return;
321
- }
322
- if (pendingBlocks.size === 0) return;
323
- regenInFlight = true;
324
- const batch = pendingBlocks;
325
- pendingBlocks = new Map();
326
- try {
327
- const { readBlockDelta } = await loadGenModule();
328
- const start = Date.now();
329
- const files = [...batch.entries()].map(([name, isDelete]) => ({
330
- name,
331
- isDelete,
332
- }));
333
- const delta = readBlockDelta({ blocksDir, files, silent: true });
334
- const keys = Object.keys(delta);
335
- if (keys.length === 0) return;
336
-
337
- // Patch the merged map + rewrite blocks.gen.json so an SSR re-eval on
338
- // reload reads fresh content. ensureMerged() seeds from a single full
339
- // run the first time (reading current disk, which already includes the
340
- // change); afterwards it's O(changed keys).
341
- const { merged } = await ensureMerged();
342
- for (const [name, value] of Object.entries(delta)) {
343
- if (value === null) delete merged[name];
344
- else merged[name] = value;
345
- }
346
- try {
347
- writeFileSync(jsonFile, JSON.stringify(merged));
348
- } catch (writeErr) {
349
- console.warn("[deco] failed to write blocks.gen.json:", writeErr?.message ?? writeErr);
350
- }
351
-
352
- // POST a delta envelope ({ blocks: {...} }) so handleDecofileReload
353
- // merges it over the current snapshot instead of replacing the whole
354
- // decofile. setBlocks() runs inside the workerd SSR runtime.
355
- const addr = server.httpServer?.address();
356
- const port = typeof addr === "object" && addr ? addr.port : 5173;
357
- const res = await fetch(`http://localhost:${port}/.decofile`, {
358
- method: "POST",
359
- headers: { "Content-Type": "application/json" },
360
- body: JSON.stringify({ blocks: delta }),
361
- });
362
- const ms = Date.now() - start;
363
- if (res.ok) {
364
- console.log(`[deco] applied ${keys.length}-block delta in ${ms}ms`);
365
- server.hot?.send({ type: "full-reload", path: "*" });
366
- } else {
367
- console.warn(`[deco] block delta reload failed: ${res.status}`);
368
- }
369
- } catch (err) {
370
- console.warn("[deco] failed to apply block delta:", err?.message ?? err);
371
- } finally {
372
- regenInFlight = false;
373
- if (regenQueued) {
374
- regenQueued = false;
375
- scheduleRegen();
376
- }
377
- }
378
- };
379
- const scheduleRegen = () => {
380
- if (regenTimer) clearTimeout(regenTimer);
381
- regenTimer = setTimeout(() => {
382
- regenTimer = null;
383
- runDelta();
384
- }, 150);
385
- };
386
-
387
- // chokidar (Vite's watcher) needs the directory added explicitly because
388
- // `.deco/` lives outside the module graph it walks by default.
389
- if (existsSync(blocksDir)) {
390
- server.watcher.add(blocksDir);
391
- }
392
- const handleBlocksDirEvent = (file, isDelete) => {
393
- if (!file.endsWith(".json")) return;
394
- if (!file.startsWith(blocksDir + path.sep) && file !== blocksDir) return;
395
- // Block files are flat inside `.deco/blocks/`, so the basename is the
396
- // encoded-key + ".json" filename that readBlockDelta expects.
397
- pendingBlocks.set(path.basename(file), isDelete);
398
- scheduleRegen();
399
- };
400
- server.watcher.on("add", (file) => handleBlocksDirEvent(file, false));
401
- server.watcher.on("change", (file) => handleBlocksDirEvent(file, false));
402
- server.watcher.on("unlink", (file) => handleBlocksDirEvent(file, true));
403
-
404
- // Cold-start bootstrap of `blocks.gen.json`, in two modes:
405
- //
406
- // MISSING (fresh clone): blocks.gen.json is gitignored, so a first
407
- // checkout has no file on disk. The async refresh below is
408
- // fire-and-forget and races the first request — `setup.ts` reads the
409
- // .json sibling via the blocks.gen.ts load() hook, and a miss falls
410
- // back to the empty stub, rendering a blank page until regen lands and
411
- // triggers a reload. So when the snapshot is ABSENT we generate it
412
- // SYNCHRONOUSLY, blocking startup until the very first request can see
413
- // real content. This only fires on a fresh clone, never steady-state.
414
- //
415
- // PRESENT (steady state): refresh asynchronously and DELIBERATELY NOT
416
- // gated on mtime. A fresh git checkout rewrites every file's mtime to
417
- // the checkout time, so a committed artifact could be CONTENT-stale yet
418
- // mtime-"fresh" — the old `source.mtime > artifact.mtime` gate then
419
- // served the stale snapshot (the double-render bug in branch previews).
420
- // Regen is cheap (tens of ms) and fire-and-forget, so it never blocks
421
- // startup. No POST /.decofile here — the SSR runtime isn't listening
422
- // yet; `setup.ts` reads the freshly-written .json on the first request
423
- // (the watch-driven path above handles live edits, with reload).
424
- if (existsSync(blocksDir)) {
425
- if (!existsSync(jsonFile)) {
426
- console.log("[deco] blocks.gen.json missing — generating on cold start…");
427
- try {
428
- const scriptPath = path.resolve(
429
- cwd,
430
- "node_modules/@decocms/blocks-cli/scripts/generate-blocks.ts",
431
- );
432
- execFileSync("npx", ["tsx", scriptPath], { cwd, stdio: "inherit" });
433
- } catch (err) {
434
- console.warn(
435
- "[deco] blocks.gen.json cold-start generation failed:",
436
- err?.message ?? err,
437
- );
438
- }
439
- } else {
440
- ensureMerged()
441
- .then(({ result }) => {
442
- if (result && !result.empty) {
443
- console.log(`[deco] bootstrapped ${result.count} blocks from .deco/blocks`);
444
- }
445
- })
446
- .catch((err) => {
447
- console.warn("[deco] blocks bootstrap failed:", err?.message ?? err);
448
- });
449
- }
450
- }
451
-
452
- // --- meta.gen.json auto-regeneration ---
453
- // When section/loader/app source files change (types, JSDoc, Props),
454
- // re-run generate-schema.ts so meta.gen.json stays in sync during dev.
455
- // No --out is passed to the generator below, so it writes to its own
456
- // default (.deco/meta.gen.json) — this constant must track that default.
457
- const schemaWatchDirs = ["src"];
458
- const schemaOutFile = path.resolve(cwd, ".deco/meta.gen.json");
459
-
460
- // Resolve the site name once from vite define or env.
461
- const definedSite = server.config.define?.["process.env.DECO_SITE_NAME"];
462
- const schemaSiteName = definedSite
463
- ? JSON.parse(definedSite)
464
- : process.env.DECO_SITE_NAME || "storefront";
465
-
466
- let schemaTimer = null;
467
- let schemaInFlight = false;
468
- let schemaQueued = false;
469
- const runSchemaGen = () => {
470
- if (schemaInFlight) {
471
- schemaQueued = true;
472
- return;
473
- }
474
- schemaInFlight = true;
475
- const start = Date.now();
476
- const scriptPath = path.resolve(
477
- cwd,
478
- "node_modules/@decocms/blocks-cli/scripts/generate-schema.ts",
479
- );
480
- const cmd = `npx tsx ${JSON.stringify(scriptPath)} --site ${schemaSiteName}`;
481
- exec(cmd, { cwd }, (err) => {
482
- schemaInFlight = false;
483
- if (err) {
484
- console.warn("[deco] schema generation failed:", err.message);
485
- } else {
486
- console.log(`[deco] meta.gen.json updated (${Date.now() - start}ms)`);
487
- // Invalidate the meta.gen.json module so SSR picks up fresh schema
488
- const mod =
489
- server.environments?.ssr?.moduleGraph?.getModuleById(schemaOutFile);
490
- if (mod) {
491
- server.environments.ssr.moduleGraph.invalidateModule(mod);
492
- }
493
- }
494
- if (schemaQueued) {
495
- schemaQueued = false;
496
- scheduleSchemaGen();
497
- }
498
- },
499
- );
500
- };
501
- const scheduleSchemaGen = () => {
502
- if (schemaTimer) clearTimeout(schemaTimer);
503
- schemaTimer = setTimeout(() => {
504
- schemaTimer = null;
505
- runSchemaGen();
506
- }, 500);
507
- };
508
-
509
- // Cold-start bootstrap: generate meta.gen.json if it's absent. Unlike the
510
- // decofile, meta.gen.json is normally COMMITTED (it merges cleanly), so
511
- // this is a safety net — it fires only when the file is genuinely missing
512
- // (a site that opts to gitignore it, a partial checkout, a manual delete).
513
- // It matters because setup.ts imports meta.gen.json EAGERLY via
514
- // createAdminSetup, so a missing file would reject the import on the first
515
- // request.
516
- //
517
- // Unlike the blocks bootstrap above, this is (a) gated on absence and
518
- // (b) SYNCHRONOUS: a full ts-morph schema pass takes seconds, so we only
519
- // pay it when the file is genuinely missing, and we must finish before the
520
- // server accepts a request. Once the file exists on disk (any subsequent
521
- // start), this is skipped and the watch-driven regen below keeps it fresh.
522
- if (!existsSync(schemaOutFile)) {
523
- console.log("[deco] meta.gen.json missing — generating on cold start…");
524
- try {
525
- const scriptPath = path.resolve(
526
- cwd,
527
- "node_modules/@decocms/blocks-cli/scripts/generate-schema.ts",
528
- );
529
- execFileSync("npx", ["tsx", scriptPath, "--site", schemaSiteName], {
530
- cwd,
531
- stdio: "inherit",
532
- });
533
- } catch (err) {
534
- console.warn(
535
- "[deco] meta.gen.json cold-start generation failed:",
536
- err?.message ?? err,
537
- );
538
- }
539
- }
540
-
541
- const isSchemaSource = (file) => {
542
- const rel = path.relative(cwd, file);
543
- return (
544
- schemaWatchDirs.some((d) => rel.startsWith(d + path.sep)) &&
545
- (rel.endsWith(".tsx") || rel.endsWith(".ts"))
546
- );
547
- };
548
- server.watcher.on("change", (file) => {
549
- if (isSchemaSource(file)) scheduleSchemaGen();
550
- });
551
- server.watcher.on("add", (file) => {
552
- if (isSchemaSource(file)) scheduleSchemaGen();
553
- });
554
-
555
- // --- sections.gen.ts / loaders.gen.ts / invoke.gen.ts regeneration (#371) ---
556
- // Unlike meta.gen.json (regenerated above via generate-schema.ts
557
- // directly), these three were never re-run in dev — only `npm run build`
558
- // (which chains the full `generate` orchestrator) touched them. Editing
559
- // a section/loader's TS interface (new prop, new @title) updated the TS
560
- // source but left the `.gen` files stale until a manual `generate` run:
561
- // typecheck passed and the runtime worked, but the studio/admin form
562
- // silently kept showing the old schema.
563
- //
564
- // Reuses the SAME `generate.ts` orchestrator sites already run for
565
- // `build`, restricted to --only sections,loaders,invoke so the schema
566
- // regen above isn't duplicated. The orchestrator's own two-tier digest
567
- // cache (.deco/generate.digests.json + .deco/.cache/stat-memo.json)
568
- // makes a steady-state run (nothing changed) a cheap no-op — a cache
569
- // miss only pays the cost for the generator(s) whose actual inputs
570
- // changed. Best-effort: a failure here only warns (matches the schema
571
- // regen's own error handling above) — dev keeps running off whatever
572
- // was last generated, same as before this feature existed.
573
- let scaffoldTimer = null;
574
- let scaffoldInFlight = false;
575
- let scaffoldQueued = false;
576
- const runScaffoldGen = () => {
577
- if (scaffoldInFlight) {
578
- scaffoldQueued = true;
579
- return;
580
- }
581
- scaffoldInFlight = true;
582
- const start = Date.now();
583
- const scriptPath = path.resolve(cwd, "node_modules/@decocms/blocks-cli/scripts/generate.ts");
584
- const cmd = `npx tsx ${JSON.stringify(scriptPath)} --only sections,loaders,invoke --site ${schemaSiteName}`;
585
- exec(cmd, { cwd }, (err) => {
586
- scaffoldInFlight = false;
587
- if (err) {
588
- console.warn("[deco] sections/loaders/invoke generation failed:", err.message);
589
- } else {
590
- console.log(`[deco] sections/loaders/invoke checked (${Date.now() - start}ms)`);
591
- }
592
- if (scaffoldQueued) {
593
- scaffoldQueued = false;
594
- scheduleScaffoldGen();
595
- }
596
- });
597
- };
598
- const scheduleScaffoldGen = () => {
599
- if (scaffoldTimer) clearTimeout(scaffoldTimer);
600
- scaffoldTimer = setTimeout(() => {
601
- scaffoldTimer = null;
602
- runScaffoldGen();
603
- }, 500);
604
- };
605
-
606
- // Cold-start: run once on dev startup. The digest cache makes this a
607
- // fast no-op when nothing changed since the last `generate` run (e.g.
608
- // right after a `build`) — fire-and-forget, doesn't block the first request.
609
- scheduleScaffoldGen();
610
-
611
- // Reuse the same src/**/*.{ts,tsx} watch predicate as the schema regen
612
- // above — sections/loaders/actions all live under the same tree.
613
- server.watcher.on("change", (file) => {
614
- if (isSchemaSource(file)) scheduleScaffoldGen();
615
- });
616
- server.watcher.on("add", (file) => {
617
- if (isSchemaSource(file)) scheduleScaffoldGen();
618
- });
619
-
620
- // Tunnel + daemon: connect local dev to admin.deco.cx
621
- // Activated only when both DECO_SITE_NAME and DECO_ENV_NAME are set.
622
- // Omitting DECO_ENV_NAME runs Vite fully local (no tunnel registration),
623
- // since DECO_SITE_NAME alone is also consumed by site builds via vite's
624
- // `define` for `process.env.DECO_SITE_NAME` and shouldn't force a tunnel.
625
- const siteName = process.env.DECO_SITE_NAME;
626
- const envName = process.env.DECO_ENV_NAME;
627
- if (siteName && envName) {
628
- // Daemon files are .ts and live inside node_modules. Node's
629
- // experimental strip-types refuses to transpile node_modules, so
630
- // a plain dynamic `import()` blows up under `vite dev`. Use tsx's
631
- // ad-hoc loader (`tsImport`) — scoped to this import, doesn't
632
- // register a global hook.
633
- const loadDaemon = (specifier) =>
634
- import("tsx/esm/api").then(({ tsImport }) => tsImport(specifier, import.meta.url));
635
-
636
- // Add daemon middleware (x-daemon-api interception + auth + volumes + SSE + admin routes)
637
- loadDaemon("../daemon/middleware.ts")
638
- .then(({ createDaemonMiddleware }) => {
639
- server.middlewares.use(createDaemonMiddleware({ site: siteName, server }));
640
- })
641
- .catch((err) => {
642
- console.warn("[deco] Failed to load daemon middleware:", err.message);
643
- });
644
-
645
- // Start tunnel after HTTP server is listening (so we know the real port)
646
- server.httpServer?.once("listening", async () => {
647
- const addr = server.httpServer?.address();
648
- const port = typeof addr === "object" && addr ? addr.port : 5173;
649
- try {
650
- const { startTunnel } = await loadDaemon("../daemon/tunnel.ts");
651
- const tunnel = await startTunnel({
652
- site: siteName,
653
- env: envName,
654
- port,
655
- // Default to the .deco.host relay (matches startTunnel's documented
656
- // default). Set DECO_HOST=false to opt back into the legacy
657
- // simpletunnel.deco.site relay.
658
- decoHost: process.env.DECO_HOST !== "false",
659
- });
660
- server.httpServer?.on("close", () => tunnel.close());
661
- } catch (err) {
662
- console.warn("[deco] Failed to start tunnel:", err.message);
663
- }
664
- });
665
- }
666
- },
667
-
668
- config(_cfg, { command }) {
669
- /** @type {import("vite").UserConfig} */
670
- const cfg = {};
671
-
672
- // Allow tunnel domains through Vite's host check.
673
- // .deco.studio is the new admin frontend; both real-world Deco sites
674
- // (casaevideo-storefront, baggagio-tanstack) duplicated this list to
675
- // include it — bundling it here removes that boilerplate.
676
- if (process.env.DECO_SITE_NAME) {
677
- cfg.server = {
678
- allowedHosts: [".deco.host", ".decocdn.com", ".deco.studio"],
679
- };
680
- }
681
-
682
- // Inject a per-build identifier as `__DECO_BUILD_HASH__` so
683
- // createDecoWorkerEntry can fall back to it when env.BUILD_HASH is
684
- // unset (the default on Cloudflare Workers Builds, where there's
685
- // no GH-Actions step injecting --var BUILD_HASH).
686
- //
687
- // Dev gets the literal "dev" so SSR doesn't crash on an undefined
688
- // identifier; prod gets WORKERS_CI_COMMIT_SHA → git rev-parse →
689
- // time-based fallback (see resolveBuildHash above).
690
- const buildHash = command === "build" ? resolveBuildHash() : "dev";
691
- cfg.define = {
692
- ...cfg.define,
693
- __DECO_BUILD_HASH__: JSON.stringify(buildHash),
694
- };
695
-
696
- // Only split chunks for production builds — dev uses unbundled ESM.
697
- if (command !== "build") return cfg;
698
- return {
699
- ...cfg,
700
- build: {
701
- rollupOptions: {
702
- output: {
703
- manualChunks(id) {
704
- if (id.includes("node_modules/react-dom") || id.includes("node_modules/react/")) {
705
- return "vendor-react";
706
- }
707
-
708
- // TanStack Router — client-side router (always needed)
709
- if (id.includes("@tanstack/react-router") || id.includes("@tanstack/router-core")) {
710
- return "vendor-router";
711
- }
712
-
713
- // TanStack Start — specific checks before broad catch-all
714
- // (react-start-client includes "react-start" so must come first)
715
- if (
716
- id.includes("@tanstack/react-start-client") ||
717
- id.includes("@tanstack/start-client-core")
718
- ) {
719
- return "vendor-router";
720
- }
721
- // Server-only TanStack packages — let Rollup tree-shake
722
- if (
723
- id.includes("@tanstack/react-start-server") ||
724
- id.includes("@tanstack/start-server-core")
725
- ) {
726
- return undefined;
727
- }
728
- // Remaining @tanstack/start (storage-context, plugin-core, etc.)
729
- if (id.includes("@tanstack/start")) {
730
- return "vendor-router";
731
- }
732
-
733
- // isbot — server-only (bot detection in resolve.ts)
734
- if (id.includes("node_modules/isbot")) {
735
- return undefined;
736
- }
737
-
738
- if (id.includes("@tanstack/react-query")) {
739
- return "vendor-query";
740
- }
741
- // Intentionally NOT splitting @decocms/tanstack,
742
- // @decocms/blocks, @decocms/blocks-admin, or
743
- // @decocms/apps: they have circular re-exports (e.g. apps
744
- // imports from runtime/sdk/cachedLoader, admin
745
- // imports from apps). Splitting them into separate chunks
746
- // produces a Rollup chunk-load order that crashes at runtime
747
- // ("undefined is not a function") — both real-world sites
748
- // worked around this by overriding manualChunks. Letting
749
- // Rollup bundle them together (or with the importing chunk)
750
- // is correct.
751
- },
752
- },
753
- },
754
- },
755
- };
756
- },
757
-
758
- configEnvironment(name, env) {
759
- if (name === "ssr" || name === "client") {
760
- env.optimizeDeps = env.optimizeDeps || {};
761
- env.optimizeDeps.esbuildOptions = env.optimizeDeps.esbuildOptions || {};
762
- env.optimizeDeps.esbuildOptions.jsx = "automatic";
763
- env.optimizeDeps.esbuildOptions.jsxImportSource = "react";
764
- }
765
-
766
- // Force @decocms/tanstack through the SSR transform pipeline so
767
- // TanStack Start's compiler can register its createServerFn handlers
768
- // (loadDeferredSection in routes/cmsRoute.ts, and loadCmsPage /
769
- // loadCmsHomePage alongside it) in the per-environment serverFnsById
770
- // manifest. Without this, Vite pre-bundles the package via
771
- // optimizeDeps before plugins run, the handler never enters the
772
- // manifest, and every POST /_serverFn/* call from the browser returns
773
- // HTTP 500 ("Invalid server function ID"). See #197.
774
- //
775
- // @decocms/apps-vtex does NOT need this: its invoke.ts has zero real
776
- // createServerFn call sites reachable by any site (it's a
777
- // codegen-time-only template that blocks-cli's generate-invoke.ts
778
- // statically parses, never imports, to emit each site's own
779
- // src/server/invoke.gen.ts with real top-level createServerFn consts;
780
- // createInvokeFn itself is a non-functional type-only marker for that
781
- // template, see sdk/createInvoke.ts's doc comment). Only add a
782
- // package here once it has a real `createServerFn(...)` call site.
783
- if (name === "ssr") {
784
- env.resolve = env.resolve || {};
785
- const existing = env.resolve.noExternal;
786
- const additions = ["@decocms/tanstack"];
787
- if (existing === true) {
788
- // Already noExternal everything — nothing to add.
789
- } else if (Array.isArray(existing)) {
790
- env.resolve.noExternal = [...new Set([...existing, ...additions])];
791
- } else if (existing) {
792
- env.resolve.noExternal = [existing, ...additions];
793
- } else {
794
- env.resolve.noExternal = additions;
795
- }
796
-
797
- // The noExternal setting above only controls whether Vite's SSR
798
- // *output* inlines vs. externalizes this package — it does NOT
799
- // stop Vite's dev-server-startup dependency optimizer (esbuild via
800
- // `optimizeDeps`) from pre-bundling it. Some Cloudflare Workers
801
- // targets (via @cloudflare/vite-plugin) already force
802
- // `resolve.noExternal = true` unconditionally for this same "ssr"
803
- // environment before this hook even runs, making the block above a
804
- // complete no-op there — yet the crash below still happened,
805
- // proving pre-bundling (not noExternal) was always the real cause.
806
- //
807
- // Confirmed via direct diagnostic instrumentation of
808
- // @tanstack/start-plugin-core: once esbuild pre-bundles this
809
- // package into a single node_modules/.vite/deps_ssr/*.js chunk,
810
- // Cloudflare's separate worker-export static-analysis pass
811
- // (getWorkerEntryExportTypes, a distinct pipeline stage from
812
- // Vite's own SSR transform — see workers/runner-worker in the
813
- // stack trace) throws "createServerFn must be assigned to a
814
- // variable!" on this package's own legitimate, already-top-level
815
- // createServerFn calls (loadCmsPage / loadCmsHomePage /
816
- // loadDeferredSection) — apparently that scan doesn't recognize
817
- // esbuild-bundled `var X = createServerFn(...)` output the same
818
- // way it recognizes the original, unbundled source. Excluding this
819
- // package from `optimizeDeps` entirely routes it through Vite's
820
- // normal plugin pipeline (where TanStack Start's compiler
821
- // transforms it correctly) instead of esbuild's pre-bundler.
822
- env.optimizeDeps = env.optimizeDeps || {};
823
- env.optimizeDeps.exclude = [...new Set([...(env.optimizeDeps.exclude || []), "@decocms/tanstack"])];
824
- }
825
- },
826
-
827
- generateBundle(_, bundle) {
828
- // Build a mapping from section key to chunk filename.
829
- // Sites use this to emit <link rel="modulepreload"> for eager sections.
830
- const map = {};
831
- for (const [fileName, chunk] of Object.entries(bundle)) {
832
- if (chunk.type === "chunk" && chunk.facadeModuleId) {
833
- const match = chunk.facadeModuleId.match(/\/(sections\/.+\.tsx)$/);
834
- if (match) {
835
- map["site/" + match[1]] = fileName;
836
- }
837
- }
838
- }
839
- if (Object.keys(map).length > 0) {
840
- this.emitFile({
841
- type: "asset",
842
- fileName: "section-chunks.json",
843
- source: JSON.stringify(map),
844
- });
845
- }
846
- },
847
- };
848
-
849
- return plugin;
850
- }