@usequeek/create-theme 0.8.0 → 0.10.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/dist/add.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { type BusinessVocabularyData } from '@usequeek/theme-check';
2
+ import { type BusinessLists } from './lists.js';
3
+ /** Pickers over one resolved vocabulary copy (the command's `--offline`/`--vocabulary`, else bundled). */
4
+ export declare function vocabularyLists(data: BusinessVocabularyData, fallback?: BusinessLists): BusinessLists;
5
+ export interface AddPlan {
6
+ /** Absolute theme folder. */
7
+ dir: string;
8
+ /** What was added, printed by `--json`. */
9
+ added: Record<string, unknown>;
10
+ /** Files written, absolute. */
11
+ files: string[];
12
+ /** File writes, in order. */
13
+ writes: Array<{
14
+ path: string;
15
+ content: string;
16
+ }>;
17
+ /** The new theme.config.ts source (when the plan edits it). */
18
+ configSource?: string;
19
+ }
20
+ /**
21
+ * Add a template for a vocabulary business key: a new demo store (the
22
+ * skeleton's, built the same way `create` builds one per template) declared
23
+ * as the template's design 1. At most the vocabulary and the duplicate
24
+ * checks can refuse it.
25
+ */
26
+ export declare function planAddTemplate(themeDir: string, input: {
27
+ business: string;
28
+ label?: string;
29
+ }, lists?: BusinessLists): Promise<AddPlan>;
30
+ /**
31
+ * Add a design to a template: a copy of the template's first design with
32
+ * fresh ids, declared `{ id, template, design_label }`. The id suggestion is
33
+ * `<key>-2`, then `-3`; a 4th design is refused.
34
+ */
35
+ export declare function planAddDesign(themeDir: string, input: {
36
+ template: string;
37
+ label?: string;
38
+ firstLabel?: string;
39
+ }): Promise<AddPlan>;
40
+ /**
41
+ * Add an optional page (contact, faq) to a design's store, from the
42
+ * skeleton's page — plus the skeleton's menu item for it when the store's
43
+ * header menu lacks one. A page the store already has is refused.
44
+ */
45
+ export declare function planAddPage(themeDir: string, input: {
46
+ page: string;
47
+ template?: string;
48
+ }): Promise<AddPlan>;
49
+ /** Write a plan's files, creating folders. Every path must stay inside the theme folder. */
50
+ export declare function applyAddPlan(plan: AddPlan): void;
package/dist/add.js ADDED
@@ -0,0 +1,257 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { designsOf, groupTemplates, loadContext, TEMPLATE_DESIGNS_MAX, } from '@usequeek/theme-check';
4
+ import { appendDemoEntry, setDesignLabel } from './config-edit.js';
5
+ import { bundledLists, createLists, nearest } from './lists.js';
6
+ import { planTemplates } from './naming.js';
7
+ import { UsageError } from './options.js';
8
+ import { renameContent, SKELETON } from './rename.js';
9
+ import { buildDemoStore, optionalPagesOf, TEMPLATE_DESCRIPTION } from './setup.js';
10
+ import skeletonData from './data/skeleton-store.json' with { type: 'json' };
11
+ /** The skeleton's store, bundled so `add` builds without a starter download. Must match fixtures/starter (add.test.ts fails on drift). */
12
+ const SKELETON_STORE = skeletonData;
13
+ /** Pickers over one resolved vocabulary copy (the command's `--offline`/`--vocabulary`, else bundled). */
14
+ export function vocabularyLists(data, fallback = bundledLists()) {
15
+ return createLists({
16
+ services: data.services,
17
+ catalogue: data.catalogue,
18
+ subcategories: data.subcategories,
19
+ root_service: data.root_service,
20
+ labels: data.labels ?? Object.fromEntries(fallback.businessKeys.map((key) => [key, fallback.labelOf(key)])),
21
+ });
22
+ }
23
+ async function readTheme(themeDir) {
24
+ const dir = resolve(themeDir);
25
+ if (!existsSync(join(dir, 'theme.config.ts'))) {
26
+ throw new UsageError(`No theme.config.ts in ${themeDir}: run this in a theme project (npm create @usequeek/theme), or pass --path.`);
27
+ }
28
+ if (!existsSync(join(dir, 'demo.json'))) {
29
+ throw new UsageError(`No demo.json in ${themeDir}: the primary store is missing, so there is nothing to add to.`);
30
+ }
31
+ const context = await loadContext(dir);
32
+ if (context.themeConfig === null || context.declaredDemos === null) {
33
+ throw new UsageError('theme.config.ts could not be loaded. Fix it first — add writes nothing until it parses.');
34
+ }
35
+ const designs = designsOf({ ...context.themeConfig, demos: context.declaredDemos });
36
+ const name = context.themeConfig.name;
37
+ return {
38
+ dir,
39
+ slug: context.slug,
40
+ name: typeof name === 'string' && name.trim() !== '' ? name : context.slug,
41
+ configSource: readFileSync(join(dir, 'theme.config.ts'), 'utf8'),
42
+ templates: groupTemplates(designs),
43
+ designs,
44
+ stores: context.demos.map((store) => ({ id: store.id, file: store.file, data: (store.data ?? null) })),
45
+ };
46
+ }
47
+ function templateChoices(theme) {
48
+ return theme.templates.map((template) => template.key).filter((key) => key !== null).join(', ');
49
+ }
50
+ /** A store object no other store in the theme uses: the cart is keyed by it. */
51
+ function uniqueShopId(theme, candidate) {
52
+ const clash = theme.stores.find((store) => store.data?.profile?.id === candidate);
53
+ if (clash)
54
+ throw new UsageError(`profile.id "${candidate}" is already used by ${clash.file}. Each store needs its own — the cart is keyed by it.`);
55
+ }
56
+ function checkBusiness(business, lists) {
57
+ if (lists.businessKeys.includes(business))
58
+ return;
59
+ const hint = nearest(business, lists.businessKeys);
60
+ throw new UsageError(hint
61
+ ? `Unknown business "${business}" — did you mean "${hint}"?`
62
+ : `Unknown business "${business}". Choose from: ${lists.businessKeys.join(', ')}`);
63
+ }
64
+ function templateOf(theme, key) {
65
+ const template = theme.templates.find((candidate) => candidate.key === key);
66
+ if (!template) {
67
+ const hint = nearest(key, theme.templates.map((candidate) => candidate.key).filter((candidate) => candidate !== null));
68
+ throw new UsageError(hint
69
+ ? `Unknown template "${key}" — did you mean "${hint}"? Templates: ${templateChoices(theme)}.`
70
+ : `Unknown template "${key}". Templates: ${templateChoices(theme)}.`);
71
+ }
72
+ return template;
73
+ }
74
+ /**
75
+ * Add a template for a vocabulary business key: a new demo store (the
76
+ * skeleton's, built the same way `create` builds one per template) declared
77
+ * as the template's design 1. At most the vocabulary and the duplicate
78
+ * checks can refuse it.
79
+ */
80
+ export async function planAddTemplate(themeDir, input, lists = bundledLists()) {
81
+ const theme = await readTheme(themeDir);
82
+ const business = input.business.trim();
83
+ checkBusiness(business, lists);
84
+ if (theme.templates.some((template) => template.key === business)) {
85
+ throw new UsageError(`Template "${business}" already exists (design "${theme.templates.find((template) => template.key === business).designs[0].id}"). Each business gets one template; add a design to it instead: queek theme add design ${business} --label "<design label>".`);
86
+ }
87
+ if (theme.designs.some((design) => design.id === business)) {
88
+ throw new UsageError(`Design id "${business}" is already taken, and template keys share one namespace with design ids. Pick another business.`);
89
+ }
90
+ const label = (input.label ?? lists.labelOf(business)).trim();
91
+ if (!label)
92
+ throw new UsageError('--label cannot be empty.');
93
+ // The template's `for`, category first (contract R2.7): planTemplates
94
+ // already computes it — a category leads with itself, a niche names only
95
+ // its own key. The new template is never the primary, so its design 1 id
96
+ // is its key, never `default`.
97
+ const [planned] = planTemplates([business], business, lists);
98
+ const forKeys = planned?.for ?? [business];
99
+ // The skeleton renamed to this theme (what `create` runs on the starter
100
+ // before building stores), with the prefix passes as no-ops: only the
101
+ // slug, name and store ids move.
102
+ const renamed = renameContent(JSON.stringify(SKELETON_STORE), '.json', SKELETON, { slug: theme.slug, prefix: SKELETON.prefix, name: theme.name });
103
+ const primary = theme.stores.find((store) => store.id === 'default');
104
+ const store = buildDemoStore(JSON.parse(renamed), {
105
+ slug: theme.slug,
106
+ shopId: `demo-${theme.slug}-${business}`,
107
+ pages: optionalPagesOf((primary?.data ?? {})),
108
+ });
109
+ uniqueShopId(theme, `demo-${theme.slug}-${business}`);
110
+ const entry = { id: business, template: business, label, for: forKeys, description: TEMPLATE_DESCRIPTION };
111
+ return {
112
+ dir: theme.dir,
113
+ added: { type: 'template', template: business, id: business, label, for: forKeys },
114
+ files: [join(theme.dir, 'demos', `${business}.json`), join(theme.dir, 'theme.config.ts')],
115
+ writes: [
116
+ { path: join(theme.dir, 'demos', `${business}.json`), content: `${JSON.stringify(store, null, 2)}\n` },
117
+ { path: join(theme.dir, 'theme.config.ts'), content: appendDemoEntry(theme.configSource, entry) },
118
+ ],
119
+ };
120
+ }
121
+ /**
122
+ * Add a design to a template: a copy of the template's first design with
123
+ * fresh ids, declared `{ id, template, design_label }`. The id suggestion is
124
+ * `<key>-2`, then `-3`; a 4th design is refused.
125
+ */
126
+ export async function planAddDesign(themeDir, input) {
127
+ const theme = await readTheme(themeDir);
128
+ const template = templateOf(theme, input.template.trim());
129
+ const key = template.key;
130
+ if (template.designs.length >= TEMPLATE_DESIGNS_MAX) {
131
+ throw new UsageError(`Template "${key}" already has ${template.designs.length} designs (${template.designs.map((design) => design.id).join(', ')}); a template has at most ${TEMPLATE_DESIGNS_MAX}. Make it a template of another business instead: queek theme add template <business>.`);
132
+ }
133
+ const taken = new Set([...theme.designs.map((design) => design.id), ...theme.templates.map((candidate) => candidate.key)]);
134
+ const id = [`${key}-2`, `${key}-3`].find((candidate) => !taken.has(candidate));
135
+ if (!id)
136
+ throw new UsageError(`No free design id for template "${key}" (${key}-2 and ${key}-3 are both taken).`);
137
+ const label = (input.label ?? '').trim();
138
+ if (!label)
139
+ throw new UsageError('--label <design label> names what tells this design from its template\'s others ("Grill house"). It is required.');
140
+ const [first] = template.designs;
141
+ const firstStore = theme.stores.find((store) => store.id === first.id);
142
+ if (!firstStore || !firstStore.data)
143
+ throw new UsageError(`${first.id === 'default' ? 'demo.json' : `demos/${first.id}.json`} could not be read. Fix it first — add writes nothing until it parses.`);
144
+ const needsFirstLabel = first.designLabel === null;
145
+ const firstLabel = (input.firstLabel ?? '').trim();
146
+ if (needsFirstLabel && !firstLabel) {
147
+ throw new UsageError(`Design "${first.id}" has no design_label, and a template with ${template.designs.length + 1} designs needs one on each. Pass --first-label "<what tells ${first.id} apart>" to name it.`);
148
+ }
149
+ // Fresh ids: its own profile id (the cart is keyed by it), matching shop
150
+ // ids, and page ids under it — everything else stays the template's.
151
+ const shopId = `demo-${theme.slug}-${id}`;
152
+ uniqueShopId(theme, shopId);
153
+ const source = structuredClone(firstStore.data);
154
+ const oldProfileId = source.profile?.id;
155
+ source.profile.id = shopId;
156
+ for (const product of source.products ?? []) {
157
+ product.shop_id = shopId;
158
+ if (product.shop && typeof product.shop === 'object')
159
+ product.shop = { ...product.shop, id: shopId };
160
+ }
161
+ if (typeof oldProfileId === 'string' && oldProfileId !== '') {
162
+ for (const page of Object.values(source.pages ?? {})) {
163
+ if (typeof page.id === 'string' && page.id.startsWith(oldProfileId))
164
+ page.id = `${shopId}${page.id.slice(oldProfileId.length)}`;
165
+ }
166
+ }
167
+ let configSource = appendDemoEntry(theme.configSource, { id, template: key, design_label: label, description: TEMPLATE_DESCRIPTION });
168
+ if (needsFirstLabel)
169
+ configSource = setDesignLabel(configSource, first.id, firstLabel);
170
+ return {
171
+ dir: theme.dir,
172
+ added: { type: 'design', template: key, id, design_label: label, ...(needsFirstLabel ? { first_label: firstLabel, first_design: first.id } : {}) },
173
+ files: [join(theme.dir, 'demos', `${id}.json`), join(theme.dir, 'theme.config.ts')],
174
+ writes: [
175
+ { path: join(theme.dir, 'demos', `${id}.json`), content: `${JSON.stringify(source, null, 2)}\n` },
176
+ { path: join(theme.dir, 'theme.config.ts'), content: configSource },
177
+ ],
178
+ };
179
+ }
180
+ /** Where `add page` writes: the `--template` template's first design, a design id, or the primary. */
181
+ function targetStore(theme, template) {
182
+ if (template === undefined || template.trim() === '') {
183
+ const primary = theme.stores.find((store) => store.id === 'default');
184
+ if (!primary?.data)
185
+ throw new UsageError('demo.json could not be read. Fix it first — add writes nothing until it parses.');
186
+ return { id: primary.id, file: primary.file, data: primary.data };
187
+ }
188
+ const wanted = template.trim();
189
+ const byTemplate = theme.templates.find((candidate) => candidate.key === wanted);
190
+ const designId = byTemplate ? byTemplate.designs[0].id : wanted;
191
+ const store = theme.stores.find((candidate) => candidate.id === designId);
192
+ if (!byTemplate && !store) {
193
+ const hint = nearest(wanted, theme.templates.map((candidate) => candidate.key).filter((candidate) => candidate !== null));
194
+ throw new UsageError(hint
195
+ ? `Unknown template "${wanted}" — did you mean "${hint}"? Templates: ${templateChoices(theme)}.`
196
+ : `Unknown template "${wanted}". Templates: ${templateChoices(theme)}.`);
197
+ }
198
+ if (!store?.data)
199
+ throw new UsageError(`${designId === 'default' ? 'demo.json' : `demos/${designId}.json`} could not be read. Fix it first — add writes nothing until it parses.`);
200
+ return { id: store.id, file: store.file, data: store.data };
201
+ }
202
+ /**
203
+ * Add an optional page (contact, faq) to a design's store, from the
204
+ * skeleton's page — plus the skeleton's menu item for it when the store's
205
+ * header menu lacks one. A page the store already has is refused.
206
+ */
207
+ export async function planAddPage(themeDir, input) {
208
+ if (input.page !== 'contact' && input.page !== 'faq') {
209
+ throw new UsageError(`Unknown page "${input.page}". Choose from: contact, faq.`);
210
+ }
211
+ const theme = await readTheme(themeDir);
212
+ const target = targetStore(theme, input.template);
213
+ const pages = target.data.pages ?? {};
214
+ if (input.page in pages) {
215
+ throw new UsageError(`Design "${target.id}" already has a ${input.page} page (${target.file}). Nothing was written.`);
216
+ }
217
+ const skeletonPages = (SKELETON_STORE.pages ?? {});
218
+ const skeletonPage = skeletonPages[input.page];
219
+ if (!skeletonPage)
220
+ throw new Error(`The bundled skeleton has no ${input.page} page.`);
221
+ const page = structuredClone(skeletonPage);
222
+ const profileId = target.data.profile?.id;
223
+ if (typeof page.id === 'string' && typeof profileId === 'string' && page.id.startsWith('demo-bare')) {
224
+ page.id = `${profileId}${page.id.slice('demo-bare'.length)}`;
225
+ }
226
+ const store = structuredClone(target.data);
227
+ store.pages = { ...pages, [input.page]: page };
228
+ // The skeleton's menu item for the page (faq has one; contact does not),
229
+ // restored when the store's header menu lacks it — the inverse of create
230
+ // dropping it when the page is not written.
231
+ const skeletonItem = (SKELETON_STORE.menus ?? [])
232
+ .flatMap((menu) => menu.items ?? [])
233
+ .find((item) => item.type === 'page' && item.ref === input.page);
234
+ const menus = store.menus ?? [];
235
+ const header = menus.find((menu) => menu.location === 'header' && Array.isArray(menu.items)) ?? menus.find((menu) => Array.isArray(menu.items));
236
+ if (skeletonItem && header && !header.items.some((item) => item.type === 'page' && item.ref === input.page)) {
237
+ header.items = [...header.items, structuredClone(skeletonItem)];
238
+ }
239
+ const path = join(theme.dir, target.file);
240
+ return {
241
+ dir: theme.dir,
242
+ added: { type: 'page', page: input.page, design: target.id },
243
+ files: [path],
244
+ writes: [{ path, content: `${JSON.stringify(store, null, 2)}\n` }],
245
+ };
246
+ }
247
+ /** Write a plan's files, creating folders. Every path must stay inside the theme folder. */
248
+ export function applyAddPlan(plan) {
249
+ for (const write of plan.writes) {
250
+ const relativePath = relative(plan.dir, write.path);
251
+ if (relativePath.startsWith('..') || relativePath === '') {
252
+ throw new Error(`Refusing to write outside the theme folder: ${write.path}`);
253
+ }
254
+ mkdirSync(join(plan.dir, relativePath.split('/').slice(0, -1).join('/')), { recursive: true });
255
+ writeFileSync(write.path, write.content);
256
+ }
257
+ }
@@ -0,0 +1,7 @@
1
+ /** Push a demos[] entry, creating the array when the config has none. Everything else stays byte-identical. */
2
+ export declare function appendDemoEntry(source: string, entry: Record<string, unknown>): string;
3
+ /**
4
+ * Set `design_label` on the main design (`designId: 'default'` → default_demo)
5
+ * or a demos[] entry, replacing it when present. Everything else stays byte-identical.
6
+ */
7
+ export declare function setDesignLabel(source: string, designId: string, label: string): string;
@@ -0,0 +1,205 @@
1
+ import { builders, generateCode, parseModule } from 'magicast';
2
+ import { UsageError } from './options.js';
3
+ const isNode = (value) => typeof value === 'object' && value !== null && typeof value.type === 'string';
4
+ const offset = (value) => typeof value === 'number' ? value : null;
5
+ /** The object theme.config.ts declares as its config, located through magicast's AST. */
6
+ function configObjectOf(source) {
7
+ let mod;
8
+ try {
9
+ mod = parseModule(source);
10
+ }
11
+ catch (error) {
12
+ throw new UsageError(`theme.config.ts does not parse (${error.message}). Fix it first — add writes nothing until it parses.`);
13
+ }
14
+ const root = mod.$ast;
15
+ const body = isNode(root) && root.type === 'Program' && Array.isArray(root.body) ? root.body : null;
16
+ if (!body)
17
+ throw new UsageError('theme.config.ts has no config the add command understands. Fix it first — add writes nothing until it parses.');
18
+ const exported = body.find((node) => node.type === 'ExportDefaultDeclaration')?.declaration;
19
+ if (isNode(exported) && exported.type === 'ObjectExpression')
20
+ return exported;
21
+ if (isNode(exported) && exported.type === 'Identifier' && typeof exported.name === 'string') {
22
+ for (const node of body) {
23
+ if (node.type !== 'VariableDeclaration' || !Array.isArray(node.declarations))
24
+ continue;
25
+ for (const declaration of node.declarations) {
26
+ if (isNode(declaration.id) && declaration.id.type === 'Identifier' && declaration.id.name === exported.name &&
27
+ isNode(declaration.init) && declaration.init.type === 'ObjectExpression')
28
+ return declaration.init;
29
+ }
30
+ }
31
+ }
32
+ throw new UsageError('theme.config.ts has no config object as its default export (expected `const config = { … }; export default config;`). Fix it first — add writes nothing until it parses.');
33
+ }
34
+ function objectProperty(obj, name) {
35
+ if (!Array.isArray(obj.properties))
36
+ return null;
37
+ return obj.properties.find((prop) => (prop.type === 'ObjectProperty' || prop.type === 'Property') && !prop.computed &&
38
+ ((isNode(prop.key) && prop.key.type === 'Identifier' && prop.key.name === name) ||
39
+ (isNode(prop.key) && prop.key.type === 'StringLiteral' && prop.key.value === name))) ?? null;
40
+ }
41
+ /** The whitespace starting the line `offset` sits on — the indent new lines mimic. No pattern matching: a plain scan. */
42
+ function indentOfLine(source, offset) {
43
+ let start = offset;
44
+ while (start > 0 && source[start - 1] !== '\n')
45
+ start--;
46
+ let end = start;
47
+ while (end < source.length && (source[end] === ' ' || source[end] === '\t'))
48
+ end++;
49
+ return source.slice(start, end);
50
+ }
51
+ /** Render a value the way the new entry is written: single quotes, two-space indent, escaped. */
52
+ function renderValue(value) {
53
+ return generateCode(builders.literal(value), { quote: 'single', tabWidth: 2 }).code;
54
+ }
55
+ /**
56
+ * The last significant character between two offsets: whitespace, line and
57
+ * block comments and string literals are skipped, so a comma inside a comment
58
+ * never reads as a trailing comma. A small lexer, not a pattern for code.
59
+ */
60
+ function lastSignificantChar(source, from, to) {
61
+ let last = null;
62
+ let i = from;
63
+ while (i < to) {
64
+ const char = source[i];
65
+ if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
66
+ i++;
67
+ continue;
68
+ }
69
+ if (char === '/' && source[i + 1] === '/') {
70
+ while (i < to && source[i] !== '\n')
71
+ i++;
72
+ continue;
73
+ }
74
+ if (char === '/' && source[i + 1] === '*') {
75
+ i += 2;
76
+ while (i < to && !(source[i] === '*' && source[i + 1] === '/'))
77
+ i++;
78
+ i += 2;
79
+ continue;
80
+ }
81
+ if (char === "'" || char === '"' || char === '`') {
82
+ const quote = char;
83
+ i++;
84
+ while (i < to) {
85
+ if (source[i] === '\\') {
86
+ i += 2;
87
+ continue;
88
+ }
89
+ if (source[i] === quote)
90
+ break;
91
+ // A template literal's holes hold code, not text — but only the last
92
+ // character matters here, and a hole cannot end the span.
93
+ i++;
94
+ }
95
+ i++;
96
+ last = quote;
97
+ continue;
98
+ }
99
+ last = char;
100
+ i++;
101
+ }
102
+ return last;
103
+ }
104
+ const newlineOf = (source) => (source.includes('\r\n') ? '\r\n' : '\n');
105
+ /**
106
+ * `key: value` freshly rendered, spliced before the object's closing brace.
107
+ * The text between the last property and the brace decides the comma: a
108
+ * trailing comma already there means none is added, otherwise one is.
109
+ */
110
+ function insertProperty(source, obj, key, renderedValue) {
111
+ let end = offset(obj.end);
112
+ if (end === null || end < 1)
113
+ throw new UsageError('theme.config.ts has a config object the add command cannot place an entry in. Fix it first — add writes nothing until it parses.');
114
+ const properties = Array.isArray(obj.properties) ? obj.properties : [];
115
+ const last = properties[properties.length - 1];
116
+ const lastEnd = last ? offset(last.end) : null;
117
+ // The comma belongs right after the last property, not at the insertion
118
+ // point before the closing brace — splice it there first.
119
+ if (last && lastEnd !== null && lastSignificantChar(source, lastEnd, end - 1) !== ',') {
120
+ source = `${source.slice(0, lastEnd)},${source.slice(lastEnd)}`;
121
+ end += 1;
122
+ }
123
+ const newline = newlineOf(source);
124
+ const outer = indentOfLine(source, end - 1);
125
+ const inner = `${outer} `;
126
+ // The closing brace usually starts its own line already; only add a break
127
+ // when it does not, so no blank line appears.
128
+ const before = source[end - 2];
129
+ const lead = before === '\n' || before === '\r' ? '' : newline;
130
+ const value = renderedValue.split('\n').join(`${newline}${inner}`);
131
+ const text = `${lead}${inner}${key}: ${value}${newline}${outer}`;
132
+ return `${source.slice(0, end - 1)}${text}${source.slice(end - 1)}`;
133
+ }
134
+ /** Push a demos[] entry, creating the array when the config has none. Everything else stays byte-identical. */
135
+ export function appendDemoEntry(source, entry) {
136
+ const config = configObjectOf(source);
137
+ const demos = objectProperty(config, 'demos');
138
+ const newline = newlineOf(source);
139
+ // The array rendered whole (`[ { … } ]`): insertProperty re-indents its
140
+ // continuation lines under the new `demos:` key.
141
+ if (!demos)
142
+ return insertProperty(source, config, 'demos', renderValue([entry]));
143
+ if (!isNode(demos.value) || demos.value.type !== 'ArrayExpression' || !Array.isArray(demos.value.elements)) {
144
+ throw new UsageError('theme.config.ts `demos` is not an array. Fix it first — add writes nothing until it parses.');
145
+ }
146
+ const elements = demos.value.elements;
147
+ const rendered = renderValue(entry);
148
+ if (elements.length === 0) {
149
+ const start = offset(demos.value.start);
150
+ const end = offset(demos.value.end);
151
+ if (start === null || end === null)
152
+ throw new UsageError('theme.config.ts has a `demos` array the add command cannot place an entry in.');
153
+ const outer = indentOfLine(source, start);
154
+ const body = rendered.split('\n').join(`${newline}${outer} `);
155
+ return `${source.slice(0, start + 1)}${newline}${outer} ${body}${newline}${outer}${source.slice(end - 1)}`;
156
+ }
157
+ const lastElement = elements[elements.length - 1];
158
+ const lastEnd = offset(lastElement.end);
159
+ const lastStart = offset(lastElement.start);
160
+ if (lastEnd === null || lastStart === null)
161
+ throw new UsageError('theme.config.ts has a `demos` entry the add command cannot place an entry after.');
162
+ const indent = indentOfLine(source, lastStart);
163
+ const body = rendered.split('\n').join(`${newline}${indent}`);
164
+ return `${source.slice(0, lastEnd)},${newline}${indent}${body}${source.slice(lastEnd)}`;
165
+ }
166
+ /**
167
+ * Set `design_label` on the main design (`designId: 'default'` → default_demo)
168
+ * or a demos[] entry, replacing it when present. Everything else stays byte-identical.
169
+ */
170
+ export function setDesignLabel(source, designId, label) {
171
+ const config = configObjectOf(source);
172
+ let target = null;
173
+ if (designId === 'default') {
174
+ const main = objectProperty(config, 'default_demo');
175
+ if (!main || !isNode(main.value) || main.value.type !== 'ObjectExpression') {
176
+ throw new UsageError('theme.config.ts has no `default_demo` object to name. Fix it first — add writes nothing until it parses.');
177
+ }
178
+ target = main.value;
179
+ }
180
+ else {
181
+ const demos = objectProperty(config, 'demos');
182
+ const elements = demos && isNode(demos.value) && demos.value.type === 'ArrayExpression' && Array.isArray(demos.value.elements)
183
+ ? demos.value.elements
184
+ : null;
185
+ if (!elements)
186
+ throw new UsageError('theme.config.ts has no `demos` array holding the design. Fix it first — add writes nothing until it parses.');
187
+ target = elements.find((element) => {
188
+ if (!isNode(element) || element.type !== 'ObjectExpression')
189
+ return false;
190
+ const id = objectProperty(element, 'id');
191
+ return !!id && isNode(id.value) && id.value.type === 'StringLiteral' && id.value.value === designId;
192
+ }) ?? null;
193
+ if (!target)
194
+ throw new UsageError(`theme.config.ts has no demos[] entry with id "${designId}". Fix it first — add writes nothing until it parses.`);
195
+ }
196
+ const current = objectProperty(target, 'design_label');
197
+ if (current && isNode(current.value)) {
198
+ const start = offset(current.value.start);
199
+ const end = offset(current.value.end);
200
+ if (start === null || end === null)
201
+ throw new UsageError('theme.config.ts has a `design_label` the add command cannot replace.');
202
+ return `${source.slice(0, start)}${renderValue(label)}${source.slice(end)}`;
203
+ }
204
+ return insertProperty(source, target, 'design_label', renderValue(label));
205
+ }