@velastack/patterns 0.1.6 → 0.1.7

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": "@velastack/patterns",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -1,304 +0,0 @@
1
- import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { n as t } from "./logger-CQONztPm.js";
3
- import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
4
- import { a as r, n as i, o as a } from "./ts-morph-helpers-Bk82Z2n7.js";
5
- import { a as o, t as s } from "./config-target-DOi8kI_f.js";
6
- import c from "node:path";
7
- import l from "node:fs";
8
- import { Node as u, Project as d, QuoteKind as f, SyntaxKind as p } from "ts-morph";
9
- //#region src/patterns/enable/cms/modifies/vite-config.ts
10
- var m = [
11
- "Add the CMS plugin to your Vite config, ahead of sveltekit():",
12
- "",
13
- "import { cms } from '@velastack/cms/vite';",
14
- "",
15
- "export default defineConfig({",
16
- " plugins: [cms(), sveltekit(), /* ...existing plugins */],",
17
- "});"
18
- ].join("\n"), h = [
19
- "Create a Vite config with the CMS plugin ahead of sveltekit():",
20
- "",
21
- "import { defineConfig } from 'vite';",
22
- "import { sveltekit } from '@sveltejs/kit/vite';",
23
- "import { cms } from '@velastack/cms/vite';",
24
- "",
25
- "export default defineConfig({",
26
- " plugins: [cms(), sveltekit()],",
27
- "});"
28
- ].join("\n");
29
- function g(e) {
30
- return e.replace(/\s/g, "");
31
- }
32
- function _(e) {
33
- if (!l.existsSync(e)) return {
34
- status: "not-found",
35
- message: h
36
- };
37
- let t = new d({
38
- compilerOptions: { allowJs: !0 },
39
- manipulationSettings: { quoteKind: f.Single }
40
- }).addSourceFileAtPath(e), n = !1, r = !1;
41
- t.getImportDeclarations().some((e) => e.getModuleSpecifierValue() === "@velastack/cms/vite") || (t.insertImportDeclaration(0, {
42
- namedImports: ["cms"],
43
- moduleSpecifier: "@velastack/cms/vite"
44
- }), n = !0);
45
- let i = t.getDescendantsOfKind(p.CallExpression).find((e) => e.getExpression().getText() === "defineConfig")?.getArguments()?.[0], a = i?.getKind() === p.ObjectLiteralExpression ? i : null;
46
- if (!a) r = !0;
47
- else {
48
- let e = a.getProperty("plugins");
49
- if (!e) a.addPropertyAssignment({
50
- name: "plugins",
51
- initializer: "[cms()]"
52
- }), n = !0;
53
- else if (e.getKind() !== p.PropertyAssignment) r = !0;
54
- else {
55
- let t = e.getInitializer();
56
- if (!t) e.setInitializer("[cms()]"), n = !0;
57
- else if (t.getKind() !== p.ArrayLiteralExpression) r = !0;
58
- else {
59
- let e = t, r = e.getElements();
60
- if (!r.some((e) => g(e.getText()).startsWith("cms("))) {
61
- let t = r.findIndex((e) => g(e.getText()).startsWith("sveltekit("));
62
- e.insertElement(t === -1 ? 0 : t, "cms()"), n = !0;
63
- }
64
- }
65
- }
66
- }
67
- return n && (t.formatText(), t.saveSync()), r ? {
68
- status: "failed",
69
- message: m
70
- } : {
71
- status: "success",
72
- changed: n
73
- };
74
- }
75
- //#endregion
76
- //#region src/patterns/enable/cms/modifies/layout.server.ts
77
- var v = { expression: () => "'en'" }, y = {
78
- expression: (e) => `getLocale(${e}.url)`,
79
- imports: [{
80
- namedImports: ["getLocale"],
81
- moduleSpecifier: "$locales/main.url"
82
- }]
83
- };
84
- function b(t, n) {
85
- return e`
86
- const { cms, notFound, gone, redirectTo } = await loadCms(${t}, { locale: ${n} });
87
- if (redirectTo) redirect(308, redirectTo);
88
- if (gone) error(410, 'Gone');
89
- if (notFound) error(404, 'Not found');
90
- `;
91
- }
92
- var x = e`
93
- import { error, redirect } from '@sveltejs/kit';
94
- import { loadCms } from '$lib/cms';
95
-
96
- export const load = async (event) => {
97
- ${b("event", "'en'").split("\n").join("\n ")}
98
-
99
- return { cms };
100
- };
101
- `, S = [
102
- "Call loadCms from the root +layout.server.ts load and return `cms`:",
103
- "",
104
- x,
105
- "",
106
- "loadCms needs the whole event, so a destructured parameter has to become",
107
- "`event` with the destructuring moved into the body."
108
- ].join("\n"), C = [
109
- "Create src/routes/+layout.server.ts with a load that calls loadCms:",
110
- "",
111
- x
112
- ].join("\n");
113
- function w(e, t, n) {
114
- let r = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t);
115
- if (!r) {
116
- e.addImportDeclaration({
117
- namedImports: n,
118
- moduleSpecifier: t
119
- });
120
- return;
121
- }
122
- for (let e of n) r.getNamedImports().some((t) => t.getName() === e) || r.addNamedImport(e);
123
- }
124
- function T(e, t) {
125
- t.namedImports?.length && w(e, t.moduleSpecifier, t.namedImports), !e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t.moduleSpecifier) && e.addImportDeclaration({
126
- moduleSpecifier: t.moduleSpecifier,
127
- defaultImport: t.defaultImport,
128
- namespaceImport: t.namespaceImport
129
- });
130
- }
131
- function E(e) {
132
- if (u.isArrowFunction(e) || u.isFunctionExpression(e)) return e;
133
- if (u.isParenthesizedExpression(e) || u.isAsExpression(e) || u.isSatisfiesExpression(e)) return E(e.getExpression());
134
- if (u.isCallExpression(e)) for (let t of e.getArguments()) {
135
- let e = E(t);
136
- if (e) return e;
137
- }
138
- return null;
139
- }
140
- function D(e) {
141
- let t = e.getFunction("load");
142
- if (t) return t.isExported() ? t : null;
143
- let n = e.getVariableDeclaration("load");
144
- if (!n || !n.getVariableStatement()?.isExported()) return null;
145
- let r = n.getInitializer();
146
- return r ? E(r) : null;
147
- }
148
- function O(e) {
149
- return u.isArrowFunction(e) || u.isFunctionExpression(e) || u.isFunctionDeclaration(e) || u.isMethodDeclaration(e);
150
- }
151
- function k(e, t) {
152
- let n = t.getStatements(), r = n[n.length - 1];
153
- if (!r || !u.isReturnStatement(r) || t.getDescendantsOfKind(p.ReturnStatement).filter((t) => t.getFirstAncestor(O) === e).length !== 1) return null;
154
- let i = r.getExpression();
155
- for (; i && u.isParenthesizedExpression(i);) i = i.getExpression();
156
- return !i || !u.isObjectLiteralExpression(i) ? null : {
157
- statement: r,
158
- object: i
159
- };
160
- }
161
- function A(e, t) {
162
- return e.getProperties().some((e) => u.isPropertyAssignment(e) || u.isShorthandPropertyAssignment(e) ? e.getName() === t : !1);
163
- }
164
- function j(e, t = v) {
165
- if (!l.existsSync(e)) return {
166
- status: "not-found",
167
- message: C
168
- };
169
- if (l.readFileSync(e, "utf8").includes("loadCms(")) return {
170
- status: "success",
171
- changed: !1
172
- };
173
- let n = new d({
174
- compilerOptions: { allowJs: !0 },
175
- manipulationSettings: { quoteKind: f.Single }
176
- }).addSourceFileAtPath(e), r = D(n);
177
- if (!r) return {
178
- status: "failed",
179
- message: S
180
- };
181
- let i = r.getBody();
182
- if (!i || !u.isBlock(i)) return {
183
- status: "failed",
184
- message: S
185
- };
186
- let a = r.getParameters();
187
- if (a.length > 1) return {
188
- status: "failed",
189
- message: S
190
- };
191
- let o = a[0], s = "event", c = null;
192
- if (o) {
193
- if (o.getInitializer() || o.isRestParameter()) return {
194
- status: "failed",
195
- message: S
196
- };
197
- let e = o.getNameNode();
198
- if (u.isIdentifier(e)) s = e.getText();
199
- else if (u.isObjectBindingPattern(e)) c = e.getText();
200
- else return {
201
- status: "failed",
202
- message: S
203
- };
204
- }
205
- let p = k(r, i);
206
- if (!p) return {
207
- status: "failed",
208
- message: S
209
- };
210
- if (!A(p.object, "cms")) {
211
- let e = p.object.getProperties().findIndex((e) => u.isSpreadAssignment(e));
212
- e === -1 ? p.object.addShorthandPropertyAssignment({ name: "cms" }) : p.object.insertShorthandPropertyAssignment(e, { name: "cms" });
213
- }
214
- let m = i.getStatements().indexOf(p.statement);
215
- if (i.insertStatements(m, `\n${b(s, t.expression(s))}\n`), c && o) {
216
- i.insertStatements(0, `const ${c} = ${s};`);
217
- let e = o.getTypeNode()?.getText();
218
- o.replaceWithText(e ? `${s}: ${e}` : s);
219
- } else o || r.addParameter({ name: s });
220
- r.isAsync() || r.setIsAsync(!0), w(n, "@sveltejs/kit", ["error", "redirect"]), w(n, "$lib/cms", ["loadCms"]);
221
- for (let e of t.imports ?? []) T(n, e);
222
- return n.formatText(), n.saveSync(), {
223
- status: "success",
224
- changed: !0
225
- };
226
- }
227
- //#endregion
228
- //#region src/patterns/enable/cms/modifies/layout.svelte.ts
229
- var M = e`
230
- import { AdminBar } from '@velastack/cms';
231
- `, N = "\n<AdminBar />\n", P = [
232
- "Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.",
233
- "",
234
- "Import for the <script> tag:",
235
- "",
236
- M,
237
- "",
238
- "Markup to add at the top level of the layout:",
239
- N.trim()
240
- ].join("\n"), F = [
241
- "Mount <AdminBar /> in the root src/routes/+layout.svelte.",
242
- "",
243
- "Import for a <script lang=\"ts\"> tag:",
244
- "",
245
- M,
246
- "",
247
- "Markup to add at the top level of the layout:",
248
- N.trim()
249
- ].join("\n");
250
- function I(e) {
251
- if (!l.existsSync(e)) return {
252
- status: "not-found",
253
- message: P
254
- };
255
- let t = a.fromPath(e);
256
- return t.hasElement("AdminBar") ? {
257
- status: "success",
258
- changed: !1
259
- } : t.getScript() ? (t.modifyScript((e) => {
260
- let { source: t } = r(e, (e) => {
261
- i(e, [{
262
- namedImports: ["AdminBar"],
263
- moduleSpecifier: "@velastack/cms"
264
- }]);
265
- });
266
- return t;
267
- }), t.appendMarkup(N), t.writeTo(e), {
268
- status: "success",
269
- changed: t.hasChanged()
270
- }) : {
271
- status: "failed",
272
- message: F
273
- };
274
- }
275
- //#endregion
276
- //#region src/patterns/enable/cms/generate.runtime.ts
277
- function L(e, t) {
278
- return e.filter((e) => !l.existsSync(c.join(t, e.path)));
279
- }
280
- async function R(e) {
281
- let r = t(e), i = [], a = (e) => {
282
- e && i.push(e);
283
- };
284
- r.info("Modifying vite.config");
285
- let l = o(e.root, s) ?? c.join(e.root, s[0]);
286
- a(n(l, _(l))), r.info("Modifying src/routes/+layout.server.ts");
287
- let u = c.join(e.root, "src", "routes", "+layout.server.ts"), d = e.features.i18n ? y : v;
288
- a(n(u, j(u, d))), r.info("Modifying src/routes/+layout.svelte");
289
- let f = c.join(e.root, "src", "routes", "+layout.svelte");
290
- return a(n(f, I(f))), {
291
- creates: [],
292
- modifies: i,
293
- deletes: [],
294
- components: [],
295
- packages: [],
296
- collections: [],
297
- collectionPatches: [],
298
- collectionDrops: []
299
- };
300
- }
301
- //#endregion
302
- export { R as generate, L as keepMissing };
303
-
304
- //# sourceMappingURL=generate.runtime-D_acSkBW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-D_acSkBW.js","names":[],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms()` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: \"[cms()]\",\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(\"[cms()]\");\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(\n sveltekitIndex === -1 ? 0 : sveltekitIndex,\n \"cms()\",\n );\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\ntype LoadFunction = ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"$locales/main.url\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nconst LOAD_SNIPPET = dedent`\n import { error, redirect } from '@sveltejs/kit';\n import { loadCms } from '$lib/cms';\n\n export const load = async (event) => {\n ${cmsSnippet(\"event\", \"'en'\").split(\"\\n\").join(\"\\n \")}\n\n return { cms };\n };\n`;\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n LOAD_SNIPPET,\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/+layout.server.ts with a load that calls loadCms:\",\n \"\",\n LOAD_SNIPPET,\n].join(\"\\n\");\n\nfunction ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nfunction ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nfunction findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/** The single, final `return { ... }` of the load body, or null for any other shape. */\nfunction findReturnedObject(\n fn: LoadFunction,\n body: Block,\n): { statement: ReturnStatement; object: ObjectLiteralExpression } | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n // Early returns would need the cms block hoisted above them; refuse rather\n // than guess where it belongs.\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n let expression = last.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n\n return { statement: last, object: expression };\n}\n\nfunction hasProperty(object: ObjectLiteralExpression, name: string): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const params = fn.getParameters();\n if (params.length > 1) return { status: \"failed\", message: FAILURE_HINT };\n\n const param = params[0];\n let eventName = \"event\";\n let destructuring: string | null = null;\n if (param) {\n if (param.getInitializer() || param.isRestParameter()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n eventName = nameNode.getText();\n } else if (Node.isObjectBindingPattern(nameNode)) {\n destructuring = nameNode.getText();\n } else {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n }\n\n const returned = findReturnedObject(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(returned.object, \"cms\")) {\n const spreadIndex = returned.object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n returned.object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n returned.object.insertShorthandPropertyAssignment(spreadIndex, {\n name: \"cms\",\n });\n }\n }\n\n const returnIndex = body.getStatements().indexOf(returned.statement);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (destructuring && param) {\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = param.getTypeNode()?.getText();\n param.replaceWithText(typeText ? `${eventName}: ${typeText}` : eventName);\n } else if (!param) {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"$lib/cms\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/** Mounts `<AdminBar />` at the top level of the root layout. */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which for these files would mean a re-run silently\n * resetting a developer's edits to `$lib/cms.ts` or the backend config. The\n * wiring is theirs once it has been written; a re-run only fills in what is\n * missing.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, modifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = options.features.i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;AAWA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAY,GAAsB;CACzC,OAAO,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgB,EAAiB,GAAuC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAOxD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAc,GAEzD,IAAU,IACV,IAAS;CAMb,AAJkB,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAE1C,MACH,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,KAAK;EACpB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAM,IAJmB,EACtB,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,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