@domandigital/create-site 0.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/dist/cli.js ADDED
@@ -0,0 +1,1094 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/cli.ts
9
+ import { execFileSync } from "child_process";
10
+ import { createInterface } from "readline/promises";
11
+
12
+ // src/run.ts
13
+ import { readFileSync as readFileSync6 } from "fs";
14
+ import { resolve as resolve2 } from "path";
15
+
16
+ // src/answers.ts
17
+ import { readFileSync } from "fs";
18
+
19
+ // src/sectors.ts
20
+ var SECTORS = {
21
+ trades: { label: "Trades and construction", businessTypes: ["LocalBusiness", "HomeAndConstructionBusiness"] },
22
+ beauty: { label: "Beauty and hair", businessTypes: ["LocalBusiness", "HealthAndBeautyBusiness"] },
23
+ clinics: { label: "Clinics and aesthetics", businessTypes: ["LocalBusiness", "MedicalBusiness"] },
24
+ professional: { label: "Professional services", businessTypes: ["LocalBusiness", "ProfessionalService"] }
25
+ };
26
+ var REGISTERS_CHECKED_ON = null;
27
+ var REGISTERS = [
28
+ { id: "gbp", name: "Google Business Profile", url: "https://business.google.com/", condition: "Every business with a place or a service area", sectors: "all" },
29
+ { id: "bing-places", name: "Bing Places", url: "https://www.bingplaces.com/", condition: "Every business with a place or a service area", sectors: "all" },
30
+ { id: "apple-business-connect", name: "Apple Business Connect", url: "https://businessconnect.apple.com/", condition: "Every business with a place or a service area", sectors: "all" },
31
+ { id: "companies-house", name: "Companies House", url: "https://find-and-update.company-information.service.gov.uk/", condition: "Limited companies and LLPs: check the registered name matches site.facts.ts", sectors: "all" },
32
+ { id: "ico", name: "ICO data protection fee register", url: "https://ico.org.uk/", condition: "Businesses that have paid the data protection fee", sectors: "all" },
33
+ { id: "yell", name: "Yell", url: "https://www.yell.com/", condition: "One general UK directory, for consistent contact details", sectors: "all" },
34
+ { id: "gas-safe", name: "Gas Safe Register", url: "https://www.gassaferegister.co.uk/", condition: "Gas work", sectors: ["trades"] },
35
+ { id: "niceic", name: "NICEIC", url: "https://www.niceic.com/", condition: "Electrical contractors registered with NICEIC", sectors: ["trades"] },
36
+ { id: "napit", name: "NAPIT", url: "https://www.napit.org.uk/", condition: "Contractors registered with NAPIT", sectors: ["trades"] },
37
+ { id: "oftec", name: "OFTEC", url: "https://www.oftec.org/", condition: "Oil heating work", sectors: ["trades"] },
38
+ { id: "hetas", name: "HETAS", url: "https://www.hetas.co.uk/", condition: "Solid fuel and stove installation", sectors: ["trades"] },
39
+ { id: "fensa", name: "FENSA", url: "https://www.fensa.org.uk/", condition: "Window and door installation", sectors: ["trades"] },
40
+ { id: "certass", name: "CERTASS", url: "https://www.certass.co.uk/", condition: "Window and door installation", sectors: ["trades"] },
41
+ { id: "mcs", name: "MCS", url: "https://mcscertified.com/", condition: "Heat pumps, solar and other renewables", sectors: ["trades"] },
42
+ { id: "trustmark", name: "TrustMark", url: "https://www.trustmark.org.uk/", condition: "TrustMark registered businesses", sectors: ["trades"] },
43
+ { id: "fmb", name: "Federation of Master Builders", url: "https://www.fmb.org.uk/", condition: "FMB members", sectors: ["trades"] },
44
+ { id: "buy-with-confidence", name: "Buy With Confidence", url: "https://www.buywithconfidence.gov.uk/", condition: "Where the local trading standards service runs it and the business is approved", sectors: ["trades"] },
45
+ { id: "installer-finders", name: "Manufacturer installer finders", url: null, condition: "Accredited installers of a brand that lists them (boilers, EV chargers, heat pumps)", sectors: ["trades"] },
46
+ { id: "babtac", name: "BABTAC", url: "https://www.babtac.com/", condition: "BABTAC members", sectors: ["beauty"] },
47
+ { id: "beauty-guild", name: "The Guild of Beauty Therapists", url: "https://www.beautyguild.com/", condition: "Guild members", sectors: ["beauty"] },
48
+ { id: "council-licence", name: "Council special treatment licence or registration", url: null, condition: "Where the local council licenses the treatments offered", sectors: ["beauty", "clinics"] },
49
+ { id: "brand-salon-finders", name: "Product brand salon finders", url: null, condition: "Salons stocking or trained on a brand that lists them", sectors: ["beauty"] },
50
+ { id: "fresha", name: "Fresha", url: "https://www.fresha.com/", condition: "If the business already takes bookings there", sectors: ["beauty"] },
51
+ { id: "treatwell", name: "Treatwell", url: "https://www.treatwell.co.uk/", condition: "If the business already takes bookings there", sectors: ["beauty"] },
52
+ { id: "cqc", name: "Care Quality Commission", url: "https://www.cqc.org.uk/", condition: "Only where the clinic carries out regulated activities", sectors: ["clinics"] },
53
+ { id: "save-face", name: "Save Face", url: "https://www.saveface.co.uk/", condition: "Accredited aesthetic practitioners", sectors: ["clinics"] },
54
+ { id: "jccp", name: "JCCP", url: "https://www.jccp.org.uk/", condition: "Practitioners on the JCCP register", sectors: ["clinics"] },
55
+ { id: "gmc", name: "GMC register", url: "https://www.gmc-uk.org/", condition: "Doctors", sectors: ["clinics"], personLevel: true },
56
+ { id: "nmc", name: "NMC register", url: "https://www.nmc.org.uk/", condition: "Nurses", sectors: ["clinics"], personLevel: true },
57
+ { id: "gdc", name: "GDC register", url: "https://www.gdc-uk.org/", condition: "Dentists and dental professionals", sectors: ["clinics"], personLevel: true },
58
+ { id: "gphc", name: "GPhC register", url: "https://www.pharmacyregulation.org/", condition: "Pharmacists", sectors: ["clinics"], personLevel: true },
59
+ { id: "doctify", name: "Doctify", url: "https://www.doctify.com/", condition: "Clinics and practitioners listed there", sectors: ["clinics"] },
60
+ { id: "insurer-finders", name: "Private insurer practitioner finders", url: null, condition: "Clinics recognised by a private health insurer", sectors: ["clinics"] },
61
+ { id: "sra", name: "Solicitors Regulation Authority", url: "https://www.sra.org.uk/", condition: "SRA regulated firms", sectors: ["professional"] },
62
+ { id: "law-society", name: "Law Society Find a Solicitor", url: "https://solicitors.lawsociety.org.uk/", condition: "Solicitors' firms", sectors: ["professional"] },
63
+ { id: "icaew", name: "ICAEW", url: "https://www.icaew.com/", condition: "ICAEW registered firms", sectors: ["professional"] },
64
+ { id: "acca", name: "ACCA", url: "https://www.accaglobal.com/", condition: "ACCA practising members", sectors: ["professional"] },
65
+ { id: "aat", name: "AAT", url: "https://www.aat.org.uk/", condition: "AAT licensed accountants", sectors: ["professional"] },
66
+ { id: "ciot", name: "Chartered Institute of Taxation", url: "https://www.tax.org.uk/", condition: "CIOT members", sectors: ["professional"] },
67
+ { id: "fca", name: "FCA register", url: "https://register.fca.org.uk/", condition: "FCA authorised firms", sectors: ["professional"] },
68
+ { id: "rics", name: "RICS", url: "https://www.rics.org/", condition: "RICS regulated firms", sectors: ["professional"] },
69
+ { id: "arb", name: "Architects Registration Board", url: "https://arb.org.uk/", condition: "Architects", sectors: ["professional"], personLevel: true }
70
+ ];
71
+ function registersFor(sector) {
72
+ return REGISTERS.filter((r) => r.sectors === "all" || r.sectors.includes(sector));
73
+ }
74
+
75
+ // src/answers.ts
76
+ var REQUIRED = [
77
+ ["legalName", "--client", "Registered business name"],
78
+ ["siteUrl", "--site-url", "Website address (https://...)"],
79
+ ["sector", "--sector", "Sector (trades, beauty, clinics, professional)"],
80
+ ["description", "--description", "What the business does and where, in a sentence or two"]
81
+ ];
82
+ var list = (value) => Array.isArray(value) ? value.map(String).map((s) => s.trim()).filter(Boolean) : typeof value === "string" ? value.split(",").map((s) => s.trim()).filter(Boolean) : [];
83
+ var text = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
84
+ function validateSiteUrl(value) {
85
+ try {
86
+ const url = new URL(value);
87
+ if (url.protocol !== "https:") return "the site URL must be https";
88
+ if (url.pathname !== "/" || url.search || url.hash) return "the site URL is the origin only, e.g. https://example.co.uk";
89
+ return null;
90
+ } catch {
91
+ return `not a URL: ${value}`;
92
+ }
93
+ }
94
+ async function collectAnswers(sources) {
95
+ let file = {};
96
+ if (sources.file) {
97
+ try {
98
+ file = JSON.parse(readFileSync(sources.file.startsWith("/") ? sources.file : `${sources.cwd}/${sources.file}`, "utf8"));
99
+ } catch (error) {
100
+ return `could not read --answers ${sources.file}: ${error.message}`;
101
+ }
102
+ }
103
+ const pick = (key) => text(sources.flags[key]) ?? text(file[key]);
104
+ const values = {};
105
+ for (const [key] of REQUIRED) values[key] = pick(key);
106
+ const missing = REQUIRED.filter(([key]) => !values[key]);
107
+ if (missing.length > 0 && !sources.ask) {
108
+ return `missing required answers (no prompting without a terminal, or with --yes): ${missing.map(([, flag]) => flag).join(", ")}`;
109
+ }
110
+ for (const [key, , question] of missing) {
111
+ values[key] = text(await sources.ask(`${question}: `));
112
+ if (!values[key]) return `${question} is required`;
113
+ }
114
+ const sector = values.sector;
115
+ if (!(sector in SECTORS)) return `unknown sector "${values.sector}": use one of ${Object.keys(SECTORS).join(", ")}`;
116
+ const urlProblem = validateSiteUrl(values.siteUrl);
117
+ if (urlProblem) return urlProblem;
118
+ const optional = async (key, question) => {
119
+ if (key in file) return file[key];
120
+ if (!sources.ask) return null;
121
+ return (await sources.ask(`${question} (Enter to skip): `)).trim() || null;
122
+ };
123
+ const tradingName = pick("tradingName") ?? text(await optional("tradingName", "Trading name, if different")) ?? values.legalName;
124
+ const phone = text(await optional("phone", "Phone"));
125
+ const email = text(await optional("email", "Email"));
126
+ const locality = text(await optional("locality", "Town or city"));
127
+ const postalCode = text(await optional("postalCode", "Postcode"));
128
+ const serviceAreas = list(await optional("serviceAreas", "Areas served, comma separated"));
129
+ const known = registersFor(sector);
130
+ const registersQuestion = `Registers already held, comma separated ids (${known.map((r) => r.id).join(", ")})`;
131
+ const registers = list(await optional("registers", registersQuestion));
132
+ const unknownRegisters = registers.filter((id) => !known.some((r) => r.id === id));
133
+ if (unknownRegisters.length > 0) return `unknown register id for ${sector}: ${unknownRegisters.join(", ")}`;
134
+ const previousHosts = list(await optional("previousHosts", "Previous website hostname, if moving from one"));
135
+ return {
136
+ legalName: values.legalName,
137
+ tradingName,
138
+ siteUrl: values.siteUrl.replace(/\/$/, ""),
139
+ sector,
140
+ description: values.description,
141
+ phone,
142
+ email,
143
+ locality,
144
+ postalCode,
145
+ serviceAreas,
146
+ registers,
147
+ previousHosts
148
+ };
149
+ }
150
+
151
+ // src/apply.ts
152
+ import { existsSync, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
153
+ import { dirname, join, resolve } from "path";
154
+ function writeInside(root, path, contents) {
155
+ const abs = resolve(root, path);
156
+ if (!abs.startsWith(resolve(root))) throw new Error(`refusing to write outside the project: ${path}`);
157
+ mkdirSync(dirname(abs), { recursive: true });
158
+ writeFileSync(abs, contents);
159
+ }
160
+ function applyPlan(plan, clientName, exec) {
161
+ const { root } = plan.project;
162
+ const pending = [];
163
+ for (const f of plan.files) {
164
+ if (f.action === "create" || f.action === "overwrite") writeInside(root, f.path, f.contents);
165
+ }
166
+ if (plan.packageJson) writeInside(root, "package.json", plan.packageJson.text);
167
+ if (plan.config) writeInside(root, plan.config.file, plan.config.text);
168
+ if (plan.claudeMd) writeInside(root, "CLAUDE.md", plan.claudeMd.text);
169
+ for (const c of plan.commands) exec(c.cmd, c.args, root);
170
+ if (plan.craftInit) {
171
+ const manifest = join(root, "node_modules", "@domandigital", "craft", "package.json");
172
+ if (existsSync(manifest)) {
173
+ const bin = JSON.parse(readFileSync2(manifest, "utf8")).bin?.craft;
174
+ if (bin) exec(process.execPath, [join(dirname(manifest), bin), "direction", "init", "--client", clientName], root);
175
+ else pending.push(`npx craft direction init --client ${JSON.stringify(clientName)}`);
176
+ } else {
177
+ pending.push(`npx craft direction init --client ${JSON.stringify(clientName)}`);
178
+ }
179
+ }
180
+ return pending;
181
+ }
182
+
183
+ // src/args.ts
184
+ import { parseArgs } from "util";
185
+ var USAGE = `create-site: start a Doman Digital client site on the house foundation.
186
+
187
+ Run it inside a fresh Next.js (App Router) or Astro TypeScript project:
188
+ pnpm create next-app@latest acme && cd acme && pnpm create @domandigital/site
189
+ npm create @domandigital/site@latest -- --dry-run (npm needs the --)
190
+
191
+ Usage
192
+ create-site [dir] [--client <legal name>] [--trading-name <name>]
193
+ [--site-url <https://...>] [--sector trades|beauty|clinics|professional]
194
+ [--description "<one or two sentences>"] [--answers <file.json>]
195
+ [--dry-run] [--force] [--skip-install] [--yes] [--help] [--version]
196
+
197
+ --dry-run Print the plan and stop. Writes nothing, runs nothing.
198
+ --force Replace house template files that differ. Data files (the facts,
199
+ routes, links, redirects, DIRECTION and baseline) are never replaced.
200
+ --skip-install Write the package ranges into package.json instead of installing.
201
+ --yes Never prompt. Missing required answers are an error, not a guess.
202
+
203
+ Exit codes: 0 done, 1 refused (nothing written), 2 usage error.`;
204
+ function parseOptions(argv) {
205
+ try {
206
+ const { values, positionals } = parseArgs({
207
+ args: argv,
208
+ allowPositionals: true,
209
+ strict: true,
210
+ options: {
211
+ client: { type: "string" },
212
+ "trading-name": { type: "string" },
213
+ "site-url": { type: "string" },
214
+ sector: { type: "string" },
215
+ description: { type: "string" },
216
+ answers: { type: "string" },
217
+ "dry-run": { type: "boolean", default: false },
218
+ force: { type: "boolean", default: false },
219
+ "skip-install": { type: "boolean", default: false },
220
+ yes: { type: "boolean", short: "y", default: false },
221
+ help: { type: "boolean", short: "h", default: false },
222
+ version: { type: "boolean", default: false }
223
+ }
224
+ });
225
+ if (positionals.length > 1) return `one directory at most, got ${positionals.length}`;
226
+ return {
227
+ dir: positionals[0],
228
+ client: values.client,
229
+ tradingName: values["trading-name"],
230
+ siteUrl: values["site-url"],
231
+ sector: values.sector,
232
+ description: values.description,
233
+ answers: values.answers,
234
+ dryRun: values["dry-run"] ?? false,
235
+ force: values.force ?? false,
236
+ skipInstall: values["skip-install"] ?? false,
237
+ yes: values.yes ?? false,
238
+ help: values.help ?? false,
239
+ version: values.version ?? false
240
+ };
241
+ } catch (error) {
242
+ return error.message;
243
+ }
244
+ }
245
+
246
+ // src/detect.ts
247
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
248
+ import { join as join2 } from "path";
249
+ var LOCKFILES = [
250
+ ["pnpm-lock.yaml", "pnpm"],
251
+ ["package-lock.json", "npm"],
252
+ ["yarn.lock", "yarn"],
253
+ ["bun.lock", "bun"],
254
+ ["bun.lockb", "bun"]
255
+ ];
256
+ var MANAGERS = ["pnpm", "yarn", "bun", "npm"];
257
+ function detectPackageManager(root, userAgent) {
258
+ let fromField;
259
+ try {
260
+ const field = JSON.parse(readFileSync3(join2(root, "package.json"), "utf8")).packageManager;
261
+ fromField = MANAGERS.find((pm) => field?.startsWith(`${pm}@`));
262
+ } catch {
263
+ fromField = void 0;
264
+ }
265
+ const fromLock = LOCKFILES.find(([file]) => existsSync2(join2(root, file)))?.[1] ?? fromField;
266
+ const fromAgent = MANAGERS.find((pm) => userAgent?.startsWith(`${pm}/`));
267
+ if (fromLock && fromAgent && fromLock !== fromAgent) {
268
+ return { pm: fromLock, warning: `this project uses ${fromLock} but this ran under ${fromAgent}: installing with ${fromLock}` };
269
+ }
270
+ return { pm: fromLock ?? fromAgent ?? "npm", warning: null };
271
+ }
272
+ function detectProject(root, userAgent) {
273
+ const pkgPath = join2(root, "package.json");
274
+ if (!existsSync2(pkgPath)) {
275
+ return `no package.json in ${root}. Create the site first (pnpm create next-app@latest, or pnpm create astro@latest), then run this inside it.`;
276
+ }
277
+ const packageJson = readFileSync3(pkgPath, "utf8");
278
+ let pkg;
279
+ try {
280
+ pkg = JSON.parse(packageJson);
281
+ } catch {
282
+ return `package.json in ${root} is not valid JSON.`;
283
+ }
284
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
285
+ const hasNext = "next" in deps;
286
+ const hasAstro = "astro" in deps;
287
+ if (hasNext && hasAstro) return "this project depends on both next and astro. Run it in a project that uses one.";
288
+ if (!hasNext && !hasAstro) return "this is not a Next.js or Astro project (neither next nor astro is a dependency).";
289
+ if (!existsSync2(join2(root, "tsconfig.json"))) return "no tsconfig.json. House sites are TypeScript: create the project with TypeScript on.";
290
+ const { pm, warning } = detectPackageManager(root, userAgent);
291
+ const configFile = (names) => names.find((n) => existsSync2(join2(root, n))) ?? null;
292
+ if (hasNext) {
293
+ const routesDir = ["app", "src/app"].find((d) => existsSync2(join2(root, d)));
294
+ if (!routesDir) {
295
+ const pages = ["pages", "src/pages"].some((d) => existsSync2(join2(root, d)));
296
+ return pages ? "this Next.js project uses the Pages Router only. The scaffold supports the App Router." : "no app/ or src/app/ directory. Run it in a Next.js App Router project.";
297
+ }
298
+ return {
299
+ root,
300
+ framework: "next",
301
+ routesDir,
302
+ srcBase: routesDir === "src/app" ? "src/" : "",
303
+ configFile: configFile(["next.config.ts", "next.config.mjs", "next.config.js"]),
304
+ packageManager: pm,
305
+ packageManagerWarning: warning,
306
+ packageJson
307
+ };
308
+ }
309
+ if (!existsSync2(join2(root, "src", "pages"))) return "no src/pages/ directory. Run it in an Astro project.";
310
+ return {
311
+ root,
312
+ framework: "astro",
313
+ routesDir: "src/pages",
314
+ srcBase: "src/",
315
+ configFile: configFile(["astro.config.mjs", "astro.config.ts", "astro.config.js"]),
316
+ packageManager: pm,
317
+ packageManagerWarning: warning,
318
+ packageJson
319
+ };
320
+ }
321
+
322
+ // src/plan.ts
323
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5 } from "fs";
324
+ import { join as join5 } from "path";
325
+
326
+ // src/adapters.ts
327
+ function layoutFor(project) {
328
+ const base = project.srcBase;
329
+ const shared = [
330
+ { template: "shared/lib/graph/site-adapter.ts", dest: `${base}lib/graph/site-adapter.ts` },
331
+ { template: "shared/lib/graph/page-graph.ts", dest: `${base}lib/graph/page-graph.ts` },
332
+ { template: "shared/tests/seo/coverage.test.ts", dest: "tests/seo/coverage.test.ts" },
333
+ { template: "shared/tests/seo/redirects.test.ts", dest: "tests/seo/redirects.test.ts" },
334
+ { template: "shared/tests/seo/graph.test.ts", dest: "tests/seo/graph.test.ts" },
335
+ { template: "shared/tests/house.test.ts", dest: "tests/house.test.ts" }
336
+ ];
337
+ const siteKeys = {
338
+ facts: "site.facts.ts",
339
+ routes: "site.routes.ts",
340
+ "links.json": "links.json",
341
+ "redirects.json": "redirects.json",
342
+ "site-adapter": `${base}lib/graph/site-adapter.ts`,
343
+ "page-graph": `${base}lib/graph/page-graph.ts`,
344
+ "routes-on-disk": "tests/seo/routes-on-disk.ts"
345
+ };
346
+ if (project.configFile) siteKeys["framework-config"] = project.configFile;
347
+ if (project.framework === "next") {
348
+ siteKeys["components/JsonLd"] = `${base}components/JsonLd.tsx`;
349
+ return {
350
+ siteKeys,
351
+ templates: [
352
+ ...shared,
353
+ { template: "next/tests/seo/routes-on-disk.ts", dest: "tests/seo/routes-on-disk.ts" },
354
+ { template: "next/tests/seo/config.test.ts", dest: "tests/seo/config.test.ts" },
355
+ { template: "next/components/JsonLd.tsx", dest: `${base}components/JsonLd.tsx` },
356
+ { template: "next/components/DesignerCredit.tsx", dest: `${base}components/DesignerCredit.tsx` },
357
+ { template: "next/app/press/page.tsx", dest: `${project.routesDir}/press/page.tsx` },
358
+ { template: "next/app/resources/page.tsx", dest: `${project.routesDir}/resources/page.tsx` }
359
+ ]
360
+ };
361
+ }
362
+ siteKeys["components/JsonLd.astro"] = "src/components/JsonLd.astro";
363
+ return {
364
+ siteKeys,
365
+ templates: [
366
+ ...shared,
367
+ { template: "astro/tests/seo/routes-on-disk.ts", dest: "tests/seo/routes-on-disk.ts" },
368
+ { template: "astro/tests/seo/config.test.ts", dest: "tests/seo/config.test.ts" },
369
+ { template: "astro/components/JsonLd.astro", dest: "src/components/JsonLd.astro" },
370
+ { template: "astro/components/DesignerCredit.astro", dest: "src/components/DesignerCredit.astro" },
371
+ { template: "astro/pages/press.astro", dest: "src/pages/press.astro" },
372
+ { template: "astro/pages/resources/index.astro", dest: "src/pages/resources/index.astro" }
373
+ ]
374
+ };
375
+ }
376
+
377
+ // src/config-patch.ts
378
+ var HEADER_COMMENT = `// redirects.json is the site's one redirect list; tests/seo/redirects.test.ts
379
+ // checks it against every earned link. Added by @domandigital/create-site.`;
380
+ var MANUAL_INSTRUCTIONS = {
381
+ next: "read redirects.json in next.config and return its entries from redirects() as { source: from, destination: to, permanent: permanent ?? true }",
382
+ astro: "read redirects.json in astro.config and set redirects to { [from]: { status: permanent === false ? 302 : 301, destination: to } }"
383
+ };
384
+ function insertAfterImports(text2, block) {
385
+ const lines = text2.split("\n");
386
+ let last = -1;
387
+ lines.forEach((line, i) => {
388
+ if (/from\s+["'][^"']+["'];?\s*$/.test(line) || /^import\s+["'][^"']+["'];?\s*$/.test(line)) last = i;
389
+ });
390
+ lines.splice(last + 1, 0, ...last === -1 ? [block, ""] : ["", block]);
391
+ return lines.join("\n");
392
+ }
393
+ function patchConfig(framework, file, text2) {
394
+ if (text2.includes("redirects.json")) return { kind: "already" };
395
+ if (/\bredirects\b/.test(text2)) return { kind: "manual", reason: `${file} already defines redirects` };
396
+ if (file.endsWith(".js") && /module\.exports/.test(text2)) return { kind: "manual", reason: `${file} is CommonJS` };
397
+ const typed = file.endsWith(".ts");
398
+ const anchor = framework === "next" ? /const nextConfig(?:\s*:\s*NextConfig)?\s*=\s*\{/g : /defineConfig\(\s*\{/g;
399
+ const matches = [...text2.matchAll(anchor)];
400
+ if (matches.length !== 1) return { kind: "manual", reason: `${file} does not have the one config object this can edit safely` };
401
+ const shape = "{ from: string; to: string; permanent?: boolean }[]";
402
+ const type = typed ? `: ${shape}` : "";
403
+ const jsdoc = typed ? "" : `
404
+ /** @type {${shape}} */`;
405
+ const read = framework === "next" ? `JSON.parse(readFileSync(join(process.cwd(), "redirects.json"), "utf8")).redirects` : `JSON.parse(readFileSync(new URL("./redirects.json", import.meta.url), "utf8")).redirects`;
406
+ const imports = framework === "next" ? `import { readFileSync } from "node:fs";
407
+ import { join } from "node:path";` : `import { readFileSync } from "node:fs";`;
408
+ const block = `${imports}
409
+
410
+ ${HEADER_COMMENT}${jsdoc}
411
+ const siteRedirects${type} = ${read};`;
412
+ const property = framework === "next" ? `
413
+ async redirects() {
414
+ return siteRedirects.map((r) => ({ source: r.from, destination: r.to, permanent: r.permanent ?? true }));
415
+ },` : `
416
+ redirects: Object.fromEntries(
417
+ siteRedirects.map((r) => [r.from, { status: r.permanent === false ? 302 : 301, destination: r.to }]),
418
+ ),`;
419
+ const match = matches[0];
420
+ const at = match.index + match[0].length;
421
+ const rest = text2.slice(at);
422
+ const withProperty = `${text2.slice(0, at)}${property}${rest.startsWith("}") ? "\n" : ""}${rest}`;
423
+ return { kind: "patched", text: insertAfterImports(withProperty, block) };
424
+ }
425
+
426
+ // src/package-json.ts
427
+ function patchPackageJson(text2, patch, force) {
428
+ const indent = /^([ \t]+)"/m.exec(text2)?.[1] ?? " ";
429
+ const pkg = JSON.parse(text2);
430
+ const changes = [];
431
+ const section = (key) => {
432
+ if (!pkg[key] || typeof pkg[key] !== "object") pkg[key] = {};
433
+ return pkg[key];
434
+ };
435
+ const scripts = section("scripts");
436
+ for (const [name, command] of Object.entries(patch.scripts)) {
437
+ if (scripts[name] === command) continue;
438
+ if (name in scripts && !force) continue;
439
+ scripts[name] = command;
440
+ changes.push(`script ${name}`);
441
+ }
442
+ for (const [name, command] of Object.entries(patch.scriptsIfMissing)) {
443
+ if (name in scripts) continue;
444
+ scripts[name] = command;
445
+ changes.push(`script ${name}`);
446
+ }
447
+ for (const key of ["dependencies", "devDependencies"]) {
448
+ const wanted = patch[key];
449
+ if (Object.keys(wanted).length === 0) continue;
450
+ const existing = { ...pkg.dependencies, ...pkg.devDependencies };
451
+ const deps = section(key);
452
+ for (const [name, range] of Object.entries(wanted)) {
453
+ if (name in existing) continue;
454
+ deps[name] = range;
455
+ changes.push(`${key === "dependencies" ? "dependency" : "dev dependency"} ${name}@${range}`);
456
+ }
457
+ }
458
+ if (changes.length === 0) return { text: text2, changes };
459
+ return { text: `${JSON.stringify(pkg, null, indent)}${text2.endsWith("\n") ? "\n" : ""}`, changes };
460
+ }
461
+ function hasDependency(text2, name) {
462
+ const pkg = JSON.parse(text2);
463
+ return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
464
+ }
465
+
466
+ // src/patterns.ts
467
+ var DYNAMIC = /^\[.+\]$/;
468
+ var OPTIONAL_CATCH_ALL = /^\[\[\.\.\..+\]\]$/;
469
+ var ROUTE_GROUP = /^\([^.)][^)]*\)$/;
470
+ function policyPatternsFor(bracketPath) {
471
+ const kept = [];
472
+ for (const segment of bracketPath.split("/").filter(Boolean)) {
473
+ if (ROUTE_GROUP.test(segment)) continue;
474
+ if (DYNAMIC.test(segment)) {
475
+ const parent = kept.length > 0 ? `/${kept.join("/")}` : "";
476
+ const pattern = `${parent}/*`;
477
+ return OPTIONAL_CATCH_ALL.test(segment) ? [parent || "/", pattern] : [pattern];
478
+ }
479
+ kept.push(segment);
480
+ }
481
+ return [`/${kept.join("/")}`];
482
+ }
483
+
484
+ // src/render/data.ts
485
+ var q = (value) => value === null ? "null" : JSON.stringify(value);
486
+ var arr = (values) => `[${values.map((v) => JSON.stringify(v)).join(", ")}]`;
487
+ function renderFacts(a, siteAdapterSpec) {
488
+ const address = a.locality || a.postalCode ? `{
489
+ streetAddress: null,
490
+ locality: ${q(a.locality)},
491
+ region: null,
492
+ postalCode: ${q(a.postalCode)},
493
+ country: "GB",
494
+ }` : "null";
495
+ return `// The single source of this business's name, contact details, places and
496
+ // profiles. Pages, components, JSON-LD and the launch checklist all read this
497
+ // file; tests/house.test.ts fails if a page hard-codes a phone number, email
498
+ // or postcode instead. Unknown is null, never a placeholder.
499
+ //
500
+ // Written by @domandigital/create-site. Yours to edit; never overwritten.
501
+
502
+ import type { SiteFacts } from "${siteAdapterSpec}";
503
+
504
+ export const facts: SiteFacts = {
505
+ url: ${JSON.stringify(a.siteUrl)},
506
+ legalName: ${JSON.stringify(a.legalName)},
507
+ tradingName: ${JSON.stringify(a.tradingName)},
508
+ description: ${JSON.stringify(a.description)},
509
+ businessTypes: ${arr(SECTORS[a.sector].businessTypes)},
510
+ phone: ${q(a.phone)},
511
+ email: ${q(a.email)},
512
+ address: ${address},
513
+ geo: null,
514
+ openingHours: [],
515
+ serviceAreas: ${arr(a.serviceAreas)},
516
+ // { name, scheme, number, registerUrl, verifiedOn }. Reaches JSON-LD and
517
+ // the press page only once registerUrl and verifiedOn are both set.
518
+ accreditations: [],
519
+ // { kind, name, url, status }. Only "live" profiles become sameAs.
520
+ profiles: [],
521
+ previousHosts: ${arr(a.previousHosts)},
522
+ };
523
+ `;
524
+ }
525
+ function renderRoutes(routesOnDisk3, dynamicRoutesOnDisk3 = []) {
526
+ const routes = [.../* @__PURE__ */ new Set([...routesOnDisk3, "/press"])].filter((r) => r !== "/resources").sort();
527
+ const entries = routes.map((path) => ` { path: ${JSON.stringify(path)}, indexable: true, inSitemap: true },`);
528
+ const patterns = /* @__PURE__ */ new Map();
529
+ for (const route of dynamicRoutesOnDisk3) {
530
+ for (const pattern of policyPatternsFor(route)) if (pattern.endsWith("/*") && !patterns.has(pattern)) patterns.set(pattern, route);
531
+ }
532
+ for (const [pattern, route] of [...patterns].sort()) {
533
+ entries.push(
534
+ ` { path: ${JSON.stringify(pattern)}, indexable: true, inSitemap: false, isDynamicPattern: true, reason: ${JSON.stringify(
535
+ `Served by ${route}. List each generated URL in the sitemap from its data source.`
536
+ )} },`
537
+ );
538
+ }
539
+ entries.push(
540
+ ` { path: "/resources", indexable: false, inSitemap: false, reason: "Empty until the first linkable asset ships. Index it then." },`
541
+ );
542
+ return `// Every page on the site, what it is trying to rank for, and how pages
543
+ // link to each other. Add a policy entry in the same change that adds a
544
+ // page: tests/seo/coverage.test.ts fails until you do. Every path and
545
+ // routeKey is the URL path with a leading slash.
546
+ //
547
+ // Written by @domandigital/create-site. Yours to edit; never overwritten.
548
+
549
+ import type { LinkDeclaration, PageTarget, RoutePolicyEntry, TrailLabel } from "@domandigital/seo";
550
+
551
+ export const policy: RoutePolicyEntry[] = [
552
+ ${entries.join("\n")}
553
+ ];
554
+
555
+ /** The pages the business wants to rank. Each needs an entry in targets. */
556
+ export const moneyRoutes: string[] = [];
557
+
558
+ export const targets: PageTarget[] = [];
559
+
560
+ /** Which money pages each content page sends authority to. */
561
+ export const internalLinks: LinkDeclaration[] = [];
562
+
563
+ export const trailLabels: TrailLabel[] = [
564
+ { path: "/", label: "Home" },
565
+ { path: "/press", label: "Press" },
566
+ { path: "/resources", label: "Resources" },
567
+ ];
568
+
569
+ /**
570
+ * The site's linkable assets: a cost guide from the client's own job data
571
+ * (only with enough jobs that one outlier cannot move an average; state the
572
+ * method and the date), a calculator, or a practical guide from their own
573
+ * work. dataSource says where the numbers come from; refreshDue is when
574
+ * they are next checked.
575
+ */
576
+ export type LinkableAsset = {
577
+ path: string;
578
+ title: string;
579
+ kind: "cost-guide" | "calculator" | "guide";
580
+ summary: string;
581
+ dataSource: string | null;
582
+ refreshDue: string | null;
583
+ };
584
+
585
+ export const linkableAssets: LinkableAsset[] = [];
586
+ `;
587
+ }
588
+ function renderLinks() {
589
+ return `${JSON.stringify({ $schema: "./node_modules/@domandigital/seo/links.schema.json", links: [] }, null, 2)}
590
+ `;
591
+ }
592
+ function renderRedirects() {
593
+ return `${JSON.stringify({ $schema: "./node_modules/@domandigital/seo/redirects.schema.json", redirects: [] }, null, 2)}
594
+ `;
595
+ }
596
+
597
+ // src/render/docs.ts
598
+ var run = (pm, script) => pm === "npm" ? `npm run ${script}` : `${pm} ${script}`;
599
+ function renderHouseMd(a, project) {
600
+ const pm = project.packageManager;
601
+ const base = project.srcBase;
602
+ return `# ${a.tradingName}
603
+
604
+ The house rules for this Doman Digital site, set up by \`@domandigital/create-site\`
605
+ and imported by \`CLAUDE.md\`. Read \`docs/DIRECTION.md\` before changing anything a
606
+ visitor can read.
607
+
608
+ ## Where things live
609
+
610
+ | What | Where |
611
+ | --- | --- |
612
+ | Name, contact details, places, accreditations, profiles | \`site.facts.ts\` |
613
+ | Every page, its indexing, keyword targets, internal links | \`site.routes.ts\` |
614
+ | Links the business has earned | \`links.json\` |
615
+ | Redirects, including every moved URL | \`redirects.json\` |
616
+ | JSON-LD for a page | \`buildPageGraph\` in \`${base}lib/graph/page-graph.ts\`, through the JsonLd component |
617
+ | Art direction and the reason for each choice | \`art-direction.json\` |
618
+ | Decisions and what is blocked | \`docs/DIRECTION.md\` |
619
+ | Launch listings for this sector | \`docs/seo-launch-checklist.md\` |
620
+ | Search results at launch, 90 days, 6 and 12 months | \`docs/seo-baseline.md\` |
621
+
622
+ ## Rules
623
+
624
+ - **The facts file is the only source of contact details.** Import \`facts\`; never type a phone number, email or postcode into a page. \`tests/house.test.ts\` fails if you do.
625
+ - **Every page gets a policy entry in the same change.** \`tests/seo/coverage.test.ts\` fails until it has one. Paths and routeKeys are URL paths with a leading slash.
626
+ - **Every moved URL gets a redirect**, one hop, to a live page. \`tests/seo/redirects.test.ts\` checks every earned link in \`links.json\`.
627
+ - **One JSON-LD script per page**, built by \`buildPageGraph\`. Never hand-write JSON-LD.
628
+ - **The designer credit** is the DesignerCredit component, unchanged: "Website by Doman Digital", linking to the Doman Digital homepage, \`rel="nofollow"\`. It is never a contract term and never tied to a discount.
629
+ - **Links are earned.** Paying for a link, swapping links, badges that link back and testimonials written for someone else are all out. A sponsorship is for the community, and any link it brings is marked \`rel="sponsored"\` by whoever places it. Any ask for a link goes from the client to someone they already deal with. \`links.json\` records links that exist, not asks.
630
+ - **Every claim cites a source a person can check.** Unknown stays null. A cost guide publishes only with enough real jobs that one outlier cannot move an average, and says how the figures were made and when.
631
+ - **Copy passes the house gate**: \`npx craft copy --gate <files>\`. Art direction passes \`npx craft direction validate\`.
632
+
633
+ ## Commands
634
+
635
+ \`\`\`bash
636
+ ${run(pm, "seo:check")} # coverage, redirects, JSON-LD, house rules
637
+ ${run(pm, "launch:check")} # adds the launch block: credit placed, contact details, a live profile, checked accreditations
638
+ \`\`\`
639
+ `;
640
+ }
641
+ function renderDirection(a, today) {
642
+ return `# ${a.tradingName}: direction
643
+
644
+ Started ${today} by \`@domandigital/create-site\`.
645
+
646
+ ## 0. Authority
647
+
648
+ When two sources disagree, the higher one wins, and the disagreement is written down in section 1, never settled silently. A later date does not settle it.
649
+
650
+ 1. The law and the rules of any regulator the business answers to.
651
+ 2. What the client has signed or confirmed in writing.
652
+ 3. The decisions in section 1 of this file.
653
+ 4. The defaults of the house packages (\`@domandigital/*\`).
654
+ 5. \`CLAUDE.md\`.
655
+ 6. Anything else, including what the live site currently says.
656
+
657
+ ## 1. Decisions
658
+
659
+ A decision that lives only in a conversation will be argued again. Record it here, with what it replaces.
660
+
661
+ | Decision | Reason | Supersedes |
662
+ | --- | --- | --- |
663
+ | ${today}: The site starts on the Doman Digital house foundation: facts file, route policy, backlink register, redirects gate, JSON-LD through the house graph package, and the designer credit | Every build starts the same way and upgrades by bumping packages | Nothing |
664
+
665
+ ## 2. Blocked
666
+
667
+ | Item | Blocked by | Owner | Unblocks |
668
+ | --- | --- | --- | --- |
669
+ | Launch | \`launch:check\` passing: credit placed, phone and postcode set, one live profile, every accreditation checked | Doman Digital | Go-live |
670
+ `;
671
+ }
672
+ function renderChecklist(a) {
673
+ const sector = SECTORS[a.sector];
674
+ const registers = registersFor(a.sector);
675
+ const held = registers.filter((r) => a.registers.includes(r.id));
676
+ const rest = registers.filter((r) => !a.registers.includes(r.id));
677
+ const line = (r) => `- [ ] **${r.name}**${r.url ? ` (${r.url})` : ""}: ${r.condition}.${r.personLevel ? " Held by a person: list it on their profile, not the business." : ""}`;
678
+ const checked = REGISTERS_CHECKED_ON ? `Register list last checked by a person on ${REGISTERS_CHECKED_ON}.` : "**The register list has not yet been checked by a person.** Open each entry before relying on it: confirm the register still exists, that it shows a business website, and how it links.";
679
+ return `# Launch checklist: ${a.tradingName}
680
+
681
+ Sector: ${sector.label}. ${checked}
682
+
683
+ Claim a listing only where the business already qualifies. Nothing here is paid for to get a link, and nobody is cold-asked for one. When a listing goes live, add it to \`profiles\` in \`site.facts.ts\` with status "live" and its URL, and record the link in \`links.json\`.
684
+
685
+ ## Claim: registers the business holds
686
+
687
+ ${held.length > 0 ? held.map(line).join("\n") : "None recorded yet."}
688
+
689
+ ## Only if it applies
690
+
691
+ ${rest.map(line).join("\n")}
692
+
693
+ ## Before launch
694
+
695
+ - [ ] Every URL of any previous site that other sites link to has a redirect in \`redirects.json\`, and \`seo:check\` passes. On Astro with static output, redirects are meta-refresh pages: use a host adapter or host-level redirects for a migration.
696
+ - [ ] \`launch:check\` passes.
697
+ - [ ] Search Console property verified and the sitemap submitted.
698
+ - [ ] The launch column of \`docs/seo-baseline.md\` filled in.
699
+ `;
700
+ }
701
+ function renderBaseline(a, today) {
702
+ const rows = [
703
+ ["Search Console clicks, last 28 days (per money page)", "Search Console"],
704
+ ["Search Console impressions, last 28 days (per money page)", "Search Console"],
705
+ ["Average position for each target keyword", "Search Console"],
706
+ ["Pages indexed", "Search Console, Pages report"],
707
+ ["Business Profile calls, direction requests, website clicks", "Business Profile performance"],
708
+ ["Live referring domains", "links.json and the backlink report"],
709
+ ["Core Web Vitals (mobile)", "Search Console or PageSpeed Insights"],
710
+ ["Enquiries", "The site's forms and calls"]
711
+ ];
712
+ return `# Search baseline: ${a.tradingName}
713
+
714
+ The proof that the site performs. Fill the launch column before go-live, then each column on its date. A figure without a source is not recorded.
715
+
716
+ Started ${today}.
717
+
718
+ | Measure | Launch | 90 days | 6 months | 12 months | Source |
719
+ | --- | --- | --- | --- | --- | --- |
720
+ ${rows.map(([measure, source]) => `| ${measure} | | | | | ${source} |`).join("\n")}
721
+ `;
722
+ }
723
+ function renderWorkflow(project) {
724
+ const pm = project.packageManager;
725
+ if (pm !== "pnpm" && pm !== "npm") return null;
726
+ const setup = pm === "pnpm" ? ` - uses: pnpm/action-setup@v4
727
+ - uses: actions/setup-node@v5
728
+ with:
729
+ node-version: '22.x'
730
+ cache: 'pnpm'
731
+ - run: pnpm install --frozen-lockfile
732
+ - run: pnpm seo:check` : ` - uses: actions/setup-node@v5
733
+ with:
734
+ node-version: '22.x'
735
+ cache: 'npm'
736
+ - run: npm ci
737
+ - run: npm run seo:check`;
738
+ return `name: seo-check
739
+
740
+ # The house SEO checks on every pull request: route coverage, redirects,
741
+ # JSON-LD and the facts-file rule. Written by @domandigital/create-site.
742
+
743
+ on:
744
+ pull_request:
745
+
746
+ permissions:
747
+ contents: read
748
+
749
+ concurrency:
750
+ group: \${{ github.workflow }}-\${{ github.ref }}
751
+ cancel-in-progress: true
752
+
753
+ jobs:
754
+ seo:
755
+ runs-on: ubuntu-latest
756
+ timeout-minutes: 10
757
+ steps:
758
+ - uses: actions/checkout@v5
759
+ ${setup}
760
+ `;
761
+ }
762
+
763
+ // src/templates.ts
764
+ import { readFileSync as readFileSync4 } from "fs";
765
+ import { dirname as dirname2, posix, relative } from "path";
766
+ import { fileURLToPath } from "url";
767
+ var TEMPLATE_ROOT = fileURLToPath(new URL("../templates/", import.meta.url));
768
+ function readTemplate(path) {
769
+ return readFileSync4(`${TEMPLATE_ROOT}${path}`, "utf8");
770
+ }
771
+ var SITE_IMPORT = /(["'])~site\/([^"']+)\1/g;
772
+ function rewriteSiteImports(text2, dest, siteKeys) {
773
+ return text2.replace(SITE_IMPORT, (_match, quote, key) => {
774
+ const target = siteKeys[key];
775
+ if (!target) throw new Error(`template for ${dest} imports ~site/${key}, which this project layout does not provide`);
776
+ const fromDir = dirname2(dest);
777
+ let spec = relative(fromDir, target).split("\\").join(posix.sep).replace(/\.tsx?$/, "");
778
+ if (!spec.startsWith(".")) spec = `./${spec}`;
779
+ return `${quote}${spec}${quote}`;
780
+ });
781
+ }
782
+
783
+ // src/versions.ts
784
+ var HOUSE_DEPENDENCIES = {
785
+ "@domandigital/graph": "^0.7.0",
786
+ "@domandigital/seo": "^0.3.0"
787
+ };
788
+ var HOUSE_DEV_DEPENDENCIES = {
789
+ "@domandigital/craft": "^0.12.0",
790
+ "@types/node": "^22.0.0",
791
+ vitest: "^4.1.11"
792
+ };
793
+
794
+ // templates/next/tests/seo/routes-on-disk.ts
795
+ var routes_on_disk_exports = {};
796
+ __export(routes_on_disk_exports, {
797
+ dynamicRoutesOnDisk: () => dynamicRoutesOnDisk,
798
+ routesOnDisk: () => routesOnDisk
799
+ });
800
+ import { existsSync as existsSync3, readdirSync } from "fs";
801
+ import { join as join3 } from "path";
802
+ var PAGE_FILE = /^page\.(tsx|ts|jsx|js|mdx|md)$/;
803
+ var OPTIONAL_CATCH_ALL2 = /^\[\[\.\.\..+\]\]$/;
804
+ function walk(root) {
805
+ const appDir = [join3(root, "app"), join3(root, "src", "app")].find((dir) => existsSync3(dir));
806
+ const routes = /* @__PURE__ */ new Set();
807
+ const dynamicRoutes = /* @__PURE__ */ new Set();
808
+ if (!appDir) return { routes: [], dynamicRoutes: [] };
809
+ const visit = (dir, segments) => {
810
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
811
+ const name = entry.name;
812
+ if (entry.isDirectory()) {
813
+ if (name.startsWith("_") || name.startsWith("@") || name.startsWith("(.")) continue;
814
+ const isGroup = name.startsWith("(") && name.endsWith(")");
815
+ visit(join3(dir, name), isGroup ? segments : [...segments, name]);
816
+ } else if (PAGE_FILE.test(name)) {
817
+ const path = `/${segments.join("/")}`;
818
+ const firstDynamic = segments.findIndex((s) => s.startsWith("["));
819
+ if (firstDynamic === -1) {
820
+ routes.add(path);
821
+ continue;
822
+ }
823
+ dynamicRoutes.add(path);
824
+ if (OPTIONAL_CATCH_ALL2.test(segments[firstDynamic])) routes.add(`/${segments.slice(0, firstDynamic).join("/")}`);
825
+ }
826
+ }
827
+ };
828
+ visit(appDir, []);
829
+ return { routes: [...routes].sort(), dynamicRoutes: [...dynamicRoutes].sort() };
830
+ }
831
+ function routesOnDisk(root = process.cwd()) {
832
+ return walk(root).routes;
833
+ }
834
+ function dynamicRoutesOnDisk(root = process.cwd()) {
835
+ return walk(root).dynamicRoutes;
836
+ }
837
+
838
+ // templates/astro/tests/seo/routes-on-disk.ts
839
+ var routes_on_disk_exports2 = {};
840
+ __export(routes_on_disk_exports2, {
841
+ dynamicRoutesOnDisk: () => dynamicRoutesOnDisk2,
842
+ routesOnDisk: () => routesOnDisk2
843
+ });
844
+ import { existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
845
+ import { join as join4 } from "path";
846
+ var PAGE_FILE2 = /^(.+)\.(astro|md|mdx|html)$/;
847
+ var NOT_PAGES = /* @__PURE__ */ new Set(["404", "500"]);
848
+ function walk2(root) {
849
+ const pagesDir = join4(root, "src", "pages");
850
+ const routes = /* @__PURE__ */ new Set();
851
+ const dynamicRoutes = /* @__PURE__ */ new Set();
852
+ if (!existsSync4(pagesDir)) return { routes: [], dynamicRoutes: [] };
853
+ const visit = (dir, segments) => {
854
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
855
+ const name = entry.name;
856
+ if (name.startsWith("_")) continue;
857
+ if (entry.isDirectory()) {
858
+ visit(join4(dir, name), [...segments, name]);
859
+ continue;
860
+ }
861
+ const match = PAGE_FILE2.exec(name);
862
+ if (!match) continue;
863
+ const base = match[1];
864
+ if (segments.length === 0 && NOT_PAGES.has(base)) continue;
865
+ const parts = base === "index" ? segments : [...segments, base];
866
+ const path = `/${parts.join("/")}`;
867
+ (parts.some((p) => p.startsWith("[")) ? dynamicRoutes : routes).add(path);
868
+ }
869
+ };
870
+ visit(pagesDir, []);
871
+ return { routes: [...routes].sort(), dynamicRoutes: [...dynamicRoutes].sort() };
872
+ }
873
+ function routesOnDisk2(root = process.cwd()) {
874
+ return walk2(root).routes;
875
+ }
876
+ function dynamicRoutesOnDisk2(root = process.cwd()) {
877
+ return walk2(root).dynamicRoutes;
878
+ }
879
+
880
+ // src/plan.ts
881
+ var PM_ADD = {
882
+ pnpm: { add: ["add"], dev: "-D" },
883
+ npm: { add: ["install"], dev: "--save-dev" },
884
+ yarn: { add: ["add"], dev: "-D" },
885
+ bun: { add: ["add"], dev: "-d" }
886
+ };
887
+ var HOUSE_IMPORT = "@docs/HOUSE.md";
888
+ var specs = (deps) => Object.entries(deps).map(([name, range]) => `${name}@${range}`);
889
+ function hasWorkflows(root) {
890
+ const dir = join5(root, ".github", "workflows");
891
+ return existsSync5(dir) && readdirSync3(dir).some((f) => /\.ya?ml$/.test(f));
892
+ }
893
+ function actionFor(root, path, contents, data, force) {
894
+ const abs = join5(root, path);
895
+ if (!existsSync5(abs)) return "create";
896
+ if (readFileSync5(abs, "utf8") === contents) return "unchanged";
897
+ if (data) return "keep-data";
898
+ return force ? "overwrite" : "skip-exists";
899
+ }
900
+ function planScaffold(project, answers, options) {
901
+ const { root } = project;
902
+ const layout = layoutFor(project);
903
+ const notes = [];
904
+ if (project.packageManagerWarning) notes.push(project.packageManagerWarning);
905
+ const files = [];
906
+ for (const t of layout.templates) {
907
+ if (t.template.endsWith("config.test.ts") && !project.configFile) {
908
+ notes.push(`no ${project.framework} config file, so tests/seo/config.test.ts was not written: ${MANUAL_INSTRUCTIONS[project.framework]}`);
909
+ continue;
910
+ }
911
+ files.push({ path: t.dest, contents: rewriteSiteImports(readTemplate(t.template), t.dest, layout.siteKeys), data: false });
912
+ }
913
+ const adapterSpec = `./${layout.siteKeys["site-adapter"].replace(/\.ts$/, "")}`;
914
+ const enumerate = project.framework === "next" ? routes_on_disk_exports : routes_on_disk_exports2;
915
+ files.push(
916
+ { path: "site.facts.ts", contents: renderFacts(answers, adapterSpec), data: true },
917
+ { path: "site.routes.ts", contents: renderRoutes(enumerate.routesOnDisk(root), enumerate.dynamicRoutesOnDisk(root)), data: true },
918
+ { path: "links.json", contents: renderLinks(), data: true },
919
+ { path: "redirects.json", contents: renderRedirects(), data: true },
920
+ { path: "docs/HOUSE.md", contents: renderHouseMd(answers, project), data: false },
921
+ { path: "docs/DIRECTION.md", contents: renderDirection(answers, options.today), data: true },
922
+ { path: "docs/seo-launch-checklist.md", contents: renderChecklist(answers), data: true },
923
+ { path: "docs/seo-baseline.md", contents: renderBaseline(answers, options.today), data: true }
924
+ );
925
+ const workflowPath = ".github/workflows/seo-check.yml";
926
+ const workflow = renderWorkflow(project);
927
+ if (existsSync5(join5(root, workflowPath)) || workflow && !hasWorkflows(root)) {
928
+ if (workflow) files.push({ path: workflowPath, contents: workflow, data: false });
929
+ } else if (!workflow) {
930
+ notes.push(`no CI workflow written for ${project.packageManager}: run seo:check in your CI`);
931
+ } else {
932
+ notes.push(`this project already has CI workflows, so ${workflowPath} was not added: run seo:check in yours`);
933
+ }
934
+ const planned = files.map((f) => ({ ...f, action: actionFor(root, f.path, f.contents, f.data, options.force) }));
935
+ for (const f of planned) {
936
+ if (f.action === "keep-data" && options.force) notes.push(`${f.path} is yours and was kept (--force never replaces data files)`);
937
+ }
938
+ const pkg = patchPackageJson(
939
+ project.packageJson,
940
+ {
941
+ scripts: { "seo:check": "vitest run tests/seo tests/house.test.ts", "launch:check": "vitest run tests --mode launch" },
942
+ scriptsIfMissing: { test: "vitest run" },
943
+ dependencies: options.skipInstall ? { ...HOUSE_DEPENDENCIES } : {},
944
+ devDependencies: options.skipInstall ? { ...HOUSE_DEV_DEPENDENCIES } : {}
945
+ },
946
+ options.force
947
+ );
948
+ const commands = [];
949
+ if (!options.skipInstall) {
950
+ const pm = PM_ADD[project.packageManager];
951
+ const missing = (deps2) => Object.fromEntries(Object.entries(deps2).filter(([name]) => !hasDependency(project.packageJson, name)));
952
+ const deps = missing(HOUSE_DEPENDENCIES);
953
+ const dev = missing(HOUSE_DEV_DEPENDENCIES);
954
+ if (Object.keys(deps).length) commands.push({ cmd: project.packageManager, args: [...pm.add, ...specs(deps)] });
955
+ if (Object.keys(dev).length) commands.push({ cmd: project.packageManager, args: [...pm.add, pm.dev, ...specs(dev)] });
956
+ }
957
+ let config = null;
958
+ if (project.configFile) {
959
+ const patched = patchConfig(project.framework, project.configFile, readFileSync5(join5(root, project.configFile), "utf8"));
960
+ if (patched.kind === "patched") config = { file: project.configFile, text: patched.text };
961
+ if (patched.kind === "manual") notes.push(`${patched.reason}: ${MANUAL_INSTRUCTIONS[project.framework]}. tests/seo/config.test.ts fails until it does.`);
962
+ }
963
+ const claudePath = join5(root, "CLAUDE.md");
964
+ const claudeText = existsSync5(claudePath) ? readFileSync5(claudePath, "utf8") : null;
965
+ const claudeMd = claudeText === null ? { text: `${HOUSE_IMPORT}
966
+ `, created: true } : claudeText.includes(HOUSE_IMPORT) ? null : { text: `${claudeText.trimEnd()}
967
+ ${HOUSE_IMPORT}
968
+ `, created: false };
969
+ const artDirection = existsSync5(join5(root, "art-direction.json"));
970
+ const craftInstalled = existsSync5(join5(root, "node_modules", "@domandigital", "craft", "package.json"));
971
+ const craftInit = !artDirection && (craftInstalled || commands.length > 0);
972
+ if (!artDirection && !craftInit) notes.push(`after installing, run: npx craft direction init --client ${JSON.stringify(answers.tradingName)}`);
973
+ return {
974
+ project,
975
+ files: planned,
976
+ packageJson: pkg.changes.length ? pkg : null,
977
+ config,
978
+ claudeMd,
979
+ commands,
980
+ craftInit,
981
+ notes
982
+ };
983
+ }
984
+ function hasWork(plan) {
985
+ return plan.files.some((f) => f.action === "create" || f.action === "overwrite") || plan.packageJson !== null || plan.config !== null || plan.claudeMd !== null || plan.commands.length > 0 || plan.craftInit;
986
+ }
987
+ var LABEL = {
988
+ create: "create ",
989
+ unchanged: "unchanged",
990
+ "skip-exists": "differs ",
991
+ overwrite: "replace ",
992
+ "keep-data": "keep "
993
+ };
994
+ var SUFFIX = {
995
+ "skip-exists": " (differs from the house template: --force to replace)",
996
+ "keep-data": " (yours: never replaced)"
997
+ };
998
+ function formatPlan(plan, clientName) {
999
+ const { project } = plan;
1000
+ const where = project.framework === "next" ? `Next.js, ${project.routesDir}/` : "Astro, src/pages/";
1001
+ const lines = [`create-site: ${where}, ${project.packageManager}`];
1002
+ for (const f of plan.files) lines.push(` ${LABEL[f.action]} ${f.path}${SUFFIX[f.action] ?? ""}`);
1003
+ if (plan.packageJson) lines.push(` patch package.json: ${plan.packageJson.changes.join(", ")}`);
1004
+ if (plan.config) lines.push(` patch ${plan.config.file}: serve redirects.json`);
1005
+ if (plan.claudeMd) lines.push(` ${plan.claudeMd.created ? "create " : "patch "} CLAUDE.md: import docs/HOUSE.md`);
1006
+ for (const c of plan.commands) lines.push(` run ${c.cmd} ${c.args.join(" ")}`);
1007
+ if (plan.craftInit) lines.push(` run craft direction init --client ${JSON.stringify(clientName)}`);
1008
+ for (const note of plan.notes) lines.push(` note ${note}`);
1009
+ if (!hasWork(plan)) lines.push(" nothing to do");
1010
+ return lines.join("\n");
1011
+ }
1012
+
1013
+ // src/run.ts
1014
+ async function run2(argv, io) {
1015
+ const options = parseOptions(argv);
1016
+ if (typeof options === "string") {
1017
+ io.err(`create-site: ${options}
1018
+
1019
+ ${USAGE}`);
1020
+ return 2;
1021
+ }
1022
+ if (options.help) {
1023
+ io.out(USAGE);
1024
+ return 0;
1025
+ }
1026
+ if (options.version) {
1027
+ io.out(JSON.parse(readFileSync6(`${TEMPLATE_ROOT}../package.json`, "utf8")).version);
1028
+ return 0;
1029
+ }
1030
+ const root = resolve2(io.cwd, options.dir ?? ".");
1031
+ const project = detectProject(root, io.userAgent);
1032
+ if (typeof project === "string") {
1033
+ io.err(`create-site: ${project}`);
1034
+ return 1;
1035
+ }
1036
+ const answers = await collectAnswers({
1037
+ flags: {
1038
+ legalName: options.client,
1039
+ tradingName: options.tradingName,
1040
+ siteUrl: options.siteUrl,
1041
+ sector: options.sector,
1042
+ description: options.description
1043
+ },
1044
+ file: options.answers,
1045
+ cwd: io.cwd,
1046
+ ask: options.yes ? void 0 : io.ask
1047
+ });
1048
+ if (typeof answers === "string") {
1049
+ io.err(`create-site: ${answers}`);
1050
+ return 2;
1051
+ }
1052
+ const today = io.now().toISOString().slice(0, 10);
1053
+ const plan = planScaffold(project, answers, { force: options.force, skipInstall: options.skipInstall, today });
1054
+ io.out(formatPlan(plan, answers.tradingName));
1055
+ if (options.dryRun || !hasWork(plan)) return 0;
1056
+ const pending = applyPlan(plan, answers.tradingName, io.exec);
1057
+ const pm = project.packageManager === "npm" ? "npm run" : project.packageManager;
1058
+ io.out(
1059
+ [
1060
+ "",
1061
+ "Next:",
1062
+ " 1. Fill in site.facts.ts: contact details, hours, accreditations, profiles. Unknown stays null.",
1063
+ " 2. Put <DesignerCredit /> in the footer, and <JsonLd graph={buildPageGraph(...)} /> on every page.",
1064
+ " 3. Work through docs/seo-launch-checklist.md.",
1065
+ ` 4. ${pm} seo:check now, and ${pm} launch:check before go-live.`,
1066
+ ...pending.map((p) => ` Still to run: ${p}`)
1067
+ ].join("\n")
1068
+ );
1069
+ return 0;
1070
+ }
1071
+
1072
+ // src/cli.ts
1073
+ process.stdout.on("error", (error) => {
1074
+ if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1075
+ throw error;
1076
+ });
1077
+ var interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1078
+ var rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : void 0;
1079
+ void run2(process.argv.slice(2), {
1080
+ cwd: process.cwd(),
1081
+ out: (text2) => process.stdout.write(`${text2}
1082
+ `),
1083
+ err: (text2) => process.stderr.write(`${text2}
1084
+ `),
1085
+ ask: rl ? (question) => rl.question(question) : void 0,
1086
+ // No shell: arguments reach the command as they are, on every platform.
1087
+ exec: (cmd, args, cwd) => {
1088
+ execFileSync(cmd, args, { cwd, stdio: "inherit", shell: process.platform === "win32" && cmd !== process.execPath });
1089
+ },
1090
+ now: () => /* @__PURE__ */ new Date(),
1091
+ userAgent: process.env.npm_config_user_agent
1092
+ }).then((code) => {
1093
+ process.exitCode = code;
1094
+ }).finally(() => rl?.close());