@decocms/tanstack 8.1.0-next.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 (177) 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 +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  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/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
@@ -1,1022 +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
- // Virtual id for meta.gen.json on the server: the real path wrapped so the id
88
- // does NOT end in `.json` (Vite's `vite:json` would re-parse our JS output).
89
- const META_GEN_PREFIX = "\0deco-meta:";
90
- const META_GEN_SUFFIX = ".deco-meta.js";
91
- const metaGenSsrId = (file) => META_GEN_PREFIX + file + META_GEN_SUFFIX;
92
-
93
- // Bare-specifier stubs resolved by ID before Vite touches them.
94
- /** @type {Record<string, string>} */
95
- const CLIENT_STUBS = {
96
- "react-dom/server": "\0stub:react-dom-server",
97
- "react-dom/server.browser": "\0stub:react-dom-server",
98
- "node:stream": "\0stub:node-stream",
99
- "node:stream/web": "\0stub:node-stream-web",
100
- "node:async_hooks": "\0stub:node-async-hooks",
101
- "tanstack-start-injected-head-scripts:v": "\0stub:tanstack-head-scripts",
102
- };
103
-
104
- // SSR-only stubs. Same mechanism as CLIENT_STUBS but applied to the worker
105
- // SSR build instead of the browser build.
106
- /** @type {Record<string, string>} */
107
- const SSR_STUBS = {
108
- // `@opentelemetry/resources` (transitively pulled in by sdk-logs /
109
- // sdk-metrics / exporter-* OTel packages — five copies in node_modules due
110
- // to OTel monorepo peer-dep version pinning) statically imports bare `fs`
111
- // inside its node-platform machine-id detectors. We never call those
112
- // detectors — `instrumentWorker` builds the OTel Resource from explicit
113
- // attributes only — but Vite's CF Workers SSR resolver still walks the
114
- // re-export barrel and chokes on the bare `fs` specifier (workerd's
115
- // `nodejs_compat` only exposes the prefixed `node:fs`, not the legacy
116
- // bare form). Stub it; the static import resolves and the unreachable
117
- // detector code is never executed.
118
- fs: "\0stub:bare-fs",
119
- };
120
-
121
- // Minimal stub source for each virtual module.
122
- /** @type {Record<string, string>} */
123
- const STUB_SOURCE = {
124
- "\0stub:react-dom-server": [
125
- "const noop = () => '';",
126
- "export const renderToString = noop;",
127
- "export const renderToStaticMarkup = noop;",
128
- "export const renderToReadableStream = noop;",
129
- "export const resume = noop;",
130
- "export const version = '19.0.0';",
131
- "export default { renderToString: noop, renderToStaticMarkup: noop, renderToReadableStream: noop, resume: noop, version: '19.0.0' };",
132
- ].join("\n"),
133
-
134
- "\0stub:node-stream":
135
- "export class PassThrough {}; export class Readable {}; export class Writable {}; export default { PassThrough, Readable, Writable };",
136
-
137
- "\0stub:node-stream-web":
138
- "export const ReadableStream = globalThis.ReadableStream; export const WritableStream = globalThis.WritableStream; export const TransformStream = globalThis.TransformStream; export default { ReadableStream, WritableStream, TransformStream };",
139
-
140
- "\0stub:node-async-hooks": [
141
- "class _ALS { getStore() { return undefined; } run(_store, fn, ...args) { return fn(...args); } enterWith() {} disable() {} }",
142
- "export const AsyncLocalStorage = _ALS;",
143
- "export const AsyncResource = class {};",
144
- "export function executionAsyncId() { return 0; }",
145
- "export function createHook() { return { enable() {}, disable() {} }; }",
146
- "export default { AsyncLocalStorage: _ALS, AsyncResource, executionAsyncId, createHook };",
147
- ].join("\n"),
148
-
149
- "\0stub:tanstack-head-scripts": "export const injectedHeadScripts = undefined;",
150
-
151
- // The admin schema bundle is server-only — the client receives pre-resolved
152
- // blocks via the SSR payload. Stubbing it on the client cuts a large module
153
- // (typically 0.5-5 MB) out of the browser bundle.
154
- "\0stub:meta-gen": "export default {};",
155
-
156
- // Bare `fs` shim — see SSR_STUBS comment above for the rationale. Surfaces
157
- // just enough of `import { promises as fs } from 'fs'` to satisfy static
158
- // module resolution; method calls would throw, but the OTel detector code
159
- // path is unreachable from `instrumentWorker`.
160
- "\0stub:bare-fs": "export const promises = {}; export default { promises };",
161
- };
162
-
163
- /**
164
- * Argv (after the generate-schema.ts script path) for a meta.gen.json run.
165
- *
166
- * generate-schema ALWAYS composes before writing, so the emitted meta.gen.json
167
- * carries every framework `website/*` block (Page, matchers, __SECTION_REF__,
168
- * Resolvable). This matters because meta.gen.json is committed and Studio reads
169
- * it as-is (no composeMeta at read time) — an uncomposed rewrite would silently
170
- * break the admin editors, e.g. the date matcher powering variant rules
171
- * disappearing (a production storefront regression). Mirrors `npm run generate`'s schema
172
- * step. Both invocation sites in configureServer derive their args here so they
173
- * can never drift apart.
174
- *
175
- * @param {string} siteName
176
- * @returns {string[]}
177
- */
178
- export function generateSchemaArgs(siteName) {
179
- return ["--site", siteName];
180
- }
181
-
182
- /**
183
- * Env var a deploy pipeline sets to declare "I seed `decofile:<deployment-id>`
184
- * into KV BEFORE activating this version". Set by the cfworkers-builder under
185
- * exactly the condition that guards its seed step, so the stub below and the
186
- * seed can never drift apart.
187
- */
188
- const SEEDED_DEPLOY_ENV = "DECO_SEEDED_DEPLOY";
189
-
190
- /** Whether this build runs inside a pipeline that seeds KV before activation. */
191
- function isSeededDeployPipeline() {
192
- const v = process.env[SEEDED_DEPLOY_ENV];
193
- return v === "1" || v === "true";
194
- }
195
-
196
- /**
197
- * @param {object} [opts]
198
- * @param {boolean | "auto"} [opts.fastDeploy="auto"] Stub `blocks.gen` out of
199
- * the SERVER bundle too, so the worker's only copy of the decofile is the one
200
- * hydrated from KV at cold start.
201
- *
202
- * Without this, a fast-deploy site holds the decofile TWICE: the bundled
203
- * `JSON.parse(...)` graph stays permanently reachable through the site's
204
- * `import { blocks } from ".deco/blocks.gen"` module binding, and
205
- * `ensureBlocksHydrated` adds a second graph via `setBlocks()`. For a 10MB
206
- * decofile that is tens of MB of avoidable isolate memory, on a platform
207
- * whose per-isolate cap is 128MB and has no GC knob.
208
- *
209
- * It is gated because it removes the fallback: with no bundled snapshot, a
210
- * cold start that cannot read KV has no content to serve, and
211
- * `ensureBlocksHydrated` fails the request loudly (5xx) rather than serving
212
- * an empty site that the edge would then cache — see `kvHydration.ts`. That
213
- * is only safe when the deploy pipeline seeds `decofile:<deployment-id>`
214
- * BEFORE the new version activates.
215
- *
216
- * `"auto"` (default) stubs only when the pipeline declares it seeds, via
217
- * `DECO_SEEDED_DEPLOY`. A site building through Cloudflare Workers Builds or
218
- * a manual `wrangler deploy` never sets it, so it keeps the bundled snapshot
219
- * and behaves exactly as before — no site-side config, no way to half-enable
220
- * it. `true` forces the stub, `false` disables it. A stubbed bundle also
221
- * needs `DECO_FAST_DEPLOY=1` and a `DECO_KV` binding at runtime — without
222
- * them `ensureBlocksHydrated` fails every request rather than serve `{}`.
223
- * @returns {import("vite").PluginOption}
224
- */
225
- export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
226
- // Resolved once: the pipeline's answer cannot change mid-build.
227
- const stubBlocks = fastDeploy === "auto" ? isSeededDeployPipeline() : fastDeploy === true;
228
- // Set from the `config` hook (which Vite always runs before `load`). The
229
- // fastDeploy stub must apply to production builds ONLY: `vite dev` has no KV
230
- // to hydrate from, and the dev bootstrap below deliberately relies on reading
231
- // the `.json` sibling that the stub bypasses — stubbing there blanks the
232
- // local site.
233
- let isBuild = false;
234
-
235
- /** @type {import("vite").Plugin} */
236
- const plugin = {
237
- name: "deco-server-only-stubs",
238
- enforce: "pre",
239
-
240
- resolveId(id, importer, options) {
241
- // SSR-only stubs — must be checked first since the client guard below
242
- // returns undefined for everything that hasn't matched yet on SSR.
243
- if (options?.ssr && SSR_STUBS[id]) return SSR_STUBS[id];
244
- // meta.gen.json on the SERVER → a virtual id that does NOT end in
245
- // `.json`. `load` below emits JS (`JSON.parse("...")`), and Vite's
246
- // `vite:json` transform runs on every id matching `\.json$` regardless
247
- // of who loaded it — it would try to JSON.parse that JS and fail the
248
- // build ("Failed to parse JSON file").
249
- if (options?.ssr && importer && id.endsWith("meta.gen.json")) {
250
- if (id.startsWith(".") || path.isAbsolute(id)) {
251
- const file = path.resolve(path.dirname(importer), id);
252
- if (existsSync(file)) return metaGenSsrId(file);
253
- // Absent (pre-generate-schema) — let Vite report it normally.
254
- return undefined;
255
- }
256
- // Alias / bare specifier (`~/.deco/meta.gen.json`, tsconfig paths…):
257
- // let the rest of the pipeline resolve it, then wrap — otherwise it
258
- // falls through to vite:json and loses the JSON.parse optimization.
259
- if (typeof this?.resolve === "function") {
260
- return this.resolve(id, importer, { ...options, skipSelf: true }).then(
261
- (r) =>
262
- r && !r.external && r.id.endsWith("meta.gen.json") && existsSync(r.id)
263
- ? metaGenSsrId(r.id)
264
- : undefined,
265
- // A resolver in the chain threw — let Vite's normal resolution report it.
266
- () => undefined,
267
- );
268
- }
269
- }
270
- // Server builds keep the real modules.
271
- if (options?.ssr) return undefined;
272
- // Bare-specifier exact-match stubs (react-dom/server, node:stream, etc.).
273
- if (CLIENT_STUBS[id]) return CLIENT_STUBS[id];
274
- // meta.gen.{json,ts} — the admin schema bundle. Server-only; client
275
- // receives pre-resolved blocks. Matches both file extensions so the
276
- // plugin works whether `setup.ts` imports the .json directly (current)
277
- // or a future variant routes through a generated .ts wrapper.
278
- // Requires `importer` so we don't accidentally stub the entry module.
279
- if (importer && (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))) {
280
- return "\0stub:meta-gen";
281
- }
282
- return undefined;
283
- },
284
-
285
- load(id, options) {
286
- // blocks.gen.ts — the CMS block registry (can be 10MB+).
287
- if (id.endsWith("blocks.gen.ts")) {
288
- // Client: stub — the browser receives pre-resolved sections.
289
- if (!options?.ssr) {
290
- return "export const blocks = {};";
291
- }
292
-
293
- // Fast-deploy: stub on the SERVER too. The worker hydrates the decofile
294
- // from KV at cold start, so shipping it in the bundle would just pin a
295
- // second, permanently-reachable copy in isolate memory (the site's
296
- // `import { blocks }` binding keeps the bundled graph alive for the
297
- // isolate's whole life, even after `setBlocks()` swaps in the KV one).
298
- // Build only — see `isBuild` above.
299
- if (stubBlocks && isBuild) {
300
- return "export const blocks = {};";
301
- }
302
-
303
- // SSR: read .json sibling and emit JSON.parse(...) wrapper.
304
- // This avoids the Vite SSR module runner hanging on large dynamic
305
- // imports and lets V8 use its fast JSON parser (~2-10x vs object literal).
306
- const jsonPath = id.replace(/\.ts$/, ".json");
307
- if (existsSync(jsonPath)) {
308
- const raw = readFileSync(jsonPath, "utf-8");
309
- return `export const blocks = JSON.parse(${JSON.stringify(raw)});`;
310
- }
311
-
312
- // Fallback: if .json doesn't exist yet (pre-generate-blocks), let
313
- // Vite load the .ts file normally (may contain inline data for
314
- // backward-compatible sites that haven't regenerated).
315
- }
316
-
317
- // meta.gen.json — the admin JSON Schema bundle, on the SERVER.
318
- //
319
- // Vite's JSON plugin would turn it into an object literal, which V8 must
320
- // run through the full JS parser. Emitting `JSON.parse("...")` instead
321
- // (same treatment blocks.gen gets, and the same reason) uses V8's fast
322
- // JSON parser and — the part that matters for memory — keeps the schema
323
- // as ONE string until something actually calls the parse. Since
324
- // `createAdminSetup` now only invokes its loader on the first
325
- // `/live/_meta`, an isolate that never serves the admin never
326
- // materializes the object graph at all.
327
- //
328
- // The client is stubbed in `resolveId` above and never reaches here.
329
- if (id.startsWith(META_GEN_PREFIX) && id.endsWith(META_GEN_SUFFIX)) {
330
- const file = id.slice(META_GEN_PREFIX.length, -META_GEN_SUFFIX.length);
331
- // Virtual id → Vite won't watch the file on its own.
332
- this.addWatchFile?.(file);
333
- const raw = readFileSync(file, "utf-8");
334
- return `export default JSON.parse(${JSON.stringify(raw)});`;
335
- }
336
-
337
- // loaders.gen.ts — the site's invoke registry (`export const siteLoaders`).
338
- // It registers every site loader/action behind a dynamic `import()`, so if
339
- // it stays in the CLIENT module graph (it's reachable via
340
- // router -> setup -> commerce-loaders -> loaders.gen) Vite emits each
341
- // loader/action module as a public client chunk. That leaks the module's
342
- // source — including any hardcoded credential in it — into the browser
343
- // assets. The invoke handler runs server-side only (`/deco/invoke` ->
344
- // handleInvoke reads the registry via getRegisteredLoaders()), and client
345
- // components reach loaders/actions exclusively through the HTTP `invoke`
346
- // proxy (which imports no modules). So the client never needs `siteLoaders`.
347
- // Stub it to an empty object on the client, mirroring blocks.gen.ts above;
348
- // SSR keeps the real module.
349
- if (id.endsWith("loaders.gen.ts") && !options?.ssr) {
350
- return "export const siteLoaders = {};";
351
- }
352
-
353
- // Virtual module stubs.
354
- return STUB_SOURCE[id];
355
- },
356
-
357
- configureServer(server) {
358
- // Watch `.deco/blocks/**/*.json` and regenerate `blocks.gen.json` when
359
- // CMS content changes (manual edit, sync-decofile, daemon PATCH).
360
- // After regen, we POST the new blocks to the dev server's own
361
- // /.decofile endpoint — this calls setBlocks() inside the workerd SSR
362
- // runtime without any module invalidation (which breaks TanStack
363
- // Start/Router state).
364
- //
365
- // NOTE: @decocms/nextjs takes the opposite approach — a generated
366
- // static-import manifest (blocks-cli's generate-blocks-manifest.ts,
367
- // wired as `createNextSetup({ blocks, blocksDir: false })`) that makes
368
- // the bundler's own module-graph invalidation the content-reload
369
- // mechanism. That design is deliberately NOT used here: a spike on
370
- // TanStack Start 1.166 × @cloudflare/vite-plugin showed ANY SSR module
371
- // invalidation bricks the router (the pre-existing upstream bug called
372
- // out above), so this plugin's no-invalidation delta machinery below
373
- // stays the TanStack dev-reload path until that's fixed upstream.
374
- //
375
- // Generator is loaded lazily via tsImport (same pattern as the daemon
376
- // below) so we don't depend on the consumer's TS loader.
377
- const cwd = process.cwd();
378
- const blocksDir = path.resolve(cwd, ".deco/blocks");
379
- const outFile = path.resolve(cwd, ".deco/blocks.gen.ts");
380
- const jsonFile = outFile.replace(/\.ts$/, ".json");
381
-
382
- // Lazily load the block generator module (generateBlocks for the cold-start
383
- // bootstrap, readBlockDelta for live edits). Same tsImport pattern as the
384
- // daemon loader below — keeps `tsx` scoped to this single import instead of
385
- // registering a global hook.
386
- let genModule;
387
- const loadGenModule = () => {
388
- if (genModule) return Promise.resolve(genModule);
389
- return import("tsx/esm/api")
390
- .then(({ tsImport }) =>
391
- tsImport("@decocms/blocks-cli/generate-blocks", import.meta.url),
392
- )
393
- .then((mod) => {
394
- if (typeof mod.generateBlocks !== "function") {
395
- // tsx 4.22.0–4.22.4 has a loader-hook state bug (fixed upstream
396
- // in 4.22.5, "isolate hook state per async module.register()
397
- // registration"): inside a Vite dev-server process, tsImport
398
- // resolves correctly but returns an EMPTY module namespace —
399
- // no rejection, no missing-module error. blocks-cli floors its
400
- // tsx dependency at ^4.22.5, but a site's own lockfile can pin
401
- // a broken copy that hoists above it. Fail with an actionable
402
- // message instead of the bare "generateBlocks is not a
403
- // function" this used to surface as.
404
- throw new Error(
405
- "tsImport(@decocms/blocks-cli/generate-blocks) returned an empty module namespace. " +
406
- "This is the tsx 4.22.0–4.22.4 loader-hook bug — check `node -e \"console.log(require('tsx/package.json').version)\"` " +
407
- "and upgrade tsx to >=4.22.5 (e.g. `bun update tsx` or pin a newer tsx in devDependencies).",
408
- );
409
- }
410
- genModule = mod;
411
- return mod;
412
- });
413
- };
414
-
415
- // In-memory copy of the merged decofile, seeded once from the full
416
- // generator run and patched with cheap deltas thereafter. Lets us keep
417
- // `blocks.gen.json` on disk fresh WITHOUT re-reading + re-parsing all
418
- // ~hundreds of `.deco/blocks/*.json` files on every edit (that whole-dir
419
- // re-read is what pegged the event loop for seconds and tripped the
420
- // Studio liveness probe).
421
- /** @type {Record<string, unknown> | null} */
422
- let mergedBlocks = null;
423
- const ensureMerged = async () => {
424
- if (mergedBlocks) return { merged: mergedBlocks, result: null };
425
- const { generateBlocks } = await loadGenModule();
426
- const result = await generateBlocks({ blocksDir, outFile, silent: true });
427
- mergedBlocks = result.empty ? {} : result.blocks;
428
- return { merged: mergedBlocks, result };
429
- };
430
-
431
- // Live block edits are applied as a DELTA. The Studio daemon (or a manual
432
- // edit) writes a single `.deco/blocks/*.json` file; re-reading and
433
- // re-merging the whole directory on every write blocks the Node/Vite event
434
- // loop for seconds. Instead we read only the changed file(s) and:
435
- // 1. patch the in-memory merged map and rewrite `blocks.gen.json` — this
436
- // keeps the on-disk snapshot authoritative, because Vite's
437
- // `full-reload` re-evaluates the SSR entry, which re-seeds
438
- // setBlocks() from `blocks.gen.json`. A stale file here renders stale
439
- // content on the auto-reload (only a later manual refresh, which does
440
- // NOT re-evaluate, would show the edit).
441
- // 2. POST a delta envelope to `/.decofile` so the live isolate's
442
- // in-memory snapshot is updated too (covers reloads that don't
443
- // re-evaluate) — merged via applyDelta(), no module invalidation.
444
- let regenTimer = null;
445
- let regenInFlight = false;
446
- let regenQueued = false;
447
- /** @type {Map<string, boolean>} block filename -> isDelete (last event wins). */
448
- let pendingBlocks = new Map();
449
- const runDelta = async () => {
450
- if (regenInFlight) {
451
- regenQueued = true;
452
- return;
453
- }
454
- if (pendingBlocks.size === 0) return;
455
- regenInFlight = true;
456
- const batch = pendingBlocks;
457
- pendingBlocks = new Map();
458
- try {
459
- const { readBlockDelta } = await loadGenModule();
460
- const start = Date.now();
461
- const files = [...batch.entries()].map(([name, isDelete]) => ({
462
- name,
463
- isDelete,
464
- }));
465
- const delta = readBlockDelta({ blocksDir, files, silent: true });
466
- const keys = Object.keys(delta);
467
- if (keys.length === 0) return;
468
-
469
- // Patch the merged map + rewrite blocks.gen.json so an SSR re-eval on
470
- // reload reads fresh content. ensureMerged() seeds from a single full
471
- // run the first time (reading current disk, which already includes the
472
- // change); afterwards it's O(changed keys).
473
- const { merged } = await ensureMerged();
474
- for (const [name, value] of Object.entries(delta)) {
475
- if (value === null) delete merged[name];
476
- else merged[name] = value;
477
- }
478
- try {
479
- writeFileSync(jsonFile, JSON.stringify(merged));
480
- } catch (writeErr) {
481
- console.warn("[deco] failed to write blocks.gen.json:", writeErr?.message ?? writeErr);
482
- }
483
-
484
- // POST a delta envelope ({ blocks: {...} }) so handleDecofileReload
485
- // merges it over the current snapshot instead of replacing the whole
486
- // decofile. setBlocks() runs inside the workerd SSR runtime.
487
- const addr = server.httpServer?.address();
488
- const port = typeof addr === "object" && addr ? addr.port : 5173;
489
- const res = await fetch(`http://localhost:${port}/.decofile`, {
490
- method: "POST",
491
- headers: { "Content-Type": "application/json" },
492
- body: JSON.stringify({ blocks: delta }),
493
- });
494
- const ms = Date.now() - start;
495
- if (res.ok) {
496
- console.log(`[deco] applied ${keys.length}-block delta in ${ms}ms`);
497
- server.hot?.send({ type: "full-reload", path: "*" });
498
- } else {
499
- console.warn(`[deco] block delta reload failed: ${res.status}`);
500
- }
501
- } catch (err) {
502
- console.warn("[deco] failed to apply block delta:", err?.message ?? err);
503
- } finally {
504
- regenInFlight = false;
505
- if (regenQueued) {
506
- regenQueued = false;
507
- scheduleRegen();
508
- }
509
- }
510
- };
511
- const scheduleRegen = () => {
512
- if (regenTimer) clearTimeout(regenTimer);
513
- regenTimer = setTimeout(() => {
514
- regenTimer = null;
515
- runDelta();
516
- }, 150);
517
- };
518
-
519
- // chokidar (Vite's watcher) needs the directory added explicitly because
520
- // `.deco/` lives outside the module graph it walks by default.
521
- if (existsSync(blocksDir)) {
522
- server.watcher.add(blocksDir);
523
- }
524
- const handleBlocksDirEvent = (file, isDelete) => {
525
- if (!file.endsWith(".json")) return;
526
- if (!file.startsWith(blocksDir + path.sep) && file !== blocksDir) return;
527
- // Block files are flat inside `.deco/blocks/`, so the basename is the
528
- // encoded-key + ".json" filename that readBlockDelta expects.
529
- pendingBlocks.set(path.basename(file), isDelete);
530
- scheduleRegen();
531
- };
532
- server.watcher.on("add", (file) => handleBlocksDirEvent(file, false));
533
- server.watcher.on("change", (file) => handleBlocksDirEvent(file, false));
534
- server.watcher.on("unlink", (file) => handleBlocksDirEvent(file, true));
535
-
536
- // Cold-start bootstrap of `blocks.gen.json`, in two modes:
537
- //
538
- // MISSING (fresh clone): blocks.gen.json is gitignored, so a first
539
- // checkout has no file on disk. The async refresh below is
540
- // fire-and-forget and races the first request — `setup.ts` reads the
541
- // .json sibling via the blocks.gen.ts load() hook, and a miss falls
542
- // back to the empty stub, rendering a blank page until regen lands and
543
- // triggers a reload. So when the snapshot is ABSENT we generate it
544
- // SYNCHRONOUSLY, blocking startup until the very first request can see
545
- // real content. This only fires on a fresh clone, never steady-state.
546
- //
547
- // PRESENT (steady state): refresh asynchronously and DELIBERATELY NOT
548
- // gated on mtime. A fresh git checkout rewrites every file's mtime to
549
- // the checkout time, so a committed artifact could be CONTENT-stale yet
550
- // mtime-"fresh" — the old `source.mtime > artifact.mtime` gate then
551
- // served the stale snapshot (the double-render bug in branch previews).
552
- // Regen is cheap (tens of ms) and fire-and-forget, so it never blocks
553
- // startup. No POST /.decofile here — the SSR runtime isn't listening
554
- // yet; `setup.ts` reads the freshly-written .json on the first request
555
- // (the watch-driven path above handles live edits, with reload).
556
- if (existsSync(blocksDir)) {
557
- if (!existsSync(jsonFile)) {
558
- console.log("[deco] blocks.gen.json missing — generating on cold start…");
559
- try {
560
- const scriptPath = path.resolve(
561
- cwd,
562
- "node_modules/@decocms/blocks-cli/scripts/generate-blocks.ts",
563
- );
564
- execFileSync("npx", ["tsx", scriptPath], { cwd, stdio: "inherit" });
565
- } catch (err) {
566
- console.warn(
567
- "[deco] blocks.gen.json cold-start generation failed:",
568
- err?.message ?? err,
569
- );
570
- }
571
- } else {
572
- ensureMerged()
573
- .then(({ result }) => {
574
- if (result && !result.empty) {
575
- console.log(`[deco] bootstrapped ${result.count} blocks from .deco/blocks`);
576
- }
577
- })
578
- .catch((err) => {
579
- console.warn("[deco] blocks bootstrap failed:", err?.message ?? err);
580
- });
581
- }
582
- }
583
-
584
- // --- meta.gen.json auto-regeneration ---
585
- // When section/loader/app source files change (types, JSDoc, Props),
586
- // re-run generate-schema.ts so meta.gen.json stays in sync during dev.
587
- // No --out is passed to the generator below, so it writes to its own
588
- // default (.deco/meta.gen.json) — this constant must track that default.
589
- // Both invocations get their args from generateSchemaArgs() so they can't
590
- // drift apart (see its doc comment).
591
- const schemaWatchDirs = ["src"];
592
- const schemaOutFile = path.resolve(cwd, ".deco/meta.gen.json");
593
-
594
- // Resolve the site name once from vite define or env.
595
- const definedSite = server.config.define?.["process.env.DECO_SITE_NAME"];
596
- const schemaSiteName = definedSite
597
- ? JSON.parse(definedSite)
598
- : process.env.DECO_SITE_NAME || "storefront";
599
-
600
- let schemaTimer = null;
601
- let schemaInFlight = false;
602
- let schemaQueued = false;
603
- const runSchemaGen = () => {
604
- if (schemaInFlight) {
605
- schemaQueued = true;
606
- return;
607
- }
608
- schemaInFlight = true;
609
- const start = Date.now();
610
- const scriptPath = path.resolve(
611
- cwd,
612
- "node_modules/@decocms/blocks-cli/scripts/generate-schema.ts",
613
- );
614
- const cmd = `npx tsx ${JSON.stringify(scriptPath)} ${generateSchemaArgs(schemaSiteName).join(" ")}`;
615
- exec(cmd, { cwd }, (err) => {
616
- schemaInFlight = false;
617
- if (err) {
618
- console.warn("[deco] schema generation failed:", err.message);
619
- } else {
620
- console.log(`[deco] meta.gen.json updated (${Date.now() - start}ms)`);
621
- // Invalidate the meta.gen.json module so SSR picks up fresh schema
622
- const mod =
623
- server.environments?.ssr?.moduleGraph?.getModuleById(metaGenSsrId(schemaOutFile));
624
- if (mod) {
625
- server.environments.ssr.moduleGraph.invalidateModule(mod);
626
- }
627
- }
628
- if (schemaQueued) {
629
- schemaQueued = false;
630
- scheduleSchemaGen();
631
- }
632
- },
633
- );
634
- };
635
- const scheduleSchemaGen = () => {
636
- if (schemaTimer) clearTimeout(schemaTimer);
637
- schemaTimer = setTimeout(() => {
638
- schemaTimer = null;
639
- runSchemaGen();
640
- }, 500);
641
- };
642
-
643
- // Cold-start bootstrap: generate meta.gen.json if it's absent. Unlike the
644
- // decofile, meta.gen.json is normally COMMITTED (it merges cleanly), so
645
- // this is a safety net — it fires only when the file is genuinely missing
646
- // (a site that opts to gitignore it, a partial checkout, a manual delete).
647
- // It matters because setup.ts imports meta.gen.json EAGERLY via
648
- // createAdminSetup, so a missing file would reject the import on the first
649
- // request.
650
- //
651
- // Unlike the blocks bootstrap above, this is (a) gated on absence and
652
- // (b) SYNCHRONOUS: a full ts-morph schema pass takes seconds, so we only
653
- // pay it when the file is genuinely missing, and we must finish before the
654
- // server accepts a request. Once the file exists on disk (any subsequent
655
- // start), this is skipped and the watch-driven regen below keeps it fresh.
656
- if (!existsSync(schemaOutFile)) {
657
- console.log("[deco] meta.gen.json missing — generating on cold start…");
658
- try {
659
- const scriptPath = path.resolve(
660
- cwd,
661
- "node_modules/@decocms/blocks-cli/scripts/generate-schema.ts",
662
- );
663
- execFileSync("npx", ["tsx", scriptPath, ...generateSchemaArgs(schemaSiteName)], {
664
- cwd,
665
- stdio: "inherit",
666
- });
667
- } catch (err) {
668
- console.warn(
669
- "[deco] meta.gen.json cold-start generation failed:",
670
- err?.message ?? err,
671
- );
672
- }
673
- }
674
-
675
- const isSchemaSource = (file) => {
676
- const rel = path.relative(cwd, file);
677
- return (
678
- schemaWatchDirs.some((d) => rel.startsWith(d + path.sep)) &&
679
- (rel.endsWith(".tsx") || rel.endsWith(".ts"))
680
- );
681
- };
682
- server.watcher.on("change", (file) => {
683
- if (isSchemaSource(file)) scheduleSchemaGen();
684
- });
685
- server.watcher.on("add", (file) => {
686
- if (isSchemaSource(file)) scheduleSchemaGen();
687
- });
688
-
689
- // --- sections.gen.ts / loaders.gen.ts / invoke.gen.ts regeneration (#371) ---
690
- // Unlike meta.gen.json (regenerated above via generate-schema.ts
691
- // directly), these three were never re-run in dev — only `npm run build`
692
- // (which chains the full `generate` orchestrator) touched them. Editing
693
- // a section/loader's TS interface (new prop, new @title) updated the TS
694
- // source but left the `.gen` files stale until a manual `generate` run:
695
- // typecheck passed and the runtime worked, but the studio/admin form
696
- // silently kept showing the old schema.
697
- //
698
- // Reuses the SAME `generate.ts` orchestrator sites already run for
699
- // `build`, restricted to --only sections,loaders,invoke so the schema
700
- // regen above isn't duplicated. The orchestrator's own two-tier digest
701
- // cache (.deco/generate.digests.json + .deco/.cache/stat-memo.json)
702
- // makes a steady-state run (nothing changed) a cheap no-op — a cache
703
- // miss only pays the cost for the generator(s) whose actual inputs
704
- // changed. Best-effort: a failure here only warns (matches the schema
705
- // regen's own error handling above) — dev keeps running off whatever
706
- // was last generated, same as before this feature existed.
707
- let scaffoldTimer = null;
708
- let scaffoldInFlight = false;
709
- let scaffoldQueued = false;
710
- const runScaffoldGen = () => {
711
- if (scaffoldInFlight) {
712
- scaffoldQueued = true;
713
- return;
714
- }
715
- scaffoldInFlight = true;
716
- const start = Date.now();
717
- const scriptPath = path.resolve(cwd, "node_modules/@decocms/blocks-cli/scripts/generate.ts");
718
- const cmd = `npx tsx ${JSON.stringify(scriptPath)} --only sections,loaders,invoke --site ${schemaSiteName}`;
719
- exec(cmd, { cwd }, (err) => {
720
- scaffoldInFlight = false;
721
- if (err) {
722
- console.warn("[deco] sections/loaders/invoke generation failed:", err.message);
723
- } else {
724
- console.log(`[deco] sections/loaders/invoke checked (${Date.now() - start}ms)`);
725
- }
726
- if (scaffoldQueued) {
727
- scaffoldQueued = false;
728
- scheduleScaffoldGen();
729
- }
730
- });
731
- };
732
- const scheduleScaffoldGen = () => {
733
- if (scaffoldTimer) clearTimeout(scaffoldTimer);
734
- scaffoldTimer = setTimeout(() => {
735
- scaffoldTimer = null;
736
- runScaffoldGen();
737
- }, 500);
738
- };
739
-
740
- // Cold-start: run once on dev startup. The digest cache makes this a
741
- // fast no-op when nothing changed since the last `generate` run (e.g.
742
- // right after a `build`) — fire-and-forget, doesn't block the first request.
743
- scheduleScaffoldGen();
744
-
745
- // Reuse the same src/**/*.{ts,tsx} watch predicate as the schema regen
746
- // above — sections/loaders/actions all live under the same tree.
747
- server.watcher.on("change", (file) => {
748
- if (isSchemaSource(file)) scheduleScaffoldGen();
749
- });
750
- server.watcher.on("add", (file) => {
751
- if (isSchemaSource(file)) scheduleScaffoldGen();
752
- });
753
-
754
- // Tunnel + daemon: connect local dev to admin.deco.cx
755
- // Activated only when both DECO_SITE_NAME and DECO_ENV_NAME are set.
756
- // Omitting DECO_ENV_NAME runs Vite fully local (no tunnel registration),
757
- // since DECO_SITE_NAME alone is also consumed by site builds via vite's
758
- // `define` for `process.env.DECO_SITE_NAME` and shouldn't force a tunnel.
759
- const siteName = process.env.DECO_SITE_NAME;
760
- const envName = process.env.DECO_ENV_NAME;
761
- if (siteName && envName) {
762
- // Daemon files are .ts and live inside node_modules. Node's
763
- // experimental strip-types refuses to transpile node_modules, so
764
- // a plain dynamic `import()` blows up under `vite dev`. Use tsx's
765
- // ad-hoc loader (`tsImport`) — scoped to this import, doesn't
766
- // register a global hook.
767
- const loadDaemon = (specifier) =>
768
- import("tsx/esm/api").then(({ tsImport }) => tsImport(specifier, import.meta.url));
769
-
770
- // Add daemon middleware (x-daemon-api interception + auth + volumes + SSE + admin routes)
771
- loadDaemon("../daemon/middleware.ts")
772
- .then(({ createDaemonMiddleware }) => {
773
- server.middlewares.use(createDaemonMiddleware({ site: siteName, server }));
774
- })
775
- .catch((err) => {
776
- console.warn("[deco] Failed to load daemon middleware:", err.message);
777
- });
778
-
779
- // Start tunnel after HTTP server is listening (so we know the real port)
780
- server.httpServer?.once("listening", async () => {
781
- const addr = server.httpServer?.address();
782
- const port = typeof addr === "object" && addr ? addr.port : 5173;
783
- try {
784
- const { startTunnel } = await loadDaemon("../daemon/tunnel.ts");
785
- const tunnel = await startTunnel({
786
- site: siteName,
787
- env: envName,
788
- port,
789
- // Default to the .deco.host relay (matches startTunnel's documented
790
- // default). Set DECO_HOST=false to opt back into the legacy
791
- // simpletunnel.deco.site relay.
792
- decoHost: process.env.DECO_HOST !== "false",
793
- });
794
- server.httpServer?.on("close", () => tunnel.close());
795
- } catch (err) {
796
- console.warn("[deco] Failed to start tunnel:", err.message);
797
- }
798
- });
799
- }
800
- },
801
-
802
- config(_cfg, { command }) {
803
- // Gate the fastDeploy SSR stub in `load()` to production builds.
804
- isBuild = command === "build";
805
-
806
- /** @type {import("vite").UserConfig} */
807
- const cfg = {};
808
-
809
- // Supply a default TanStack Start entry when the site has none.
810
- //
811
- // `#tanstack-start-entry` is a subpath import of
812
- // @tanstack/start-client-core; with no `src/start.ts` it resolves to a
813
- // fake entry exporting `startInstance = undefined`, and the site gets no
814
- // `serverFns.fetch` hook. That hook is what appends the cache segment to
815
- // `/_serverFn` URLs (see sdk/cdnSegment), so without it CDN caching of
816
- // SPA navigation can never engage.
817
- //
818
- // Aliasing it here means a site gets that from a version bump instead of
819
- // a per-site PR. Strictly conditional on the file being absent: a site
820
- // that owns its `src/start.ts` must keep it, since ours would otherwise
821
- // silently replace whatever else it configures.
822
- const siteStartEntry = ["ts", "tsx", "js", "jsx"]
823
- .map((ext) => path.join(process.cwd(), "src", `start.${ext}`))
824
- .find((f) => existsSync(f));
825
-
826
- if (!siteStartEntry) {
827
- cfg.resolve = {
828
- ...cfg.resolve,
829
- alias: {
830
- ...cfg.resolve?.alias,
831
- "#tanstack-start-entry": "@decocms/tanstack/sdk/startEntry",
832
- },
833
- };
834
- }
835
-
836
- // Allow tunnel domains through Vite's host check.
837
- // .deco.studio is the new admin frontend; multiple real-world Deco sites
838
- // duplicated this list to include it — bundling it here removes that
839
- // boilerplate.
840
- if (process.env.DECO_SITE_NAME) {
841
- cfg.server = {
842
- allowedHosts: [".deco.host", ".decocdn.com", ".deco.studio"],
843
- };
844
- }
845
-
846
- // Inject a per-build identifier as `__DECO_BUILD_HASH__` so
847
- // createDecoWorkerEntry can fall back to it when env.BUILD_HASH is
848
- // unset (the default on Cloudflare Workers Builds, where there's
849
- // no GH-Actions step injecting --var BUILD_HASH).
850
- //
851
- // Dev gets the literal "dev" so SSR doesn't crash on an undefined
852
- // identifier; prod gets WORKERS_CI_COMMIT_SHA → git rev-parse →
853
- // time-based fallback (see resolveBuildHash above).
854
- const buildHash = command === "build" ? resolveBuildHash() : "dev";
855
- cfg.define = {
856
- ...cfg.define,
857
- __DECO_BUILD_HASH__: JSON.stringify(buildHash),
858
- // Tells the runtime whether this bundle actually ships a decofile.
859
- // `ensureBlocksHydrated` needs a build-time answer: with no bundled
860
- // snapshot, its "warn and serve bundled" recovery would serve an EMPTY
861
- // site with 200s. Inferring it from an empty in-memory map at runtime
862
- // is not equivalent — draft-preview overrides can make a stubbed bundle
863
- // look populated, and a legitimately-empty decofile (new site) would
864
- // look stubbed.
865
- __DECO_BLOCKS_STUBBED__: JSON.stringify(stubBlocks && command === "build"),
866
- };
867
-
868
- // Only split chunks for production builds — dev uses unbundled ESM.
869
- if (command !== "build") return cfg;
870
- return {
871
- ...cfg,
872
- build: {
873
- rollupOptions: {
874
- output: {
875
- manualChunks(id) {
876
- if (id.includes("node_modules/react-dom") || id.includes("node_modules/react/")) {
877
- return "vendor-react";
878
- }
879
-
880
- // TanStack Router — client-side router (always needed)
881
- if (id.includes("@tanstack/react-router") || id.includes("@tanstack/router-core")) {
882
- return "vendor-router";
883
- }
884
-
885
- // TanStack Start — specific checks before broad catch-all
886
- // (react-start-client includes "react-start" so must come first)
887
- if (
888
- id.includes("@tanstack/react-start-client") ||
889
- id.includes("@tanstack/start-client-core")
890
- ) {
891
- return "vendor-router";
892
- }
893
- // Server-only TanStack packages — let Rollup tree-shake
894
- if (
895
- id.includes("@tanstack/react-start-server") ||
896
- id.includes("@tanstack/start-server-core")
897
- ) {
898
- return undefined;
899
- }
900
- // Remaining @tanstack/start (storage-context, plugin-core, etc.)
901
- if (id.includes("@tanstack/start")) {
902
- return "vendor-router";
903
- }
904
-
905
- // isbot — server-only (bot detection in resolve.ts)
906
- if (id.includes("node_modules/isbot")) {
907
- return undefined;
908
- }
909
-
910
- if (id.includes("@tanstack/react-query")) {
911
- return "vendor-query";
912
- }
913
- // Intentionally NOT splitting @decocms/tanstack,
914
- // @decocms/blocks, @decocms/blocks-admin, or
915
- // @decocms/apps: they have circular re-exports (e.g. apps
916
- // imports from runtime/sdk/cachedLoader, admin
917
- // imports from apps). Splitting them into separate chunks
918
- // produces a Rollup chunk-load order that crashes at runtime
919
- // ("undefined is not a function") — both real-world sites
920
- // worked around this by overriding manualChunks. Letting
921
- // Rollup bundle them together (or with the importing chunk)
922
- // is correct.
923
- },
924
- },
925
- },
926
- },
927
- };
928
- },
929
-
930
- configEnvironment(name, env) {
931
- if (name === "ssr" || name === "client") {
932
- env.optimizeDeps = env.optimizeDeps || {};
933
- env.optimizeDeps.esbuildOptions = env.optimizeDeps.esbuildOptions || {};
934
- env.optimizeDeps.esbuildOptions.jsx = "automatic";
935
- env.optimizeDeps.esbuildOptions.jsxImportSource = "react";
936
- }
937
-
938
- // Force @decocms/tanstack through the SSR transform pipeline so
939
- // TanStack Start's compiler can register its createServerFn handlers
940
- // (loadDeferredSection in routes/cmsRoute.ts, and loadCmsPage /
941
- // loadCmsHomePage alongside it) in the per-environment serverFnsById
942
- // manifest. Without this, Vite pre-bundles the package via
943
- // optimizeDeps before plugins run, the handler never enters the
944
- // manifest, and every POST /_serverFn/* call from the browser returns
945
- // HTTP 500 ("Invalid server function ID"). See #197.
946
- //
947
- // @decocms/apps-vtex does NOT need this: its invoke.ts has zero real
948
- // createServerFn call sites reachable by any site (it's a
949
- // codegen-time-only template that blocks-cli's generate-invoke.ts
950
- // statically parses, never imports, to emit each site's own
951
- // src/server/invoke.gen.ts with real top-level createServerFn consts;
952
- // createInvokeFn itself is a non-functional type-only marker for that
953
- // template, see sdk/createInvoke.ts's doc comment). Only add a
954
- // package here once it has a real `createServerFn(...)` call site.
955
- if (name === "ssr") {
956
- env.resolve = env.resolve || {};
957
- const existing = env.resolve.noExternal;
958
- const additions = ["@decocms/tanstack"];
959
- if (existing === true) {
960
- // Already noExternal everything — nothing to add.
961
- } else if (Array.isArray(existing)) {
962
- env.resolve.noExternal = [...new Set([...existing, ...additions])];
963
- } else if (existing) {
964
- env.resolve.noExternal = [existing, ...additions];
965
- } else {
966
- env.resolve.noExternal = additions;
967
- }
968
-
969
- // The noExternal setting above only controls whether Vite's SSR
970
- // *output* inlines vs. externalizes this package — it does NOT
971
- // stop Vite's dev-server-startup dependency optimizer (esbuild via
972
- // `optimizeDeps`) from pre-bundling it. Some Cloudflare Workers
973
- // targets (via @cloudflare/vite-plugin) already force
974
- // `resolve.noExternal = true` unconditionally for this same "ssr"
975
- // environment before this hook even runs, making the block above a
976
- // complete no-op there — yet the crash below still happened,
977
- // proving pre-bundling (not noExternal) was always the real cause.
978
- //
979
- // Confirmed via direct diagnostic instrumentation of
980
- // @tanstack/start-plugin-core: once esbuild pre-bundles this
981
- // package into a single node_modules/.vite/deps_ssr/*.js chunk,
982
- // Cloudflare's separate worker-export static-analysis pass
983
- // (getWorkerEntryExportTypes, a distinct pipeline stage from
984
- // Vite's own SSR transform — see workers/runner-worker in the
985
- // stack trace) throws "createServerFn must be assigned to a
986
- // variable!" on this package's own legitimate, already-top-level
987
- // createServerFn calls (loadCmsPage / loadCmsHomePage /
988
- // loadDeferredSection) — apparently that scan doesn't recognize
989
- // esbuild-bundled `var X = createServerFn(...)` output the same
990
- // way it recognizes the original, unbundled source. Excluding this
991
- // package from `optimizeDeps` entirely routes it through Vite's
992
- // normal plugin pipeline (where TanStack Start's compiler
993
- // transforms it correctly) instead of esbuild's pre-bundler.
994
- env.optimizeDeps = env.optimizeDeps || {};
995
- env.optimizeDeps.exclude = [...new Set([...(env.optimizeDeps.exclude || []), "@decocms/tanstack"])];
996
- }
997
- },
998
-
999
- generateBundle(_, bundle) {
1000
- // Build a mapping from section key to chunk filename.
1001
- // Sites use this to emit <link rel="modulepreload"> for eager sections.
1002
- const map = {};
1003
- for (const [fileName, chunk] of Object.entries(bundle)) {
1004
- if (chunk.type === "chunk" && chunk.facadeModuleId) {
1005
- const match = chunk.facadeModuleId.match(/\/(sections\/.+\.tsx)$/);
1006
- if (match) {
1007
- map["site/" + match[1]] = fileName;
1008
- }
1009
- }
1010
- }
1011
- if (Object.keys(map).length > 0) {
1012
- this.emitFile({
1013
- type: "asset",
1014
- fileName: "section-chunks.json",
1015
- source: JSON.stringify(map),
1016
- });
1017
- }
1018
- },
1019
- };
1020
-
1021
- return plugin;
1022
- }