@decocms/tanstack 7.79.6 → 7.79.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.79.6",
3
+ "version": "7.79.8",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -27,9 +27,9 @@
27
27
  "lint:unused": "knip"
28
28
  },
29
29
  "dependencies": {
30
- "@decocms/blocks": "7.79.6",
31
- "@decocms/blocks-admin": "7.79.6",
32
- "@decocms/blocks-cli": "7.79.6",
30
+ "@decocms/blocks": "7.79.8",
31
+ "@decocms/blocks-admin": "7.79.8",
32
+ "@decocms/blocks-cli": "7.79.8",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -75,7 +75,7 @@ import {
75
75
  instrumentWorker,
76
76
  type OtelOptions,
77
77
  } from "@decocms/blocks/sdk/otel";
78
- import { setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
78
+ import { getRuntimeEnv, setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
79
79
  import { parseTraceparent } from "@decocms/blocks/sdk/otelHttpTracer";
80
80
  import {
81
81
  getRedirectSemantics,
@@ -91,7 +91,7 @@ import { RequestContext } from "@decocms/blocks/sdk/requestContext";
91
91
  import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
92
92
  import { cleanPathForCacheKey, hasTrackingParams } from "@decocms/blocks/sdk/urlUtils";
93
93
  import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
94
- import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
94
+ import { getRenderShellConfig, setMetaAssetFetcher } from "@decocms/blocks-admin/admin/setup";
95
95
  import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
96
96
  import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
97
97
  import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
@@ -1200,6 +1200,18 @@ export function createDecoWorkerEntry(
1200
1200
  ctx: WorkerExecutionContext,
1201
1201
  ): Promise<Response>;
1202
1202
  } {
1203
+ // `/live/_meta` reads the admin schema from the `ASSETS` binding when the
1204
+ // build published it as a static asset (`decoVitePlugin({ metaAsset: true })`).
1205
+ // Registered here so no site has to remember a setup call; inert for builds
1206
+ // that keep the schema in the bundle, since they never ask for the asset.
1207
+ setMetaAssetFetcher((assetPath) => {
1208
+ const assets = getRuntimeEnv()?.ASSETS as
1209
+ | { fetch(req: Request): Promise<Response> }
1210
+ | undefined;
1211
+ // Only the path matters to the binding; the host is a placeholder.
1212
+ return assets ? assets.fetch(new Request(new URL(assetPath, "https://assets.invalid"))) : null;
1213
+ });
1214
+
1203
1215
  const {
1204
1216
  admin,
1205
1217
  detectProfile: customDetect,
@@ -41,7 +41,8 @@
41
41
  * ```
42
42
  */
43
43
  import { exec, execFileSync } from "node:child_process";
44
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
44
+ import { createHash } from "node:crypto";
45
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
45
46
  import path from "node:path";
46
47
 
47
48
  /**
@@ -90,6 +91,39 @@ const META_GEN_PREFIX = "\0deco-meta:";
90
91
  const META_GEN_SUFFIX = ".deco-meta.js";
91
92
  const metaGenSsrId = (file) => META_GEN_PREFIX + file + META_GEN_SUFFIX;
92
93
 
94
+ /**
95
+ * Turn the raw `meta.gen.json` into the static asset `/live/_meta` serves when
96
+ * `metaAsset` is on: the exact bytes the admin receives today
97
+ * (`{...schema, etag}`), plus the ETag the server bundle keeps.
98
+ *
99
+ * Only a pre-composed schema qualifies (`framework` set — what generate-schema
100
+ * writes). A raw one still needs `composeMeta` at runtime, so serving its bytes
101
+ * verbatim would change what the admin sees; return null and the caller keeps
102
+ * the in-bundle path.
103
+ *
104
+ * The ETag is merged textually rather than via parse+stringify so the asset is
105
+ * byte-for-byte the file plus one field.
106
+ *
107
+ * @param {string} raw
108
+ * @returns {{ fileName: string, etag: string, payload: string } | null}
109
+ */
110
+ export function buildMetaAsset(raw) {
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(raw);
114
+ } catch {
115
+ return null;
116
+ }
117
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !parsed.framework) {
118
+ return null;
119
+ }
120
+ const hash = createHash("sha256").update(raw).digest("hex").slice(0, 16);
121
+ const etag = `"meta-${hash}"`;
122
+ const trimmed = raw.trimEnd();
123
+ const payload = `${trimmed.slice(0, -1)},"etag":${JSON.stringify(etag)}}`;
124
+ return { fileName: `_deco/meta-${hash}.json`, etag, payload };
125
+ }
126
+
93
127
  // Bare-specifier stubs resolved by ID before Vite touches them.
94
128
  /** @type {Record<string, string>} */
95
129
  const CLIENT_STUBS = {
@@ -220,9 +254,28 @@ function isSeededDeployPipeline() {
220
254
  * it. `true` forces the stub, `false` disables it. A stubbed bundle also
221
255
  * needs `DECO_FAST_DEPLOY=1` and a `DECO_KV` binding at runtime — without
222
256
  * them `ensureBlocksHydrated` fails every request rather than serve `{}`.
257
+ * @param {boolean} [opts.metaAsset=false] Serve the admin schema (`meta.gen`)
258
+ * as a static asset instead of carrying it in the SERVER bundle.
259
+ *
260
+ * The schema is only read by `GET /live/_meta`, yet in the bundle it costs
261
+ * roughly four times its size in every isolate: V8 keeps the module source
262
+ * and materialises the `JSON.parse` string literal separately, both two-byte
263
+ * as soon as the text holds one character above U+00FF. Measured on a
264
+ * 6 MB schema: 27.9 MB of a 54 MB cold heap.
265
+ *
266
+ * With this on, a production build writes the schema to
267
+ * `<client outDir>/_deco/meta-<hash>.json` and the server module becomes a
268
+ * tiny `{ __decoMetaAsset: { path, etag } }` marker; `handleMeta` answers
269
+ * `If-None-Match` from the ETag and streams the body from the `ASSETS`
270
+ * binding. The asset ships in the same upload as the code, so there is no
271
+ * seed step and no window where code and schema disagree.
272
+ *
273
+ * Requires an `ASSETS` binding (`"assets": { "binding": "ASSETS", ... }` in
274
+ * wrangler.jsonc). Without it `/live/_meta` answers 503 — only the admin is
275
+ * affected, the site keeps serving. Dev (`vite dev`) is unchanged.
223
276
  * @returns {import("vite").PluginOption}
224
277
  */
225
- export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
278
+ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {}) {
226
279
  // Resolved once: the pipeline's answer cannot change mid-build.
227
280
  const stubBlocks = fastDeploy === "auto" ? isSeededDeployPipeline() : fastDeploy === true;
228
281
  // Set from the `config` hook (which Vite always runs before `load`). The
@@ -231,6 +284,12 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
231
284
  // the `.json` sibling that the stub bypasses — stubbing there blanks the
232
285
  // local site.
233
286
  let isBuild = false;
287
+ // `metaAsset`: the schema asset captured while loading meta.gen on the
288
+ // server, and where the client build writes its output.
289
+ /** @type {{ fileName: string, etag: string, payload: string } | null} */
290
+ let metaAssetFile = null;
291
+ /** @type {string | null} */
292
+ let clientOutDir = null;
234
293
 
235
294
  /** @type {import("vite").Plugin} */
236
295
  const plugin = {
@@ -330,8 +389,26 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
330
389
  const file = id.slice(META_GEN_PREFIX.length, -META_GEN_SUFFIX.length);
331
390
  // Virtual id → Vite won't watch the file on its own.
332
391
  this.addWatchFile?.(file);
333
- const raw = readFileSync(file, "utf-8");
334
- return `export default JSON.parse(${JSON.stringify(raw)});`;
392
+ // Re-serialize compactly: generate-schema writes it indented, and every
393
+ // byte of that whitespace is paid twice in the isolate (module source +
394
+ // the string literal), at two-byte width since the schema has accented
395
+ // text. On a real site: 7.3 MB chunk / +15 MB heap, vs 3.3 MB compact.
396
+ // The static asset uses the compact form too, so `/live/_meta` serves
397
+ // the same bytes either way.
398
+ const compact = JSON.stringify(JSON.parse(readFileSync(file, "utf-8")));
399
+ if (metaAsset && isBuild) {
400
+ const asset = buildMetaAsset(compact);
401
+ if (asset) {
402
+ metaAssetFile = asset;
403
+ const ref = { __decoMetaAsset: { path: `/${asset.fileName}`, etag: asset.etag } };
404
+ return `export default ${JSON.stringify(ref)};`;
405
+ }
406
+ this.warn?.(
407
+ `metaAsset: ${file} is not a pre-composed schema (no \`framework\` field) — ` +
408
+ "keeping it in the server bundle. Regenerate it with generate-schema.",
409
+ );
410
+ }
411
+ return `export default JSON.parse(${JSON.stringify(compact)});`;
335
412
  }
336
413
 
337
414
  // loaders.gen.ts — the site's invoke registry (`export const siteLoaders`).
@@ -996,7 +1073,33 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
996
1073
  }
997
1074
  },
998
1075
 
1076
+ configResolved(config) {
1077
+ const outDir = config.environments?.client?.build?.outDir;
1078
+ clientOutDir = outDir ? path.resolve(config.root, outDir) : null;
1079
+ },
1080
+
1081
+ writeBundle() {
1082
+ // The server build runs after the client one, so the schema captured in
1083
+ // `load` is written straight into the client output — the directory
1084
+ // wrangler uploads as static assets. (`generateBundle` below covers the
1085
+ // opposite order.)
1086
+ if (!metaAssetFile || this.environment?.name === "client") return;
1087
+ if (!clientOutDir) {
1088
+ this.error("metaAsset: no client build outDir to write the admin schema to");
1089
+ }
1090
+ const out = path.join(clientOutDir, metaAssetFile.fileName);
1091
+ mkdirSync(path.dirname(out), { recursive: true });
1092
+ writeFileSync(out, metaAssetFile.payload);
1093
+ },
1094
+
999
1095
  generateBundle(_, bundle) {
1096
+ if (metaAssetFile && this.environment?.name === "client") {
1097
+ this.emitFile({
1098
+ type: "asset",
1099
+ fileName: metaAssetFile.fileName,
1100
+ source: metaAssetFile.payload,
1101
+ });
1102
+ }
1000
1103
  // Build a mapping from section key to chunk filename.
1001
1104
  // Sites use this to emit <link rel="modulepreload"> for eager sections.
1002
1105
  const map = {};
@@ -1,8 +1,8 @@
1
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { decoVitePlugin, generateSchemaArgs } from "./plugin.js";
5
+ import { buildMetaAsset, decoVitePlugin, generateSchemaArgs } from "./plugin.js";
6
6
 
7
7
  /**
8
8
  * The Vite plugin's `resolveId` / `load` hooks are pure functions over their
@@ -155,6 +155,21 @@ describe("decoVitePlugin meta.gen.json on SSR (regression: vite:json double-pars
155
155
  expect(watched).toEqual([path.join(dir, ".deco", "meta.gen.json")]);
156
156
  });
157
157
 
158
+ it("embeds an indented meta.gen.json compacted (whitespace costs isolate heap)", () => {
159
+ writeFileSync(
160
+ path.join(dir, ".deco", "meta.gen.json"),
161
+ JSON.stringify({ major: 1, schema: { title: "Coleção" } }, null, 2),
162
+ );
163
+ const p = getPlugin();
164
+ const id = p.resolveId.call({}, "../.deco/meta.gen.json", path.join(dir, "src", "setup.ts"), {
165
+ ssr: true,
166
+ });
167
+ const code = p.load.call({ addWatchFile() {} }, id, { ssr: true });
168
+ expect(code).toBe(
169
+ `export default JSON.parse(${JSON.stringify('{"major":1,"schema":{"title":"Coleção"}}')});`,
170
+ );
171
+ });
172
+
158
173
  it("gives each meta.gen.json its own module id (no shared state)", () => {
159
174
  const p = getPlugin();
160
175
  const other = mkdtempSync(path.join(tmpdir(), "deco-meta-other-"));
@@ -236,3 +251,85 @@ describe("decoVitePlugin meta.gen.json on SSR (regression: vite:json double-pars
236
251
  );
237
252
  });
238
253
  });
254
+
255
+ describe("decoVitePlugin({ metaAsset }) — admin schema as a static asset", () => {
256
+ // The schema costs ~4x its size per isolate when bundled (source + JSON.parse
257
+ // literal, two-byte). With metaAsset the server bundle carries only a marker
258
+ // and the bytes ship as a client asset, served through the ASSETS binding.
259
+ const COMPOSED = '{"major":1,"framework":"tanstack","schema":{"definitions":{}}}\n';
260
+ let dir;
261
+
262
+ beforeEach(() => {
263
+ dir = mkdtempSync(path.join(tmpdir(), "deco-meta-asset-"));
264
+ mkdirSync(path.join(dir, ".deco"));
265
+ mkdirSync(path.join(dir, "src"));
266
+ });
267
+
268
+ afterEach(() => {
269
+ rmSync(dir, { recursive: true, force: true });
270
+ });
271
+
272
+ function buildPlugin(opts) {
273
+ const result = decoVitePlugin(opts);
274
+ const p = Array.isArray(result) ? result[0] : result;
275
+ p.config({}, { command: "build" });
276
+ p.configResolved({ root: dir, environments: { client: { build: { outDir: "dist/client" } } } });
277
+ return p;
278
+ }
279
+
280
+ function loadMeta(p, contents, ctx = {}) {
281
+ writeFileSync(path.join(dir, ".deco", "meta.gen.json"), contents);
282
+ const id = p.resolveId.call({}, "../.deco/meta.gen.json", path.join(dir, "src", "setup.ts"), {
283
+ ssr: true,
284
+ });
285
+ return p.load.call(ctx, id, { ssr: true });
286
+ }
287
+
288
+ it("replaces the server module with a tiny marker and writes the asset to the client outDir", () => {
289
+ const p = buildPlugin({ metaAsset: true });
290
+ const code = loadMeta(p, COMPOSED);
291
+ expect(code).not.toContain("JSON.parse");
292
+ const ref = JSON.parse(code.replace(/^export default /, "").replace(/;$/, "")).__decoMetaAsset;
293
+ expect(ref.path).toMatch(/^\/_deco\/meta-[0-9a-f]{16}\.json$/);
294
+
295
+ p.writeBundle.call({ environment: { name: "ssr" } });
296
+ const written = JSON.parse(readFileSync(path.join(dir, "dist/client", ref.path), "utf8"));
297
+ // Same wire format handleMeta always served: the schema plus its ETag.
298
+ expect(written).toEqual({ ...JSON.parse(COMPOSED), etag: ref.etag });
299
+ });
300
+
301
+ it("emits the asset from the client build too, for the reverse build order", () => {
302
+ const p = buildPlugin({ metaAsset: true });
303
+ loadMeta(p, COMPOSED);
304
+ const emitted = [];
305
+ p.generateBundle.call(
306
+ { environment: { name: "client" }, emitFile: (f) => emitted.push(f) },
307
+ {},
308
+ {},
309
+ );
310
+ expect(emitted).toHaveLength(1);
311
+ expect(emitted[0].fileName).toMatch(/^_deco\/meta-[0-9a-f]{16}\.json$/);
312
+ });
313
+
314
+ it("keeps a raw (not pre-composed) schema in the bundle, with a warning", () => {
315
+ const p = buildPlugin({ metaAsset: true });
316
+ const warn = vi.fn();
317
+ const code = loadMeta(p, '{"major":1,"schema":{}}', { warn });
318
+ expect(code).toContain("JSON.parse(");
319
+ expect(warn).toHaveBeenCalledOnce();
320
+ });
321
+
322
+ it("is off by default, and off in dev", () => {
323
+ expect(loadMeta(buildPlugin(), COMPOSED)).toContain("JSON.parse(");
324
+ const dev = buildPlugin({ metaAsset: true });
325
+ dev.config({}, { command: "serve" });
326
+ expect(loadMeta(dev, COMPOSED)).toContain("JSON.parse(");
327
+ });
328
+
329
+ it("buildMetaAsset merges the etag textually and rejects non-objects", () => {
330
+ const asset = buildMetaAsset(COMPOSED);
331
+ expect(JSON.parse(asset.payload).etag).toBe(asset.etag);
332
+ expect(buildMetaAsset("[1]")).toBeNull();
333
+ expect(buildMetaAsset("not json")).toBeNull();
334
+ });
335
+ });