@dogsbay/commands 0.2.0-beta.182 → 0.2.0-beta.184

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,428 @@
1
+ /**
2
+ * Moving and deleting files with every reference kept, as PLANS: what would be written, moved and
3
+ * left broken, computed before anything is touched (plans/browser-refactor.md, the playground's
4
+ * item 36). `rename-file`, `move-folder` and `safe-delete` run these; a host shows the plan
5
+ * ("N links in M files will change") and applies it as one step with `applyPlan`.
6
+ *
7
+ * No zod, no engine, no Node: `@dogsbay/commands/refactor` bundles for a browser.
8
+ *
9
+ * One pass for any set of moves (a file, a folder): every file that moves or refers to a file that
10
+ * moves has each reference — a link, an image, a directive prop, an include, a menu path, a key's
11
+ * href, a site path — rewritten from the referrer's NEW place to the target's NEW place. A
12
+ * reference that cannot be rewritten is a miss, with its file and line: never silent.
13
+ */
14
+ import { dirname } from "@dogsbay/format-topicmap";
15
+ import { buildWorkspaceIndex } from "./indexes.js";
16
+ import { normalizeStoragePath } from "./storage.js";
17
+ import { relativeHref, replaceIncludePath, replaceLinkHrefsAll, replaceMapHref } from "./edits.js";
18
+ import { resolveSitePath, siteLayout } from "./site-layout.js";
19
+ const isExternal = (href) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(href) || href.startsWith("//");
20
+ const refuse = (code, message, file) => ({ ok: false, code, message, ...(file ? { file } : {}) });
21
+ /** `path` and the rest (`?query#fragment`) of an href as written. */
22
+ const splitHref = (href) => {
23
+ const at = href.search(/[?#]/);
24
+ return at < 0 ? [href, ""] : [href.slice(0, at), href.slice(at)];
25
+ };
26
+ /**
27
+ * A new path as a link destination: percent-encoded when the old one was, or when it holds what
28
+ * would end or split the destination (a space, `<>`, `#`, `?`, unbalanced parentheses).
29
+ */
30
+ const asWritten = (oldPath, newPath) => {
31
+ const parens = (newPath.match(/\(/g)?.length ?? 0) !== (newPath.match(/\)/g)?.length ?? 0);
32
+ if (!/%[0-9A-Fa-f]{2}/.test(oldPath) && !/[\s<>#?"'{}]/.test(newPath) && !parens)
33
+ return newPath;
34
+ return encodeURI(newPath).replace(/#/g, "%23").replace(/\?/g, "%3F").replace(/'/g, "%27").replace(/\(/g, parens ? "%28" : "(").replace(/\)/g, parens ? "%29" : ")");
35
+ };
36
+ const isIndexPage = (p) => p === "index.md" || p.endsWith("/index.md");
37
+ const folderOfIndex = (p) => p.slice(0, -"index.md".length).replace(/\/$/, "");
38
+ /** The page an address names (`install/`, `../`, `guide/install`): `x.md`, `x.mdx`, `x/index.md`. */
39
+ const pageFor = (files, address) => {
40
+ const bare = address.replace(/\/+$/, "");
41
+ const candidates = bare ? [`${bare}.md`, `${bare}.mdx`, `${bare}/index.md`] : ["index.md", "index.mdx"];
42
+ return candidates.find((c) => files.has(c));
43
+ };
44
+ const PAGE_EXT = /\.(?:md|mdx)$/i;
45
+ /**
46
+ * A page's address under a content root (`guide/install.md` → `guide/install`, `guide/index.md` →
47
+ * `guide`, the root's `index.md` → ``), or undefined when the file is not under the root or sits
48
+ * in a `_` folder the build does not route (`_assets/` is served).
49
+ */
50
+ const addressUnder = (root, file) => {
51
+ const rel = root ? (file.startsWith(`${root}/`) ? file.slice(root.length + 1) : undefined) : file;
52
+ if (rel === undefined)
53
+ return undefined;
54
+ if (!rel.startsWith("_assets/") && !rel.includes("/_assets/") && rel.split("/").some((seg) => seg.startsWith("_")))
55
+ return undefined;
56
+ if (!PAGE_EXT.test(rel))
57
+ return rel; // an asset keeps its name
58
+ const bare = rel.replace(PAGE_EXT, "");
59
+ return bare === "index" ? "" : bare.replace(/\/index$/, "");
60
+ };
61
+ /**
62
+ * The content folder a menu's "/"-rooted `file: /x.md` is read from: the folder of the nearest
63
+ * root menu (`nav.yml` / `nav.yaml` / `nav.json`) at or above the menu file, else the workspace root.
64
+ */
65
+ const contentFolderOf = (isMenu, menuPath) => {
66
+ for (let dir = dirname(menuPath);; dir = dirname(dir)) {
67
+ const base = dir === "." ? "" : dir;
68
+ if (["nav.yml", "nav.yaml", "nav.json"].some((n) => isMenu(base ? `${base}/${n}` : n)))
69
+ return base;
70
+ if (!base)
71
+ return "";
72
+ }
73
+ };
74
+ /** Plan moving files (`moves`: from → to, workspace paths). Nothing is written. */
75
+ export async function planMove(storage, moves, options = {}) {
76
+ const move = new Map();
77
+ const targets = new Set();
78
+ for (const m of moves) {
79
+ const from = normalizeStoragePath(m.from);
80
+ const to = normalizeStoragePath(m.to);
81
+ if (!from || !to || from.startsWith("../") || to.startsWith("../") || from === ".." || to === "..")
82
+ return refuse("rename-path-invalid", `"${m.from}" → "${m.to}" is not a path in the workspace`);
83
+ if (from === to)
84
+ return refuse("rename-noop", "from and to are the same path", from);
85
+ if (move.has(from))
86
+ return refuse("rename-duplicate", `${from} is moved twice`, from);
87
+ if (targets.has(to))
88
+ return refuse("rename-target-twice", `two files would move to ${to}`, to);
89
+ move.set(from, to);
90
+ targets.add(to);
91
+ }
92
+ if (!move.size)
93
+ return refuse("rename-noop", "nothing to move");
94
+ for (const [from, to] of move) {
95
+ if (!(await storage.exists(from)))
96
+ return refuse("rename-source-missing", `${from} does not exist`, from);
97
+ // a target may be a file that moves away in the same plan only if… it never is: refuse, rather than order writes
98
+ if (await storage.exists(to))
99
+ return refuse("rename-target-exists", `${to} already exists`, to);
100
+ }
101
+ const index = options.index ?? (await buildWorkspaceIndex(storage));
102
+ const layout = await siteLayout(storage);
103
+ const newPath = (p) => move.get(p) ?? p;
104
+ const moving = (...paths) => paths.some((p) => move.has(p));
105
+ const byFile = new Map();
106
+ const misses = [];
107
+ const want = (file, group, raw, next, ref) => {
108
+ if (next === raw)
109
+ return;
110
+ const pending = byFile.get(file) ?? new Map();
111
+ byFile.set(file, pending);
112
+ const key = `${group}\u0000${raw}`;
113
+ const have = pending.get(key);
114
+ if (have && have.next !== next) {
115
+ misses.push({ ...ref, reason: `"${raw}" is written for two targets in this file` });
116
+ return;
117
+ }
118
+ if (have)
119
+ have.refs.push(ref);
120
+ else
121
+ pending.set(key, { group, raw, next, refs: [ref] });
122
+ };
123
+ // A site path (`/guide/install`, a menu's `href: /guide/install`) to the new page's address,
124
+ // written in the author's style: their prefix, trailing slash and suffix kept
125
+ const sitePathFor = (raw) => {
126
+ if (!layout.checkable)
127
+ return {};
128
+ const [pathPart, suffix] = splitHref(raw);
129
+ let sitePath = pathPart.replace(/^\/+/, "").replace(/\/+$/, "");
130
+ try {
131
+ sitePath = decodeURIComponent(sitePath);
132
+ }
133
+ catch { /* as written */ }
134
+ if (!sitePath)
135
+ return {};
136
+ const hit = resolveSitePath(index, layout, sitePath);
137
+ if (!hit.file || !move.has(hit.file))
138
+ return {};
139
+ const to = newPath(hit.file);
140
+ const root = layout.roots.find((r) => addressUnder(r, hit.file) !== undefined) ?? "";
141
+ const address = addressUnder(root, to);
142
+ if (address === undefined)
143
+ return { target: hit.file, reason: `${to} is not under the content folder${root ? ` (${root})` : ""}, so it has no site address` };
144
+ const prefix = layout.prefixes.find((pre) => sitePath === pre || sitePath.startsWith(`${pre}/`));
145
+ const path = [prefix, address].filter(Boolean).join("/");
146
+ const slash = pathPart.endsWith("/") && path ? "/" : "";
147
+ return { target: hit.file, next: `/${asWritten(pathPart, path)}${slash}${suffix}` };
148
+ };
149
+ for (const doc of index.docs.values()) {
150
+ const dir = dirname(newPath(doc.path));
151
+ for (const link of doc.links) {
152
+ const ref = { file: doc.path, ...(link.line !== undefined ? { line: link.line } : {}), kind: link.kind, raw: link.href };
153
+ if (link.siteAbsolute) {
154
+ const site = sitePathFor(link.href);
155
+ if (site.reason)
156
+ misses.push({ ...ref, kind: "site", reason: site.reason });
157
+ else if (site.next)
158
+ want(doc.path, "link", link.href, site.next, { ...ref, kind: "site" });
159
+ continue;
160
+ }
161
+ // (`../` to the root is the target "")
162
+ if (link.target === undefined || link.href.startsWith("#"))
163
+ continue;
164
+ const [pathPart, suffix] = splitHref(link.href);
165
+ let target = link.target;
166
+ let style = "file";
167
+ // a path above the workspace (`../../x.md`) is kept pointing where it did from the new place
168
+ if (!link.escapes && !index.files.has(target)) {
169
+ // an address, not a file (`install/`, `../`, `../guide/install`): the page it names
170
+ const found = pageFor(index.files, target);
171
+ if (!found) {
172
+ // a folder with no page, or nothing: from a file that moves, it no longer points there
173
+ if (move.has(doc.path))
174
+ misses.push({ ...ref, reason: `"${pathPart}" names no file or page, so it could not follow the move` });
175
+ continue;
176
+ }
177
+ target = found;
178
+ style = isIndexPage(found) ? "folder" : "page";
179
+ }
180
+ if (!moving(doc.path, target))
181
+ continue;
182
+ let rel = relativeHref(dir, newPath(target));
183
+ if (style !== "file") {
184
+ const moved = newPath(target);
185
+ if (!PAGE_EXT.test(moved)) {
186
+ misses.push({ ...ref, reason: `${moved} is not a page, so "${pathPart}" has no address to follow it` });
187
+ continue;
188
+ }
189
+ rel = isIndexPage(moved)
190
+ ? relativeHref(dir, folderOfIndex(moved) ? `${folderOfIndex(moved)}/x` : "x").replace(/\/?x$/, "") || "."
191
+ : rel.replace(PAGE_EXT, "");
192
+ if (pathPart.endsWith("/") && rel !== "." && !rel.endsWith("/"))
193
+ rel += "/";
194
+ }
195
+ want(doc.path, "link", link.href, asWritten(pathPart, rel) + suffix, ref);
196
+ }
197
+ for (const include of doc.includes) {
198
+ if (!moving(doc.path, include.target))
199
+ continue;
200
+ want(doc.path, "include", include.raw, relativeHref(dir, newPath(include.target)), {
201
+ file: doc.path, ...(include.line !== undefined ? { line: include.line } : {}), kind: "include", raw: include.raw,
202
+ });
203
+ }
204
+ }
205
+ // where each menu's "/"-rooted paths are read from, before and after the moves
206
+ const newMenus = new Set([...index.maps.keys()].map(newPath));
207
+ const oldRootOf = (menu) => contentFolderOf((p) => index.maps.has(p), menu);
208
+ const newRootOf = (menu) => contentFolderOf((p) => newMenus.has(p), newPath(menu));
209
+ for (const map of index.maps.values()) {
210
+ const dir = dirname(newPath(map.path));
211
+ for (const r of map.refs) {
212
+ const ref = { file: map.path, ...(r.line !== undefined ? { line: r.line } : {}), kind: "menu", raw: r.href };
213
+ if (r.target) {
214
+ if (!moving(map.path, r.target))
215
+ continue;
216
+ const hash = r.href.indexOf("#");
217
+ want(map.path, "menu", r.href, relativeHref(dir, newPath(r.target)) + (hash >= 0 ? r.href.slice(hash) : ""), ref);
218
+ }
219
+ else if (r.rootRelative) {
220
+ // `file: /guide/x.md`: from the content folder
221
+ const [pathPart, suffix] = splitHref(r.href);
222
+ const rel = pathPart.replace(/^\/+/, "");
223
+ const oldRoot = oldRootOf(map.path);
224
+ const target = oldRoot ? `${oldRoot}/${rel}` : rel;
225
+ if (!index.files.has(target))
226
+ continue;
227
+ const newRoot = newRootOf(map.path);
228
+ if (!move.has(target) && newRoot === oldRoot)
229
+ continue;
230
+ const to = newPath(target);
231
+ if (newRoot && !to.startsWith(`${newRoot}/`))
232
+ misses.push({ ...ref, reason: `${to} is not in the content folder (${newRoot}) this menu reads "/" paths from` });
233
+ else
234
+ want(map.path, "menu", r.href, `/${newRoot ? to.slice(newRoot.length + 1) : to}${suffix}`, ref);
235
+ }
236
+ else if (r.field === "href" && r.href.startsWith("/") && !r.href.startsWith("//")) {
237
+ const site = sitePathFor(r.href);
238
+ if (site.reason)
239
+ misses.push({ ...ref, kind: "site", reason: site.reason });
240
+ else if (site.next)
241
+ want(map.path, "menu", r.href, site.next, { ...ref, kind: "site" });
242
+ }
243
+ }
244
+ }
245
+ for (const defs of index.keys.values()) {
246
+ for (const def of defs) {
247
+ const href = def.def.href;
248
+ if (typeof href !== "string" || isExternal(href) || href.startsWith("/"))
249
+ continue;
250
+ const [pathPart, suffix] = splitHref(href);
251
+ const target = normalizeStoragePath(`${dirname(def.file)}/${pathPart}`);
252
+ if (!moving(def.file, target))
253
+ continue;
254
+ want(def.file, "menu", href, relativeHref(dirname(newPath(def.file)), newPath(target)) + suffix, { file: def.file, kind: "key", raw: href });
255
+ }
256
+ }
257
+ // Each file's rewrites: every link in ONE pass (a hub page linking a whole folder), then includes
258
+ // and menu paths through placeholders, so a new value is never matched as another's old one
259
+ const edits = new Map();
260
+ const movedText = new Map();
261
+ let rewritten = 0;
262
+ let n = 0;
263
+ const notFound = (p) => {
264
+ for (const ref of p.refs)
265
+ misses.push({ ...ref, reason: `"${p.raw}" could not be found as written, so it was not changed — update it by hand` });
266
+ };
267
+ for (const [file, pending] of byFile) {
268
+ const original = await storage.read(file);
269
+ const links = [...pending.values()].filter((p) => p.group === "link");
270
+ let text = original;
271
+ if (links.length) {
272
+ const out = replaceLinkHrefsAll(text, new Map(links.map((p) => [p.raw, p.next])));
273
+ text = out.text;
274
+ for (const p of links) {
275
+ if (out.hits.has(p.raw))
276
+ rewritten += p.refs.length;
277
+ else
278
+ notFound(p);
279
+ }
280
+ }
281
+ const swaps = [];
282
+ for (const p of pending.values()) {
283
+ if (p.group === "link")
284
+ continue;
285
+ if (p.group === "menu" && p.next.includes("#") && !p.raw.includes("#")) {
286
+ for (const ref of p.refs)
287
+ misses.push({ ...ref, reason: `the new path "${p.next}" has a "#", which a menu reads as a fragment` });
288
+ continue;
289
+ }
290
+ const ph = `\u0000${n++}\u0000`;
291
+ const before = text;
292
+ text = p.group === "include" ? replaceIncludePath(text, p.raw, ph) : replaceMapHref(text, p.raw, ph);
293
+ if (text === before) {
294
+ notFound(p);
295
+ continue;
296
+ }
297
+ swaps.push([ph, p.next]);
298
+ rewritten += p.refs.length;
299
+ }
300
+ for (const [ph, next] of swaps)
301
+ text = text.split(ph).join(next);
302
+ if (text === original)
303
+ continue;
304
+ if (move.has(file))
305
+ movedText.set(file, text);
306
+ else
307
+ edits.set(file, text);
308
+ }
309
+ return {
310
+ ok: true,
311
+ moves: [...move].map(([from, to]) => ({ from, to, ...(movedText.has(from) ? { text: movedText.get(from) } : {}) })),
312
+ edits,
313
+ changed: [...edits.keys()].sort(),
314
+ rewritten,
315
+ misses,
316
+ };
317
+ }
318
+ /** Plan moving a folder and everything in it (`guide` → `guides`). */
319
+ export async function planFolderMove(storage, from, to, options = {}) {
320
+ const src = normalizeStoragePath(from);
321
+ const dst = normalizeStoragePath(to);
322
+ if (!src || !dst || src.startsWith("..") || dst.startsWith(".."))
323
+ return refuse("rename-path-invalid", `"${from}" → "${to}" is not a folder in the workspace`);
324
+ if (src === dst)
325
+ return refuse("rename-noop", "from and to are the same folder", src);
326
+ if (dst.startsWith(`${src}/`))
327
+ return refuse("rename-into-itself", `${dst} is inside ${src}`, src);
328
+ const files = (await storage.list()).filter((p) => p.startsWith(`${src}/`));
329
+ if (!files.length)
330
+ return refuse("rename-source-missing", `${src}/ holds no files`, src);
331
+ return planMove(storage, files.map((p) => ({ from: p, to: `${dst}${p.slice(src.length)}` })), options);
332
+ }
333
+ /** Files a refactor can move by reading and writing text, when the storage cannot move files. */
334
+ const TEXT_FILE = /\.(?:md|mdx|markdown|txt|ya?ml|json|csv|tsv|toml|html?|xml|svg|css|js|mjs|ts|adoc|rst)$/i;
335
+ /**
336
+ * Write a plan: the referrers' new text, then each move (a file that did not change moves as it
337
+ * is, through `Storage.move`). Without `Storage.move` a file that is not text (an image) is refused
338
+ * BEFORE anything is written: read and written as text, it would be corrupted.
339
+ */
340
+ export async function applyPlan(storage, plan) {
341
+ if (!storage.move) {
342
+ const binary = plan.moves.find((m) => m.text === undefined && !TEXT_FILE.test(m.from));
343
+ if (binary)
344
+ throw new Error(`${binary.from} is not a text file and this storage cannot move files (Storage.move)`);
345
+ }
346
+ for (const [file, text] of plan.edits)
347
+ await storage.write(file, text);
348
+ for (const m of plan.moves) {
349
+ if (m.text !== undefined) {
350
+ await storage.write(m.to, m.text);
351
+ await storage.delete(m.from);
352
+ }
353
+ else if (storage.move) {
354
+ await storage.move(m.from, m.to);
355
+ }
356
+ else {
357
+ await storage.write(m.to, await storage.read(m.from));
358
+ await storage.delete(m.from);
359
+ }
360
+ }
361
+ }
362
+ /** What deleting `file` would break. Nothing is deleted. */
363
+ export async function planDelete(storage, file, options = {}) {
364
+ const path = normalizeStoragePath(file);
365
+ if (!(await storage.exists(path)))
366
+ return refuse("delete-source-missing", `${path} does not exist`, path);
367
+ const index = options.index ?? (await buildWorkspaceIndex(storage));
368
+ const referrers = (index.inbound.get(path) ?? [])
369
+ .filter((ref) => ref.from !== path)
370
+ .map((ref) => ({ file: ref.from, ...(ref.line !== undefined ? { line: ref.line } : {}), kind: ref.kind, raw: ref.raw }));
371
+ // an address, not a file (`install/`, `/guide/install`), names the page too
372
+ const layout = await siteLayout(storage);
373
+ const seen = new Set(referrers.map((r) => `${r.file}\u0000${r.line}\u0000${r.raw}`));
374
+ const add = (r) => {
375
+ const key = `${r.file}\u0000${r.line}\u0000${r.raw}`;
376
+ if (!seen.has(key)) {
377
+ seen.add(key);
378
+ referrers.push(r);
379
+ }
380
+ };
381
+ for (const doc of index.docs.values()) {
382
+ if (doc.path === path)
383
+ continue;
384
+ for (const link of doc.links) {
385
+ const at = link.line !== undefined ? { line: link.line } : {};
386
+ if (link.siteAbsolute && layout.checkable && link.sitePath) {
387
+ if (resolveSitePath(index, layout, link.sitePath).file === path)
388
+ add({ file: doc.path, ...at, kind: "site", raw: link.href });
389
+ }
390
+ else if (link.target !== undefined && !link.escapes && !index.files.has(link.target)) {
391
+ if (pageFor(index.files, link.target) === path)
392
+ add({ file: doc.path, ...at, kind: link.kind, raw: link.href });
393
+ }
394
+ }
395
+ }
396
+ for (const map of index.maps.values()) {
397
+ for (const r of map.refs) {
398
+ if (r.target || !r.href.startsWith("/") || r.href.startsWith("//"))
399
+ continue;
400
+ const at = r.line !== undefined ? { line: r.line } : {};
401
+ if (r.rootRelative) {
402
+ const rel = splitHref(r.href)[0].replace(/^\/+/, "");
403
+ const root = contentFolderOf((p) => index.maps.has(p), map.path);
404
+ if ((root ? `${root}/${rel}` : rel) === path)
405
+ add({ file: map.path, ...at, kind: "menu", raw: r.href });
406
+ }
407
+ else if (layout.checkable) {
408
+ let sp = splitHref(r.href)[0].replace(/^\/+|\/+$/g, "");
409
+ try {
410
+ sp = decodeURIComponent(sp);
411
+ }
412
+ catch { /* as written */ }
413
+ if (sp && resolveSitePath(index, layout, sp).file === path)
414
+ add({ file: map.path, ...at, kind: "site", raw: r.href });
415
+ }
416
+ }
417
+ }
418
+ for (const defs of index.keys.values()) {
419
+ for (const def of defs) {
420
+ const href = def.def.href;
421
+ if (def.file === path || typeof href !== "string" || isExternal(href) || href.startsWith("/"))
422
+ continue;
423
+ if (normalizeStoragePath(`${dirname(def.file)}/${splitHref(href)[0]}`) === path)
424
+ add({ file: def.file, kind: "key", raw: href, reason: `key "${def.name}"` });
425
+ }
426
+ }
427
+ return { ok: true, file: path, referrers };
428
+ }
@@ -0,0 +1,24 @@
1
+ import type { Storage } from "./storage.js";
2
+ import type { WorkspaceIndex } from "./indexes.js";
3
+ /**
4
+ * What the SITE BUILD needs to resolve a site-absolute link: the content
5
+ * roots (`content.sources[].path` of dogsbay.config.*, else the workspace
6
+ * root — which is right when the workspace IS the content dir) and the
7
+ * basePath / site.url path to strip. Read from the workspace storage, so the
8
+ * engine stays host-agnostic. A `git:` source or several sources with
9
+ * namespace/version/locale axes produce route prefixes this cannot know —
10
+ * the check is then skipped rather than guessed.
11
+ */
12
+ export interface SiteLayout {
13
+ roots: string[];
14
+ prefixes: string[];
15
+ /** False when the config names sources whose route prefixes are not knowable here. */
16
+ checkable: boolean;
17
+ }
18
+ export declare function siteLayout(storage: Storage): Promise<SiteLayout>;
19
+ /** A site path is a page when a content root has it as `x.md`, `x/index.md`, `x.mdx` — or an existing FILE (an asset); `_`-prefixed segments are never routed (except `_assets`). */
20
+ export declare function resolveSitePath(index: WorkspaceIndex, layout: SiteLayout, sitePath: string): {
21
+ doc?: string;
22
+ file?: string;
23
+ candidates: string[];
24
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Where a site-absolute link (`/guide/install`) lands, as the SITE BUILD routes it: the content
3
+ * roots and basePath of dogsbay.config.*, a page as `x.md` / `x/index.md` / `x.mdx`, else an
4
+ * existing file. Shared by `validate` and the refactors (a moved page's site-path links follow
5
+ * it). No Node: js-yaml and the workspace Storage.
6
+ */
7
+ import { load as loadYaml } from "js-yaml";
8
+ export async function siteLayout(storage) {
9
+ const out = { roots: [""], prefixes: [], checkable: true };
10
+ for (const name of ["dogsbay.config.yml", "dogsbay.config.yaml", "dogsbay.config.json"]) {
11
+ if (!(await storage.exists(name)))
12
+ continue;
13
+ try {
14
+ const text = await storage.read(name);
15
+ const cfg = (name.endsWith(".json") ? JSON.parse(text) : loadYaml(text));
16
+ if (!cfg || typeof cfg !== "object")
17
+ return out;
18
+ const site = (cfg.site ?? {});
19
+ if (typeof site.basePath === "string" && site.basePath.replace(/\//g, ""))
20
+ out.prefixes.push(site.basePath.replace(/^\/+|\/+$/g, ""));
21
+ if (typeof site.url === "string") {
22
+ try {
23
+ const u = new URL(site.url);
24
+ const pth = u.pathname.replace(/^\/+|\/+$/g, "");
25
+ if (pth)
26
+ out.prefixes.push(pth);
27
+ }
28
+ catch { /* not a URL */ }
29
+ }
30
+ const content = (cfg.content ?? {});
31
+ const sources = Array.isArray(content.sources) ? content.sources : [];
32
+ const roots = [];
33
+ for (const src of sources) {
34
+ if (!src || typeof src !== "object")
35
+ continue;
36
+ const rec = src;
37
+ if (typeof rec.git === "string" || typeof rec.repo === "string") {
38
+ out.checkable = false;
39
+ continue;
40
+ }
41
+ if (typeof rec.namespace === "string" || typeof rec.version === "string" || typeof rec.locale === "string")
42
+ out.checkable = false;
43
+ if (typeof rec.path === "string") {
44
+ const root = rec.path.replace(/^\.\/+/, "").replace(/^\/+|\/+$/g, "");
45
+ if (root.startsWith("..")) {
46
+ out.checkable = false;
47
+ continue;
48
+ } // above the workspace: unknowable
49
+ roots.push(root);
50
+ }
51
+ }
52
+ if (typeof content.path === "string")
53
+ roots.push(content.path.replace(/^\.\/+/, "").replace(/^\/+|\/+$/g, ""));
54
+ if (roots.length)
55
+ out.roots = [...new Set(roots)];
56
+ }
57
+ catch {
58
+ /* unreadable config: resolve against the workspace root */
59
+ }
60
+ break;
61
+ }
62
+ return out;
63
+ }
64
+ /** A site path is a page when a content root has it as `x.md`, `x/index.md`, `x.mdx` — or an existing FILE (an asset); `_`-prefixed segments are never routed (except `_assets`). */
65
+ export function resolveSitePath(index, layout, sitePath) {
66
+ const candidates = [];
67
+ let p = sitePath;
68
+ for (const pre of layout.prefixes)
69
+ if (p === pre || p.startsWith(pre + "/")) {
70
+ p = p.slice(pre.length).replace(/^\/+/, "");
71
+ break;
72
+ }
73
+ // `_`-prefixed segments are never routed by the build (fragments, includes) — except under `_assets/`, which is served
74
+ const hidden = (path) => {
75
+ if (path.startsWith("_assets/") || path.includes("/_assets/"))
76
+ return false;
77
+ return path.split("/").some((seg) => seg.startsWith("_"));
78
+ };
79
+ for (const root of layout.roots) {
80
+ const base = root ? `${root}/${p}` : p;
81
+ for (const c of [`${base}.md`, `${base}/index.md`, `${base}.mdx`]) {
82
+ candidates.push(c);
83
+ if (!hidden(c) && (index.docs.has(c) || index.maps.has(c)))
84
+ return { doc: index.docs.has(c) ? c : undefined, file: c, candidates };
85
+ }
86
+ candidates.push(base);
87
+ if (!hidden(base) && index.files.has(base))
88
+ return { file: base, candidates };
89
+ }
90
+ return { candidates };
91
+ }
package/dist/storage.d.ts CHANGED
@@ -27,6 +27,11 @@ export interface Storage {
27
27
  /** Delete a file. Rejects if missing. */
28
28
  delete(path: string): Promise<void>;
29
29
  exists(path: string): Promise<boolean>;
30
+ /**
31
+ * Move a file as it is, bytes and all (a refactor moving an image). Optional: without it a
32
+ * refactor moves a file by reading and writing its text.
33
+ */
34
+ move?(from: string, to: string): Promise<void>;
30
35
  }
31
36
  /** Normalize any incoming path to the workspace-relative posix form. */
32
37
  export declare const normalizeStoragePath: (path: string) => string;
@@ -39,4 +44,5 @@ export declare class MemoryStorage implements Storage {
39
44
  write(path: string, content: string): Promise<void>;
40
45
  delete(path: string): Promise<void>;
41
46
  exists(path: string): Promise<boolean>;
47
+ move(from: string, to: string): Promise<void>;
42
48
  }
package/dist/storage.js CHANGED
@@ -55,4 +55,11 @@ export class MemoryStorage {
55
55
  async exists(path) {
56
56
  return this.files.has(normalizeStoragePath(path));
57
57
  }
58
+ async move(from, to) {
59
+ const content = this.files.get(normalizeStoragePath(from));
60
+ if (content === undefined)
61
+ throw new Error(`File not found: ${from}`);
62
+ this.files.set(normalizeStoragePath(to), content);
63
+ this.files.delete(normalizeStoragePath(from));
64
+ }
58
65
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/commands",
3
- "version": "0.2.0-beta.182",
3
+ "version": "0.2.0-beta.184",
4
4
  "description": "Typed, headless-first command engine for the Dogsbay platform — one zod-defined command yields CLI, JSON-RPC, and MCP surfaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -13,6 +13,10 @@
13
13
  "./indexes": {
14
14
  "types": "./dist/indexes-entry.d.ts",
15
15
  "import": "./dist/indexes-entry.js"
16
+ },
17
+ "./refactor": {
18
+ "types": "./dist/refactor-entry.d.ts",
19
+ "import": "./dist/refactor-entry.js"
16
20
  }
17
21
  },
18
22
  "sideEffects": false,
@@ -31,11 +35,11 @@
31
35
  "js-yaml": "^5.2.1",
32
36
  "yaml": "^2.9.0",
33
37
  "zod": "^4.4.3",
34
- "@dogsbay/format-dogsbay-md": "0.2.0-beta.182",
35
- "@dogsbay/format-topicmap": "0.2.0-beta.182",
36
- "@dogsbay/minja": "0.2.0-beta.182",
37
- "@dogsbay/render": "0.2.0-beta.182",
38
- "@dogsbay/types": "0.2.0-beta.182"
38
+ "@dogsbay/format-dogsbay-md": "0.2.0-beta.184",
39
+ "@dogsbay/format-topicmap": "0.2.0-beta.184",
40
+ "@dogsbay/minja": "0.2.0-beta.184",
41
+ "@dogsbay/render": "0.2.0-beta.184",
42
+ "@dogsbay/types": "0.2.0-beta.184"
39
43
  },
40
44
  "license": "MIT",
41
45
  "repository": {