@dogsbay/commands 0.2.0-beta.176 → 0.2.0-beta.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,7 +21,11 @@ Storage (injected I/O) NodeStorage | MemoryStorage | (Electron IPC …)
21
21
  - **Browser-safe at import**: nothing reaches a Node built-in until a
22
22
  `NodeStorage` is used (it loads `node:fs` then). With `MemoryStorage`
23
23
  or a host's own `Storage`, the package bundles for a browser or Worker;
24
- `tests/browser-bundle.test.ts` checks it.
24
+ `tests/browser-bundle.test.ts` checks it. A bundler still makes a chunk
25
+ for every `import()` it finds, so the main entry brings `@dogsbay/render`'s
26
+ chunks and one that imports `node:fs/promises`, even when only the index is
27
+ used. A host that wants only the index imports `@dogsbay/commands/indexes`
28
+ (below).
25
29
  - **Indexes** are built in one pass: per-doc table (frontmatter,
26
30
  headings, anchors, links, includes, `key:` uses), topic-map table,
27
31
  key-definition table (from `*.keys.yaml`), and the inverted
@@ -97,6 +101,54 @@ const workspace = new Workspace(
97
101
  );
98
102
  ```
99
103
 
104
+ ### The index alone: `@dogsbay/commands/indexes`
105
+
106
+ For an editor in a browser (link completion, Go to Definition) that needs the
107
+ workspace index and no verbs:
108
+
109
+ ```ts
110
+ import { buildWorkspaceIndex, MemoryStorage, type DocTarget } from "@dogsbay/commands/indexes";
111
+
112
+ const index = await buildWorkspaceIndex(new MemoryStorage(files));
113
+ const targets: DocTarget[] = index.docs.get("guide.md")?.targets ?? [];
114
+ ```
115
+
116
+ It exports `buildWorkspaceIndex`, `Workspace`, `MemoryStorage`,
117
+ `normalizeStoragePath`, `contentHash`, `anchorAliases`, `anchorAliasTargets`,
118
+ `blankCodeRegions` and the index types, `DocTarget` included. They are the same
119
+ functions the main entry exports. It reaches no zod, no engine or verb, no
120
+ `@dogsbay/render` and no Node built-in, not even through `import()`, and it
121
+ bundles to one file; `tests/indexes-entry.test.ts` checks this. It does use
122
+ the parser through `@dogsbay/format-dogsbay-md/browser`. A host that imports
123
+ that entry too ships one copy, as long as both resolve to the same version.
124
+ `NodeStorage` is only in the main entry.
125
+
126
+ Both `@dogsbay/commands` and `@dogsbay/render` declare `"sideEffects": false`.
127
+
128
+ ### Variables
129
+
130
+ The index lists every template variable (`index.variables`, by lookup name: hyphens as
131
+ underscores, as the build reads them), each with its definitions and uses as ranges (1-based
132
+ line, 0-based columns, end exclusive, as `DocTarget`), from the files alone:
133
+
134
+ - **Definitions** (`via`): `config` (the config's `attributes:`, site-wide or a source's), `set`
135
+ (`{% set %}`, with the `{% if %}` / `{% elif %}` / `{% else %}` / `{% case %}` branches it sits
136
+ under), `with` (an include's `{% with %}` parameters), `param` (a partial's `params:`).
137
+ - **Uses** (`form`): `output` (`{{ }}`; `plain` when the tag is only `{{ name }}`, else its
138
+ `filters`), `condition` (an `if`/`elif`/`switch` test), `expression` (a set's or with's value, a
139
+ `for` list). Code blocks and inline code (but not `{minja}` fences), `{% raw %}` and loop
140
+ variables are not symbols. Each page is read as the build reads it: an ordinary page in content
141
+ mode (front matter included, hyphens in names, no comments, `for` or `with`); a template page or
142
+ a partial with `params:` in template mode (Jinja's grammar). A use's range is the root name.
143
+ - **Variants** (`index.variants`): one per `content.sources` entry, with the site's attributes
144
+ under the source's own. Each definition says whether it applies in each (`variants`): its
145
+ conditions evaluated against that variant's attributes; `null` when a condition reads a name only
146
+ a `{% set %}` gives.
147
+
148
+ The CLI's `--attribute` is not in the files, so it is not in the index. Several definitions per
149
+ name, a `kind` and a resolution `context` keep the shape open to DITA keys and conrefs. The fixture
150
+ `@dogsbay/samples/fixtures/variants` is the shared example.
151
+
100
152
  ## Defining a command
101
153
 
102
154
  ```ts
@@ -14,6 +14,7 @@
14
14
  * H1) is refused with an issue, never guessed.
15
15
  */
16
16
  import { z } from "zod";
17
+ import { contentHash } from "../sha256.js";
17
18
  export interface SectionInfo {
18
19
  level: number;
19
20
  text: string;
@@ -27,13 +28,7 @@ export interface SectionInfo {
27
28
  /** 0-based exclusive end of the section's OWN text (before its first sub-heading). */
28
29
  ownEnd: number;
29
30
  }
30
- /**
31
- * Divergence gate (plans/ide-change-review.md §3): a short content hash the
32
- * agent gets from `topic-read` and hands back as `expect` on a mutation. If
33
- * the target changed in between (a human typing, another agent), the verb
34
- * refuses with the current hash instead of writing over the newer text.
35
- */
36
- export declare const contentHash: (text: string) => string;
31
+ export { contentHash };
37
32
  export declare const topicReadCommand: import("../engine.js").CommandDef<z.ZodObject<{
38
33
  file: z.ZodString;
39
34
  includeBody: z.ZodDefault<z.ZodBoolean>;
@@ -14,7 +14,7 @@
14
14
  * H1) is refused with an issue, never guessed.
15
15
  */
16
16
  import { z } from "zod";
17
- import { sha256Hex } from "../sha256.js";
17
+ import { contentHash } from "../sha256.js";
18
18
  import { dump as dumpYaml, load as loadYaml } from "js-yaml";
19
19
  import { containerOpenBefore, fenceOpenBefore, slugifyHeadingText } from "@dogsbay/format-dogsbay-md/browser";
20
20
  import { normalizeStoragePath } from "../storage.js";
@@ -95,13 +95,7 @@ const loadDoc = async (ctx, rawFile) => {
95
95
  return { file, doc: { frontmatter, body, lines, openBefore, sections, eol } };
96
96
  };
97
97
  const isOutput = (x) => typeof x === "object" && x !== null && "data" in x;
98
- /**
99
- * Divergence gate (plans/ide-change-review.md §3): a short content hash the
100
- * agent gets from `topic-read` and hands back as `expect` on a mutation. If
101
- * the target changed in between (a human typing, another agent), the verb
102
- * refuses with the current hash instead of writing over the newer text.
103
- */
104
- export const contentHash = (text) => sha256Hex(text).slice(0, 16);
98
+ export { contentHash };
105
99
  const sectionHash = (doc, s) => contentHash(doc.lines.slice(s.line, s.end).join("\n"));
106
100
  const fileHash = (doc) => contentHash(doc.frontmatter + doc.lines.join("\n"));
107
101
  const STALE_PREVIEW_LINES = 40;
@@ -0,0 +1,12 @@
1
+ import type { SymbolDefinition, Variant } from "./variables.js";
2
+ export declare const CONFIG_FILES: string[];
3
+ export interface ConfigVariables {
4
+ file?: string;
5
+ variants: Variant[];
6
+ definitions: SymbolDefinition[];
7
+ /** Source folders whose pages are template pages (`templates: jinja`). */
8
+ templateSources: string[];
9
+ }
10
+ export declare function readConfigVariables(file: string | undefined, text: string | undefined): ConfigVariables;
11
+ /** Is `path` inside the source folder `dir` (workspace-relative; `""` is the root)? */
12
+ export declare const inFolder: (path: string, dir: string) => boolean;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The config's part in the variables index: one variant per `content.sources` entry (the site's
3
+ * `attributes:` under the source's own), and each attribute as a definition with its range in the
4
+ * YAML. Read with `yaml` (js-yaml gives no positions). Never throws: a config that does not parse
5
+ * gives no variants and no definitions.
6
+ */
7
+ import { isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
8
+ export const CONFIG_FILES = ["dogsbay.config.yml", "dogsbay.config.yaml", "dogsbay.config.json"];
9
+ const clean = (p) => p.replace(/\\/g, "/").replace(/^\.\/?/, "").replace(/\/+$/, "");
10
+ const get = (map, key) => (isMap(map) ? map.get(key, true) : undefined);
11
+ export function readConfigVariables(file, text) {
12
+ const out = { variants: [], definitions: [], templateSources: [], ...(file ? { file } : {}) };
13
+ if (!file || text === undefined)
14
+ return out;
15
+ const counter = new LineCounter();
16
+ let doc;
17
+ try {
18
+ doc = parseDocument(text, { lineCounter: counter, uniqueKeys: false });
19
+ }
20
+ catch {
21
+ return out;
22
+ }
23
+ if (doc.errors.length || !isMap(doc.contents))
24
+ return out;
25
+ const root = doc.contents;
26
+ const attrsOf = (node, context) => {
27
+ const values = {};
28
+ if (!isMap(node))
29
+ return values;
30
+ for (const pair of node.items) {
31
+ const key = pair.key;
32
+ if (!isScalar(key) || typeof key.value !== "string" && typeof key.value !== "number")
33
+ continue;
34
+ const name = String(key.value);
35
+ const value = pair.value;
36
+ // toJS with the document resolves an alias (`*no`), within yaml's alias-count limit
37
+ try {
38
+ values[name] = value && typeof value.toJS === "function" ? value.toJS(doc) : null;
39
+ }
40
+ catch {
41
+ values[name] = null;
42
+ }
43
+ const [start, end] = key.range ?? [0, 0];
44
+ const pos = counter.linePos(start);
45
+ // a quoted key: the name starts after the quote
46
+ const quoted = text[start] === '"' || text[start] === "'" ? 1 : 0;
47
+ out.definitions.push({
48
+ kind: "variable", name, via: "config",
49
+ ...(isScalar(value) && value.range ? { value: text.slice(value.range[0], value.range[1]) } : {}),
50
+ conditions: [], context,
51
+ file, line: pos.line, from: pos.col - 1 + quoted, to: pos.col - 1 + quoted + (end - start - 2 * quoted),
52
+ });
53
+ }
54
+ return values;
55
+ };
56
+ const site = attrsOf(get(root, "attributes"), { scope: "site" });
57
+ const sources = get(get(root, "content"), "sources");
58
+ if (isSeq(sources) && sources.items.length) {
59
+ sources.items.forEach((item, i) => {
60
+ const ns = get(item, "namespace");
61
+ const namespace = isScalar(ns) && ns.value != null ? String(ns.value) : undefined;
62
+ const p = get(item, "path");
63
+ const path = isScalar(p) && typeof p.value === "string" ? clean(p.value) : "";
64
+ const id = namespace ?? `source-${i}`;
65
+ const own = attrsOf(get(item, "attributes"), { scope: "source", source: id });
66
+ const t = get(item, "templates");
67
+ if (isScalar(t) && t.value === "jinja")
68
+ out.templateSources.push(path);
69
+ out.variants.push({ id, ...(namespace ? { namespace } : {}), path, attributes: { ...site, ...own } });
70
+ });
71
+ }
72
+ else if (out.definitions.length) {
73
+ out.variants.push({ id: "default", path: "", attributes: site });
74
+ }
75
+ return out;
76
+ }
77
+ /** Is `path` inside the source folder `dir` (workspace-relative; `""` is the root)? */
78
+ export const inFolder = (path, dir) => dir === "" || path === dir || path.startsWith(`${dir}/`);
package/dist/index.d.ts CHANGED
@@ -9,9 +9,11 @@
9
9
  * No I/O assumptions: commands see an injected Storage (real fs in Node,
10
10
  * memory in tests/browser, IPC-backed in Electron).
11
11
  */
12
- export { type Storage, MemoryStorage, NodeStorage, normalizeStoragePath, } from "./storage.js";
12
+ export { type Storage, MemoryStorage, normalizeStoragePath, } from "./storage.js";
13
+ export { NodeStorage, type NodeStorageOptions } from "./node-storage.js";
13
14
  export { Workspace } from "./workspace.js";
14
- export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
15
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type DocTarget, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
16
+ export { expressionNames, variableKey, type SymbolEntry, type SymbolDefinition, type SymbolUse, type SymbolRange, type SymbolCondition, type SymbolContext, type DefinitionVia, type UseForm, type FileVariables, type Variant, } from "./variables.js";
15
17
  export { flagForField, FlagArgumentError, type FlagSpec } from "./flags.js";
16
18
  export { commandInputJsonSchema, type CommandJsonSchema } from "./json-schema.js";
17
19
  export { defineCommand, CommandRegistry, createTaskQueue, shapeOf, unwrap, isRequired, type CommandDef, type CommandContext, type CommandWrites, type CommandOutput, type CommandResult, type EngineIssue, type IssueSeverity, } from "./engine.js";
@@ -29,7 +31,7 @@ import { splitTopicCommand, mergeTopicsCommand } from "./commands/refactor-struc
29
31
  export { WELL_KNOWN_FIELDS, type FieldSpec, type FrontmatterPolicy, } from "@dogsbay/types";
30
32
  export { linkRetargetCommand } from "./commands/link-retarget.js";
31
33
  export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, topicmapResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
32
- export { contentHash } from "./commands/content.js";
34
+ export { contentHash } from "./sha256.js";
33
35
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
34
36
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
35
37
  export declare const createDefaultRegistry: () => CommandRegistry;
package/dist/index.js CHANGED
@@ -9,9 +9,11 @@
9
9
  * No I/O assumptions: commands see an injected Storage (real fs in Node,
10
10
  * memory in tests/browser, IPC-backed in Electron).
11
11
  */
12
- export { MemoryStorage, NodeStorage, normalizeStoragePath, } from "./storage.js";
12
+ export { MemoryStorage, normalizeStoragePath, } from "./storage.js";
13
+ export { NodeStorage } from "./node-storage.js";
13
14
  export { Workspace } from "./workspace.js";
14
15
  export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, } from "./indexes.js";
16
+ export { expressionNames, variableKey, } from "./variables.js";
15
17
  export { flagForField, FlagArgumentError } from "./flags.js";
16
18
  export { commandInputJsonSchema } from "./json-schema.js";
17
19
  export { defineCommand, CommandRegistry, createTaskQueue, shapeOf, unwrap, isRequired, } from "./engine.js";
@@ -31,7 +33,7 @@ export { WELL_KNOWN_FIELDS, } from "@dogsbay/types";
31
33
  export { linkRetargetCommand } from "./commands/link-retarget.js";
32
34
  import { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
33
35
  export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, topicmapResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
34
- export { contentHash } from "./commands/content.js";
36
+ export { contentHash } from "./sha256.js";
35
37
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
36
38
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
37
39
  /** The standard registry with every built-in command registered. */
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@dogsbay/commands/indexes` — the workspace index on its own, for a browser or Worker bundle
3
+ * (the playground's link box, completion, Go to Definition; item 26).
4
+ *
5
+ * It reaches no zod, no command engine, no @dogsbay/render and no Node built-in, not even
6
+ * through a dynamic import: `tests/indexes-entry.test.ts` bundles this file and fails on any of
7
+ * them. The parser it does need (format-dogsbay-md's `/browser` entry) is the same module the
8
+ * host already ships, so a bundler keeps one copy. Everything here is also exported by the main
9
+ * entry, which adds the verbs and `NodeStorage`.
10
+ */
11
+ export { type Storage, MemoryStorage, normalizeStoragePath } from "./storage.js";
12
+ export { Workspace } from "./workspace.js";
13
+ export { contentHash } from "./sha256.js";
14
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type DocTarget, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
15
+ export { expressionNames, variableKey, type SymbolEntry, type SymbolDefinition, type SymbolUse, type SymbolRange, type SymbolCondition, type SymbolContext, type DefinitionVia, type UseForm, type FileVariables, type Variant, } from "./variables.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@dogsbay/commands/indexes` — the workspace index on its own, for a browser or Worker bundle
3
+ * (the playground's link box, completion, Go to Definition; item 26).
4
+ *
5
+ * It reaches no zod, no command engine, no @dogsbay/render and no Node built-in, not even
6
+ * through a dynamic import: `tests/indexes-entry.test.ts` bundles this file and fails on any of
7
+ * them. The parser it does need (format-dogsbay-md's `/browser` entry) is the same module the
8
+ * host already ships, so a bundler keeps one copy. Everything here is also exported by the main
9
+ * entry, which adds the verbs and `NodeStorage`.
10
+ */
11
+ export { MemoryStorage, normalizeStoragePath } from "./storage.js";
12
+ export { Workspace } from "./workspace.js";
13
+ export { contentHash } from "./sha256.js";
14
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, } from "./indexes.js";
15
+ export { expressionNames, variableKey, } from "./variables.js";
package/dist/indexes.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type TopicMapError } from "@dogsbay/format-topicmap";
2
2
  import type { Storage } from "./storage.js";
3
+ import { type FileVariables, type SymbolEntry, type Variant } from "./variables.js";
3
4
  export interface DocHeading {
4
5
  level: number;
5
6
  text: string;
@@ -87,6 +88,8 @@ export interface DocIndexEntry {
87
88
  frontmatterEmpty: boolean;
88
89
  /** Set when the file could not be parsed; the entry is otherwise empty. */
89
90
  parseError?: string;
91
+ /** Template variables this file defines (`{% set %}`, `{% with %}`, `params:`) and reads, with ranges. */
92
+ variables: FileVariables;
90
93
  /**
91
94
  * Hash of the source bytes this entry was built from — the same hash
92
95
  * `topic-read` returns and the content verbs accept as `expect`, so a fix
@@ -146,6 +149,14 @@ export interface WorkspaceIndex {
146
149
  inbound: Map<string, InboundRef[]>;
147
150
  /** Key name → files that use it (via key: hrefs). */
148
151
  keyUses: Map<string, string[]>;
152
+ /**
153
+ * Template variables by lookup name (hyphens as underscores): every definition (the config's
154
+ * `attributes:`, `{% set %}`, `{% with %}`, `params:`) and every use, config first, then files in
155
+ * path order. See plans/variables-in-the-index.md.
156
+ */
157
+ variables: Map<string, SymbolEntry>;
158
+ /** One per `content.sources` entry of the config (none without a config). */
159
+ variants: Variant[];
149
160
  stats: {
150
161
  files: number;
151
162
  docs: number;
package/dist/indexes.js CHANGED
@@ -13,7 +13,9 @@ import { dogsbayMdToTree, headingIds, pageId, isMinjaProcessedFence, transformCo
13
13
  import { includeDirectiveRe } from "@dogsbay/minja/browser";
14
14
  import { parseTopicMap, isTopicMapPath, isExternalHref, normalizePath, dirname, joinPath, } from "@dogsbay/format-topicmap";
15
15
  import { load as loadYaml } from "js-yaml";
16
- import { contentHash } from "./commands/content.js";
16
+ import { contentHash } from "./sha256.js";
17
+ import { appliesIn, scanFileVariables, scanParams, variableKey } from "./variables.js";
18
+ import { CONFIG_FILES, inFolder, readConfigVariables } from "./config-variables.js";
17
19
  const isKeysFilePath = (path) => path.endsWith(".keys.yaml") || path.endsWith(".keys.yml") || /(^|\/)keys\.ya?ml$/.test(path);
18
20
  const isDocPath = (path) => path.endsWith(".md");
19
21
  /**
@@ -254,7 +256,29 @@ const scanFrontmatter = (source) => {
254
256
  frontmatterEmpty: closed ? empty : true,
255
257
  };
256
258
  };
257
- const indexDoc = (path, source) => {
259
+ const TEMPLATE_PAGE = /^template:[ \t]*["']?jinja["']?[ \t]*$/m;
260
+ const NOT_TEMPLATE = /^template:[ \t]*false[ \t]*$/m;
261
+ const NO_PREPROCESS = /^preprocess:[ \t]*false[ \t]*$/m;
262
+ const indexDoc = (path, source, templateSource = false) => {
263
+ const front = scanFrontmatter(source);
264
+ // where the body starts: past the closing `---` line of a terminated block
265
+ let bodyStart = 0;
266
+ if (front.frontmatterBlock === "block") {
267
+ const m = /\n(?:---|\.\.\.)[ \t]*\r?(?:\n|$)/.exec(source.slice(source.indexOf("\n")));
268
+ if (m)
269
+ bodyStart = source.indexOf("\n") + m.index + m[0].length;
270
+ }
271
+ const fmText = source.slice(0, bodyStart);
272
+ const masked = blankCodeRegions(source);
273
+ // as the build decides (TemplatePages.isTemplatePage): `template: jinja`, or a `templates: jinja`
274
+ // source unless the page says `template: false`; `preprocess: false` is never evaluated
275
+ // a partial declaring `params:` is included by template pages, so it is read as one
276
+ const template = TEMPLATE_PAGE.test(fmText) || /^params:/m.test(fmText) || (templateSource && !NOT_TEMPLATE.test(fmText));
277
+ const variables = NO_PREPROCESS.test(fmText)
278
+ ? { definitions: [], uses: [] }
279
+ // an ordinary page is rendered front matter and all; a template page's body only
280
+ : scanFileVariables(path, source, masked, template ? bodyStart : 0, { template });
281
+ variables.definitions.unshift(...scanParams(path, source, bodyStart));
258
282
  const entry = {
259
283
  path,
260
284
  frontmatter: {},
@@ -265,14 +289,14 @@ const indexDoc = (path, source) => {
265
289
  includes: [],
266
290
  keyUses: [],
267
291
  hash: contentHash(source),
268
- ...scanFrontmatter(source),
292
+ variables,
293
+ ...front,
269
294
  };
270
295
  const state = { entry, docDir: dirname(path), lines: source.split("\n"), taken: new Set() };
271
296
  // Includes come from the RAW source (code regions masked): the
272
297
  // markdown parser's attrs plugin mangles `{% include %}` lines into
273
298
  // element attributes, so the tree never sees them. The raw scan is
274
299
  // exactly what the build preprocessor will execute anyway.
275
- const masked = blankCodeRegions(source);
276
300
  // line starts once; lineAt is a binary search (O(links × log lines), not O(links × bytes))
277
301
  const lineStarts = [0];
278
302
  for (let i = 0; i < masked.length; i++)
@@ -514,6 +538,35 @@ export function anchorAliases(headings) {
514
538
  }
515
539
  return out;
516
540
  }
541
+ /** The variables table: definitions and uses by lookup name, and where each definition applies. */
542
+ const variableTable = (configDefs, docs, variants) => {
543
+ const table = new Map();
544
+ const entry = (name) => {
545
+ const key = variableKey(name);
546
+ let e = table.get(key);
547
+ if (!e)
548
+ table.set(key, (e = { kind: "variable", name: key, definitions: [], uses: [] }));
549
+ return e;
550
+ };
551
+ const sorted = [...docs].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
552
+ const fileDefs = sorted.flatMap((d) => d.variables.definitions);
553
+ const setNames = new Set(fileDefs.filter((d) => d.via === "set" || d.via === "with").map((d) => variableKey(d.name)));
554
+ for (const def of [...configDefs, ...fileDefs]) {
555
+ const out = variants.length ? { ...def, variants: Object.fromEntries(variants.map((v) => [v.id, applies(def, v, setNames)])) } : def;
556
+ entry(def.name).definitions.push(out);
557
+ }
558
+ for (const d of sorted)
559
+ for (const use of d.variables.uses)
560
+ entry(use.name).uses.push(use);
561
+ return table;
562
+ };
563
+ const applies = (def, v, setNames) => {
564
+ if (def.via === "config")
565
+ return def.context.scope === "site" || def.context.source === v.id;
566
+ if (!inFolder(def.file, v.path))
567
+ return false;
568
+ return appliesIn(def.conditions, v.attributes, setNames);
569
+ };
517
570
  /** Build every index in one pass over the workspace (or patch a previous one — see BuildIndexOptions). */
518
571
  export async function buildWorkspaceIndex(storage, options = {}) {
519
572
  const files = (await storage.list()).map(normalizePath);
@@ -531,8 +584,12 @@ export async function buildWorkspaceIndex(storage, options = {}) {
531
584
  if (current.has(path) && !changed.has(path))
532
585
  maps.set(path, map);
533
586
  }
587
+ // the config first: its sources decide which pages are template pages
588
+ const configFile = CONFIG_FILES.find((f) => current.has(f));
589
+ const config = readConfigVariables(configFile, configFile ? await storage.read(configFile) : undefined);
590
+ const configChanged = changed !== null && CONFIG_FILES.some((f) => changed.has(f));
534
591
  for (const path of files) {
535
- const reuse = changed !== null && !changed.has(path);
592
+ const reuse = changed !== null && !changed.has(path) && !configChanged;
536
593
  if (isTopicMapPath(path)) {
537
594
  if (!(reuse && maps.has(path)))
538
595
  maps.set(path, indexMap(path, await storage.read(path)));
@@ -542,7 +599,7 @@ export async function buildWorkspaceIndex(storage, options = {}) {
542
599
  }
543
600
  else if (isDocPath(path)) {
544
601
  if (!(reuse && docs.has(path)))
545
- docs.set(path, indexDoc(path, await storage.read(path)));
602
+ docs.set(path, indexDoc(path, await storage.read(path), config.templateSources.some((dir) => inFolder(path, dir))));
546
603
  }
547
604
  }
548
605
  // ---- inverted graphs --------------------------------------------------
@@ -585,6 +642,7 @@ export async function buildWorkspaceIndex(storage, options = {}) {
585
642
  }
586
643
  }
587
644
  }
645
+ const variables = variableTable(config.definitions, [...docs.values()], config.variants);
588
646
  return {
589
647
  files: current,
590
648
  docs,
@@ -593,6 +651,8 @@ export async function buildWorkspaceIndex(storage, options = {}) {
593
651
  keyFileErrors,
594
652
  inbound,
595
653
  keyUses,
654
+ variables,
655
+ variants: config.variants,
596
656
  stats: {
597
657
  files: files.length,
598
658
  docs: docs.size,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Real-filesystem `Storage` (Node only). Kept out of storage.ts so a browser bundle that wants
3
+ * only MemoryStorage and the index (`@dogsbay/commands/indexes`) never reaches node:fs, even
4
+ * through a dynamic import (the playground's item 26).
5
+ */
6
+ import { type Storage } from "./storage.js";
7
+ /**
8
+ * Real-filesystem storage rooted at a directory. Node-only (dynamic
9
+ * fs imports keep the module loadable in browser bundles that only
10
+ * use MemoryStorage).
11
+ */
12
+ export interface NodeStorageOptions {
13
+ /**
14
+ * Refuse symlinks whose target resolves OUTSIDE the workspace root
15
+ * (list skips them; read/write/delete/exists throw). Default false —
16
+ * pnpm/monorepo layouts legitimately symlink content in, and the CLI
17
+ * runs on the user's own tree. Turn it on where the tree is UNTRUSTED
18
+ * and the verbs are reachable by an agent (the IDE sidecar does):
19
+ * a repo containing `docs/x -> ~/.ssh` would otherwise expose those files
20
+ * to `where-used`/`validate`/`read`-style verbs.
21
+ */
22
+ containSymlinks?: boolean;
23
+ }
24
+ export declare class NodeStorage implements Storage {
25
+ private root;
26
+ private readonly containSymlinks;
27
+ private rootReal;
28
+ constructor(root: string, options?: NodeStorageOptions);
29
+ private fs;
30
+ private abs;
31
+ /** `abs()` plus, when contained, a realpath check that no symlink escapes the root. */
32
+ private safeAbs;
33
+ private isInsideRoot;
34
+ list(): Promise<string[]>;
35
+ read(path: string): Promise<string>;
36
+ readBytes(path: string, options?: {
37
+ maxBytes?: number;
38
+ }): Promise<Uint8Array>;
39
+ write(path: string, content: string): Promise<void>;
40
+ delete(path: string): Promise<void>;
41
+ exists(path: string): Promise<boolean>;
42
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Real-filesystem `Storage` (Node only). Kept out of storage.ts so a browser bundle that wants
3
+ * only MemoryStorage and the index (`@dogsbay/commands/indexes`) never reaches node:fs, even
4
+ * through a dynamic import (the playground's item 26).
5
+ */
6
+ import { normalizeStoragePath } from "./storage.js";
7
+ /** Directories never part of a content workspace. */
8
+ const IGNORED_DIRS = new Set([
9
+ "node_modules", ".git", ".dogsbay", "dist", ".astro", ".turbo",
10
+ ]);
11
+ export class NodeStorage {
12
+ root;
13
+ containSymlinks;
14
+ rootReal;
15
+ constructor(root, options = {}) {
16
+ this.root = root;
17
+ this.containSymlinks = options.containSymlinks ?? false;
18
+ }
19
+ async fs() {
20
+ return import("node:fs/promises");
21
+ }
22
+ abs(path) {
23
+ const rel = normalizeStoragePath(path);
24
+ if (rel.startsWith("..")) {
25
+ throw new Error(`Path escapes the workspace root: ${path}`);
26
+ }
27
+ return `${this.root}/${rel}`;
28
+ }
29
+ /** `abs()` plus, when contained, a realpath check that no symlink escapes the root. */
30
+ async safeAbs(path) {
31
+ const abs = this.abs(path);
32
+ if (!this.containSymlinks)
33
+ return abs;
34
+ if (!(await this.isInsideRoot(abs))) {
35
+ throw new Error(`Path resolves outside the workspace root: ${path}`);
36
+ }
37
+ return abs;
38
+ }
39
+ async isInsideRoot(abs) {
40
+ const fs = await this.fs();
41
+ this.rootReal ??= fs.realpath(this.root).catch(() => this.root);
42
+ const rootReal = await this.rootReal;
43
+ // realpath the deepest existing ancestor (the target may not exist yet on write)
44
+ let probe = abs;
45
+ let suffix = "";
46
+ for (;;) {
47
+ try {
48
+ const real = await fs.realpath(probe);
49
+ const full = real + suffix;
50
+ return full === rootReal || full.startsWith(rootReal + "/");
51
+ }
52
+ catch {
53
+ const cut = probe.lastIndexOf("/");
54
+ if (cut <= 0)
55
+ return false;
56
+ suffix = probe.slice(cut) + suffix;
57
+ probe = probe.slice(0, cut);
58
+ }
59
+ }
60
+ }
61
+ async list() {
62
+ const fs = await this.fs();
63
+ const out = [];
64
+ // Symlinked directories are walked (pnpm/monorepo layouts symlink
65
+ // content in); the realpath set breaks symlink cycles
66
+ const visited = new Set([await fs.realpath(this.root).catch(() => this.root)]);
67
+ const walk = async (dir, prefix) => {
68
+ let entries;
69
+ try {
70
+ entries = await fs.readdir(dir, { withFileTypes: true });
71
+ }
72
+ catch {
73
+ return;
74
+ }
75
+ for (const entry of entries) {
76
+ const full = `${dir}/${entry.name}`;
77
+ let isDirectory = entry.isDirectory();
78
+ let isFile = entry.isFile();
79
+ if (entry.isSymbolicLink()) {
80
+ if (this.containSymlinks && !(await this.isInsideRoot(full)))
81
+ continue; // escapes the root
82
+ try {
83
+ const stat = await fs.stat(full); // follows the link
84
+ isDirectory = stat.isDirectory();
85
+ isFile = stat.isFile();
86
+ }
87
+ catch {
88
+ continue; // dangling symlink
89
+ }
90
+ }
91
+ if (isDirectory) {
92
+ if (IGNORED_DIRS.has(entry.name))
93
+ continue;
94
+ if (entry.isSymbolicLink()) {
95
+ try {
96
+ const real = await fs.realpath(full);
97
+ if (visited.has(real))
98
+ continue;
99
+ visited.add(real);
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ }
105
+ await walk(full, `${prefix}${entry.name}/`);
106
+ }
107
+ else if (isFile) {
108
+ out.push(`${prefix}${entry.name}`);
109
+ }
110
+ }
111
+ };
112
+ await walk(this.root, "");
113
+ return out.sort();
114
+ }
115
+ async read(path) {
116
+ const fs = await this.fs();
117
+ return fs.readFile(await this.safeAbs(path), "utf-8");
118
+ }
119
+ async readBytes(path, options = {}) {
120
+ const fs = await this.fs();
121
+ // Contained whatever containSymlinks says: this reads binaries for a page that leaves
122
+ // the workspace, so a symlink out (docs/k.png -> ~/.ssh/key) must not be followed.
123
+ const abs = this.abs(path);
124
+ if (!(await this.isInsideRoot(abs)))
125
+ throw new Error(`Path resolves outside the workspace root: ${path}`);
126
+ const st = await fs.stat(abs);
127
+ if (!st.isFile())
128
+ throw new Error(`Not a file: ${path}`);
129
+ if (options.maxBytes !== undefined && st.size > options.maxBytes)
130
+ throw new Error(`File is over ${options.maxBytes} bytes: ${path}`);
131
+ return new Uint8Array(await fs.readFile(abs));
132
+ }
133
+ async write(path, content) {
134
+ const fs = await this.fs();
135
+ const abs = await this.safeAbs(path);
136
+ const dir = abs.slice(0, abs.lastIndexOf("/"));
137
+ await fs.mkdir(dir, { recursive: true });
138
+ await fs.writeFile(abs, content, "utf-8");
139
+ }
140
+ async delete(path) {
141
+ const fs = await this.fs();
142
+ await fs.unlink(await this.safeAbs(path));
143
+ }
144
+ async exists(path) {
145
+ const fs = await this.fs();
146
+ try {
147
+ await fs.access(await this.safeAbs(path));
148
+ return true;
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
154
+ }
package/dist/sha256.d.ts CHANGED
@@ -1 +1,7 @@
1
1
  export declare function sha256Hex(text: string): string;
2
+ /**
3
+ * Divergence gate (plans/ide-change-review.md §3): a short content hash the agent gets from
4
+ * `topic-read` and hands back as `expect` on a mutation; the index records it per file. Here, not
5
+ * in commands/content.ts, so the index reaches no zod or engine.
6
+ */
7
+ export declare const contentHash: (text: string) => string;