@timber-js/app 0.2.0-alpha.111 → 0.2.0-alpha.113

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.
@@ -0,0 +1,2 @@
1
+ import { i as runSchemaSync } from "./cli-schema-sync-DFZmnmqG.js";
2
+ export { runSchemaSync };
@@ -0,0 +1,357 @@
1
+ import { t as scanRoutes } from "./scanner-DmfoB7iK.js";
2
+ import { join } from "node:path";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { performance } from "node:perf_hooks";
6
+ //#region src/utils/startup-timer.ts
7
+ /**
8
+ * Startup timer — records named phases with their durations.
9
+ *
10
+ * Used by the plugin system to instrument cold start and report a
11
+ * timing breakdown in dev mode. Zero overhead in production (disabled).
12
+ *
13
+ * See design/18-build-system.md, TIM-155.
14
+ */
15
+ /**
16
+ * Create a startup timer that records phase durations.
17
+ */
18
+ function createStartupTimer() {
19
+ const pending = /* @__PURE__ */ new Map();
20
+ const phases = [];
21
+ return {
22
+ start(phase) {
23
+ pending.set(phase, performance.now());
24
+ },
25
+ end(phase) {
26
+ const startMs = pending.get(phase);
27
+ if (startMs === void 0) return 0;
28
+ pending.delete(phase);
29
+ const durationMs = performance.now() - startMs;
30
+ phases.push({
31
+ name: phase,
32
+ startMs,
33
+ durationMs
34
+ });
35
+ return durationMs;
36
+ },
37
+ getPhases() {
38
+ return [...phases].sort((a, b) => a.startMs - b.startMs);
39
+ },
40
+ totalMs() {
41
+ if (phases.length === 0) return 0;
42
+ const sorted = this.getPhases();
43
+ const first = sorted[0];
44
+ const last = sorted[sorted.length - 1];
45
+ return last.startMs + last.durationMs - first.startMs;
46
+ },
47
+ formatSummary() {
48
+ const sorted = this.getPhases();
49
+ if (sorted.length === 0) return "No phases recorded.";
50
+ const lines = sorted.map((p) => {
51
+ const ms = p.durationMs.toFixed(1);
52
+ return ` ${p.name.padEnd(30)} ${ms.padStart(8)}ms`;
53
+ });
54
+ const total = this.totalMs().toFixed(1);
55
+ lines.push(` ${"total".padEnd(30)} ${total.padStart(8)}ms`);
56
+ return ["[timber] startup timing:", ...lines].join("\n");
57
+ }
58
+ };
59
+ }
60
+ /**
61
+ * No-op timer for production builds — all methods are empty.
62
+ */
63
+ function createNoopTimer() {
64
+ return {
65
+ start() {},
66
+ end() {
67
+ return 0;
68
+ },
69
+ getPhases() {
70
+ return [];
71
+ },
72
+ totalMs() {
73
+ return 0;
74
+ },
75
+ formatSummary() {
76
+ return "";
77
+ }
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/plugin-context.ts
82
+ /**
83
+ * Plugin context — internal types and helpers for timber sub-plugins.
84
+ *
85
+ * These are NOT part of the user-facing API. They are consumed by
86
+ * sub-plugins (routing, entries, shims, etc.) via relative imports.
87
+ * The root entry point (index.ts) does not re-export them.
88
+ *
89
+ * Design doc: 18-build-system.md §"Shared Plugin Context"
90
+ */
91
+ /**
92
+ * Resolve `clientJavascript` into a fully resolved config.
93
+ */
94
+ function resolveClientJavascript(config) {
95
+ if (config.clientJavascript !== void 0) {
96
+ if (typeof config.clientJavascript === "boolean") return {
97
+ disabled: !config.clientJavascript,
98
+ enableHMRInDev: !config.clientJavascript
99
+ };
100
+ return {
101
+ disabled: config.clientJavascript.disabled,
102
+ enableHMRInDev: config.clientJavascript.enableHMRInDev ?? config.clientJavascript.disabled
103
+ };
104
+ }
105
+ return {
106
+ disabled: false,
107
+ enableHMRInDev: false
108
+ };
109
+ }
110
+ /**
111
+ * Resolve the app directory. Checks (in order):
112
+ * 1. Explicit `configAppDir` from timber.config.ts
113
+ * 2. `<root>/app`
114
+ * 3. `<root>/src/app`
115
+ *
116
+ * Throws if none exist.
117
+ */
118
+ function resolveAppDir(root, configAppDir) {
119
+ if (configAppDir) {
120
+ const explicit = join(root, configAppDir);
121
+ if (!existsSync(explicit)) throw new Error(`[timber] Configured appDir "${configAppDir}" does not exist at ${explicit}`);
122
+ return explicit;
123
+ }
124
+ const rootApp = join(root, "app");
125
+ if (existsSync(rootApp)) return rootApp;
126
+ const srcApp = join(root, "src", "app");
127
+ if (existsSync(srcApp)) return srcApp;
128
+ throw new Error(`[timber] Could not find app directory. Expected "app/" or "src/app/" in ${root}. You can set appDir in timber.config.ts to specify a custom location.`);
129
+ }
130
+ function createPluginContext(config, root) {
131
+ const projectRoot = root ?? process.cwd();
132
+ const resolvedConfig = { ...config };
133
+ return {
134
+ config: resolvedConfig,
135
+ clientJavascript: resolveClientJavascript(resolvedConfig),
136
+ routeTree: null,
137
+ appDir: join(projectRoot, "app"),
138
+ root: projectRoot,
139
+ dev: false,
140
+ buildManifest: null,
141
+ deploymentId: null,
142
+ timer: createStartupTimer(),
143
+ holdingServer: null,
144
+ buildDir: resolveBuildDir(projectRoot, resolvedConfig.buildDir)
145
+ };
146
+ }
147
+ /** Default build output directory (relative to root). */
148
+ var DEFAULT_BUILD_DIR = join(".timber", "dist");
149
+ /**
150
+ * Resolve the build output directory.
151
+ *
152
+ * Priority:
153
+ * 1. Explicit `timberBuildDir` from timber.config.ts
154
+ * 2. Explicit `viteBuildOutDir` from Vite's build.outDir (if not the default 'dist')
155
+ * 3. Default: `.timber/dist`
156
+ *
157
+ * Returns an absolute path.
158
+ */
159
+ function resolveBuildDir(root, timberBuildDir, viteBuildOutDir) {
160
+ if (timberBuildDir) return join(root, timberBuildDir);
161
+ if (viteBuildOutDir && viteBuildOutDir !== "dist") return join(root, viteBuildOutDir);
162
+ return join(root, DEFAULT_BUILD_DIR);
163
+ }
164
+ /**
165
+ * Load timber.config.ts (or .js, .mjs) from the project root.
166
+ * Returns the config object or null if no config file is found.
167
+ *
168
+ * Uses require() which works for ESM modules on Node 22.12+.
169
+ * This keeps timber() synchronous — no async config loading needed.
170
+ */
171
+ function loadTimberConfigFile(root) {
172
+ const configNames = [
173
+ "timber.config.ts",
174
+ "timber.config.js",
175
+ "timber.config.mjs"
176
+ ];
177
+ const req = createRequire(join(root, "package.json"));
178
+ for (const name of configNames) {
179
+ const configPath = join(root, name);
180
+ if (existsSync(configPath)) {
181
+ const mod = req(configPath);
182
+ return mod.default ?? mod;
183
+ }
184
+ }
185
+ return null;
186
+ }
187
+ /**
188
+ * Detect config keys set in both inline (vite.config.ts) and file (timber.config.ts)
189
+ * and warn the user. The `output` key is excluded because it defaults to 'server'
190
+ * in createPluginContext and would always appear as an inline key.
191
+ *
192
+ * Returns the list of conflicting key names (for testing).
193
+ */
194
+ function warnConfigConflicts(inline, fileConfig) {
195
+ const conflicts = [];
196
+ for (const key of Object.keys(fileConfig)) if (key in inline && inline[key] !== void 0) conflicts.push(key);
197
+ if (conflicts.length > 0) console.warn(`[timber] Config conflict: ${conflicts.map((k) => `"${k}"`).join(", ")} set in both vite.config.ts (inline) and timber.config.ts. Move all config to timber.config.ts to avoid confusion. The inline value from vite.config.ts will be used.`);
198
+ return conflicts;
199
+ }
200
+ /**
201
+ * Merge file-based config into ctx.config. Inline config (already in ctx.config)
202
+ * takes precedence — file config only fills in missing fields.
203
+ */
204
+ function mergeFileConfig(ctx, fileConfig) {
205
+ const inline = ctx.config;
206
+ warnConfigConflicts(inline, fileConfig);
207
+ ctx.config = {
208
+ ...fileConfig,
209
+ ...inline,
210
+ ...fileConfig.limits && inline.limits ? { limits: {
211
+ ...fileConfig.limits,
212
+ ...inline.limits
213
+ } } : {},
214
+ ...fileConfig.dev && inline.dev ? { dev: {
215
+ ...fileConfig.dev,
216
+ ...inline.dev
217
+ } } : {},
218
+ ...fileConfig.mdx && inline.mdx ? { mdx: {
219
+ ...fileConfig.mdx,
220
+ ...inline.mdx
221
+ } } : {}
222
+ };
223
+ }
224
+ //#endregion
225
+ //#region src/cli-schema-sync.ts
226
+ /**
227
+ * `timber schema sync` — scan filesystem for dynamic segments and append
228
+ * missing entries to app/schema.ts with `codec.string` defaults.
229
+ *
230
+ * Only adds, never removes or modifies existing entries.
231
+ *
232
+ * Design doc: design/41-global-params.md §Auto-Scaffolding
233
+ */
234
+ /**
235
+ * Collect all unique bracket-keyed dynamic segment names from the route tree.
236
+ * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.
237
+ */
238
+ function collectDynamicSegments(appDir) {
239
+ const tree = scanRoutes(appDir);
240
+ const segments = /* @__PURE__ */ new Set();
241
+ walkSegments(tree.root, segments);
242
+ return [...segments].sort();
243
+ }
244
+ function walkSegments(node, segments) {
245
+ if (node.paramName) segments.add(node.segmentName);
246
+ for (const child of node.children) walkSegments(child, segments);
247
+ for (const slot of Object.values(node.slots)) walkSegments(slot, segments);
248
+ }
249
+ /**
250
+ * Parse existing bracket keys from an app/schema.ts file.
251
+ * Uses regex to find keys in segmentParams: { '[key]': ... } blocks.
252
+ */
253
+ function parseExistingSchemaKeys(content) {
254
+ const keys = [];
255
+ const re = /['"](\[{1,2}(?:\.{3})?\w+\]{1,2})['"]\s*:/g;
256
+ let m;
257
+ while ((m = re.exec(content)) !== null) keys.push(m[1]);
258
+ return keys;
259
+ }
260
+ /** Schema file extensions to check. */
261
+ var SCHEMA_EXTENSIONS = [
262
+ ".ts",
263
+ ".tsx",
264
+ ".js",
265
+ ".jsx"
266
+ ];
267
+ /**
268
+ * Find the schema file path if it exists.
269
+ */
270
+ function findSchemaFile(appDir) {
271
+ for (const ext of SCHEMA_EXTENSIONS) {
272
+ const p = join(appDir, `schema${ext}`);
273
+ if (existsSync(p)) return p;
274
+ }
275
+ }
276
+ /**
277
+ * Generate the content for a new app/schema.ts with the given segment keys.
278
+ */
279
+ function generateNewSchema(segments) {
280
+ const lines = [];
281
+ lines.push("import { defineSchema, codec } from '@timber-js/app';");
282
+ lines.push("");
283
+ lines.push("export default defineSchema({");
284
+ lines.push(" segmentParams: {");
285
+ for (const seg of segments) lines.push(` '${seg}': codec.string,`);
286
+ lines.push(" },");
287
+ lines.push("});");
288
+ lines.push("");
289
+ return lines.join("\n");
290
+ }
291
+ /**
292
+ * Append missing segment entries to an existing schema file.
293
+ * Inserts new entries before the closing `}` of segmentParams.
294
+ */
295
+ function appendToSchema(content, newSegments) {
296
+ const spIndex = content.indexOf("segmentParams");
297
+ if (spIndex === -1) throw new Error("[timber] Could not find segmentParams in schema file. Expected a defineSchema({ segmentParams: { ... } }) call.");
298
+ const openBrace = content.indexOf("{", spIndex + 13);
299
+ if (openBrace === -1) throw new Error("[timber] Could not find opening brace for segmentParams.");
300
+ let depth = 1;
301
+ let i = openBrace + 1;
302
+ while (i < content.length && depth > 0) {
303
+ if (content[i] === "{") depth++;
304
+ else if (content[i] === "}") depth--;
305
+ i++;
306
+ }
307
+ const closeBrace = i - 1;
308
+ const existingLine = content.slice(openBrace, closeBrace).match(/^(\s+)['"]\[/m);
309
+ const indent = existingLine ? existingLine[1] : " ";
310
+ const insertion = newSegments.map((seg) => `${indent}'${seg}': codec.string,`).join("\n");
311
+ const before = content.slice(0, closeBrace);
312
+ const after = content.slice(closeBrace);
313
+ return before + (before.trimEnd().endsWith(",") ? "\n" : "\n") + insertion + "\n" + after;
314
+ }
315
+ /**
316
+ * Run the schema sync: scan filesystem, diff against schema, append missing.
317
+ */
318
+ function runSchemaSync(projectRoot) {
319
+ const appDir = resolveAppDir(projectRoot);
320
+ const filesystemSegments = collectDynamicSegments(appDir);
321
+ if (filesystemSegments.length === 0) return {
322
+ filesystemSegments: [],
323
+ existingSegments: [],
324
+ addedSegments: [],
325
+ created: false
326
+ };
327
+ const schemaPath = findSchemaFile(appDir);
328
+ if (!schemaPath) {
329
+ writeFileSync(join(appDir, "schema.ts"), generateNewSchema(filesystemSegments), "utf-8");
330
+ return {
331
+ filesystemSegments,
332
+ existingSegments: [],
333
+ addedSegments: filesystemSegments,
334
+ created: true
335
+ };
336
+ }
337
+ const content = readFileSync(schemaPath, "utf-8");
338
+ const existingSegments = parseExistingSchemaKeys(content);
339
+ const missing = filesystemSegments.filter((seg) => !existingSegments.includes(seg));
340
+ if (missing.length === 0) return {
341
+ filesystemSegments,
342
+ existingSegments,
343
+ addedSegments: [],
344
+ created: false
345
+ };
346
+ writeFileSync(schemaPath, appendToSchema(content, missing), "utf-8");
347
+ return {
348
+ filesystemSegments,
349
+ existingSegments,
350
+ addedSegments: missing,
351
+ created: false
352
+ };
353
+ }
354
+ //#endregion
355
+ export { DEFAULT_BUILD_DIR as a, mergeFileConfig as c, resolveClientJavascript as d, createNoopTimer as f, runSchemaSync as i, resolveAppDir as l, findSchemaFile as n, createPluginContext as o, parseExistingSchemaKeys as r, loadTimberConfigFile as s, collectDynamicSegments as t, resolveBuildDir as u };
356
+
357
+ //# sourceMappingURL=cli-schema-sync-DFZmnmqG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-schema-sync-DFZmnmqG.js","names":[],"sources":["../../src/utils/startup-timer.ts","../../src/plugin-context.ts","../../src/cli-schema-sync.ts"],"sourcesContent":["/**\n * Startup timer — records named phases with their durations.\n *\n * Used by the plugin system to instrument cold start and report a\n * timing breakdown in dev mode. Zero overhead in production (disabled).\n *\n * See design/18-build-system.md, TIM-155.\n */\n\nimport { performance } from 'node:perf_hooks';\n\nexport interface PhaseRecord {\n name: string;\n startMs: number;\n durationMs: number;\n}\n\nexport interface StartupTimer {\n /** Mark the beginning of a named phase. */\n start(phase: string): void;\n /** Mark the end of a named phase. Returns duration in ms. */\n end(phase: string): number;\n /** Get all completed phase records, ordered by start time. */\n getPhases(): PhaseRecord[];\n /** Total elapsed time from first start() to last end(). */\n totalMs(): number;\n /** Format a human-readable summary string. */\n formatSummary(): string;\n}\n\n/**\n * Create a startup timer that records phase durations.\n */\nexport function createStartupTimer(): StartupTimer {\n const pending = new Map<string, number>();\n const phases: PhaseRecord[] = [];\n\n return {\n start(phase: string): void {\n pending.set(phase, performance.now());\n },\n\n end(phase: string): number {\n const startMs = pending.get(phase);\n if (startMs === undefined) {\n return 0;\n }\n pending.delete(phase);\n const durationMs = performance.now() - startMs;\n phases.push({ name: phase, startMs, durationMs });\n return durationMs;\n },\n\n getPhases(): PhaseRecord[] {\n return [...phases].sort((a, b) => a.startMs - b.startMs);\n },\n\n totalMs(): number {\n if (phases.length === 0) return 0;\n const sorted = this.getPhases();\n const first = sorted[0];\n const last = sorted[sorted.length - 1];\n return last.startMs + last.durationMs - first.startMs;\n },\n\n formatSummary(): string {\n const sorted = this.getPhases();\n if (sorted.length === 0) return 'No phases recorded.';\n\n const lines = sorted.map((p) => {\n const ms = p.durationMs.toFixed(1);\n return ` ${p.name.padEnd(30)} ${ms.padStart(8)}ms`;\n });\n\n const total = this.totalMs().toFixed(1);\n lines.push(` ${'total'.padEnd(30)} ${total.padStart(8)}ms`);\n\n return ['[timber] startup timing:', ...lines].join('\\n');\n },\n };\n}\n\n/**\n * No-op timer for production builds — all methods are empty.\n */\nexport function createNoopTimer(): StartupTimer {\n return {\n start() {},\n end() {\n return 0;\n },\n getPhases() {\n return [];\n },\n totalMs() {\n return 0;\n },\n formatSummary() {\n return '';\n },\n };\n}\n","/**\n * Plugin context — internal types and helpers for timber sub-plugins.\n *\n * These are NOT part of the user-facing API. They are consumed by\n * sub-plugins (routing, entries, shims, etc.) via relative imports.\n * The root entry point (index.ts) does not re-export them.\n *\n * Design doc: 18-build-system.md §\"Shared Plugin Context\"\n */\n\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { createRequire } from 'node:module';\nimport type { RouteTree } from './routing/types';\nimport type { BuildManifest } from './server/build-manifest';\nimport type { StartupTimer } from './utils/startup-timer';\nimport { createStartupTimer } from './utils/startup-timer';\nimport type { TimberUserConfig, ClientJavascriptConfig } from './config-types.js';\nimport type { HoldingServer } from './dev-tools/holding-server.js';\n\n// Re-export for sub-plugin convenience — they import from plugin-context.ts\nexport type { TimberUserConfig, ClientJavascriptConfig } from './config-types.js';\n\n// ── Client JavaScript config ─────────────────────────────────────────────\n\n/** Fully resolved client JavaScript configuration (no optionals). */\nexport interface ResolvedClientJavascript {\n disabled: boolean;\n enableHMRInDev: boolean;\n}\n\n/**\n * Resolve `clientJavascript` into a fully resolved config.\n */\nexport function resolveClientJavascript(config: TimberUserConfig): ResolvedClientJavascript {\n if (config.clientJavascript !== undefined) {\n if (typeof config.clientJavascript === 'boolean') {\n return {\n disabled: !config.clientJavascript,\n enableHMRInDev: !config.clientJavascript,\n };\n }\n return {\n disabled: config.clientJavascript.disabled,\n enableHMRInDev: config.clientJavascript.enableHMRInDev ?? config.clientJavascript.disabled,\n };\n }\n return { disabled: false, enableHMRInDev: false };\n}\n\n// ── Plugin Context ────────────────────────────────────────────────────────\n\n/**\n * Shared context object passed to all sub-plugins via closure.\n *\n * Sub-plugins communicate through this context — not through Vite's\n * plugin API or global state.\n * See design/18-build-system.md §\"Shared Plugin Context\".\n */\nexport interface PluginContext {\n config: TimberUserConfig;\n /** Resolved client JavaScript configuration */\n clientJavascript: ResolvedClientJavascript;\n /** The scanned route tree (populated by timber-routing, consumed by timber-entries) */\n routeTree: RouteTree | null;\n /** Absolute path to the app/ directory */\n appDir: string;\n /** Absolute path to the project root */\n root: string;\n /** Whether the dev server is running (set by timber-root-sync in configResolved) */\n dev: boolean;\n /** CSS build manifest (populated by adapter after client build, null in dev) */\n buildManifest: BuildManifest | null;\n /** Per-build deployment ID for version skew detection (null in dev) */\n deploymentId: string | null;\n /** Startup timer for profiling cold start phases (active in dev, no-op in prod) */\n timer: StartupTimer;\n /** Holding server that binds the port during dev startup (closed in timber-dev-server) */\n holdingServer?: HoldingServer | null;\n /**\n * Resolved absolute path to the build output directory.\n *\n * Defaults to `<root>/.timber/dist`. Can be overridden via\n * `timber.config.ts` `buildDir` or Vite's `build.outDir`.\n * Timber config takes precedence when both are set.\n *\n * Used by adapter-build and cli preview.\n */\n buildDir: string;\n}\n\n// ── App directory resolution ──────────────────────────────────────────────\n\n/**\n * Resolve the app directory. Checks (in order):\n * 1. Explicit `configAppDir` from timber.config.ts\n * 2. `<root>/app`\n * 3. `<root>/src/app`\n *\n * Throws if none exist.\n */\nexport function resolveAppDir(root: string, configAppDir?: string): string {\n if (configAppDir) {\n const explicit = join(root, configAppDir);\n if (!existsSync(explicit)) {\n throw new Error(`[timber] Configured appDir \"${configAppDir}\" does not exist at ${explicit}`);\n }\n return explicit;\n }\n\n const rootApp = join(root, 'app');\n if (existsSync(rootApp)) return rootApp;\n\n const srcApp = join(root, 'src', 'app');\n if (existsSync(srcApp)) return srcApp;\n\n throw new Error(\n `[timber] Could not find app directory. Expected \"app/\" or \"src/app/\" in ${root}. ` +\n `You can set appDir in timber.config.ts to specify a custom location.`\n );\n}\n\n// ── Plugin context factory ────────────────────────────────────────────────\n\nexport function createPluginContext(config?: TimberUserConfig, root?: string): PluginContext {\n const projectRoot = root ?? process.cwd();\n const resolvedConfig: TimberUserConfig = { ...config };\n return {\n config: resolvedConfig,\n clientJavascript: resolveClientJavascript(resolvedConfig),\n routeTree: null,\n appDir: join(projectRoot, 'app'),\n root: projectRoot,\n dev: false,\n buildManifest: null,\n deploymentId: null,\n timer: createStartupTimer(),\n holdingServer: null,\n buildDir: resolveBuildDir(projectRoot, resolvedConfig.buildDir),\n };\n}\n\n// ── Build directory resolution ────────────────────────────────────────────\n\n/** Default build output directory (relative to root). */\nexport const DEFAULT_BUILD_DIR = join('.timber', 'dist');\n\n/**\n * Resolve the build output directory.\n *\n * Priority:\n * 1. Explicit `timberBuildDir` from timber.config.ts\n * 2. Explicit `viteBuildOutDir` from Vite's build.outDir (if not the default 'dist')\n * 3. Default: `.timber/dist`\n *\n * Returns an absolute path.\n */\nexport function resolveBuildDir(\n root: string,\n timberBuildDir?: string,\n viteBuildOutDir?: string\n): string {\n if (timberBuildDir) {\n return join(root, timberBuildDir);\n }\n if (viteBuildOutDir && viteBuildOutDir !== 'dist') {\n return join(root, viteBuildOutDir);\n }\n return join(root, DEFAULT_BUILD_DIR);\n}\n\n// ── Config file loading ───────────────────────────────────────────────────\n\n/**\n * Load timber.config.ts (or .js, .mjs) from the project root.\n * Returns the config object or null if no config file is found.\n *\n * Uses require() which works for ESM modules on Node 22.12+.\n * This keeps timber() synchronous — no async config loading needed.\n */\nexport function loadTimberConfigFile(root: string): TimberUserConfig | null {\n const configNames = ['timber.config.ts', 'timber.config.js', 'timber.config.mjs'];\n const req = createRequire(join(root, 'package.json'));\n\n for (const name of configNames) {\n const configPath = join(root, name);\n if (existsSync(configPath)) {\n const mod = req(configPath);\n return (mod.default ?? mod) as TimberUserConfig;\n }\n }\n return null;\n}\n\n/**\n * Detect config keys set in both inline (vite.config.ts) and file (timber.config.ts)\n * and warn the user. The `output` key is excluded because it defaults to 'server'\n * in createPluginContext and would always appear as an inline key.\n *\n * Returns the list of conflicting key names (for testing).\n */\nexport function warnConfigConflicts(\n inline: TimberUserConfig,\n fileConfig: TimberUserConfig\n): string[] {\n const conflicts: string[] = [];\n for (const key of Object.keys(fileConfig) as (keyof TimberUserConfig)[]) {\n if (key in inline && inline[key] !== undefined) {\n conflicts.push(key);\n }\n }\n if (conflicts.length > 0) {\n console.warn(\n `[timber] Config conflict: ${conflicts.map((k) => `\"${k}\"`).join(', ')} set in both ` +\n `vite.config.ts (inline) and timber.config.ts. ` +\n `Move all config to timber.config.ts to avoid confusion. ` +\n `The inline value from vite.config.ts will be used.`\n );\n }\n return conflicts;\n}\n\n/**\n * Merge file-based config into ctx.config. Inline config (already in ctx.config)\n * takes precedence — file config only fills in missing fields.\n */\nexport function mergeFileConfig(ctx: PluginContext, fileConfig: TimberUserConfig): void {\n const inline = ctx.config;\n warnConfigConflicts(inline, fileConfig);\n\n ctx.config = {\n ...fileConfig,\n ...inline,\n ...(fileConfig.limits && inline.limits\n ? { limits: { ...fileConfig.limits, ...inline.limits } }\n : {}),\n ...(fileConfig.dev && inline.dev ? { dev: { ...fileConfig.dev, ...inline.dev } } : {}),\n ...(fileConfig.mdx && inline.mdx ? { mdx: { ...fileConfig.mdx, ...inline.mdx } } : {}),\n };\n}\n","/**\n * `timber schema sync` — scan filesystem for dynamic segments and append\n * missing entries to app/schema.ts with `codec.string` defaults.\n *\n * Only adds, never removes or modifies existing entries.\n *\n * Design doc: design/41-global-params.md §Auto-Scaffolding\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { scanRoutes } from './routing/scanner.js';\nimport type { SegmentNode } from './routing/types.js';\nimport { resolveAppDir } from './plugin-context.js';\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from the route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegments(appDir: string): string[] {\n const tree = scanRoutes(appDir);\n const segments = new Set<string>();\n walkSegments(tree.root, segments);\n return [...segments].sort();\n}\n\nfunction walkSegments(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName) {\n // Reconstruct bracket key from segmentName (already has brackets)\n segments.add(node.segmentName);\n }\n for (const child of node.children) {\n walkSegments(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkSegments(slot, segments);\n }\n}\n\n/**\n * Parse existing bracket keys from an app/schema.ts file.\n * Uses regex to find keys in segmentParams: { '[key]': ... } blocks.\n */\nexport function parseExistingSchemaKeys(content: string): string[] {\n const keys: string[] = [];\n // Match quoted bracket keys like '[artistSlug]', '[...slug]', '[[...topic]]'\n const re = /['\"](\\[{1,2}(?:\\.{3})?\\w+\\]{1,2})['\"]\\s*:/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(content)) !== null) {\n keys.push(m[1]);\n }\n return keys;\n}\n\n/** Schema file extensions to check. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Find the schema file path if it exists.\n */\nexport function findSchemaFile(appDir: string): string | undefined {\n for (const ext of SCHEMA_EXTENSIONS) {\n const p = join(appDir, `schema${ext}`);\n if (existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Generate the content for a new app/schema.ts with the given segment keys.\n */\nfunction generateNewSchema(segments: string[]): string {\n const lines: string[] = [];\n lines.push(\"import { defineSchema, codec } from '@timber-js/app';\");\n lines.push('');\n lines.push('export default defineSchema({');\n lines.push(' segmentParams: {');\n for (const seg of segments) {\n lines.push(` '${seg}': codec.string,`);\n }\n lines.push(' },');\n lines.push('});');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Append missing segment entries to an existing schema file.\n * Inserts new entries before the closing `}` of segmentParams.\n */\nfunction appendToSchema(content: string, newSegments: string[]): string {\n // Find the closing brace of segmentParams object.\n // Strategy: find the last entry in segmentParams block, insert after it.\n // Look for the pattern: segmentParams: { ... }\n // We find the closing `},` or `}` that ends segmentParams.\n\n // Find \"segmentParams\" key position\n const spIndex = content.indexOf('segmentParams');\n if (spIndex === -1) {\n throw new Error(\n '[timber] Could not find segmentParams in schema file. ' +\n 'Expected a defineSchema({ segmentParams: { ... } }) call.'\n );\n }\n\n // Find the opening brace after segmentParams\n const openBrace = content.indexOf('{', spIndex + 'segmentParams'.length);\n if (openBrace === -1) {\n throw new Error('[timber] Could not find opening brace for segmentParams.');\n }\n\n // Count braces to find the matching close\n let depth = 1;\n let i = openBrace + 1;\n while (i < content.length && depth > 0) {\n if (content[i] === '{') depth++;\n else if (content[i] === '}') depth--;\n i++;\n }\n // i now points to just after the closing brace\n const closeBrace = i - 1;\n\n // Detect indentation from existing entries\n const existingLine = content.slice(openBrace, closeBrace).match(/^(\\s+)['\"]\\[/m);\n const indent = existingLine ? existingLine[1] : ' ';\n\n // Build insertion text\n const insertion = newSegments.map((seg) => `${indent}'${seg}': codec.string,`).join('\\n');\n\n // Insert before the closing brace\n const before = content.slice(0, closeBrace);\n const after = content.slice(closeBrace);\n\n // Add newline if the content before doesn't end with one\n const separator = before.trimEnd().endsWith(',') ? '\\n' : '\\n';\n\n return before + separator + insertion + '\\n' + after;\n}\n\nexport interface SchemaSyncResult {\n /** Segments found in the filesystem. */\n filesystemSegments: string[];\n /** Segments already defined in app/schema.ts. */\n existingSegments: string[];\n /** Segments that were added. */\n addedSegments: string[];\n /** Whether a new schema file was created. */\n created: boolean;\n}\n\n/**\n * Run the schema sync: scan filesystem, diff against schema, append missing.\n */\nexport function runSchemaSync(projectRoot: string): SchemaSyncResult {\n const appDir = resolveAppDir(projectRoot);\n\n const filesystemSegments = collectDynamicSegments(appDir);\n\n if (filesystemSegments.length === 0) {\n return {\n filesystemSegments: [],\n existingSegments: [],\n addedSegments: [],\n created: false,\n };\n }\n\n const schemaPath = findSchemaFile(appDir);\n\n if (!schemaPath) {\n // Create new schema file\n const newPath = join(appDir, 'schema.ts');\n writeFileSync(newPath, generateNewSchema(filesystemSegments), 'utf-8');\n return {\n filesystemSegments,\n existingSegments: [],\n addedSegments: filesystemSegments,\n created: true,\n };\n }\n\n // Read existing schema and find missing segments\n const content = readFileSync(schemaPath, 'utf-8');\n const existingSegments = parseExistingSchemaKeys(content);\n const missing = filesystemSegments.filter((seg) => !existingSegments.includes(seg));\n\n if (missing.length === 0) {\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: [],\n created: false,\n };\n }\n\n // Append missing segments\n const updated = appendToSchema(content, missing);\n writeFileSync(schemaPath, updated, 'utf-8');\n\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: missing,\n created: false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,SAAgB,qBAAmC;CACjD,MAAM,0BAAU,IAAI,KAAqB;CACzC,MAAM,SAAwB,EAAE;AAEhC,QAAO;EACL,MAAM,OAAqB;AACzB,WAAQ,IAAI,OAAO,YAAY,KAAK,CAAC;;EAGvC,IAAI,OAAuB;GACzB,MAAM,UAAU,QAAQ,IAAI,MAAM;AAClC,OAAI,YAAY,KAAA,EACd,QAAO;AAET,WAAQ,OAAO,MAAM;GACrB,MAAM,aAAa,YAAY,KAAK,GAAG;AACvC,UAAO,KAAK;IAAE,MAAM;IAAO;IAAS;IAAY,CAAC;AACjD,UAAO;;EAGT,YAA2B;AACzB,UAAO,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,MAAM,EAAE,UAAU,EAAE,QAAQ;;EAG1D,UAAkB;AAChB,OAAI,OAAO,WAAW,EAAG,QAAO;GAChC,MAAM,SAAS,KAAK,WAAW;GAC/B,MAAM,QAAQ,OAAO;GACrB,MAAM,OAAO,OAA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aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,6CAA6C;IAC7C,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,gBAAgB,CAwDnE"}
1
+ {"version":3,"file":"cli-schema-sync.d.ts","sourceRoot":"","sources":["../src/cli-schema-sync.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAQH;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAK/D;AAeD;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CASjE;AAKD;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMjE;AAyED,MAAM,WAAW,gBAAgB;IAC/B,wCAAwC;IACxC,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,iDAAiD;IACjD,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,gCAAgC;IAChC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,6CAA6C;IAC7C,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,gBAAgB,CAoDnE"}
package/dist/cli.js CHANGED
@@ -119,7 +119,7 @@ async function runCheck(options) {
119
119
  async function runSchema(args) {
120
120
  const subcommand = args[0];
121
121
  if (subcommand !== "sync") throw new Error(`Unknown schema subcommand: ${subcommand ?? "(none)"}. Usage: timber schema sync`);
122
- const { runSchemaSync } = await import("./_chunks/cli-schema-sync-i2OEL2-p.js");
122
+ const { runSchemaSync } = await import("./_chunks/cli-schema-sync-BhXdbmgS.js");
123
123
  const result = runSchemaSync(process.cwd());
124
124
  if (result.filesystemSegments.length === 0) {
125
125
  console.log("[timber] No dynamic segments found in app/.");