@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.
@@ -28,9 +28,9 @@ export declare const mapAddRefCommand: import("../engine.js").CommandDef<z.ZodOb
28
28
  toc: z.ZodOptional<z.ZodBoolean>;
29
29
  unlisted: z.ZodOptional<z.ZodBoolean>;
30
30
  singlePage: z.ZodOptional<z.ZodEnum<{
31
+ children: "children";
31
32
  yes: "yes";
32
33
  no: "no";
33
- children: "children";
34
34
  }>>;
35
35
  }, z.core.$strict>>;
36
36
  export declare const mapMoveRefCommand: import("../engine.js").CommandDef<z.ZodObject<{
@@ -54,8 +54,8 @@ export declare const mapSetPropsCommand: import("../engine.js").CommandDef<z.Zod
54
54
  toc: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
55
55
  unlisted: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
56
56
  singlePage: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
57
+ children: "children";
57
58
  yes: "yes";
58
59
  no: "no";
59
- children: "children";
60
60
  }>>>;
61
61
  }, z.core.$strict>>;
@@ -12,6 +12,12 @@ export declare const missIssues: (misses: InboundRef[]) => EngineIssue[];
12
12
  export declare const renameFileCommand: import("../engine.js").CommandDef<z.ZodObject<{
13
13
  from: z.ZodString;
14
14
  to: z.ZodString;
15
+ dryRun: z.ZodOptional<z.ZodBoolean>;
16
+ }, z.core.$strict>>;
17
+ export declare const moveFolderCommand: import("../engine.js").CommandDef<z.ZodObject<{
18
+ from: z.ZodString;
19
+ to: z.ZodString;
20
+ dryRun: z.ZodOptional<z.ZodBoolean>;
15
21
  }, z.core.$strict>>;
16
22
  export declare const safeDeleteCommand: import("../engine.js").CommandDef<z.ZodObject<{
17
23
  file: z.ZodString;
@@ -8,9 +8,10 @@ import { z } from "zod";
8
8
  import { fenceOpenBefore } from "@dogsbay/format-dogsbay-md/browser";
9
9
  import { dirname } from "@dogsbay/format-topicmap";
10
10
  import { normalizeStoragePath } from "../storage.js";
11
- import { relativeHref, replaceLinkHrefs, replaceIncludePaths, replaceMapHref, rewriteInboundRefs, splitFrontmatter, } from "../edits.js";
11
+ import { relativeHref, splitFrontmatter } from "../edits.js";
12
12
  import { defineCommand } from "../engine.js";
13
13
  import { contentHash } from "./content.js";
14
+ import { applyPlan, planDelete, planFolderMove, planMove } from "../refactor.js";
14
15
  const fail = (code, message, file) => ({
15
16
  data: { applied: false },
16
17
  issues: [{ severity: "error", code, message, ...(file ? { file } : {}) }],
@@ -23,140 +24,85 @@ export const missIssues = (misses) => misses.map((ref) => ({
23
24
  message: `${ref.kind} reference "${ref.raw}" could not be located for rewriting — update it manually`,
24
25
  file: ref.from,
25
26
  }));
26
- const isExternal = (href) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(href);
27
- /** Batched replaceMapHref with the same anti-cross-talk placeholders. */
28
- const replaceMapHrefs = (source, pairs) => {
29
- let out = source;
30
- const entries = [...pairs.entries()];
31
- entries.forEach(([oldHref], i) => {
32
- out = replaceMapHref(out, oldHref, "\u0000" + i + "\u0000");
33
- });
34
- entries.forEach(([, newHref], i) => {
35
- out = out.split("\u0000" + i + "\u0000").join(newHref);
36
- });
37
- return out;
38
- };
27
+ /** A plan's misses as warnings, with their line: a reference not rewritten is never silent. */
28
+ const planMissIssues = (misses) => misses.map((m) => ({
29
+ severity: "warning",
30
+ code: "reference-not-rewritten",
31
+ message: `${m.kind} reference "${m.raw}" was not rewritten${m.reason ? `: ${m.reason}` : " — update it manually"}`,
32
+ file: m.file,
33
+ ...(m.line !== undefined ? { line: m.line } : {}),
34
+ }));
35
+ const planData = (plan) => ({
36
+ rewrittenFiles: plan.changed,
37
+ rewritten: plan.rewritten,
38
+ moved: plan.moves.map(({ from, to }) => ({ from, to })),
39
+ misses: plan.misses,
40
+ });
39
41
  export const renameFileCommand = defineCommand({
40
42
  name: "rename-file",
41
43
  writes: "structure",
42
- description: "Move/rename a file and rewrite every inbound reference (links, includes, menu files)",
44
+ description: "Move/rename a file and rewrite every reference to it (links, directive props, includes, menu files, keys, site paths)",
43
45
  input: z
44
46
  .object({
45
47
  from: z.string().min(1).describe("Current workspace-relative path"),
46
48
  to: z.string().min(1).describe("New workspace-relative path"),
49
+ dryRun: z.boolean().optional().describe("Return what would change, and write nothing"),
47
50
  })
48
51
  .strict(),
49
52
  positionals: ["from", "to"],
50
53
  async run(ctx, input) {
54
+ const plan = await planMove(ctx.workspace.storage, [{ from: input.from, to: input.to }], { index: await ctx.workspace.index() });
55
+ if (!plan.ok)
56
+ return fail(plan.code, plan.message, plan.file);
57
+ const { from, to } = plan.moves[0];
58
+ const issues = planMissIssues(plan.misses);
59
+ if (input.dryRun) {
60
+ return { data: { applied: false, dryRun: true, from, to, ...planData(plan) }, issues, summary: `${from} → ${to} would update ${plan.changed.length} referencing file(s) (dry run)` };
61
+ }
62
+ await applyPlan(ctx.workspace.storage, plan);
63
+ ctx.workspace.invalidate();
64
+ return {
65
+ data: { applied: true, from, to, ...planData(plan) },
66
+ issues,
67
+ summary: `${from} → ${to} (${plan.changed.length} referencing file(s) updated)`,
68
+ };
69
+ },
70
+ });
71
+ export const moveFolderCommand = defineCommand({
72
+ name: "move-folder",
73
+ writes: "structure",
74
+ description: "Move a folder and everything in it, rewriting every reference to the files in it",
75
+ input: z
76
+ .object({
77
+ from: z.string().min(1).describe("Current workspace-relative folder"),
78
+ to: z.string().min(1).describe("New workspace-relative folder"),
79
+ dryRun: z.boolean().optional().describe("Return what would change, and write nothing"),
80
+ })
81
+ .strict(),
82
+ positionals: ["from", "to"],
83
+ async run(ctx, input) {
84
+ const plan = await planFolderMove(ctx.workspace.storage, input.from, input.to, { index: await ctx.workspace.index() });
85
+ if (!plan.ok)
86
+ return fail(plan.code, plan.message, plan.file);
87
+ const issues = planMissIssues(plan.misses);
51
88
  const from = normalizeStoragePath(input.from);
52
89
  const to = normalizeStoragePath(input.to);
53
- const { storage } = ctx.workspace;
54
- if (from === to)
55
- return fail("rename-noop", "from and to are the same path");
56
- if (!(await storage.exists(from)))
57
- return fail("rename-source-missing", `${from} does not exist`);
58
- if (await storage.exists(to))
59
- return fail("rename-target-exists", `${to} already exists`);
60
- const index = await ctx.workspace.index();
61
- let content = await storage.read(from);
62
- // The moved doc's own outbound references keep pointing at their
63
- // (unmoved) targets from the file's NEW location
64
- const doc = index.docs.get(from);
65
- if (doc) {
66
- const newDir = dirname(to);
67
- const linkPairs = new Map();
68
- for (const link of doc.links) {
69
- if (!link.target || link.href.startsWith("#"))
70
- continue;
71
- const target = link.target === from ? to : link.target;
72
- const fragment = link.fragment ? `#${link.fragment}` : "";
73
- const newHref = relativeHref(newDir, target) + fragment;
74
- if (newHref !== link.href)
75
- linkPairs.set(link.href, newHref);
76
- }
77
- content = replaceLinkHrefs(content, linkPairs);
78
- const includePairs = new Map();
79
- for (const include of doc.includes) {
80
- const newPath = relativeHref(newDir, include.target);
81
- if (newPath !== include.raw)
82
- includePairs.set(include.raw, newPath);
83
- }
84
- content = replaceIncludePaths(content, includePairs);
85
- }
86
- // A moved menu file or keys file must keep addressing ITS targets
87
- // from the new location — rebase its own href entries too
88
- const movedMap = index.maps.get(from);
89
- if (movedMap && dirname(to) !== dirname(from)) {
90
- const pairs = new Map();
91
- for (const ref of movedMap.refs) {
92
- if (!ref.target)
93
- continue;
94
- // a link to part of a page keeps its fragment
95
- const hash = ref.href.indexOf("#");
96
- const newHref = relativeHref(dirname(to), ref.target) + (hash >= 0 ? ref.href.slice(hash) : "");
97
- if (newHref !== ref.href)
98
- pairs.set(ref.href, newHref);
99
- }
100
- content = replaceMapHrefs(content, pairs);
101
- }
102
- const ownKeyDefs = [...index.keys.values()].flat().filter((def) => def.file === from);
103
- if (ownKeyDefs.length > 0 && dirname(to) !== dirname(from)) {
104
- const pairs = new Map();
105
- for (const def of ownKeyDefs) {
106
- const href = def.def.href;
107
- if (typeof href !== "string" || isExternal(href))
108
- continue;
109
- const target = normalizeStoragePath(`${dirname(from)}/${href}`);
110
- const newHref = relativeHref(dirname(to), target);
111
- if (newHref !== href)
112
- pairs.set(href, newHref);
113
- }
114
- content = replaceMapHrefs(content, pairs);
90
+ if (input.dryRun) {
91
+ return { data: { applied: false, dryRun: true, from, to, ...planData(plan) }, issues, summary: `${from}/ → ${to}/ would move ${plan.moves.length} file(s) and update ${plan.changed.length} other file(s) (dry run)` };
115
92
  }
116
- const { changed, misses } = await rewriteInboundRefs(ctx.workspace, index, from, (ref) => {
117
- const fragment = ref.fragment ? `#${ref.fragment}` : "";
118
- return relativeHref(dirname(ref.from), to) + fragment;
119
- });
120
- const issues = missIssues(misses);
121
- // Key definitions addressing the moved file follow it — the key
122
- // keeps resolving (safe-delete treats these as referrers; so do we)
123
- const keyEditsByFile = new Map();
124
- for (const defs of index.keys.values()) {
125
- for (const def of defs) {
126
- if (def.file === from)
127
- continue; // rebased above, moves with the file
128
- const href = def.def.href;
129
- if (typeof href !== "string" || isExternal(href))
130
- continue;
131
- if (normalizeStoragePath(`${dirname(def.file)}/${href}`) !== from)
132
- continue;
133
- const pairs = keyEditsByFile.get(def.file) ?? new Map();
134
- pairs.set(href, relativeHref(dirname(def.file), to));
135
- keyEditsByFile.set(def.file, pairs);
136
- }
137
- }
138
- for (const [keysFile, pairs] of keyEditsByFile) {
139
- const source = await storage.read(keysFile);
140
- const updated = replaceMapHrefs(source, pairs);
141
- if (updated !== source) {
142
- await storage.write(keysFile, updated);
143
- changed.push(keysFile);
144
- }
145
- }
146
- await storage.write(to, content);
147
- await storage.delete(from);
93
+ await applyPlan(ctx.workspace.storage, plan);
148
94
  ctx.workspace.invalidate();
149
95
  return {
150
- data: { applied: true, from, to, rewrittenFiles: changed },
96
+ data: { applied: true, from, to, ...planData(plan) },
151
97
  issues,
152
- summary: `${from} → ${to} (${changed.length} referencing file(s) updated)`,
98
+ summary: `${from}/ → ${to}/ (${plan.moves.length} file(s) moved, ${plan.changed.length} other file(s) updated)`,
153
99
  };
154
100
  },
155
101
  });
156
102
  export const safeDeleteCommand = defineCommand({
157
103
  name: "safe-delete",
158
104
  writes: "structure",
159
- description: "Delete a file only when nothing references it (links, includes, menu files, keys)",
105
+ description: "Delete a file only when nothing references it (links, directive props, includes, menu files, keys, site paths)",
160
106
  input: z
161
107
  .object({
162
108
  file: z.string().min(1).describe("Workspace-relative path to delete"),
@@ -165,34 +111,17 @@ export const safeDeleteCommand = defineCommand({
165
111
  .strict(),
166
112
  positionals: ["file"],
167
113
  async run(ctx, input) {
168
- const file = normalizeStoragePath(input.file);
169
- const { storage } = ctx.workspace;
170
- if (!(await storage.exists(file)))
171
- return fail("delete-source-missing", `${file} does not exist`);
172
- const index = await ctx.workspace.index();
173
- const referrers = (index.inbound.get(file) ?? []).map((ref) => ({
114
+ const plan = await planDelete(ctx.workspace.storage, input.file, { index: await ctx.workspace.index() });
115
+ if (!plan.ok)
116
+ return fail(plan.code, plan.message, plan.file);
117
+ const { file } = plan;
118
+ const referrers = plan.referrers.map((ref) => ({
174
119
  severity: input.force ? "warning" : "error",
175
120
  code: input.force ? "delete-broke-reference" : "delete-blocked",
176
- message: `${ref.kind} reference "${ref.raw}" targets ${file}`,
177
- file: ref.from,
121
+ message: ref.kind === "key" ? `${ref.reason ?? "key"} href targets ${file}` : `${ref.kind} reference "${ref.raw}" targets ${file}`,
122
+ file: ref.file,
123
+ ...(ref.line !== undefined ? { line: ref.line } : {}),
178
124
  }));
179
- // Key definitions pointing at the file block deletion too
180
- for (const defs of index.keys.values()) {
181
- for (const def of defs) {
182
- const href = def.def.href;
183
- if (typeof href !== "string" || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(href))
184
- continue;
185
- const resolved = normalizeStoragePath(`${dirname(def.file)}/${href}`);
186
- if (resolved === file) {
187
- referrers.push({
188
- severity: input.force ? "warning" : "error",
189
- code: input.force ? "delete-broke-reference" : "delete-blocked",
190
- message: `key "${def.name}" href targets ${file}`,
191
- file: def.file,
192
- });
193
- }
194
- }
195
- }
196
125
  if (referrers.length > 0 && !input.force) {
197
126
  return {
198
127
  data: { applied: false, referrers: referrers.length },
@@ -200,7 +129,7 @@ export const safeDeleteCommand = defineCommand({
200
129
  summary: `${file} is referenced ${referrers.length} time(s) — not deleted (use --force to override)`,
201
130
  };
202
131
  }
203
- await storage.delete(file);
132
+ await ctx.workspace.storage.delete(file);
204
133
  ctx.workspace.invalidate();
205
134
  return {
206
135
  data: { applied: true, file, brokenReferences: referrers.length },
@@ -15,63 +15,8 @@ import { anchorAliases, anchorAliasTargets } from "../indexes.js";
15
15
  import { checkFrontmatter, frontmatterPolicyFromConfig, requiredFieldsFor, } from "@dogsbay/types";
16
16
  import { dirname as dirOf, relative as relPath } from "../posix-path.js";
17
17
  import { load as loadYaml } from "js-yaml";
18
+ import { resolveSitePath, siteLayout } from "../site-layout.js";
18
19
  const input = z.object({}).strict();
19
- async function siteLayout(storage) {
20
- const out = { roots: [""], prefixes: [], checkable: true };
21
- for (const name of ["dogsbay.config.yml", "dogsbay.config.yaml", "dogsbay.config.json"]) {
22
- if (!(await storage.exists(name)))
23
- continue;
24
- try {
25
- const text = await storage.read(name);
26
- const cfg = (name.endsWith(".json") ? JSON.parse(text) : loadYaml(text));
27
- if (!cfg || typeof cfg !== "object")
28
- return out;
29
- const site = (cfg.site ?? {});
30
- if (typeof site.basePath === "string" && site.basePath.replace(/\//g, ""))
31
- out.prefixes.push(site.basePath.replace(/^\/+|\/+$/g, ""));
32
- if (typeof site.url === "string") {
33
- try {
34
- const u = new URL(site.url);
35
- const pth = u.pathname.replace(/^\/+|\/+$/g, "");
36
- if (pth)
37
- out.prefixes.push(pth);
38
- }
39
- catch { /* not a URL */ }
40
- }
41
- const content = (cfg.content ?? {});
42
- const sources = Array.isArray(content.sources) ? content.sources : [];
43
- const roots = [];
44
- for (const src of sources) {
45
- if (!src || typeof src !== "object")
46
- continue;
47
- const rec = src;
48
- if (typeof rec.git === "string" || typeof rec.repo === "string") {
49
- out.checkable = false;
50
- continue;
51
- }
52
- if (typeof rec.namespace === "string" || typeof rec.version === "string" || typeof rec.locale === "string")
53
- out.checkable = false;
54
- if (typeof rec.path === "string") {
55
- const root = rec.path.replace(/^\.\/+/, "").replace(/^\/+|\/+$/g, "");
56
- if (root.startsWith("..")) {
57
- out.checkable = false;
58
- continue;
59
- } // above the workspace: unknowable
60
- roots.push(root);
61
- }
62
- }
63
- if (typeof content.path === "string")
64
- roots.push(content.path.replace(/^\.\/+/, "").replace(/^\/+|\/+$/g, ""));
65
- if (roots.length)
66
- out.roots = [...new Set(roots)];
67
- }
68
- catch {
69
- /* unreadable config: resolve against the workspace root */
70
- }
71
- break;
72
- }
73
- return out;
74
- }
75
20
  /** js-yaml's own complaint about the frontmatter block, with the line it points at. */
76
21
  function yamlErrorOf(source) {
77
22
  const lines = source.split("\n");
@@ -134,34 +79,6 @@ function frontmatterIssues(doc, keyLines, policy) {
134
79
  ...(f.fix ? { fix: { verb: "props-set", args: { file: doc.path, set: { [f.fix.key]: f.fix.value }, expect: doc.hash }, label: f.fix.label } } : {}),
135
80
  }));
136
81
  }
137
- /** 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`). */
138
- function resolveSitePath(index, layout, sitePath) {
139
- const candidates = [];
140
- let p = sitePath;
141
- for (const pre of layout.prefixes)
142
- if (p === pre || p.startsWith(pre + "/")) {
143
- p = p.slice(pre.length).replace(/^\/+/, "");
144
- break;
145
- }
146
- // `_`-prefixed segments are never routed by the build (fragments, includes) — except under `_assets/`, which is served
147
- const hidden = (path) => {
148
- if (path.startsWith("_assets/") || path.includes("/_assets/"))
149
- return false;
150
- return path.split("/").some((seg) => seg.startsWith("_"));
151
- };
152
- for (const root of layout.roots) {
153
- const base = root ? `${root}/${p}` : p;
154
- for (const c of [`${base}.md`, `${base}/index.md`, `${base}.mdx`]) {
155
- candidates.push(c);
156
- if (!hidden(c) && (index.docs.has(c) || index.maps.has(c)))
157
- return { doc: index.docs.has(c) ? c : undefined, file: c, candidates };
158
- }
159
- candidates.push(base);
160
- if (!hidden(base) && index.files.has(base))
161
- return { file: base, candidates };
162
- }
163
- return { candidates };
164
- }
165
82
  export const validateCommand = defineCommand({
166
83
  name: "validate",
167
84
  writes: "none",
package/dist/edits.d.ts CHANGED
@@ -14,10 +14,24 @@ export declare const relativeHref: (fromDir: string, targetPath: string) => stri
14
14
  * Replace a link/image href in PROSE, in both authoring forms:
15
15
  * inline `](old)` / `](old "title")` (the `](` delimiter keeps `a.md`
16
16
  * from matching inside `extra-a.md`) and reference-style definition
17
- * lines (`[label]: old`). Code regions and frontmatter are never
17
+ * lines (`[label]: old`), and where a directive or HTML names a page
18
+ * (`replaceLinkHrefsAll`). Code regions and frontmatter are never
18
19
  * touched.
19
20
  */
20
21
  export declare const replaceLinkHref: (source: string, oldHref: string, newHref: string) => string;
22
+ /**
23
+ * Every link to a page or file written in a document, replaced in ONE pass for any number of
24
+ * old → new pairs (a folder move rewrites hundreds of links in a hub page): inline links and
25
+ * images, reference definitions, a directive's attribute group (`:::card{href="x"}`,
26
+ * `:button[Go]{href=x}`), an HTML tag's `href` / `src` / `poster`, and a directive's `---` props
27
+ * block (`href: x`). Each value in its own quotes, only whole values; never in code, front matter,
28
+ * plain prose, or the props of a directive whose paths are not the page's (`::example{src}`,
29
+ * includes, data directives). `hits`: the old values found.
30
+ */
31
+ export declare const replaceLinkHrefsAll: (source: string, pairs: ReadonlyMap<string, string>) => {
32
+ text: string;
33
+ hits: Set<string>;
34
+ };
21
35
  /** Replace the path inside `{% include "old" %}` directives in prose. */
22
36
  export declare const replaceIncludePath: (source: string, oldPath: string, newPath: string) => string;
23
37
  /**
@@ -26,6 +40,7 @@ export declare const replaceIncludePath: (source: string, oldPath: string, newPa
26
40
  * Only an exact, whole value is replaced; the key, quotes and a trailing comment are kept.
27
41
  */
28
42
  export declare const replaceMapHref: (source: string, oldHref: string, newHref: string) => string;
43
+ /** A batch of link replacements: one pass, so pair A's NEW value is never matched as pair B's OLD one. */
29
44
  export declare const replaceLinkHrefs: (source: string, pairs: Map<string, string>) => string;
30
45
  export declare const replaceIncludePaths: (source: string, pairs: Map<string, string>) => string;
31
46
  /** Apply one inbound reference rewrite to a referencing file's source. */
package/dist/edits.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * whole documents — authored formatting survives.
8
8
  */
9
9
  import { includeDirectiveRe } from "@dogsbay/minja/browser";
10
- import { transformProseSegments } from "@dogsbay/format-dogsbay-md/browser";
10
+ import { fenceOpenBefore, transformProseSegments } from "@dogsbay/format-dogsbay-md/browser";
11
11
  /**
12
12
  * Run a text edit over the PROSE of a markdown document only: the
13
13
  * frontmatter block, fenced code, and inline code spans pass through
@@ -34,19 +34,94 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34
34
  * Replace a link/image href in PROSE, in both authoring forms:
35
35
  * inline `](old)` / `](old "title")` (the `](` delimiter keeps `a.md`
36
36
  * from matching inside `extra-a.md`) and reference-style definition
37
- * lines (`[label]: old`). Code regions and frontmatter are never
37
+ * lines (`[label]: old`), and where a directive or HTML names a page
38
+ * (`replaceLinkHrefsAll`). Code regions and frontmatter are never
38
39
  * touched.
39
40
  */
40
- export const replaceLinkHref = (source, oldHref, newHref) => {
41
- const old = escapeRegExp(oldHref);
42
- const inlineRe = new RegExp(`\\]\\(\\s*${old}(?=\\s|\\))`, "g");
43
- const withInline = editMarkdownProse(source, (prose) => prose.replace(inlineRe, (match) => match.replace(oldHref, newHref)));
44
- // Reference-style definitions are whole lines; handle them on the
45
- // full body (they can't sit inside inline code, and fenced examples
46
- // are excluded by the prose walk in editMarkdownProse being
47
- // line-anchored — a defn inside a fence is code, so guard it too)
48
- const defRe = new RegExp(`^(\\s{0,3}\\[[^\\]]+\\]:\\s*)${old}((?:\\s+.*)?)$`, "gm");
49
- return editMarkdownProse(withInline, (prose) => prose.replace(defRe, `$1${newHref}$2`));
41
+ export const replaceLinkHref = (source, oldHref, newHref) => replaceLinkHrefsAll(source, new Map([[oldHref, newHref]])).text;
42
+ /** The props that name a page or file (the indexer's LINK_PROPS). */
43
+ const PROP_KEYS = "href|link|src|poster|icon|image";
44
+ /** Directives whose props are NOT relative to the page (the indexer's PROPS_NOT_LINKS). */
45
+ const PROPS_NOT_LINKS = new Set(["include", "example", "openapi", "data-table", "data-cards"]);
46
+ // `key=value` in an attribute group or tag; `data-href=` is not `href=`
47
+ const ATTR_RE = new RegExp(`(?<![\\w-])(${PROP_KEYS})([ \\t]*=[ \\t]*)(?:"([^"\\n]*)"|'([^'\\n]*)'|([^\\s}"'>]+))`, "g");
48
+ // a directive's attribute group, with the directive's name when it has one (`:::card{…}`,
49
+ // `:button[Go]{…}`); `{{`/`{%` are template syntax, not attributes
50
+ const GROUP_RE = /(?:(?<![:\w])(:{1,4})([a-zA-Z][\w-]*)(?:\[[^\]\n]*\])?)?\{(?![{%#])([^{}\n]*)\}/g;
51
+ const TAG_RE = /<[a-zA-Z][\w-]*\s[^<>\n]*>/g;
52
+ // a destination may hold balanced parentheses (`foo_(bar).md`), as CommonMark allows
53
+ const INLINE_RE = /(\]\(\s*)((?:[^\s()]|\([^\s()]*\))+)(?=\s|\))/g;
54
+ const DEF_RE = /^(\s{0,3}\[[^\]]+\]:\s*)(\S+)((?:\s+.*)?)$/gm;
55
+ const PROPS_LINE_RE = new RegExp(`^([ \\t]*(?:${PROP_KEYS})[ \\t]*:[ \\t]*)(["']?)(.*?)\\2([ \\t]*(?:#.*)?)$`);
56
+ const OPENER_RE = /^[ \t]*:{2,}([a-zA-Z][\w-]*)/;
57
+ /**
58
+ * Every link to a page or file written in a document, replaced in ONE pass for any number of
59
+ * old → new pairs (a folder move rewrites hundreds of links in a hub page): inline links and
60
+ * images, reference definitions, a directive's attribute group (`:::card{href="x"}`,
61
+ * `:button[Go]{href=x}`), an HTML tag's `href` / `src` / `poster`, and a directive's `---` props
62
+ * block (`href: x`). Each value in its own quotes, only whole values; never in code, front matter,
63
+ * plain prose, or the props of a directive whose paths are not the page's (`::example{src}`,
64
+ * includes, data directives). `hits`: the old values found.
65
+ */
66
+ export const replaceLinkHrefsAll = (source, pairs) => {
67
+ const hits = new Set();
68
+ if (!pairs.size)
69
+ return { text: source, hits };
70
+ const swap = (value) => {
71
+ const next = pairs.get(value);
72
+ if (next !== undefined)
73
+ hits.add(value);
74
+ return next;
75
+ };
76
+ const attrs = (text) => text.replace(ATTR_RE, (m, key, eq, dq, sq, bare) => {
77
+ const value = dq ?? sq ?? bare ?? "";
78
+ const next = swap(value);
79
+ if (next === undefined)
80
+ return m;
81
+ return dq !== undefined ? `${key}${eq}"${next}"` : sq !== undefined ? `${key}${eq}'${next}'` : `${key}${eq}${next}`;
82
+ });
83
+ const [frontmatter, body] = splitFrontmatter(source);
84
+ let text = transformProseSegments(body, (prose) => prose
85
+ .replace(INLINE_RE, (m, lead, dest) => { const next = swap(dest); return next === undefined ? m : lead + next; })
86
+ .replace(DEF_RE, (m, lead, dest, rest) => { const next = swap(dest); return next === undefined ? m : lead + next + rest; })
87
+ .replace(GROUP_RE, (m, _colons, name) => (name && PROPS_NOT_LINKS.has(name) ? m : attrs(m)))
88
+ .replace(TAG_RE, (m) => attrs(m)));
89
+ // a directive's `---` props block: the `---` line right after its opener, to the next `---`
90
+ const lines = text.split("\n");
91
+ const open = fenceOpenBefore(text);
92
+ let opener;
93
+ let inProps = false;
94
+ for (let i = 0; i < lines.length; i++) {
95
+ if (open[i]) {
96
+ opener = undefined;
97
+ inProps = false;
98
+ continue;
99
+ }
100
+ const line = lines[i];
101
+ if (inProps) {
102
+ if (/^[ \t]*---[ \t]*$/.test(line)) {
103
+ inProps = false;
104
+ continue;
105
+ }
106
+ const m = PROPS_LINE_RE.exec(line);
107
+ if (m) {
108
+ const next = swap(m[3]);
109
+ if (next !== undefined)
110
+ lines[i] = `${m[1]}${m[2]}${next}${m[2]}${m[4]}`;
111
+ }
112
+ continue;
113
+ }
114
+ if (opener !== undefined && /^[ \t]*---[ \t]*$/.test(line)) {
115
+ inProps = !PROPS_NOT_LINKS.has(opener);
116
+ opener = undefined;
117
+ if (inProps)
118
+ continue;
119
+ }
120
+ const o = OPENER_RE.exec(line);
121
+ opener = o ? o[1] : undefined;
122
+ }
123
+ text = lines.join("\n");
124
+ return { text: frontmatter + text, hits };
50
125
  };
51
126
  /** Replace the path inside `{% include "old" %}` directives in prose. */
52
127
  export const replaceIncludePath = (source, oldPath, newPath) => editMarkdownProse(source, (prose) => prose.replace(includeDirectiveRe(), (match, path) => path === oldPath
@@ -70,26 +145,13 @@ export const replaceMapHref = (source, oldHref, newHref) => {
70
145
  // a bare value is a list item: a YAML `- x` or a quoted JSON string
71
146
  /-[ \t]+$/.test(prefix) || quote === '"' ? swap(m, prefix, quote, suffix) : m);
72
147
  };
148
+ /** A batch of link replacements: one pass, so pair A's NEW value is never matched as pair B's OLD one. */
149
+ export const replaceLinkHrefs = (source, pairs) => replaceLinkHrefsAll(source, pairs).text;
73
150
  /**
74
- * Rewrite a batch of href replacements without cross-talk: pairs are
75
- * first swapped to unique NUL-delimited placeholders (impossible in
76
- * authored markdown), then resolved — so pair A's NEW value can never
77
- * be matched by pair B's OLD pattern.
151
+ * Rewrite a batch of include paths without cross-talk: pairs are first swapped to unique
152
+ * NUL-delimited placeholders (impossible in authored markdown), then resolved.
78
153
  */
79
154
  const placeholder = (i) => `\u0000${i}\u0000`;
80
- export const replaceLinkHrefs = (source, pairs) => {
81
- let out = source;
82
- const entries = [...pairs.entries()];
83
- entries.forEach(([oldHref], i) => {
84
- out = replaceLinkHref(out, oldHref, placeholder(i));
85
- });
86
- entries.forEach(([, newHref], i) => {
87
- // Split on the placeholder alone: the match step may have kept
88
- // authoring whitespace between `](` and the href
89
- out = out.split(placeholder(i)).join(newHref);
90
- });
91
- return out;
92
- };
93
155
  export const replaceIncludePaths = (source, pairs) => {
94
156
  let out = source;
95
157
  const entries = [...pairs.entries()];
package/dist/index.d.ts CHANGED
@@ -25,13 +25,14 @@ import { renderPageCommand } from "./commands/render-page.js";
25
25
  import { keysListCommand, keysResolveCommand } from "./commands/keys.js";
26
26
  import { navResolveCommand } from "./commands/nav-resolve.js";
27
27
  import { reindexCommand } from "./commands/reindex.js";
28
- import { renameFileCommand, safeDeleteCommand, extractIncludeCommand } from "./commands/refactor-files.js";
28
+ import { renameFileCommand, moveFolderCommand, safeDeleteCommand, extractIncludeCommand } from "./commands/refactor-files.js";
29
29
  import { renameKeyCommand, keyifyCommand } from "./commands/refactor-keys.js";
30
30
  import { splitTopicCommand, mergeTopicsCommand } from "./commands/refactor-structure.js";
31
31
  export { WELL_KNOWN_FIELDS, type FieldSpec, type FrontmatterPolicy, } from "@dogsbay/types";
32
32
  export { linkRetargetCommand } from "./commands/link-retarget.js";
33
- export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, navResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
33
+ export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, navResolveCommand, reindexCommand, renameFileCommand, moveFolderCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
34
34
  export { contentHash } from "./sha256.js";
35
35
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
36
36
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/menu-edit.js";
37
37
  export declare const createDefaultRegistry: () => CommandRegistry;
38
+ export { planMove, planFolderMove, planDelete, applyPlan, type FileMove, type RefactorPlan, type RefactorRefusal, type RefactorRef, type DeletePlan, type PlanOptions, } from "./refactor.js";
package/dist/index.js CHANGED
@@ -25,14 +25,14 @@ import { renderPageCommand } from "./commands/render-page.js";
25
25
  import { keysListCommand, keysResolveCommand } from "./commands/keys.js";
26
26
  import { navResolveCommand } from "./commands/nav-resolve.js";
27
27
  import { reindexCommand } from "./commands/reindex.js";
28
- import { renameFileCommand, safeDeleteCommand, extractIncludeCommand, } from "./commands/refactor-files.js";
28
+ import { renameFileCommand, moveFolderCommand, safeDeleteCommand, extractIncludeCommand, } from "./commands/refactor-files.js";
29
29
  import { renameKeyCommand, keyifyCommand } from "./commands/refactor-keys.js";
30
30
  import { splitTopicCommand, mergeTopicsCommand } from "./commands/refactor-structure.js";
31
31
  import { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
32
32
  export { WELL_KNOWN_FIELDS, } from "@dogsbay/types";
33
33
  export { linkRetargetCommand } from "./commands/link-retarget.js";
34
34
  import { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/menu-edit.js";
35
- export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, navResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
35
+ export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, navResolveCommand, reindexCommand, renameFileCommand, moveFolderCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
36
36
  export { contentHash } from "./sha256.js";
37
37
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
38
38
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/menu-edit.js";
@@ -47,6 +47,7 @@ export const createDefaultRegistry = () => {
47
47
  registry.register(navResolveCommand);
48
48
  registry.register(reindexCommand);
49
49
  registry.register(renameFileCommand);
50
+ registry.register(moveFolderCommand);
50
51
  registry.register(safeDeleteCommand);
51
52
  registry.register(extractIncludeCommand);
52
53
  registry.register(renameKeyCommand);
@@ -72,3 +73,4 @@ export const createDefaultRegistry = () => {
72
73
  registry.register(renderPageCommand);
73
74
  return registry;
74
75
  };
76
+ export { planMove, planFolderMove, planDelete, applyPlan, } from "./refactor.js";