ssqch 0.7.1 → 0.9.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.
Files changed (155) hide show
  1. package/README.md +8 -4
  2. package/bin/ssqch.js +14 -48
  3. package/bundled/README.md +1314 -0
  4. package/bundled/completions/bash +840 -0
  5. package/bundled/completions/elvish +286 -0
  6. package/bundled/completions/fish +182 -0
  7. package/bundled/completions/powershell +318 -0
  8. package/bundled/completions/zsh +510 -0
  9. package/bundled/ssqch.d.ts +540 -0
  10. package/bundled/starter/engines/index.edge +11 -0
  11. package/bundled/starter/engines/index.ejs +11 -0
  12. package/bundled/starter/engines/index.hbs +11 -0
  13. package/bundled/starter/engines/index.liquid +11 -0
  14. package/bundled/starter/engines/layout.edge +35 -0
  15. package/bundled/starter/engines/layout.ejs +35 -0
  16. package/bundled/starter/engines/layout.hbs +35 -0
  17. package/bundled/starter/engines/layout.liquid +35 -0
  18. package/bundled/starter/gitignore +3 -0
  19. package/bundled/starter/jsconfig.json +11 -0
  20. package/bundled/starter/src/404.md +8 -0
  21. package/bundled/starter/src/_blueprints/posts.md +5 -0
  22. package/bundled/starter/src/_data/site.json +4 -0
  23. package/bundled/starter/src/_includes/layout.jinja +35 -0
  24. package/bundled/starter/src/index.jinja +11 -0
  25. package/bundled/starter/src/posts/i-know-what-i-saw.md +11 -0
  26. package/bundled/starter/src/posts/posts.json +4 -0
  27. package/bundled/starter/src/posts/raiders-of-the-lost-path.md +27 -0
  28. package/bundled/starter/src/posts/the-cache-of-the-wild.md +26 -0
  29. package/bundled/starter/src/posts/the-stump-has-moved.md +15 -0
  30. package/bundled/starter/src/posts/upon-further-review-a-stump.md +18 -0
  31. package/bundled/starter/ssqch.config.js +29 -0
  32. package/bundled/starter-docs/engines/edge/base.edge +41 -0
  33. package/bundled/starter-docs/engines/edge/containers/details.edge +5 -0
  34. package/bundled/starter-docs/engines/edge/containers/tab.edge +4 -0
  35. package/bundled/starter-docs/engines/edge/containers/tabs.edge +5 -0
  36. package/bundled/starter-docs/engines/edge/doc.edge +59 -0
  37. package/bundled/starter-docs/engines/edge/hooks/heading.edge +2 -0
  38. package/bundled/starter-docs/engines/ejs/base.ejs +41 -0
  39. package/bundled/starter-docs/engines/ejs/containers/details.ejs +5 -0
  40. package/bundled/starter-docs/engines/ejs/containers/tab.ejs +4 -0
  41. package/bundled/starter-docs/engines/ejs/containers/tabs.ejs +5 -0
  42. package/bundled/starter-docs/engines/ejs/doc.ejs +59 -0
  43. package/bundled/starter-docs/engines/ejs/hooks/heading.ejs +2 -0
  44. package/bundled/starter-docs/engines/hbs/base.hbs +41 -0
  45. package/bundled/starter-docs/engines/hbs/containers/details.hbs +5 -0
  46. package/bundled/starter-docs/engines/hbs/containers/tab.hbs +4 -0
  47. package/bundled/starter-docs/engines/hbs/containers/tabs.hbs +5 -0
  48. package/bundled/starter-docs/engines/hbs/doc.hbs +58 -0
  49. package/bundled/starter-docs/engines/hbs/hooks/heading.hbs +2 -0
  50. package/bundled/starter-docs/engines/liquid/base.liquid +41 -0
  51. package/bundled/starter-docs/engines/liquid/containers/details.liquid +5 -0
  52. package/bundled/starter-docs/engines/liquid/containers/tab.liquid +4 -0
  53. package/bundled/starter-docs/engines/liquid/containers/tabs.liquid +5 -0
  54. package/bundled/starter-docs/engines/liquid/doc.liquid +60 -0
  55. package/bundled/starter-docs/engines/liquid/hooks/heading.liquid +2 -0
  56. package/bundled/starter-docs/gitignore +4 -0
  57. package/bundled/starter-docs/src/404.md +12 -0
  58. package/bundled/starter-docs/src/_blueprints/docs.md +5 -0
  59. package/bundled/starter-docs/src/_data/nav.yml +10 -0
  60. package/bundled/starter-docs/src/_data/site.json +5 -0
  61. package/bundled/starter-docs/src/_includes/base.jinja +41 -0
  62. package/bundled/starter-docs/src/_includes/containers/details.jinja +5 -0
  63. package/bundled/starter-docs/src/_includes/containers/tab.jinja +4 -0
  64. package/bundled/starter-docs/src/_includes/containers/tabs.jinja +5 -0
  65. package/bundled/starter-docs/src/_includes/doc.jinja +59 -0
  66. package/bundled/starter-docs/src/_includes/hooks/heading.jinja +2 -0
  67. package/bundled/starter-docs/src/assets/docs.css +257 -0
  68. package/bundled/starter-docs/src/assets/docs.js +67 -0
  69. package/bundled/starter-docs/src/docs/docs.json +1 -0
  70. package/bundled/starter-docs/src/docs/guides/deploying.md +77 -0
  71. package/bundled/starter-docs/src/docs/guides/writing.md +65 -0
  72. package/bundled/starter-docs/src/docs/index.md +29 -0
  73. package/bundled/starter-docs/src/docs/install.md +42 -0
  74. package/bundled/starter-docs/src/index.md +13 -0
  75. package/bundled/starter-docs/ssqch.config.js +40 -0
  76. package/bundled/trailheads/from-component-frameworks.md +116 -0
  77. package/bundled/trailheads/from-docusaurus.md +55 -0
  78. package/bundled/trailheads/from-eleventy.md +140 -0
  79. package/bundled/trailheads/from-hexo.md +92 -0
  80. package/bundled/trailheads/from-jekyll.md +79 -0
  81. package/bundled/trailheads/from-mkdocs.md +45 -0
  82. package/bundled/trailheads/from-zola.md +71 -0
  83. package/lib/assets.js +235 -3
  84. package/lib/chunk-3A647I3N.js +384 -0
  85. package/lib/chunk-3GYLOC6Y.js +1017 -0
  86. package/lib/chunk-3K3ANWZ2.js +118 -0
  87. package/lib/chunk-3NYSSA2C.js +22 -0
  88. package/lib/chunk-47P4YREZ.js +1287 -0
  89. package/lib/chunk-4Q6WMTER.js +32 -0
  90. package/lib/chunk-76NTVE34.js +338 -0
  91. package/lib/chunk-7PWCYHTJ.js +1350 -0
  92. package/lib/chunk-7RDRZHJD.js +217 -0
  93. package/lib/chunk-7SD7K567.js +57 -0
  94. package/lib/chunk-7XLK2GEG.js +54 -0
  95. package/lib/chunk-AD3HAW3W.js +10 -0
  96. package/lib/chunk-BEGC7YP6.js +502 -0
  97. package/lib/chunk-CMUWRPSQ.js +113 -0
  98. package/lib/chunk-CZ4XQC56.js +999 -0
  99. package/lib/chunk-D2XE2GTY.js +71 -0
  100. package/lib/chunk-DDV6JEC2.js +46 -0
  101. package/lib/chunk-DELWRJAO.js +37409 -0
  102. package/lib/chunk-DELWRJAO.js.LEGAL.txt +27 -0
  103. package/lib/chunk-F65YUXZ7.js +334 -0
  104. package/lib/chunk-FVZ5JBRI.js +115 -0
  105. package/lib/chunk-GRWMGC7D.js +4435 -0
  106. package/lib/chunk-GRWMGC7D.js.LEGAL.txt +41 -0
  107. package/lib/chunk-GUKSZ2XM.js +207 -0
  108. package/lib/chunk-HPXAZ2HU.js +251 -0
  109. package/lib/chunk-HXCLCXRT.js +20 -0
  110. package/lib/chunk-I3PS26CI.js +48 -0
  111. package/lib/chunk-IAFM5ITE.js +11 -0
  112. package/lib/chunk-II5DEH3Q.js +209 -0
  113. package/lib/chunk-IJWHOFRP.js +44 -0
  114. package/lib/chunk-LPHNACE4.js +29 -0
  115. package/lib/chunk-MI6EJWA2.js +175 -0
  116. package/lib/chunk-NCWFYT74.js +1541 -0
  117. package/lib/chunk-NKXEPHRZ.js +136 -0
  118. package/lib/chunk-NNUKIGOO.js +160 -0
  119. package/lib/chunk-R7K3D5W5.js +3957 -0
  120. package/lib/chunk-RNJFPFXE.js +29 -0
  121. package/lib/chunk-SF4I6Z7S.js +25 -0
  122. package/lib/chunk-SURPOAW7.js +44 -0
  123. package/lib/chunk-SXMJ52IK.js +572 -0
  124. package/lib/chunk-TICWN55Z.js +20 -0
  125. package/lib/chunk-TVU3OPPK.js +146 -0
  126. package/lib/chunk-UU43WIZG.js +29 -0
  127. package/lib/chunk-VJWQSYEG.js +119 -0
  128. package/lib/chunk-XMXBHXZR.js +75 -0
  129. package/lib/chunk-YTHQBMDJ.js +211 -0
  130. package/lib/cli.js +547 -0
  131. package/lib/elements.js +180 -3
  132. package/lib/image.js +27 -3
  133. package/lib/links.js +464 -3
  134. package/lib/minify.js +69 -3
  135. package/lib/redirects.js +152 -3
  136. package/lib/rss.js +139 -3
  137. package/lib/sass.js +256 -3
  138. package/lib/sitemap.js +113 -3
  139. package/lib/ssqch.js +28 -0
  140. package/package.json +83 -80
  141. package/src/serve/live.js +174 -0
  142. package/src/serve/not-found.html +31 -0
  143. package/types/globals.d.ts +3 -2
  144. package/types/image.d.ts +7 -3
  145. package/types/index.d.ts +28 -9
  146. package/types/links.d.ts +1 -1
  147. package/types/minify.d.ts +1 -1
  148. package/types/rss.d.ts +1 -1
  149. package/types/sass.d.ts +1 -1
  150. package/types/sitemap.d.ts +2 -0
  151. package/wasm/markdown.wasm +0 -0
  152. package/wasm/minify.wasm +0 -0
  153. package/wasm/sass.wasm +0 -0
  154. package/lib/index.js +0 -3
  155. package/platforms.json +0 -6
@@ -0,0 +1,1287 @@
1
+ import { createRequire as __ssqchCreateRequire } from "node:module";
2
+ const require = __ssqchCreateRequire(import.meta.url);
3
+ import {
4
+ rustRegExp
5
+ } from "./chunk-3GYLOC6Y.js";
6
+ import {
7
+ findConfig
8
+ } from "./chunk-R7K3D5W5.js";
9
+ import "./chunk-7XLK2GEG.js";
10
+ import "./chunk-NKXEPHRZ.js";
11
+ import {
12
+ VERSION
13
+ } from "./chunk-AD3HAW3W.js";
14
+ import "./chunk-DDV6JEC2.js";
15
+ import "./chunk-NCWFYT74.js";
16
+ import "./chunk-FVZ5JBRI.js";
17
+ import "./chunk-HPXAZ2HU.js";
18
+ import "./chunk-UU43WIZG.js";
19
+ import "./chunk-76NTVE34.js";
20
+ import "./chunk-CMUWRPSQ.js";
21
+ import {
22
+ TABLE,
23
+ TomlError,
24
+ isPlainObject,
25
+ readToml,
26
+ red,
27
+ tomlReason
28
+ } from "./chunk-GRWMGC7D.js";
29
+ import {
30
+ compareText,
31
+ isDir,
32
+ isFile
33
+ } from "./chunk-VJWQSYEG.js";
34
+ import "./chunk-I3PS26CI.js";
35
+
36
+ // src/import.ts
37
+ import fs from "node:fs";
38
+ import path from "node:path";
39
+
40
+ // src/json-edit.ts
41
+ var SPACE = /* @__PURE__ */ new Set([" ", " ", "\n", "\r"]);
42
+ function read(text) {
43
+ let i = 0;
44
+ const space = () => {
45
+ while (i < text.length && SPACE.has(text[i])) i++;
46
+ };
47
+ const string = () => {
48
+ const start = i++;
49
+ while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
50
+ i++;
51
+ return text.slice(start, i);
52
+ };
53
+ const value = () => {
54
+ space();
55
+ const start = i;
56
+ if (text[i] === "{") {
57
+ i++;
58
+ const members = [];
59
+ space();
60
+ if (text[i] === "}") i++;
61
+ else {
62
+ for (; ; ) {
63
+ space();
64
+ const at = i;
65
+ const key = JSON.parse(string());
66
+ space();
67
+ i++;
68
+ members.push({ start: at, key, value: value() });
69
+ space();
70
+ if (text[i++] === "}") break;
71
+ }
72
+ }
73
+ return { start, end: i, members };
74
+ }
75
+ if (text[i] === "[") {
76
+ i++;
77
+ space();
78
+ if (text[i] === "]") i++;
79
+ else {
80
+ for (; ; ) {
81
+ value();
82
+ space();
83
+ if (text[i++] === "]") break;
84
+ }
85
+ }
86
+ return { start, end: i };
87
+ }
88
+ if (text[i] === '"') {
89
+ string();
90
+ return { start, end: i };
91
+ }
92
+ while (i < text.length && !SPACE.has(text[i]) && !",]}".includes(text[i])) i++;
93
+ return { start, end: i };
94
+ };
95
+ return value();
96
+ }
97
+ var JsonText = class {
98
+ text;
99
+ constructor(text) {
100
+ this.text = text;
101
+ }
102
+ /** The value at `path`, by keys from the top (the last of two members with one key, as `JSON.parse` keeps it). */
103
+ find(path2) {
104
+ let at = read(this.text);
105
+ for (const key of path2) at = at?.members?.findLast((m) => m.key === key)?.value;
106
+ return at;
107
+ }
108
+ /** Gives the value at `path` the JSON `json`. */
109
+ replace(path2, json) {
110
+ const value = this.find(path2);
111
+ if (value) this.splice(value.start, value.end, json);
112
+ }
113
+ /** Takes out every member called `key` from the object at `path`, with the comma and the line break it brings. */
114
+ remove(path2, key) {
115
+ for (; ; ) {
116
+ const object = this.find(path2);
117
+ const members = object?.members;
118
+ const i = members?.findLastIndex((m) => m.key === key) ?? -1;
119
+ if (!object || !members || i === -1) return;
120
+ if (members.length === 1) this.splice(object.start + 1, object.end - 1, "");
121
+ else if (i < members.length - 1) this.splice(members[i].start, members[i + 1].start, "");
122
+ else this.splice(members[i - 1].value.end, members[i].value.end, "");
123
+ }
124
+ }
125
+ /**
126
+ * Puts `"key": json` in the object at `path`, before its first member whose key `before` says
127
+ * comes after it, or at the end. It takes the space its neighbours have between them; in an
128
+ * empty object, the file's line breaks and indentation, or none in a file on one line.
129
+ */
130
+ insert(path2, key, json, before = () => false) {
131
+ const object = this.find(path2);
132
+ const members = object?.members;
133
+ if (!object || !members) return;
134
+ const member = `${JSON.stringify(key)}: ${json}`;
135
+ const k = members.findIndex((m) => before(m.key));
136
+ const spaceBefore = (j) => {
137
+ if (members.length === 1) {
138
+ const after = this.text.slice(object.start + 1, members[0].start);
139
+ return after.includes("\n") ? after : " ";
140
+ }
141
+ const from = this.text.indexOf(",", members[Math.max(j, 1) - 1].value.end) + 1;
142
+ return this.text.slice(from, members[Math.max(j, 1)].start);
143
+ };
144
+ if (members.length === 0) {
145
+ const newline = this.newline();
146
+ if (!this.text.trim().includes("\n")) return this.splice(object.start + 1, object.end - 1, member);
147
+ const indent = this.lineIndent(object.start);
148
+ this.splice(object.start + 1, object.end - 1, `${newline}${indent}${this.unit()}${member}${newline}${indent}`);
149
+ } else if (k === -1) {
150
+ const last = members[members.length - 1];
151
+ this.splice(last.value.end, last.value.end, `,${spaceBefore(members.length - 1)}${member}`);
152
+ } else {
153
+ this.splice(members[k].start, members[k].start, `${member},${spaceBefore(k)}`);
154
+ }
155
+ }
156
+ /** An object for a new member, laid out as the file is: `{ "a": "1" }` on one line in a file on one line, else a member a line. */
157
+ object(entries, depth) {
158
+ if (!this.text.trim().includes("\n")) return `{${entries.map(([k, v]) => `${JSON.stringify(k)}: ${v}`).join(", ")}}`;
159
+ const newline = this.newline();
160
+ const inner = this.unit().repeat(depth + 1);
161
+ return `{${entries.map(([k, v]) => `${newline}${inner}${JSON.stringify(k)}: ${v}`).join(",")}${newline}${this.unit().repeat(depth)}}`;
162
+ }
163
+ splice(from, to, insert) {
164
+ this.text = this.text.slice(0, from) + insert + this.text.slice(to);
165
+ }
166
+ newline() {
167
+ return this.text.includes("\r\n") ? "\r\n" : "\n";
168
+ }
169
+ /** One level of indentation: the second line's, as npm writes it, or two spaces. */
170
+ unit() {
171
+ const second = this.text.split("\n")[1];
172
+ const indent = second === void 0 ? "" : /^[ \t]*/.exec(second)[0];
173
+ return indent === "" ? " " : indent;
174
+ }
175
+ /** The indentation of the line that `at` is on. */
176
+ lineIndent(at) {
177
+ const start = this.text.lastIndexOf("\n", at - 1) + 1;
178
+ return /^[ \t]*/.exec(this.text.slice(start))[0];
179
+ }
180
+ };
181
+
182
+ // src/import.ts
183
+ var ImportError = class extends Error {
184
+ };
185
+ var fail = (message) => {
186
+ throw new ImportError(message);
187
+ };
188
+ function runImport(generator, dir, write) {
189
+ try {
190
+ let plan;
191
+ if (generator === "eleventy" || generator === "11ty") plan = eleventy(dir);
192
+ else if (generator === "zola") plan = zola(dir);
193
+ else if (["jekyll", "hugo", "docusaurus", "mkdocs", "hexo", "astro", "vitepress"].includes(generator)) plan = fail(`there's no importer for ${generator} yet (only eleventy and zola); \`ssqch docs --from <generator>\` has trailheads for moving from Docusaurus, MkDocs, Hexo and component frameworks by hand`);
194
+ else plan = fail(`${generator}: not a generator ssqch can import from (use eleventy or zola)`);
195
+ process.stdout.write(describe(plan, dir, write));
196
+ if (write) process.stdout.write(apply(plan, dir));
197
+ return 0;
198
+ } catch (e) {
199
+ process.stderr.write(`${red("error:")} ${e instanceof Error ? e.message : String(e)}
200
+ `);
201
+ return 1;
202
+ }
203
+ }
204
+ function describe(plan, dir, write) {
205
+ let out = `Importing the ${plan.from} site in ${dir}${write ? "" : " (a dry run: nothing is changed; add --write to make the changes)"}
206
+ `;
207
+ if (plan.renames.length) {
208
+ out += `
209
+ Rename (${plan.renames.length})
210
+ `;
211
+ for (const [from, to] of plan.renames) out += ` ${from} -> ${to}
212
+ `;
213
+ }
214
+ if (plan.edits.length) {
215
+ out += `
216
+ Edit (${plan.edits.length})
217
+ `;
218
+ for (const [file, changes] of plan.edits) out += ` ${file}: ${changes.join(", ")}
219
+ `;
220
+ }
221
+ if (plan.newFiles.length) {
222
+ out += `
223
+ Create (${plan.newFiles.length})
224
+ `;
225
+ for (const [file, from] of plan.newFiles) out += ` ${file} (${from})
226
+ `;
227
+ }
228
+ if (!plan.renames.length && !plan.edits.length && !plan.newFiles.length) out += "\nNothing to rename, edit or create.\n";
229
+ if (plan.byHand.length) {
230
+ out += `
231
+ By hand (${plan.byHand.length})
232
+ `;
233
+ for (const [at, what] of plan.byHand) out += ` ${at}: ${what}
234
+ `;
235
+ }
236
+ out += `
237
+ Next: \`ssqch build\`, then compare with the site ${plan.from} built: \`ssqch diff <${plan.from}'s output> <ssqch's output>\`.
238
+ `;
239
+ return out;
240
+ }
241
+ function apply(plan, dir) {
242
+ for (const [file, , contents] of plan.edits) attempt(() => fs.writeFileSync(path.join(dir, file), contents), `writing ${file}`);
243
+ for (const [from, to] of plan.renames) {
244
+ if (fs.existsSync(path.join(dir, to))) fail(`${to} is in the way of renaming ${from}`);
245
+ attempt(() => fs.renameSync(path.join(dir, from), path.join(dir, to)), `renaming ${from} to ${to}`);
246
+ }
247
+ for (const [file, , contents] of plan.newFiles) attempt(() => fs.writeFileSync(path.join(dir, file), contents), `writing ${file}`);
248
+ return `Done: ${plan.renames.length} renamed, ${plan.edits.length} edited, ${plan.newFiles.length} created. Welcome to the woods.
249
+ `;
250
+ }
251
+ function reason(e) {
252
+ const err = e;
253
+ const words = { ENOENT: "No such file or directory", EACCES: "Permission denied", EPERM: "Operation not permitted", EISDIR: "Is a directory", ENOTDIR: "Not a directory", EEXIST: "File exists", ENOTEMPTY: "Directory not empty", EROFS: "Read-only file system", ENOSPC: "No space left on device" };
254
+ if (process.platform !== "win32" && typeof err?.code === "string" && typeof err.errno === "number" && words[err.code]) return `${words[err.code]} (os error ${Math.abs(err.errno)})`;
255
+ return e instanceof Error ? e.message : String(e);
256
+ }
257
+ function attempt(step, what) {
258
+ try {
259
+ step();
260
+ } catch (e) {
261
+ fail(`${what}: ${reason(e)}`);
262
+ }
263
+ }
264
+ var utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
265
+ function readUtf8(file) {
266
+ try {
267
+ return utf8.decode(fs.readFileSync(file));
268
+ } catch {
269
+ return void 0;
270
+ }
271
+ }
272
+ function readStrict(file, what) {
273
+ let bytes;
274
+ try {
275
+ bytes = fs.readFileSync(file);
276
+ } catch (e) {
277
+ return fail(`${what ? `${what}: ` : ""}${reason(e)}`);
278
+ }
279
+ try {
280
+ return utf8.decode(bytes);
281
+ } catch {
282
+ return fail(`${what ? `${what}: ` : ""}stream did not contain valid UTF-8`);
283
+ }
284
+ }
285
+ function extensionOf(name) {
286
+ const dot = name.lastIndexOf(".");
287
+ return dot <= 0 ? "" : name.slice(dot + 1);
288
+ }
289
+ var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
290
+ function lines(text) {
291
+ const parts = text.split("\n");
292
+ const last = parts.pop();
293
+ const out = parts.map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
294
+ if (last !== "") out.push(last);
295
+ return out;
296
+ }
297
+ function trimMatches(s, chars) {
298
+ let start = 0, end = s.length;
299
+ while (start < end && chars.includes(s[start])) start++;
300
+ while (end > start && chars.includes(s[end - 1])) end--;
301
+ return s.slice(start, end);
302
+ }
303
+ var trim = (s) => s.replace(new RegExp("^\\p{White_Space}+|\\p{White_Space}+$", "gu"), "");
304
+ var trimStart = (s) => s.replace(new RegExp("^\\p{White_Space}+", "u"), "");
305
+ var splitWhitespace = (s) => s.split(new RegExp("\\p{White_Space}+", "u")).filter((w) => w !== "");
306
+ var indentOf = (line) => line.slice(0, line.length - trimStart(line).length);
307
+ var occurrences = (text, word) => text.split(word).length - 1;
308
+ var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\#&~-]/g, "\\$&");
309
+ var IDENTIFIER = /^[\p{Alphabetic}\p{N}_$]+$/u;
310
+ function walk(root, skip, strict) {
311
+ const out = [];
312
+ if (isFile(root)) return [{ rel: "", abs: root, name: path.basename(root), isFile: true }];
313
+ const visit = (abs, rel) => {
314
+ let dirents;
315
+ try {
316
+ dirents = fs.readdirSync(abs, { withFileTypes: true });
317
+ } catch (e) {
318
+ if (strict) fail(`IO error for operation on ${abs}: ${reason(e)}: ${reason(e)}`);
319
+ return;
320
+ }
321
+ dirents.sort((a, b) => compareText(a.name, b.name));
322
+ for (const d of dirents) {
323
+ const childRel = rel === "" ? d.name : `${rel}/${d.name}`;
324
+ if (skip(d.name, childRel)) continue;
325
+ const childAbs = abs.endsWith(path.sep) ? abs + d.name : abs + path.sep + d.name;
326
+ out.push({ rel: childRel, abs: childAbs, name: d.name, isFile: d.isFile() });
327
+ if (d.isDirectory()) visit(childAbs, childRel);
328
+ }
329
+ };
330
+ visit(root, "");
331
+ return out;
332
+ }
333
+ function components(p) {
334
+ const parts = p.split(process.platform === "win32" ? /[\\/]/ : "/");
335
+ const out = parts.filter((part, i) => part !== "" && !(part === "." && i > 0));
336
+ return p.startsWith("/") ? ["/", ...out] : out;
337
+ }
338
+ var samePath = (a, b) => components(a).join("\0") === components(b).join("\0");
339
+ var ELEVENTY_CONFIGS = [".eleventy.js", "eleventy.config.js", "eleventy.config.mjs", "eleventy.config.cjs"];
340
+ var TEMPLATE_EXTENSIONS = ["md", "markdown", "njk", "liquid", "html", "hbs", "handlebars", "mustache", "edge", "ejs"];
341
+ var keys = () => TABLE.filter((e) => e.kind === "frontMatter" && e.from.includes("Eleventy")).map((e) => [e.word, e.ssqch]);
342
+ var NAVIGATION_FILTER = rustRegExp(String.raw`\|\s*eleventyNavigation(?:Breadcrumb|ToHtml|ToMarkdown)?\b|\beleventyNavigation(?:Breadcrumb|ToHtml|ToMarkdown)?\s*\(`);
343
+ var DATA_FILE = rustRegExp(String.raw`\.11tydata\.(js|cjs|mjs|json|ya?ml|toml)$`);
344
+ var IMAGE_ATTR = rustRegExp(String.raw`\beleventy:(widths|ignore)\b`, "g");
345
+ var TEMPLATE_GLOBAL = rustRegExp(String.raw`\beleventy\.(generator|version)\b`, "g");
346
+ var CALL = rustRegExp(String.raw`\.\s*(addFilter|addAsyncFilter|addNunjucksFilter|addLiquidFilter|addNunjucksAsyncFilter|addShortcode|addAsyncShortcode|addNunjucksShortcode|addNunjucksAsyncShortcode|addLiquidShortcode|addPairedShortcode|addPairedAsyncShortcode|addPairedNunjucksShortcode|addPairedNunjucksAsyncShortcode|addPairedLiquidShortcode|addNunjucksTag|addLiquidTag|addNunjucksGlobal|addMarkdownHighlighter|addCollection|addTransform|addGlobalData|addPlugin|addPassthroughCopy|addWatchTarget|setLibrary|addDataExtension|addTemplateFormats|setTemplateFormats|on)\s*\(\s*(?:["'\x60]([^"'\x60]*)["'\x60]|([A-Za-z_$][\w$.]*))?`, "g");
347
+ var SETTING = rustRegExp(String.raw`\b(input|output|includes|layouts|data|markdownTemplateEngine|htmlTemplateEngine|pathPrefix)\s*:\s*["'\x60]([^"'\x60]*)["'\x60]`, "g");
348
+ var FORMATS = rustRegExp(String.raw`templateFormats\s*:\s*\[([^\]]*)\]`);
349
+ var REQUIRE = rustRegExp(String.raw`(?:require\(\s*|from\s+)["'](@11ty/[\w./-]+|markdown-it[\w-]*|eleventy-[\w-]+|@[\w-]+/eleventy-[\w-]+)["']`, "g");
350
+ var setting = (code, key) => [...code.matchAll(SETTING)].find((c) => c[1] === key)?.[2];
351
+ function blankComments(js) {
352
+ const out = js.split("");
353
+ const blank = (from, to) => {
354
+ for (let k = from; k < to; k++) if (out[k] !== "\n") out[k] = " ";
355
+ };
356
+ let i = 0;
357
+ while (i < js.length) {
358
+ const c = js[i];
359
+ if (c === '"' || c === "'" || c === "`") {
360
+ i++;
361
+ while (i < js.length && js[i] !== c && (c === "`" || js[i] !== "\n")) i += js[i] === "\\" ? 2 : 1;
362
+ i++;
363
+ } else if (c === "/" && js[i + 1] === "/") {
364
+ const at = js.indexOf("\n", i);
365
+ const end = at === -1 ? js.length : at;
366
+ blank(i, end);
367
+ i = end;
368
+ } else if (c === "/" && js[i + 1] === "*") {
369
+ const at = js.indexOf("*/", i + 2);
370
+ const end = at === -1 ? js.length : at + 2;
371
+ blank(i, end);
372
+ i = end;
373
+ } else i++;
374
+ }
375
+ return out.join("");
376
+ }
377
+ function pluginPackage(code, name) {
378
+ const base = name.split(".")[0];
379
+ if (base === "" || !IDENTIFIER.test(base)) return void 0;
380
+ const id = escapeRegex(base);
381
+ const re = rustRegExp(String.raw`(?:\b(?:const|let|var)\s+(?:${id}|\{[^}]*\b${id}\b[^}]*\})\s*=\s*(?:await\s+)?(?:require|import)\(\s*|\bimport\s+(?:${id}|\{[^}]*\b${id}\b[^}]*\}|\*\s+as\s+${id})\s+from\s+)["'\x60]([^"'\x60]+)["'\x60]`);
382
+ return re.exec(code)?.[1];
383
+ }
384
+ function eleventy(dir) {
385
+ if (!isDir(dir)) fail(`${dir} isn't a folder`);
386
+ const config = ELEVENTY_CONFIGS.find((name) => isFile(path.join(dir, name)));
387
+ const configText = config === void 0 ? "" : readStrict(path.join(dir, config), `reading ${config}`);
388
+ const output = setting(blankComments(configText), "output") ?? "_site";
389
+ const plan = { from: "Eleventy", renames: [], edits: [], newFiles: [], byHand: [] };
390
+ const extensions = /* @__PURE__ */ new Set();
391
+ const entries = walk(dir, (name, rel) => name.startsWith(".git") || name === "node_modules" || name === ".cache" || samePath(rel, output), true);
392
+ const isTemplate = (name) => TEMPLATE_EXTENSIONS.includes(asciiLower(extensionOf(name)));
393
+ const readsNavigation = entries.some((e) => e.isFile && isTemplate(e.name) && NAVIGATION_FILTER.test(readUtf8(e.abs) ?? ""));
394
+ const keep = readsNavigation ? ["eleventyNavigation"] : [];
395
+ if (readsNavigation) {
396
+ plan.byHand.push([".", "`eleventyNavigation` front matter was left as it is, because templates call the `eleventyNavigation` filter, which reads it. To keep that filter, define it with the package's own function: `import navigation from \"@11ty/eleventy-navigation/eleventy-navigation.js\"`, then `filters: { eleventyNavigation: (pages, key) => navigation.findNavigationEntries(pages, key) }`. To move to ssqch's navigation instead (`pagesTree`), rename it to `nav` (`ssqch docs nav`)"]);
397
+ }
398
+ for (const entry of entries) {
399
+ if (!entry.isFile) continue;
400
+ const { rel, name } = entry;
401
+ const ext = asciiLower(extensionOf(name));
402
+ if (DATA_FILE.test(name)) plan.renames.push([rel, rel.replace(DATA_FILE, ".data.$1")]);
403
+ if (name.endsWith(".11ty.js") || name.endsWith(".11ty.cjs")) {
404
+ plan.byHand.push([rel, "JavaScript templates don't run in ssqch: rewrite it as a template, or as an engine of your own (`engines` in the config)"]);
405
+ continue;
406
+ }
407
+ if (ext === "webc") {
408
+ plan.byHand.push([rel, "WebC isn't supported: rewrite it as a template, with custom elements from `ssqch/elements` for the interactive parts"]);
409
+ continue;
410
+ }
411
+ const template = TEMPLATE_EXTENSIONS.includes(ext);
412
+ const data = DATA_FILE.test(name) || ["json", "yaml", "yml"].includes(ext) && !name.startsWith("package");
413
+ if (!template && !data) continue;
414
+ const text = readUtf8(entry.abs);
415
+ if (text === void 0) continue;
416
+ if (template) extensions.add(ext === "markdown" ? "md" : ext);
417
+ const [next, changes] = template ? rewriteTemplate(text, ext === "md" || ext === "markdown", keep) : rewriteData(text, keep);
418
+ if (changes.length) plan.edits.push([rel, changes, next]);
419
+ if (template && (text.includes("eleventy.env") || text.includes("eleventy.directories"))) plan.byHand.push([rel, "`eleventy.env` and `eleventy.directories` aren't there: use `ssqch.env` and `ssqch.serving`"]);
420
+ }
421
+ packageFiles(dir, plan);
422
+ if (config !== void 0) {
423
+ const [source, byHand] = draftConfig(config, configText, extensions);
424
+ plan.byHand.push(...byHand);
425
+ if (findConfig(dir) === void 0) plan.newFiles.push(["ssqch.config.js", `a first draft, from ${config}`, source]);
426
+ else plan.byHand.push(["ssqch.config.js", "it's already there, so the draft from the Eleventy config wasn't written"]);
427
+ } else {
428
+ plan.byHand.push([".", `no Eleventy config here (${ELEVENTY_CONFIGS.join(", ")}): is this the site's folder?`]);
429
+ }
430
+ return plan;
431
+ }
432
+ var HTML_TAG = /<[A-Za-z][^<>]*>/g;
433
+ var TEMPLATE_TAG = /\{\{.*?\}\}|\{%.*?%\}/gs;
434
+ function rewriteTemplate(text, markdown, keep = []) {
435
+ const changes = [];
436
+ let front = "", body = text;
437
+ if (text.startsWith("---")) {
438
+ const end = text.indexOf("\n---", 3);
439
+ if (end !== -1) {
440
+ front = text.slice(0, end + 4);
441
+ body = text.slice(end + 4);
442
+ }
443
+ }
444
+ for (const [from, to] of keys()) {
445
+ if (keep.includes(from)) continue;
446
+ const key = rustRegExp(String.raw`(?m)^(\s*["']?)${from}(["']?\s*:)`, "g");
447
+ if (front.search(key) !== -1) {
448
+ front = front.replace(key, (_, before, after) => `${before}${to}${after}`);
449
+ changes.push(`${from} -> ${to}`);
450
+ }
451
+ }
452
+ let attrs = false, globals = false;
453
+ body = outsideCode(body, markdown, (part) => {
454
+ const tagged = part.replace(HTML_TAG, (tag) => {
455
+ if (tag.search(IMAGE_ATTR) !== -1) attrs = true;
456
+ return tag.replace(IMAGE_ATTR, "ssqch:$1");
457
+ });
458
+ return tagged.replace(TEMPLATE_TAG, (tag) => {
459
+ if (tag.search(TEMPLATE_GLOBAL) !== -1) globals = true;
460
+ return tag.replace(TEMPLATE_GLOBAL, "ssqch.$1");
461
+ });
462
+ });
463
+ if (attrs) changes.push("eleventy:widths/ignore -> ssqch:widths/ignore");
464
+ if (globals) changes.push("eleventy.generator/version -> ssqch.generator/version");
465
+ return [front + body, changes];
466
+ }
467
+ function outsideCode(text, markdown, change) {
468
+ if (!markdown) return change(text);
469
+ let out = "";
470
+ let fence;
471
+ let prose = "";
472
+ for (let start = 0; start < text.length; ) {
473
+ const nl = text.indexOf("\n", start);
474
+ const end = nl === -1 ? text.length : nl + 1;
475
+ const line = text.slice(start, end);
476
+ start = end;
477
+ const trimmed = trimStart(line);
478
+ const marker = trimmed.startsWith("```") ? "```" : trimmed.startsWith("~~~") ? "~~~" : void 0;
479
+ if (fence === void 0 && marker !== void 0) {
480
+ out += changeProse(prose, change);
481
+ prose = "";
482
+ fence = marker;
483
+ out += line;
484
+ } else if (fence !== void 0 && marker === fence) {
485
+ fence = void 0;
486
+ out += line;
487
+ } else if (fence !== void 0) {
488
+ out += line;
489
+ } else {
490
+ prose += line;
491
+ }
492
+ }
493
+ return out + changeProse(prose, change);
494
+ }
495
+ function changeProse(prose, change) {
496
+ return prose.split("`").map((part, i) => i % 2 === 1 ? part : change(part)).join("`");
497
+ }
498
+ function rewriteData(text, keep = []) {
499
+ let out = text;
500
+ const changes = [];
501
+ for (const [from, to] of keys()) {
502
+ if (keep.includes(from)) continue;
503
+ const key = rustRegExp(String.raw`(?m)(["'])${from}(["']\s*:)|(^[ \t]*|[{,][ \t]*)${from}(\s*:)`, "g");
504
+ if (out.search(key) !== -1) {
505
+ out = out.replace(key, (_, open, close, before, after) => `${open ?? ""}${before ?? ""}${to}${close ?? ""}${after ?? ""}`);
506
+ changes.push(`${from} -> ${to}`);
507
+ }
508
+ }
509
+ return [out, changes];
510
+ }
511
+ function replacement(pkg) {
512
+ switch (pkg) {
513
+ case "@11ty/eleventy-img":
514
+ return '`imagePlugin()` from "ssqch/image" (every <img> becomes a <picture>), or `image()` in data files';
515
+ case "@11ty/eleventy-plugin-rss":
516
+ return '`rssPlugin()` from "ssqch/rss"';
517
+ case "@11ty/eleventy-plugin-syntaxhighlight":
518
+ return "`markdown: { highlight: true }`";
519
+ case "@11ty/eleventy-navigation":
520
+ return "`nav` front matter and `pagesTree(collections.all)`, with `navTree`, `navPager` and `navBreadcrumbs`";
521
+ case "@11ty/eleventy-fetch":
522
+ return '`fetch(url, { cache: "1d" })`';
523
+ case "@11ty/eleventy-plugin-bundle":
524
+ case "@11ty/eleventy-plugin-webc":
525
+ case "@11ty/is-land":
526
+ return 'custom elements with `elementsPlugin()` from "ssqch/elements"';
527
+ case "@11ty/eleventy-upgrade-help":
528
+ case "@11ty/eleventy":
529
+ case "@11ty/eleventy-dev-server":
530
+ return void 0;
531
+ case "markdown-it":
532
+ return "ssqch's own Markdown: see the `markdown` options, render hooks and containers";
533
+ case "markdown-it-anchor":
534
+ return "heading ids are built in; add anchor links with `_includes/hooks/heading.*`";
535
+ case "markdown-it-footnote":
536
+ return "built in (`markdown: { footnotes: true }`, the default)";
537
+ case "markdown-it-container":
538
+ return "built in: `::: name` renders `_includes/containers/name.*`";
539
+ case "markdown-it-attrs":
540
+ return "`{#id .class}` on headings is built in";
541
+ default:
542
+ return "check whether it's needed: see `ssqch docs --from eleventy`";
543
+ }
544
+ }
545
+ var PADDED = rustRegExp(String.raw`[(\[][ \t]+[^\s)\]]`, "g");
546
+ var TIGHT = rustRegExp(String.raw`[(\[][^\s)\]]`, "g");
547
+ var DANGLING = rustRegExp(String.raw`,[ \t]*\r?\n[ \t]*[}\]]`, "g");
548
+ var CLOSED = rustRegExp(String.raw`[^\s,;{\[(][ \t]*\r?\n[ \t]*[}\]]`, "g");
549
+ var BARE_KEY = rustRegExp(String.raw`[{,]\s*[A-Za-z_$][\w$]*\s*:`);
550
+ var QUOTED_KEY = rustRegExp(String.raw`[{,]\s*["'][^"'\n]*["']\s*:`);
551
+ function styleOf(text) {
552
+ const indents = lines(text).filter((l) => trim(l) !== "").map(indentOf).filter((i) => i !== "");
553
+ let indent = " ";
554
+ if (indents.length && indents[0].startsWith(" ")) indent = " ";
555
+ else if (indents.length) {
556
+ const sizes = indents.filter((i) => !i.includes(" ")).map((i) => Buffer.byteLength(i));
557
+ const smallest = sizes.length ? sizes.reduce((a, b) => Math.min(a, b)) : 2;
558
+ indent = " ".repeat(Math.min(8, Math.max(1, smallest)));
559
+ }
560
+ const count = (re) => text.match(re)?.length ?? 0;
561
+ const padded = count(PADDED) > count(TIGHT);
562
+ const dangle = count(DANGLING) >= count(CLOSED);
563
+ const quoteKeys = !BARE_KEY.test(text) && QUOTED_KEY.test(text);
564
+ return { indent, padded, dangle, quoteKeys };
565
+ }
566
+ function styleKey(style, key) {
567
+ const identifier = key !== "" && !/^[0-9]/.test(key) && IDENTIFIER.test(key);
568
+ return identifier && !style.quoteKeys ? key : `"${key}"`;
569
+ }
570
+ function styleItems(style, items) {
571
+ return items.map((item, i) => `${item}${i + 1 < items.length || style.dangle ? "," : ""}
572
+ `).join("");
573
+ }
574
+ var styleList = (style, items) => style.padded ? `[ ${items.join(", ")} ]` : `[${items.join(", ")}]`;
575
+ function closingBracket(text, open) {
576
+ let depth = 0;
577
+ let i = open;
578
+ while (i < text.length) {
579
+ const c = text[i];
580
+ if (c === '"' || c === "'" || c === "`") {
581
+ i++;
582
+ while (i < text.length && text[i] !== c) i += text[i] === "\\" ? 2 : 1;
583
+ } else if (c === "/" && text[i + 1] === "/") {
584
+ while (i < text.length && text[i] !== "\n") i++;
585
+ } else if (c === "/" && text[i + 1] === "*") {
586
+ const end = text.indexOf("*/", i + 2);
587
+ i = end === -1 ? text.length : end + 1;
588
+ } else if (c === "(" || c === "[" || c === "{") {
589
+ depth++;
590
+ } else if (c === ")" || c === "]" || c === "}") {
591
+ depth--;
592
+ if (depth === 0) return i;
593
+ }
594
+ i++;
595
+ }
596
+ return void 0;
597
+ }
598
+ function topLevelArgs(code) {
599
+ const parts = [];
600
+ let start = 0, i = 0;
601
+ while (i < code.length) {
602
+ const c = code[i];
603
+ if (c === '"' || c === "'" || c === "`") {
604
+ let j = i + 1;
605
+ while (j < code.length && code[j] !== c) j += code[j] === "\\" ? 2 : 1;
606
+ i = j;
607
+ } else if (c === "(" || c === "[" || c === "{") {
608
+ i = closingBracket(code, i) ?? code.length;
609
+ } else if (c === ",") {
610
+ parts.push(trim(code.slice(start, i)));
611
+ start = i + 1;
612
+ }
613
+ i++;
614
+ }
615
+ parts.push(trim(code.slice(Math.min(start, code.length))));
616
+ return parts.filter((p) => p !== "");
617
+ }
618
+ function stringLiteral(code) {
619
+ const s = trim(code);
620
+ const quote = s[0];
621
+ if (quote !== '"' && quote !== "'" && quote !== "`" || s.length < 2 || !s.endsWith(quote)) return void 0;
622
+ const inner = s.slice(1, -1);
623
+ if (inner.includes("\\") || inner.includes(quote) || quote === "`" && inner.includes("${")) return void 0;
624
+ return inner;
625
+ }
626
+ function passthroughObject(code) {
627
+ const s = trim(code);
628
+ if (!s.startsWith("{") || !s.endsWith("}") || s.length < 2) return void 0;
629
+ const pairs = [];
630
+ for (const pair of topLevelArgs(s.slice(1, -1))) {
631
+ const colon = pair.indexOf(":");
632
+ if (colon === -1) return void 0;
633
+ const rawKey = trim(pair.slice(0, colon));
634
+ const key = stringLiteral(rawKey) ?? (IDENTIFIER.test(rawKey) ? rawKey : void 0);
635
+ const value = stringLiteral(pair.slice(colon + 1));
636
+ if (key === void 0 || value === void 0) return void 0;
637
+ pairs.push([key, value]);
638
+ }
639
+ return pairs.length ? pairs : void 0;
640
+ }
641
+ var FUNCTION_EXPR = rustRegExp(String.raw`^(?:async\s+)?(?:function\b|\([^()]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)`);
642
+ var DECLARED = rustRegExp(String.raw`\b(?:const|let|var|function|class|import)\s+(?:\*\s+as\s+)?([A-Za-z_$][\w$]*)`, "g");
643
+ var DESTRUCTURED = rustRegExp(String.raw`\b(?:const|let|var|import)\s*\{([^}]*)\}`, "g");
644
+ function declaredNames(text) {
645
+ const names = /* @__PURE__ */ new Set();
646
+ for (const c of text.matchAll(DECLARED)) names.add(c[1]);
647
+ for (const c of text.matchAll(DESTRUCTURED)) {
648
+ for (const part of c[1].split(",")) {
649
+ const name = trim(part.split(/[: ]/).reverse().find((w) => trim(w) !== "") ?? "");
650
+ if (name !== "") names.add(name);
651
+ }
652
+ }
653
+ names.add("eleventyConfig");
654
+ return names;
655
+ }
656
+ function parameterNames(head) {
657
+ const names = /* @__PURE__ */ new Set();
658
+ const add = (text) => {
659
+ for (const word of text.split(/[^\p{Alphabetic}\p{N}_$]/u)) if (word !== "") names.add(word);
660
+ };
661
+ const open = head.indexOf("("), close = head.lastIndexOf(")");
662
+ if (open === -1 || close < open) {
663
+ add(head);
664
+ return names;
665
+ }
666
+ for (const param of topLevelArgs(head.slice(open + 1, close))) add(withoutDefaults(param));
667
+ return names;
668
+ }
669
+ function withoutDefaults(param) {
670
+ let out = "";
671
+ let skipping = -1;
672
+ let depth = 0;
673
+ for (let i = 0; i < param.length; i++) {
674
+ const c = param[i];
675
+ if (c === '"' || c === "'" || c === "`") {
676
+ let j = i + 1;
677
+ while (j < param.length && param[j] !== c) j += param[j] === "\\" ? 2 : 1;
678
+ if (skipping === -1) out += param.slice(i, j + 1);
679
+ i = j;
680
+ } else if (c === "{" || c === "[") {
681
+ depth++;
682
+ if (skipping === -1) out += c;
683
+ } else if (c === "}" || c === "]") {
684
+ if (skipping === depth) skipping = -1;
685
+ depth--;
686
+ if (skipping === -1) out += c;
687
+ } else if (c === "," && skipping === depth) {
688
+ skipping = -1;
689
+ out += c;
690
+ } else if (c === "=" && param[i + 1] !== ">" && skipping === -1) {
691
+ skipping = depth;
692
+ } else if (skipping === -1) {
693
+ out += c;
694
+ }
695
+ }
696
+ return out;
697
+ }
698
+ function portableFunction(source, config, declared) {
699
+ if (!FUNCTION_EXPR.test(source) || source.includes("this")) return void 0;
700
+ const own = declaredNames(source);
701
+ const params = parameterNames(FUNCTION_EXPR.exec(source)?.[0] ?? "");
702
+ const outside = declaredNames(config.replace(source, () => ""));
703
+ const uses = (name) => rustRegExp(String.raw`(^|[^\w$.])${escapeRegex(name)}([^\w$]|$)`).test(source);
704
+ const foreign = [...declared].some((n) => outside.has(n) && !own.has(n) && !params.has(n) && uses(n));
705
+ return foreign ? void 0 : source;
706
+ }
707
+ function reindent(source, fromIndent, toIndent) {
708
+ const [first = "", ...rest] = lines(source);
709
+ let out = first;
710
+ for (const line of rest) {
711
+ out += "\n";
712
+ if (trim(line) !== "") out += toIndent + (line.startsWith(fromIndent) ? line.slice(fromIndent.length) : trimStart(line));
713
+ }
714
+ return out;
715
+ }
716
+ function draftConfig(name, text, extensions) {
717
+ const code = blankComments(text);
718
+ const lineOf = (offset) => occurrences(text.slice(0, offset), "\n") + 1;
719
+ const style = styleOf(text);
720
+ const ind = style.indent;
721
+ const declared = declaredNames(text);
722
+ const byHand = [];
723
+ const passthrough = [], watch = [], todo = [];
724
+ const ported = [];
725
+ for (const c of code.matchAll(CALL)) {
726
+ const [whole, method, given, bare] = c;
727
+ const quoted = given !== void 0 && whole[whole.length - given.length - 2] === "`" && given.includes("${") ? void 0 : given;
728
+ const at = `${name}:${lineOf(c.index)}`;
729
+ const arg = quoted ?? bare ?? "...";
730
+ const open2 = c.index + Math.max(0, whole.indexOf("("));
731
+ const close2 = closingBracket(code, open2);
732
+ const args = close2 === void 0 ? [] : topLevelArgs(text.slice(open2 + 1, close2));
733
+ const before = text.slice(0, c.index);
734
+ const lastLine = before.slice(before.lastIndexOf("\n") + 1);
735
+ const callIndent = indentOf(lastLine);
736
+ const port = () => {
737
+ if (quoted === void 0 || args.length !== 2) return false;
738
+ const source = portableFunction(args[1], text, declared);
739
+ if (source === void 0) return false;
740
+ ported.push([quoted, reindent(source, callIndent, ind.repeat(2))]);
741
+ return true;
742
+ };
743
+ const registers = method.startsWith("add") && (method.includes("Filter") || method.includes("Shortcode") || method.includes("Tag") || method === "addNunjucksGlobal");
744
+ if (registers && quoted === void 0) {
745
+ byHand.push([at, `${method}(${arg}, ...) takes its name from a variable: find the names it's called with, and port each one to \`filters\``]);
746
+ continue;
747
+ }
748
+ switch (method) {
749
+ case "addPassthroughCopy": {
750
+ const pairs = args[0] === void 0 ? void 0 : passthroughObject(args[0]);
751
+ if (quoted !== void 0) passthrough.push(`"${quoted}"`);
752
+ else if (pairs) for (const [from, to] of pairs) passthrough.push(`{ ${styleKey(style, from)}: "${to}" }`);
753
+ else byHand.push([at, "addPassthroughCopy with a variable or a computed value -> `passthrough: [{ from: to }]`"]);
754
+ break;
755
+ }
756
+ case "addWatchTarget":
757
+ if (quoted !== void 0) watch.push(`"${quoted}"`);
758
+ else byHand.push([at, "addWatchTarget -> `watch`"]);
759
+ break;
760
+ case "addFilter":
761
+ case "addAsyncFilter":
762
+ case "addNunjucksFilter":
763
+ case "addLiquidFilter":
764
+ if (!port()) {
765
+ todo.push(`filters: ${arg}`);
766
+ byHand.push([at, `${method}("${arg}") -> \`filters: { ${arg}: ... }\` (async functions are awaited)`]);
767
+ }
768
+ break;
769
+ case "addNunjucksAsyncFilter":
770
+ todo.push(`filters: ${arg}`);
771
+ byHand.push([at, `${method}("${arg}") -> \`filters: { ${arg}: async (value) => ... }\`: return the result instead of calling the callback`]);
772
+ break;
773
+ case "addShortcode":
774
+ case "addAsyncShortcode":
775
+ case "addNunjucksShortcode":
776
+ case "addNunjucksAsyncShortcode":
777
+ case "addLiquidShortcode":
778
+ if (!port()) {
779
+ todo.push(`filters: ${arg}`);
780
+ byHand.push([at, `${method}("${arg}") -> a filter: \`filters: { ${arg}: ... }\`. Nunjucks keeps \`{% ${arg} ... %}\`; in Liquid it's \`{{ x | ${arg} }}\``]);
781
+ }
782
+ break;
783
+ case "addPairedShortcode":
784
+ case "addPairedAsyncShortcode":
785
+ case "addPairedNunjucksShortcode":
786
+ case "addPairedNunjucksAsyncShortcode":
787
+ case "addPairedLiquidShortcode":
788
+ if (!port()) {
789
+ todo.push(`filters: ${arg}`);
790
+ byHand.push([at, `${method}("${arg}") -> a filter that gets the content first. Nunjucks keeps \`{% ${arg} %}...{% end${arg} %}\`; in Markdown, a \`::: ${arg}\` container`]);
791
+ }
792
+ break;
793
+ case "addCollection":
794
+ todo.push(`collections: ${arg}`);
795
+ byHand.push([at, `addCollection("${arg}") -> \`collections: { ${arg}: (pages) => ... }\`: getAll() is pages.all(), getFilteredByTag is pages.byTag, getFilteredByGlob is pages.byGlob`]);
796
+ break;
797
+ case "addTransform":
798
+ byHand.push([at, `addTransform("${arg}") -> \`transforms: { ${arg}: (content, page) => content }\` (an HTML minifier is \`minifyPlugin()\`)`]);
799
+ break;
800
+ case "addGlobalData":
801
+ byHand.push([at, `addGlobalData("${arg}") -> \`data: { ${arg}: value or function }\``]);
802
+ break;
803
+ case "addNunjucksTag":
804
+ case "addLiquidTag":
805
+ todo.push(`filters: ${arg}`);
806
+ byHand.push([at, `${method}("${arg}") -> a custom tag is a filter in ssqch: \`filters: { ${arg}: ... }\`, and \`{% ${arg} ... %}\` keeps working in Nunjucks`]);
807
+ break;
808
+ case "addNunjucksGlobal":
809
+ byHand.push([at, `addNunjucksGlobal("${arg}") -> \`data: { ${arg}: value }\`, or a filter for a function`]);
810
+ break;
811
+ case "addMarkdownHighlighter":
812
+ byHand.push([at, "addMarkdownHighlighter -> `markdown: { highlight: true }`, or a fence hook for a highlighter of your own"]);
813
+ break;
814
+ case "addPlugin": {
815
+ const pkg = pluginPackage(code, arg);
816
+ const known = pkg !== void 0 && `require("${pkg}")`.search(REQUIRE) !== -1 && replacement(pkg) !== void 0;
817
+ const from = pkg === void 0 ? "" : ` (from ${pkg})`;
818
+ if (known) byHand.push([at, `addPlugin(${arg})${from} -> see its package below`]);
819
+ else byHand.push([at, `addPlugin(${arg})${from}: a plugin ssqch doesn't know, so the filters, shortcodes and transforms it adds aren't listed here. Read its source and port them, or put it in \`plugins: [...]\` if it's written for ssqch`]);
820
+ break;
821
+ }
822
+ case "setLibrary":
823
+ byHand.push([at, "setLibrary -> ssqch renders Markdown itself: `markdown: { ... }` options, render hooks and containers"]);
824
+ break;
825
+ case "addDataExtension":
826
+ byHand.push([at, "addDataExtension -> YAML, TOML and JSON data files load as they are"]);
827
+ break;
828
+ case "on":
829
+ if (quoted?.startsWith("eleventy.")) byHand.push([at, `on("${arg}") -> \`beforeBuild\` or \`afterBuild\``]);
830
+ break;
831
+ }
832
+ }
833
+ const packages = [...new Set([...code.matchAll(REQUIRE)].map((c) => c[1]))].filter((p) => replacement(p) !== void 0).sort(compareText);
834
+ for (const pkg of packages) byHand.push([name, `${pkg} -> ${replacement(pkg)}`]);
835
+ const engine = (key) => {
836
+ const value = setting(code, key);
837
+ if (value === "njk") return '"njk"';
838
+ if (value === "false" || value === "") return "false";
839
+ if (value !== void 0) return `"${value}"`;
840
+ return code.includes(`${key}: false`) ? "false" : void 0;
841
+ };
842
+ const markdownEngine = engine("markdownTemplateEngine"), htmlEngine = engine("htmlTemplateEngine");
843
+ const enginesComment = markdownEngine === void 0 ? htmlEngine === void 0 ? "Eleventy's defaults: Markdown and HTML run through Liquid first." : "From the Eleventy config's htmlTemplateEngine; Markdown runs through Liquid first, Eleventy's default." : htmlEngine === void 0 ? "From the Eleventy config's markdownTemplateEngine; HTML runs through Liquid first, Eleventy's default." : "From the Eleventy config's markdownTemplateEngine and htmlTemplateEngine.";
844
+ const listed = FORMATS.exec(code);
845
+ const formats = listed ? listed[1].split(",").map((f) => trimMatches(trim(f), "\"'`")).filter((f) => f !== "" && f !== "11ty.js") : [...extensions].sort(compareText).filter((e) => e !== "edge");
846
+ const quotedList = (items) => styleList(style, items.map((i) => `"${i}"`));
847
+ const dirs = [];
848
+ for (const key of ["input", "output", "includes", "layouts", "data"]) {
849
+ const value = setting(code, key);
850
+ if (value !== void 0) dirs.push(`${key}: "${value}"`);
851
+ }
852
+ const [open, close] = style.padded ? ["( {", "} )"] : ["({", "})"];
853
+ let out = `// A first draft, written by \`ssqch import eleventy\` from ${name}.
854
+ // What it couldn't carry over is listed at the end; \`ssqch docs --from eleventy\` has the whole
855
+ // mapping.
856
+ import { defineConfig } from "ssqch";
857
+
858
+ export default defineConfig${open}
859
+ `;
860
+ const entries = [];
861
+ if (dirs.length) entries.push(`${ind}dirs: { ${dirs.join(", ")} }`);
862
+ if (formats.length) entries.push(`${ind}templateFormats: ${quotedList(formats)}`);
863
+ entries.push(`${ind}// ${enginesComment}
864
+ ${ind}markdownEngine: ${markdownEngine ?? '"liquid"'}`);
865
+ entries.push(`${ind}htmlEngine: ${htmlEngine ?? '"liquid"'}`);
866
+ const prefix = setting(code, "pathPrefix");
867
+ if (prefix !== void 0 && prefix !== "/") entries.push(`${ind}base: "${prefix}"`);
868
+ if (passthrough.length) entries.push(`${ind}passthrough: ${styleList(style, passthrough)}`);
869
+ if (watch.length) entries.push(`${ind}watch: ${styleList(style, watch)}`);
870
+ let filters = `
871
+ ${ind}filters: {
872
+ `;
873
+ if (ported.length) {
874
+ filters += `${ind}${ind}// From ${name}, as written.
875
+ `;
876
+ filters += styleItems(style, ported.map(([filter, source]) => `${ind}${ind}${styleKey(style, filter)}: ${source}`));
877
+ }
878
+ if (!ported.length || todo.some((t) => t.startsWith("filters:"))) filters += `${ind}${ind}// Port each filter and shortcode here: name: (value, ...args) => result
879
+ `;
880
+ filters += `${ind}}`;
881
+ entries.push(filters);
882
+ entries.push(`${ind}collections: {
883
+ ${ind}${ind}// name: (pages) => pages.byTag("post")
884
+ ${ind}}`);
885
+ entries.push(`${ind}plugins: []`);
886
+ out += styleItems(style, entries);
887
+ out += `${close};
888
+ `;
889
+ if (todo.length) {
890
+ out += `
891
+ // To port from ${name}:
892
+ `;
893
+ for (const item of todo) out += `// ${item}
894
+ `;
895
+ }
896
+ return [out, byHand];
897
+ }
898
+ var LOCKFILES = [["pnpm", ["pnpm-lock.yaml"]], ["yarn", ["yarn.lock"]], ["bun", ["bun.lock", "bun.lockb"]], ["npm", ["package-lock.json", "npm-shrinkwrap.json"]]];
899
+ var packageManagerField = (pkg) => isPlainObject(pkg) && typeof pkg.packageManager === "string" ? pkg.packageManager : void 0;
900
+ function packageManager(dir, pkg) {
901
+ const named = (packageManagerField(pkg) ?? "").split("@")[0];
902
+ const byName = LOCKFILES.find(([pm]) => named === pm);
903
+ if (byName) return byName[0];
904
+ return LOCKFILES.find(([, lockfiles]) => lockfiles.some((l) => isFile(path.join(dir, l))))?.[0] ?? "npm";
905
+ }
906
+ var ELEVENTY_COMMAND = rustRegExp(String.raw`(?:\bnpx\s+(?:-y\s+)?)?(?:@11ty/)?\beleventy\b((?:\s+--?[\w-]+(?:[= ](?:\x22[^\x22]*\x22|'[^']*'|[^\s&|;\x22-][^\s&|;\x22]*))?)*)`, "g");
907
+ function rewriteScript(script, names) {
908
+ const unknown = [];
909
+ const out = script.replace(ELEVENTY_COMMAND, (whole, given, start) => {
910
+ if (!isEleventyCommand(script, start, start + whole.length - given.length, names)) return whole;
911
+ let command = "build";
912
+ const flags = [];
913
+ const parts = splitWhitespace(given);
914
+ for (let i = 0; i < parts.length; i++) {
915
+ const part = parts[i];
916
+ const eq = part.indexOf("=");
917
+ const flag = eq === -1 ? part : part.slice(0, eq);
918
+ let value = eq === -1 ? void 0 : part.slice(eq + 1);
919
+ const valueOf = () => {
920
+ if (value === void 0 && i + 1 < parts.length && !parts[i + 1].startsWith("-")) value = parts[++i];
921
+ return value;
922
+ };
923
+ if (flag === "--serve" || flag === "--watch") command = "serve";
924
+ else if (flag === "--quiet") flags.push("--quiet");
925
+ else if (flag === "--port") {
926
+ const port = valueOf();
927
+ if (port !== void 0) flags.push(`--port ${port}`);
928
+ } else if (flag === "--output") {
929
+ const output = valueOf();
930
+ if (output !== void 0) flags.push(`--output ${output}`);
931
+ } else if (flag === "--pathprefix" || flag === "--pathPrefix") {
932
+ const base = valueOf();
933
+ if (base !== void 0) flags.push(`--base ${base}`);
934
+ } else if (flag !== "--incremental") unknown.push(flag);
935
+ }
936
+ const kept = command === "build" ? flags.filter((f) => !f.startsWith("--port")) : flags;
937
+ return [`ssqch ${command}`, ...kept].join(" ");
938
+ });
939
+ return [out, unknown];
940
+ }
941
+ var lastChar = (s) => s === "" ? void 0 : Array.from(s.slice(-2)).pop();
942
+ var firstChar = (s) => s === "" ? void 0 : String.fromCodePoint(s.codePointAt(0));
943
+ function isEleventyCommand(script, start, wordEnd, names) {
944
+ const partOfName = (c) => c !== void 0 && (/^[\p{Alphabetic}\p{N}]$/u.test(c) || "_-:./@$".includes(c));
945
+ if (partOfName(lastChar(script.slice(0, start))) || partOfName(firstChar(script.slice(wordEnd)))) return false;
946
+ const command = script.slice(0, start).split(/[&|;]/).pop() ?? "";
947
+ const all = splitWhitespace(command);
948
+ let skip = 0;
949
+ while (skip < all.length && all[skip].includes("=") && !all[skip].startsWith("-")) skip++;
950
+ const words = all.slice(skip);
951
+ if (words.length === 0) return true;
952
+ if (["npm", "pnpm", "yarn", "bun"].includes(words[0]) && ["run", "run-script"].includes(words[1])) return false;
953
+ if (["run-s", "run-p", "npm-run-all", "npm-run-all2"].includes(words[0])) return false;
954
+ if (words.length === 1 && (words[0] === "pnpm" || words[0] === "yarn")) return !names.includes("eleventy");
955
+ return true;
956
+ }
957
+ function packageFiles(dir, plan) {
958
+ const text = readUtf8(path.join(dir, "package.json"));
959
+ if (text === void 0) return;
960
+ let pkg;
961
+ try {
962
+ pkg = JSON.parse(text);
963
+ } catch {
964
+ plan.byHand.push(["package.json", "isn't valid JSON, so its Eleventy dependency and scripts weren't changed"]);
965
+ return;
966
+ }
967
+ const root = isPlainObject(pkg) ? pkg : {};
968
+ const edits = new JsonText(text);
969
+ const version = VERSION;
970
+ const changes = [];
971
+ const hasSsqch = ["dependencies", "devDependencies"].some((k) => isPlainObject(root[k]) && Object.hasOwn(root[k], "ssqch"));
972
+ let removed = false;
973
+ for (const section of ["dependencies", "devDependencies"]) {
974
+ const deps = root[section];
975
+ if (!isPlainObject(deps)) continue;
976
+ if (Object.hasOwn(deps, "@11ty/eleventy")) {
977
+ delete deps["@11ty/eleventy"];
978
+ edits.remove([section], "@11ty/eleventy");
979
+ removed = true;
980
+ }
981
+ if (Object.keys(deps).length === 0 && section === "dependencies") {
982
+ delete root[section];
983
+ edits.remove([], section);
984
+ }
985
+ }
986
+ if (removed) {
987
+ if (hasSsqch) {
988
+ changes.push("@11ty/eleventy removed (ssqch is already there)");
989
+ } else {
990
+ const pinned = JSON.stringify(version);
991
+ if (!Object.hasOwn(root, "devDependencies")) {
992
+ root.devDependencies = { ssqch: version };
993
+ edits.insert([], "devDependencies", edits.object([["ssqch", pinned]], 1));
994
+ } else if (isPlainObject(root.devDependencies)) {
995
+ root.devDependencies.ssqch = version;
996
+ edits.insert(["devDependencies"], "ssqch", pinned, (other) => compareText(other, "ssqch") > 0);
997
+ }
998
+ changes.push(`@11ty/eleventy -> ssqch ${version} in devDependencies`);
999
+ }
1000
+ }
1001
+ const unknownFlags = [];
1002
+ const flagsAre = (unknown) => `${unknown.join(", ")} ${unknown.length === 1 ? "flag is" : "flags are"} Eleventy's: check what ssqch has (\`ssqch build --help\`, \`ssqch serve --help\`)`;
1003
+ const scripts = isPlainObject(root.scripts) ? root.scripts : void 0;
1004
+ const names = scripts ? Object.keys(scripts) : [];
1005
+ if (scripts) {
1006
+ let changed = false;
1007
+ for (const [name, script] of Object.entries(scripts)) {
1008
+ if (typeof script !== "string") continue;
1009
+ const [rewritten, unknown] = rewriteScript(script, names);
1010
+ if (rewritten !== script) {
1011
+ scripts[name] = rewritten;
1012
+ edits.replace(["scripts", name], JSON.stringify(rewritten));
1013
+ changed = true;
1014
+ }
1015
+ if (unknown.length) unknownFlags.push(`the \`${name}\` script's ${flagsAre(unknown)}`);
1016
+ }
1017
+ if (changed) changes.push("scripts: eleventy -> ssqch build, eleventy --serve -> ssqch serve");
1018
+ }
1019
+ if (isPlainObject(root.wireit)) {
1020
+ let changed = false;
1021
+ for (const [name, task] of Object.entries(root.wireit)) {
1022
+ if (!isPlainObject(task) || typeof task.command !== "string") continue;
1023
+ const [rewritten, unknown] = rewriteScript(task.command, names);
1024
+ if (rewritten !== task.command) {
1025
+ task.command = rewritten;
1026
+ edits.replace(["wireit", name, "command"], JSON.stringify(rewritten));
1027
+ changed = true;
1028
+ }
1029
+ if (unknown.length) unknownFlags.push(`wireit's \`${name}\` command's ${flagsAre(unknown)}`);
1030
+ }
1031
+ if (changed) changes.push("wireit commands: eleventy -> ssqch build, eleventy --serve -> ssqch serve");
1032
+ }
1033
+ for (const what of unknownFlags) plan.byHand.push(["package.json", what]);
1034
+ const edited = changes.length > 0;
1035
+ if (edited) plan.edits.push(["package.json", changes, edits.text]);
1036
+ const pm = packageManager(dir, pkg);
1037
+ for (const [manager, lockfiles] of LOCKFILES) {
1038
+ for (const lockfile of lockfiles) {
1039
+ const file = path.join(dir, lockfile);
1040
+ if (!isFile(file)) continue;
1041
+ let mentions = false;
1042
+ try {
1043
+ mentions = fs.readFileSync(file).includes("@11ty/eleventy");
1044
+ } catch {
1045
+ }
1046
+ if (manager !== pm) plan.byHand.push([lockfile, `${manager}'s lockfile, but the site uses ${pm}: delete it (a host that installs from it gets ${mentions ? "Eleventy" : "old packages"} and no ssqch)`]);
1047
+ else if (mentions || edited) plan.byHand.push([lockfile, `run \`${pm} install\` to update it for ssqch`]);
1048
+ }
1049
+ }
1050
+ if (pm === "pnpm" && edited && waitsForReleaseAge(dir, pkg)) {
1051
+ plan.byHand.push(["pnpm-workspace.yaml", `pnpm waits a day before installing a new release, so if ssqch ${version} came out today, the install fails: add \`ssqch\` under \`minimumReleaseAgeExclude\` (\`ssqch docs "release age"\`)`]);
1052
+ }
1053
+ }
1054
+ function waitsForReleaseAge(dir, pkg) {
1055
+ const field = packageManagerField(pkg);
1056
+ const major = field?.startsWith("pnpm@") ? field.slice(5).split(".")[0] : void 0;
1057
+ if (major !== void 0 && /^\+?\d+$/.test(major) && Number(major) <= 4294967295 && Number(major) < 11) return false;
1058
+ const workspace = lines(readUtf8(path.join(dir, "pnpm-workspace.yaml")) ?? "");
1059
+ const excluded = workspace.some((l) => trimMatches(trim(trimStart(l).replace(/^-+/, "")), `'"`).split("@")[0] === "ssqch");
1060
+ const off = workspace.some((l) => trim(l).replaceAll(" ", "") === "minimumReleaseAge:0");
1061
+ return !excluded && !off;
1062
+ }
1063
+ var TERA_CALLS = rustRegExp(String.raw`\b(get_url|get_section|get_page|get_taxonomy|get_taxonomy_url|get_image_metadata|resize_image|load_data|trans|get_hash)\s*\(`, "g");
1064
+ var NAMED_ARGUMENT = rustRegExp(String.raw`\|\s*\w+\(\s*\w+\s*=`, "g");
1065
+ var SHORTCODE_CALL = rustRegExp(String.raw`\{[{%]\s*([a-z_][a-z0-9_]*)\s*\(`, "g");
1066
+ function rewriteZolaFrontMatter(text) {
1067
+ if (!text.startsWith("+++")) return [text, []];
1068
+ const rest = text.slice(3);
1069
+ const end = rest.indexOf("\n+++");
1070
+ if (end === -1) return [text, []];
1071
+ const front = rest.slice(0, end), after = rest.slice(end);
1072
+ const newline = front.includes("\r\n") ? "\r\n" : "\n";
1073
+ const all = lines(front);
1074
+ const changes = [];
1075
+ const top = [], tables = [], tags = [];
1076
+ let table = "";
1077
+ for (let i = 0; i < all.length; i++) {
1078
+ const line = all[i];
1079
+ const trimmed = trim(line);
1080
+ if (trimmed.startsWith("[") && !trimmed.startsWith("[[") && trimmed.endsWith("]")) {
1081
+ table = trim(trimMatches(trimmed, "[]"));
1082
+ tables.push(line);
1083
+ } else if (table === "taxonomies" && trimmed.startsWith("tags") && trimStart(trimmed.slice(4)).startsWith("=")) {
1084
+ let value = line;
1085
+ while (occurrences(value, "[") > occurrences(value, "]") && i + 1 < all.length) {
1086
+ i++;
1087
+ value += newline + all[i];
1088
+ }
1089
+ tags.push(trimStart(value));
1090
+ } else if (table === "" && trimmed.startsWith("path") && trimStart(trimmed.slice(4)).startsWith("=")) {
1091
+ const value = trim(trimStart(trimmed.slice(4)).replace(/^=+/, ""));
1092
+ const quote = value[0] === '"' || value[0] === "'" ? value[0] : void 0;
1093
+ const close = quote === void 0 ? -1 : value.indexOf(quote, 1);
1094
+ if (close !== -1) {
1095
+ top.push(`permalink = "/${trimMatches(value.slice(1, close), "/")}/"`);
1096
+ changes.push("path -> permalink");
1097
+ } else {
1098
+ top.push(line);
1099
+ }
1100
+ } else if (table === "") {
1101
+ top.push(line);
1102
+ } else {
1103
+ tables.push(line);
1104
+ }
1105
+ }
1106
+ if (!tags.length && !changes.length) return [text, []];
1107
+ if (tags.length) {
1108
+ changes.push("[taxonomies] tags -> tags");
1109
+ let at = 0;
1110
+ for (let k = top.length - 1; k >= 0; k--) {
1111
+ if (trim(top[k]) !== "") {
1112
+ at = k + 1;
1113
+ break;
1114
+ }
1115
+ }
1116
+ top.splice(at, 0, ...tags);
1117
+ const header = tables.findIndex((l) => trim(l) === "[taxonomies]");
1118
+ if (header !== -1) {
1119
+ let next = tables.findIndex((l, k) => k > header && trim(l).startsWith("["));
1120
+ if (next === -1) next = tables.length;
1121
+ if (tables.slice(header + 1, next).every((l) => trim(l) === "")) {
1122
+ tables.splice(header, next - header);
1123
+ while (top.length && trim(top[top.length - 1]) === "" && !tables.length) top.pop();
1124
+ }
1125
+ }
1126
+ }
1127
+ const body = [...top, ...tables].join(newline);
1128
+ return [`+++${newline}${body.startsWith(newline) ? body.slice(newline.length) : body}${after}`, changes];
1129
+ }
1130
+ function sortedKeys(value) {
1131
+ if (Array.isArray(value)) return value.map(sortedKeys);
1132
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compareText(a, b)).map(([k, v]) => [k, sortedKeys(v)]));
1133
+ return value;
1134
+ }
1135
+ function tomlError(e, text) {
1136
+ if (!(e instanceof TomlError)) return tomlReason(e);
1137
+ const what = e.message.split("\n")[0].replace(/^Invalid TOML document: /, "");
1138
+ const gutter = " ".repeat(String(e.line).length + 1);
1139
+ const content = text.split("\n")[e.line - 1] ?? "";
1140
+ return `TOML parse error at line ${e.line}, column ${e.column}
1141
+ ${gutter}|
1142
+ ${e.line} | ${content}
1143
+ ${gutter}|${" ".repeat(e.column)}^
1144
+ ${what}
1145
+ `;
1146
+ }
1147
+ function zola(dir) {
1148
+ const configPath = path.join(dir, "config.toml");
1149
+ if (!isFile(configPath)) fail(`there's no config.toml in ${dir}: is this the Zola site's folder?`);
1150
+ const configText = readStrict(configPath);
1151
+ let config = {};
1152
+ try {
1153
+ config = readToml(configText);
1154
+ } catch (e) {
1155
+ fail(`config.toml: ${tomlError(e, configText)}`);
1156
+ }
1157
+ const plan = { from: "Zola", renames: [], edits: [], newFiles: [], byHand: [] };
1158
+ const sections = [];
1159
+ const shortcodes = /* @__PURE__ */ new Set();
1160
+ let aliases = false, bundles = false;
1161
+ for (const entry of walk(path.join(dir, "content"), () => false, false)) {
1162
+ if (!entry.isFile || extensionOf(entry.name) !== "md") continue;
1163
+ const rel = `content/${entry.rel}`;
1164
+ const text2 = readUtf8(entry.abs);
1165
+ if (text2 === void 0) continue;
1166
+ if (entry.name === "_index.md") {
1167
+ sections.push(rel);
1168
+ continue;
1169
+ }
1170
+ if (entry.name === "index.md") {
1171
+ let count = 0;
1172
+ try {
1173
+ count = fs.readdirSync(path.dirname(entry.abs)).length;
1174
+ } catch {
1175
+ }
1176
+ if (count > 1) bundles = true;
1177
+ }
1178
+ aliases ||= text2.includes("\naliases");
1179
+ for (const c of text2.matchAll(SHORTCODE_CALL)) shortcodes.add(c[1]);
1180
+ if (text2.startsWith("---") && text2.includes("taxonomies:")) plan.byHand.push([rel, "YAML front matter with `taxonomies`: move `tags` to the top level"]);
1181
+ const [next, changes] = rewriteZolaFrontMatter(text2);
1182
+ if (changes.length) plan.edits.push([rel, changes, next]);
1183
+ }
1184
+ for (const section of sections) {
1185
+ let folder = section;
1186
+ while (folder.endsWith("/_index.md")) folder = folder.slice(0, -"/_index.md".length);
1187
+ const name = folder.split("/").pop();
1188
+ plan.byHand.push([section, `a section: its settings (\`sort_by\`, \`paginate_by\`, \`page_template\`) become directory data (${folder}/${name}.json: \`layout\`, \`tags\`, \`permalink\`) and an index page that lists the folder's pages`]);
1189
+ }
1190
+ for (const name of [...shortcodes].sort(compareText)) {
1191
+ const shortcode = (ext) => isFile(path.join(dir, "templates", "shortcodes", `${name}.${ext}`));
1192
+ if (shortcode("html") || shortcode("md")) plan.byHand.push([`templates/shortcodes/${name}.html`, `a shortcode used in content: make it a config filter (\`filters: { ${name}: ... }\`) or a macro; a body shortcode (\`{% ${name}() %}...{% end %}\`) becomes a \`::: ${name}\` container`]);
1193
+ }
1194
+ const tera = /* @__PURE__ */ new Map();
1195
+ let templateCount = 0;
1196
+ for (const entry of walk(path.join(dir, "templates"), () => false, false)) {
1197
+ if (!entry.isFile) continue;
1198
+ const text2 = readUtf8(entry.abs);
1199
+ if (text2 === void 0) continue;
1200
+ templateCount++;
1201
+ const count = (what, n) => {
1202
+ if (n > 0) tera.set(what, (tera.get(what) ?? 0) + n);
1203
+ };
1204
+ count("Tera functions (get_url, get_section, load_data, resize_image...): filters or data in the config", text2.match(TERA_CALLS)?.length ?? 0);
1205
+ count('filters with named arguments (`| date(format="%Y")`): positional in ssqch (`| dateformat("%Y")`)', text2.match(NAMED_ARGUMENT)?.length ?? 0);
1206
+ count("`page.content`, `section.content`: `content` in a layout", occurrences(text2, "page.content") + occurrences(text2, "section.content"));
1207
+ count("`section.pages`, `paginator.pages`: a collection (`collections.<tag>`), and `pagination.items`", occurrences(text2, "section.pages") + occurrences(text2, "paginator."));
1208
+ count("`page.title`, `page.extra`, `page.taxonomies`: front matter is at the top level (`title`, `extra`, `tags`)", occurrences(text2, "page.title") + occurrences(text2, "page.extra") + occurrences(text2, "page.taxonomies"));
1209
+ count("`page.permalink`: `page.url`", occurrences(text2, "page.permalink") + Math.max(0, occurrences(text2, ".permalink") - occurrences(text2, "page.permalink")));
1210
+ }
1211
+ if (templateCount > 0) {
1212
+ plan.byHand.push(["templates/", `${templateCount} Tera templates: they run as Jinja (\`htmlEngine: "jinja"\` in the draft config), and these need changing:`]);
1213
+ for (const [what, n] of [...tera].sort(([a], [b]) => compareText(a, b))) plan.byHand.push(["templates/", `${n} x ${what}`]);
1214
+ }
1215
+ const text = (key) => typeof config[key] === "string" ? config[key] : void 0;
1216
+ const flag = (key) => config[key] === true || isPlainObject(config.markdown) && config.markdown[key] === true;
1217
+ const baseUrl = text("base_url") ?? "";
1218
+ const site = {};
1219
+ for (const key of ["base_url", "title", "description", "default_language"]) {
1220
+ const value = text(key);
1221
+ if (value !== void 0) site[key] = value;
1222
+ }
1223
+ if (config.extra !== void 0) site.extra = sortedKeys(config.extra);
1224
+ const imports = ['import { defineConfig } from "ssqch";', 'import { linksPlugin } from "ssqch/links";'];
1225
+ const plugins = [];
1226
+ if (baseUrl.startsWith("http")) {
1227
+ imports.push('import { sitemapPlugin } from "ssqch/sitemap";');
1228
+ plugins.push(`sitemapPlugin({ url: ${JSON.stringify(baseUrl)} })`);
1229
+ }
1230
+ if (aliases) {
1231
+ imports.push('import { redirectsPlugin } from "ssqch/redirects";');
1232
+ plugins.push("redirectsPlugin()");
1233
+ }
1234
+ if (flag("compile_sass") && isDir(path.join(dir, "sass"))) {
1235
+ imports.push('import { sassPlugin } from "ssqch/sass";');
1236
+ plugins.push('sassPlugin({ files: { sass: "/" } })');
1237
+ }
1238
+ plugins.push("linksPlugin()");
1239
+ const markdown = ['headingIds: "ascii"'];
1240
+ if (flag("highlight_code")) markdown.push("highlight: true");
1241
+ if (flag("smart_punctuation")) markdown.push("smartPunctuation: true");
1242
+ let out = `// A first draft, written by \`ssqch import zola\` from config.toml.
1243
+ // \`ssqch docs --from zola\` has the whole mapping.
1244
+ ${imports.join("\n")}
1245
+
1246
+ export default defineConfig({
1247
+ `;
1248
+ out += ` dirs: { input: "content", output: ${JSON.stringify(text("output_dir") ?? "public")}, includes: "../templates" },
1249
+ `;
1250
+ out += ' // Tera templates are close to Jinja: Markdown and the .html templates run through it.\n templateFormats: ["md"],\n markdownEngine: "jinja",\n htmlEngine: "jinja",\n';
1251
+ if (sections.length) out += ' // Section files: their settings go in directory data (see the list `ssqch import` printed).\n ignore: ["**/_index.md"],\n';
1252
+ if (bundles) out += " // Pages that are a folder (`post/index.md`) keep the files next to them.\n bundles: true,\n";
1253
+ out += ` markdown: { ${markdown.join(", ")} },
1254
+ `;
1255
+ if (isDir(path.join(dir, "static"))) out += ' passthrough: [{ static: "." }],\n';
1256
+ out += ` // \`config.title\` and \`config.extra.*\` in templates read this.
1257
+ data: {
1258
+ config: ${JSON.stringify(site, null, 2).replaceAll("\n", "\n ")},
1259
+ },
1260
+ `;
1261
+ out += ` filters: {
1262
+ // Port shortcodes and Tera functions here: name: (...args) => result
1263
+ },
1264
+ plugins: [${plugins.join(", ")}],
1265
+ });
1266
+ `;
1267
+ if (config.taxonomies !== void 0) plan.byHand.push(["config.toml", "taxonomies: tags are built in (`collections.<tag>`); tag pages are a template paginated over the tags (the `blog-tags` example), and other taxonomies are custom `collections`"]);
1268
+ if (flag("build_search_index")) plan.byHand.push(["config.toml", 'build_search_index: Pagefind after the build (`afterBuild: { run: "npx -y pagefind --site public" }`)']);
1269
+ if (flag("generate_feeds") || flag("generate_feed")) plan.byHand.push(["config.toml", "generate_feeds: a feed template with `rssPlugin()`'s filters (the `blog-tags` example has one)"]);
1270
+ if (findConfig(dir) === void 0) plan.newFiles.push(["ssqch.config.js", "a first draft, from config.toml", out]);
1271
+ else plan.byHand.push(["ssqch.config.js", "it's already there, so the draft from config.toml wasn't written"]);
1272
+ return plan;
1273
+ }
1274
+ export {
1275
+ apply,
1276
+ blankComments,
1277
+ describe,
1278
+ draftConfig,
1279
+ eleventy,
1280
+ rewriteData,
1281
+ rewriteScript,
1282
+ rewriteTemplate,
1283
+ rewriteZolaFrontMatter,
1284
+ runImport,
1285
+ tomlError,
1286
+ zola
1287
+ };