@decocms/start 4.0.0 → 4.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/start",
3
- "version": "4.0.0",
3
+ "version": "4.1.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework for TanStack Start - CMS bridge, admin protocol, hooks, schema generation",
6
6
  "main": "./src/index.ts",
@@ -6,6 +6,7 @@ import {
6
6
  getLogLevel,
7
7
  type LoggerAdapter,
8
8
  logger,
9
+ serializeError,
9
10
  setLogLevel,
10
11
  } from "./logger";
11
12
 
@@ -133,3 +134,55 @@ describe("configureLogger", () => {
133
134
  logSpy.mockRestore();
134
135
  });
135
136
  });
137
+
138
+ describe("serializeError", () => {
139
+ it("flattens an Error into a JSON-safe shape with stack", () => {
140
+ const err = new Error("boom");
141
+ const out = serializeError(err);
142
+ expect(out).toEqual({ name: "Error", message: "boom", stack: err.stack });
143
+ });
144
+
145
+ it("preserves subclass name (TypeError, RangeError, custom)", () => {
146
+ expect(serializeError(new TypeError("bad type")).name).toBe("TypeError");
147
+ class MyErr extends Error {
148
+ override name = "MyErr";
149
+ }
150
+ expect(serializeError(new MyErr("custom")).name).toBe("MyErr");
151
+ });
152
+
153
+ it("survives JSON.stringify round-trip", () => {
154
+ const err = new Error("round-trip");
155
+ const out = serializeError(err);
156
+ expect(() => JSON.parse(JSON.stringify(out))).not.toThrow();
157
+ expect(JSON.parse(JSON.stringify(out)).message).toBe("round-trip");
158
+ });
159
+
160
+ it("captures plain objects as JSON in message, marking them as NonError", () => {
161
+ const out = serializeError({ code: 500, body: "vtex down" });
162
+ expect(out.name).toBe("NonError");
163
+ expect(out.message).toBe('{"code":500,"body":"vtex down"}');
164
+ expect(out.stack).toBeUndefined();
165
+ });
166
+
167
+ it("falls back to String() when an object has circular refs", () => {
168
+ const circ: Record<string, unknown> = { a: 1 };
169
+ circ.self = circ;
170
+ const out = serializeError(circ);
171
+ expect(out.name).toBe("NonError");
172
+ expect(typeof out.message).toBe("string");
173
+ expect(out.stack).toBeUndefined();
174
+ });
175
+
176
+ it("handles primitives (string, number, null, undefined)", () => {
177
+ expect(serializeError("just a string")).toEqual({
178
+ name: "NonError",
179
+ message: "just a string",
180
+ });
181
+ expect(serializeError(42)).toEqual({ name: "NonError", message: "42" });
182
+ expect(serializeError(null)).toEqual({ name: "NonError", message: "null" });
183
+ expect(serializeError(undefined)).toEqual({
184
+ name: "NonError",
185
+ message: "undefined",
186
+ });
187
+ });
188
+ });
package/src/sdk/logger.ts CHANGED
@@ -127,11 +127,25 @@ function shouldLog(level: LogLevel): boolean {
127
127
  // ---------------------------------------------------------------------------
128
128
 
129
129
  /**
130
- * Mirrors `@deco/deco/o11y` logger:
131
- * - first arg is the message
130
+ * Strict structured logger. Mirrors `@deco/deco/o11y`:
131
+ * - first arg is a human-readable message string
132
132
  * - optional second arg is a flat attributes object
133
133
  *
134
- * Adapters decide the destination (stdout JSON, OTLP, both, …).
134
+ * Adapters decide the destination (stdout JSON, OTLP, both, …). The
135
+ * contract is intentionally narrow so structured output stays predictable
136
+ * across all sinks.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * logger.info("checkout started", { orderFormId, items });
141
+ * logger.warn("retrying vtex call", { attempt, host });
142
+ *
143
+ * // For Errors, serialize explicitly into the attrs payload:
144
+ * try { ... } catch (err) {
145
+ * const e = serializeError(err);
146
+ * logger.error(e.message, { error: e, stage: "checkout" });
147
+ * }
148
+ * ```
135
149
  */
136
150
  export interface Logger {
137
151
  debug(msg: string, attrs?: Record<string, unknown>): void;
@@ -140,6 +154,47 @@ export interface Logger {
140
154
  error(msg: string, attrs?: Record<string, unknown>): void;
141
155
  }
142
156
 
157
+ /**
158
+ * Normalised, JSON-safe error shape suitable for inclusion in logger
159
+ * attributes. `serializeError` always returns this shape regardless of
160
+ * what was thrown.
161
+ */
162
+ export interface SerializedError {
163
+ name: string;
164
+ message: string;
165
+ stack?: string;
166
+ }
167
+
168
+ /**
169
+ * Convert any thrown value into a flat, structured object that survives
170
+ * `JSON.stringify` and round-trips cleanly to OTel / Cloudflare Logs.
171
+ * Strict logger sites should call this from their catch blocks rather
172
+ * than passing the Error directly.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * try { ... } catch (err) {
177
+ * const e = serializeError(err);
178
+ * logger.error(e.message, { error: e });
179
+ * }
180
+ * ```
181
+ */
182
+ export function serializeError(err: unknown): SerializedError {
183
+ if (err instanceof Error) {
184
+ return { name: err.name, message: err.message, stack: err.stack };
185
+ }
186
+ if (err && typeof err === "object") {
187
+ let body: string;
188
+ try {
189
+ body = JSON.stringify(err);
190
+ } catch {
191
+ body = String(err);
192
+ }
193
+ return { name: "NonError", message: body };
194
+ }
195
+ return { name: "NonError", message: String(err) };
196
+ }
197
+
143
198
  function emit(level: LogLevel, msg: string, attrs?: Record<string, unknown>): void {
144
199
  if (!shouldLog(level)) return;
145
200
  try {
@@ -31,7 +31,7 @@
31
31
  * export default defineConfig({ plugins: [decoVitePlugin(), ...] });
32
32
  * ```
33
33
  */
34
- import { readFileSync, existsSync } from "node:fs";
34
+ import { existsSync, readFileSync } from "node:fs";
35
35
 
36
36
  // Bare-specifier stubs resolved by ID before Vite touches them.
37
37
  /** @type {Record<string, string>} */
@@ -44,6 +44,23 @@ const CLIENT_STUBS = {
44
44
  "tanstack-start-injected-head-scripts:v": "\0stub:tanstack-head-scripts",
45
45
  };
46
46
 
47
+ // SSR-only stubs. Same mechanism as CLIENT_STUBS but applied to the worker
48
+ // SSR build instead of the browser build.
49
+ /** @type {Record<string, string>} */
50
+ const SSR_STUBS = {
51
+ // `@opentelemetry/resources` (transitively pulled in by sdk-logs /
52
+ // sdk-metrics / exporter-* OTel packages — five copies in node_modules due
53
+ // to OTel monorepo peer-dep version pinning) statically imports bare `fs`
54
+ // inside its node-platform machine-id detectors. We never call those
55
+ // detectors — `instrumentWorker` builds the OTel Resource from explicit
56
+ // attributes only — but Vite's CF Workers SSR resolver still walks the
57
+ // re-export barrel and chokes on the bare `fs` specifier (workerd's
58
+ // `nodejs_compat` only exposes the prefixed `node:fs`, not the legacy
59
+ // bare form). Stub it; the static import resolves and the unreachable
60
+ // detector code is never executed.
61
+ fs: "\0stub:bare-fs",
62
+ };
63
+
47
64
  // Minimal stub source for each virtual module.
48
65
  /** @type {Record<string, string>} */
49
66
  const STUB_SOURCE = {
@@ -72,13 +89,18 @@ const STUB_SOURCE = {
72
89
  "export default { AsyncLocalStorage: _ALS, AsyncResource, executionAsyncId, createHook };",
73
90
  ].join("\n"),
74
91
 
75
- "\0stub:tanstack-head-scripts":
76
- "export const injectedHeadScripts = undefined;",
92
+ "\0stub:tanstack-head-scripts": "export const injectedHeadScripts = undefined;",
77
93
 
78
94
  // The admin schema bundle is server-only — the client receives pre-resolved
79
95
  // blocks via the SSR payload. Stubbing it on the client cuts a large module
80
96
  // (typically 0.5-5 MB) out of the browser bundle.
81
97
  "\0stub:meta-gen": "export default {};",
98
+
99
+ // Bare `fs` shim — see SSR_STUBS comment above for the rationale. Surfaces
100
+ // just enough of `import { promises as fs } from 'fs'` to satisfy static
101
+ // module resolution; method calls would throw, but the OTel detector code
102
+ // path is unreachable from `instrumentWorker`.
103
+ "\0stub:bare-fs": "export const promises = {}; export default { promises };",
82
104
  };
83
105
 
84
106
  /** @returns {import("vite").PluginOption} */
@@ -89,6 +111,9 @@ export function decoVitePlugin() {
89
111
  enforce: "pre",
90
112
 
91
113
  resolveId(id, importer, options) {
114
+ // SSR-only stubs — must be checked first since the client guard below
115
+ // returns undefined for everything that hasn't matched yet on SSR.
116
+ if (options?.ssr && SSR_STUBS[id]) return SSR_STUBS[id];
92
117
  // Server builds keep the real modules.
93
118
  if (options?.ssr) return undefined;
94
119
  // Bare-specifier exact-match stubs (react-dom/server, node:stream, etc.).
@@ -98,10 +123,7 @@ export function decoVitePlugin() {
98
123
  // plugin works whether `setup.ts` imports the .json directly (current)
99
124
  // or a future variant routes through a generated .ts wrapper.
100
125
  // Requires `importer` so we don't accidentally stub the entry module.
101
- if (
102
- importer &&
103
- (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))
104
- ) {
126
+ if (importer && (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))) {
105
127
  return "\0stub:meta-gen";
106
128
  }
107
129
  return undefined;
@@ -154,7 +176,6 @@ export function decoVitePlugin() {
154
176
  const siteName = process.env.DECO_SITE_NAME;
155
177
  const envName = process.env.DECO_ENV_NAME;
156
178
  if (siteName && envName) {
157
-
158
179
  // Daemon files are .ts and live inside node_modules. Node's
159
180
  // experimental strip-types refuses to transpile node_modules, so
160
181
  // a plain dynamic `import()` blows up under `vite dev`. Use tsx's
@@ -214,18 +235,12 @@ export function decoVitePlugin() {
214
235
  rollupOptions: {
215
236
  output: {
216
237
  manualChunks(id) {
217
- if (
218
- id.includes("node_modules/react-dom") ||
219
- id.includes("node_modules/react/")
220
- ) {
238
+ if (id.includes("node_modules/react-dom") || id.includes("node_modules/react/")) {
221
239
  return "vendor-react";
222
240
  }
223
241
 
224
242
  // TanStack Router — client-side router (always needed)
225
- if (
226
- id.includes("@tanstack/react-router") ||
227
- id.includes("@tanstack/router-core")
228
- ) {
243
+ if (id.includes("@tanstack/react-router") || id.includes("@tanstack/router-core")) {
229
244
  return "vendor-router";
230
245
  }
231
246
 
@@ -275,8 +290,7 @@ export function decoVitePlugin() {
275
290
  configEnvironment(name, env) {
276
291
  if (name === "ssr" || name === "client") {
277
292
  env.optimizeDeps = env.optimizeDeps || {};
278
- env.optimizeDeps.esbuildOptions =
279
- env.optimizeDeps.esbuildOptions || {};
293
+ env.optimizeDeps.esbuildOptions = env.optimizeDeps.esbuildOptions || {};
280
294
  env.optimizeDeps.esbuildOptions.jsx = "automatic";
281
295
  env.optimizeDeps.esbuildOptions.jsxImportSource = "react";
282
296
  }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { decoVitePlugin } from "./plugin.js";
3
+
4
+ /**
5
+ * The Vite plugin's `resolveId` / `load` hooks are pure functions over their
6
+ * inputs, so we can exercise them without spinning up a Vite environment.
7
+ */
8
+
9
+ function getPlugin() {
10
+ const result = decoVitePlugin();
11
+ // decoVitePlugin returns a single plugin object today, but the type is
12
+ // `PluginOption` which permits arrays — handle both.
13
+ return Array.isArray(result) ? result[0] : result;
14
+ }
15
+
16
+ describe("decoVitePlugin SSR stubs", () => {
17
+ it("rewrites bare `fs` to a virtual module on SSR", () => {
18
+ const p = getPlugin();
19
+ const id = p.resolveId.call({}, "fs", undefined, { ssr: true });
20
+ expect(id).toBe("\0stub:bare-fs");
21
+ });
22
+
23
+ it("does NOT rewrite bare `fs` on client (browser builds don't import fs)", () => {
24
+ const p = getPlugin();
25
+ const id = p.resolveId.call({}, "fs", undefined, { ssr: false });
26
+ expect(id).toBeUndefined();
27
+ });
28
+
29
+ it("loads an empty surface for the bare-fs virtual module", () => {
30
+ const p = getPlugin();
31
+ const src = p.load.call({}, "\0stub:bare-fs", { ssr: true });
32
+ expect(src).toContain("export const promises = {}");
33
+ expect(src).toContain("export default");
34
+ });
35
+
36
+ it("does not interfere with real SSR modules", () => {
37
+ const p = getPlugin();
38
+ expect(p.resolveId.call({}, "@decocms/start/cms", undefined, { ssr: true })).toBeUndefined();
39
+ });
40
+ });
41
+
42
+ describe("decoVitePlugin client stubs (regression guard)", () => {
43
+ it("still rewrites node:async_hooks on the client build", () => {
44
+ const p = getPlugin();
45
+ const id = p.resolveId.call({}, "node:async_hooks", undefined, { ssr: false });
46
+ expect(id).toBe("\0stub:node-async-hooks");
47
+ });
48
+
49
+ it("does not rewrite client stubs on SSR", () => {
50
+ const p = getPlugin();
51
+ const id = p.resolveId.call({}, "react-dom/server", undefined, { ssr: true });
52
+ expect(id).toBeUndefined();
53
+ });
54
+ });