@okforest/okf 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as TreeSettings, a as FootnoteReference, b as Verification, c as MarkdownFile, d as ReservedFile, f as Source, g as TreeOutline, h as TreeFile, i as DiagramSettings, l as MermaidRenderer, m as Tree, n as Concept, o as KeyPath, p as Status, r as Diagnostic, s as Link, t as CodeBlock, u as Position, v as TrustTier, y as TypeSchema } from "./types-4j7GeRZ-.mjs";
1
+ import { _ as TreeSettings, a as FootnoteReference, b as TypeTemplate, c as MarkdownFile, d as ReservedFile, f as Source, g as TreeOutline, h as TreeFile, i as DiagramSettings, l as MermaidRenderer, m as Tree, n as Concept, o as KeyPath, p as Status, r as Diagnostic, s as Link, t as CodeBlock, u as Position, v as TrustTier, x as Verification, y as TypeSchema } from "./types-DhAXCb-h.mjs";
2
2
  import { Nodes } from "mdast";
3
3
  /** Depth-first, document-order walk over an mdast tree. */
4
4
  export declare function visit(node: Nodes, fn: (node: Nodes) => void): void;
@@ -65,6 +65,20 @@ export declare function editDistance(a: string, b: string, limit: number): numbe
65
65
  * `*` and `?` stay within one path segment, `**` crosses segments, and a
66
66
  * trailing `/` matches everything under a directory. */
67
67
  export declare function globToRegExp(glob: string): RegExp;
68
+ /** What a new page is given by whoever creates it. */
69
+ interface PageStart {
70
+ type: string;
71
+ title?: string;
72
+ description?: string;
73
+ }
74
+ /**
75
+ * A new concept's text: its type's template as written, with `title` and
76
+ * `description` set to those given (in place, where the template has them;
77
+ * otherwise after `type`), every other byte of the template kept: its key
78
+ * order, comments, and body. Without a usable template (none, or front matter
79
+ * that isn't a mapping), just `type`, `title`, and `description`.
80
+ */
81
+ export declare function startPage(start: PageStart, template?: Pick<TypeTemplate, "text" | "frontmatter">): string;
68
82
  /** Where OKForest keeps a bundle's settings (an OKForest convention, not OKF). */
69
83
  export declare const SETTINGS_PATH = ".okforest/settings.yaml";
70
84
  /** What may draw a bundle's ```mermaid blocks (`diagrams.mermaid.renderer`
@@ -76,6 +90,12 @@ export declare const TYPES_FOLDER = ".okforest/types/";
76
90
  /** Whether a bundle path is a type schema: a `.schema.json` file in
77
91
  * {@link TYPES_FOLDER}, the name editors check as a JSON Schema. */
78
92
  export declare function isTypeSchemaPath(path: string): boolean;
93
+ /** Whether a bundle path is a type template: a `.template.md` file in
94
+ * {@link TYPES_FOLDER}, the page a new concept of its type starts as. */
95
+ export declare function isTypeTemplatePath(path: string): boolean;
96
+ /** Whether a bundle path is a type schema or template, whose text
97
+ * {@link outlineTree} needs. */
98
+ export declare function isTypeFilePath(path: string): boolean;
79
99
  /**
80
100
  * Build a {@link Tree} from files. Pure: no file system access, so the same
81
101
  * code runs in Node, browsers, and Workers (see `@okforest/okf/node` for
@@ -89,7 +109,7 @@ export declare function parseTree(input: Iterable<TreeFile>): Tree;
89
109
  /**
90
110
  * Outline a tree from its file paths, the text of its settings file
91
111
  * (`.okforest/settings.yaml`, when it has one), and the texts of its type
92
- * schemas by path ({@link isTypeSchemaPath}), without reading its markdown:
112
+ * schemas and templates by path ({@link isTypeFilePath}), without reading its markdown:
93
113
  * a tree too large to hold parsed at once is then read one file at a time
94
114
  * with {@link TreeOutline.read}, each file as {@link parseTree} reads it.
95
115
  */
@@ -98,6 +118,8 @@ export declare function outlineTree(paths: Iterable<string>, settingsText?: stri
98
118
  * reports (text that isn't JSON) leaves `data` undefined. Keys are located
99
119
  * by reading the text as YAML, which JSON is. */
100
120
  export declare function readTypeSchema(path: string, text: string): TypeSchema;
121
+ /** A type template, its front matter read as a concept's is. */
122
+ export declare function readTypeTemplate(path: string, text: string): TypeTemplate;
101
123
  /** Lifecycle status (spec §5.4): absent, or not a recognized value, means `stable`. */
102
124
  export declare function deriveStatus(value: unknown): Status;
103
125
  export declare function isStatus(value: unknown): value is Status;
@@ -113,4 +135,4 @@ export declare function deriveTrustTier(verified: readonly Verification[]): Trus
113
135
  export declare function isStaleAt(staleAfter: string | undefined, now: Date): boolean;
114
136
  export declare function normalizeSources(value: unknown): Source[];
115
137
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
116
- export type { CodeBlock, Concept, Count, Diagnostic, DiagramSettings, FootnoteReference, Inventory, KeyPath, Link, MarkdownFile, MermaidRenderer, NearDuplicates, Position, ReservedFile, Source, Status, Tree, TreeFile, TreeOutline, TreeSettings, TrustTier, TypeSchema, Verification };
138
+ export type { CodeBlock, Concept, Count, Diagnostic, DiagramSettings, FootnoteReference, Inventory, KeyPath, Link, MarkdownFile, MermaidRenderer, NearDuplicates, PageStart, Position, ReservedFile, Source, Status, Tree, TreeFile, TreeOutline, TreeSettings, TrustTier, TypeSchema, TypeTemplate, Verification };
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { _ as normalizeText, a as isTypeSchemaPath, d as deriveTrustTier, f as isStaleAt, g as globToRegExp, h as normalizeVerified, l as readTypeSchema, m as normalizeSources, n as SETTINGS_PATH, o as outlineTree, p as isStatus, r as TYPES_FOLDER, s as parseTree, t as MERMAID_RENDERERS, u as deriveStatus, v as isRecord, y as visit } from "./tree-cHPdftiv.mjs";
1
+ import { S as visit, _ as normalizeSources, a as isTypeFilePath, b as normalizeText, c as outlineTree, d as readTypeSchema, f as readTypeTemplate, g as isStatus, h as isStaleAt, l as parseTree, m as deriveTrustTier, n as SETTINGS_PATH, o as isTypeSchemaPath, p as deriveStatus, r as TYPES_FOLDER, s as isTypeTemplatePath, t as MERMAID_RENDERERS, v as normalizeVerified, x as isRecord, y as globToRegExp } from "./tree-D-UhzEOI.mjs";
2
+ import { isMap, isScalar, parseDocument, stringify } from "yaml";
2
3
  // src/fields.ts
3
4
  /** The frontmatter keys OKF defines (§4.1, §5, §10.2). A type's schema
4
5
  * describes the type's own fields, so these are left out of it unless it
@@ -169,4 +170,65 @@ function editDistance(a, b, limit) {
169
170
  }
170
171
  return previous[b.length];
171
172
  }
172
- export { MERMAID_RENDERERS, OKF_FIELDS, SETTINGS_PATH, TYPES_FOLDER, buildInventory, deriveStatus, deriveTrustTier, editDistance, findNearDuplicates, globToRegExp, isRecord, isStaleAt, isStatus, isTypeSchemaPath, normalizeSources, normalizeText, normalizeVerified, outlineTree, parseTree, readTypeSchema, visit };
173
+ // src/template.ts
174
+ const DELIMITER = /^---[ \t]*$/;
175
+ /**
176
+ * A new concept's text: its type's template as written, with `title` and
177
+ * `description` set to those given (in place, where the template has them;
178
+ * otherwise after `type`), every other byte of the template kept: its key
179
+ * order, comments, and body. Without a usable template (none, or front matter
180
+ * that isn't a mapping), just `type`, `title`, and `description`.
181
+ */
182
+ function startPage(start, template) {
183
+ if (!template?.frontmatter) {
184
+ const { type, title, description } = start;
185
+ return `---\n${stringify({
186
+ type,
187
+ ...title && { title },
188
+ ...description && { description }
189
+ }, { lineWidth: 0 })}---\n\n`;
190
+ }
191
+ const lines = normalizeText(template.text).split("\n");
192
+ const close = lines.findIndex((line, i) => i > 0 && DELIMITER.test(line));
193
+ let yaml = lines.slice(1, close).join("\n");
194
+ if (yaml !== "") yaml += "\n";
195
+ if (start.title !== void 0) yaml = setField(yaml, "title", start.title, ["type"]);
196
+ if (start.description !== void 0) yaml = setField(yaml, "description", start.description, ["title", "type"]);
197
+ return [lines[0], `${yaml}${lines.slice(close).join("\n")}`].join("\n");
198
+ }
199
+ /** `yaml` with top-level `key` set to `value`: its text replaced where it's
200
+ * written (a comment after it kept), or a line added after the first of
201
+ * `after` it has, else first. */
202
+ function setField(yaml, key, value, after) {
203
+ const line = `${key}: ${stringify(value, { lineWidth: 0 }).trimEnd()}`;
204
+ const pairs = topLevelPairs(yaml);
205
+ const existing = pairs.get(key);
206
+ if (existing) {
207
+ const [start, keyEnd] = range(existing.key);
208
+ let end = Math.max(range(existing.value)[1], keyEnd);
209
+ while (end > keyEnd && yaml[end - 1] === "\n") end--;
210
+ return `${yaml.slice(0, start)}${line}${yaml.slice(end)}`;
211
+ }
212
+ const anchor = after.map((name) => pairs.get(name)).find(Boolean);
213
+ if (!anchor) return `${line}\n${yaml}`;
214
+ const end = range(anchor.value)[2];
215
+ const at = yaml.indexOf("\n", end - 1) + 1;
216
+ return `${yaml.slice(0, at)}${line}\n${yaml.slice(at)}`;
217
+ }
218
+ /** A mapping's top-level pairs by key, as written. */
219
+ function topLevelPairs(yaml) {
220
+ const document = parseDocument(yaml, {
221
+ version: "1.2",
222
+ schema: "core"
223
+ });
224
+ const pairs = /* @__PURE__ */ new Map();
225
+ if (!isMap(document.contents)) return pairs;
226
+ for (const pair of document.contents.items) if (isScalar(pair.key)) pairs.set(String(pair.key.value), pair);
227
+ return pairs;
228
+ }
229
+ /** A parsed node's `[start, valueEnd, nodeEnd]` offsets: every key and value
230
+ * read from text has them, an empty value (`title:`) too. */
231
+ function range(node) {
232
+ return node.range;
233
+ }
234
+ export { MERMAID_RENDERERS, OKF_FIELDS, SETTINGS_PATH, TYPES_FOLDER, buildInventory, deriveStatus, deriveTrustTier, editDistance, findNearDuplicates, globToRegExp, isRecord, isStaleAt, isStatus, isTypeFilePath, isTypeSchemaPath, isTypeTemplatePath, normalizeSources, normalizeText, normalizeVerified, outlineTree, parseTree, readTypeSchema, readTypeTemplate, startPage, visit };
package/dist/node.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { h as TreeFile, m as Tree } from "./types-4j7GeRZ-.mjs";
1
+ import { h as TreeFile, m as Tree } from "./types-DhAXCb-h.mjs";
2
2
  /**
3
3
  * Read a tree from disk and build its model with {@link parseTree}. Reads the
4
- * text of `.okforest/settings.yaml`, of its type schemas, and of markdown
4
+ * text of `.okforest/settings.yaml`, of its type schemas and templates, and of markdown
5
5
  * files its `ignore:` globs don't leave out; other files are listed by path
6
6
  * only, so links to them can be checked. `.git/` is not walked, and symbolic links are not followed.
7
7
  */
package/dist/node.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { a as isTypeSchemaPath, c as readSettings, i as ignoreMatcher, n as SETTINGS_PATH, s as parseTree } from "./tree-cHPdftiv.mjs";
1
+ import { a as isTypeFilePath, i as ignoreMatcher, l as parseTree, n as SETTINGS_PATH, u as readSettings } from "./tree-D-UhzEOI.mjs";
2
2
  import { readFile, readdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  // src/node.ts
5
5
  /**
6
6
  * Read a tree from disk and build its model with {@link parseTree}. Reads the
7
- * text of `.okforest/settings.yaml`, of its type schemas, and of markdown
7
+ * text of `.okforest/settings.yaml`, of its type schemas and templates, and of markdown
8
8
  * files its `ignore:` globs don't leave out; other files are listed by path
9
9
  * only, so links to them can be checked. `.git/` is not walked, and symbolic links are not followed.
10
10
  */
@@ -33,7 +33,7 @@ async function readTreeFiles(root) {
33
33
  path,
34
34
  text: settingsText
35
35
  });
36
- else if (isTypeSchemaPath(path)) files.push({
36
+ else if (isTypeFilePath(path)) files.push({
37
37
  path,
38
38
  text: await read(path)
39
39
  });
@@ -315,6 +315,16 @@ const TYPES_FOLDER = ".okforest/types/";
315
315
  function isTypeSchemaPath(path) {
316
316
  return path.startsWith(".okforest/types/") && path.endsWith(".schema.json");
317
317
  }
318
+ /** Whether a bundle path is a type template: a `.template.md` file in
319
+ * {@link TYPES_FOLDER}, the page a new concept of its type starts as. */
320
+ function isTypeTemplatePath(path) {
321
+ return path.startsWith(".okforest/types/") && path.endsWith(".template.md");
322
+ }
323
+ /** Whether a bundle path is a type schema or template, whose text
324
+ * {@link outlineTree} needs. */
325
+ function isTypeFilePath(path) {
326
+ return isTypeSchemaPath(path) || isTypeTemplatePath(path);
327
+ }
318
328
  /** Folders never part of a tree: OKForest's own and version control's. */
319
329
  const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([".okforest", ".git"]);
320
330
  const RESERVED = /* @__PURE__ */ new Set(["index.md", "log.md"]);
@@ -334,7 +344,7 @@ function parseTree(input) {
334
344
  if (path) texts.set(path, file.text);
335
345
  }
336
346
  const typeTexts = /* @__PURE__ */ new Map();
337
- for (const [path, text] of texts) if (text !== void 0 && isTypeSchemaPath(path)) typeTexts.set(path, text);
347
+ for (const [path, text] of texts) if (text !== void 0 && isTypeFilePath(path)) typeTexts.set(path, text);
338
348
  const outline = outlineTree(texts.keys(), texts.get(SETTINGS_PATH), typeTexts);
339
349
  const concepts = [];
340
350
  const reserved = [];
@@ -359,6 +369,7 @@ function parseTree(input) {
359
369
  ignored: outline.ignored,
360
370
  ...outline.settings ? { settings: outline.settings } : {},
361
371
  types: outline.types,
372
+ templates: outline.templates,
362
373
  ...rootIndex?.frontmatter && "okf_version" in rootIndex.frontmatter ? { okfVersion: rootIndex.frontmatter.okf_version } : {},
363
374
  links: [...concepts, ...reserved].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).flatMap((doc) => doc.links),
364
375
  concept: (id) => byId.get(id),
@@ -368,7 +379,7 @@ function parseTree(input) {
368
379
  /**
369
380
  * Outline a tree from its file paths, the text of its settings file
370
381
  * (`.okforest/settings.yaml`, when it has one), and the texts of its type
371
- * schemas by path ({@link isTypeSchemaPath}), without reading its markdown:
382
+ * schemas and templates by path ({@link isTypeFilePath}), without reading its markdown:
372
383
  * a tree too large to hold parsed at once is then read one file at a time
373
384
  * with {@link TreeOutline.read}, each file as {@link parseTree} reads it.
374
385
  */
@@ -399,12 +410,17 @@ function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map())
399
410
  const text = typeTextOf.get(path);
400
411
  return text !== void 0 && isTypeSchemaPath(path) ? [readTypeSchema(path, text)] : [];
401
412
  });
413
+ const templates = files.flatMap((path) => {
414
+ const text = typeTextOf.get(path);
415
+ return text !== void 0 && isTypeTemplatePath(path) ? [readTypeTemplate(path, text)] : [];
416
+ });
402
417
  return {
403
418
  files,
404
419
  markdown,
405
420
  ignored,
406
421
  ...settings ? { settings } : {},
407
422
  types,
423
+ templates,
408
424
  read(path, text) {
409
425
  if (!inTree.has(path)) throw new Error(`${path} is not one of the tree's markdown files.`);
410
426
  const { rawLinks, ...rest } = readMarkdownFile(path, text);
@@ -573,6 +589,20 @@ function readTypeSchema(path, text) {
573
589
  locate
574
590
  };
575
591
  }
592
+ /** A type template, its front matter read as a concept's is. */
593
+ function readTypeTemplate(path, text) {
594
+ const file = readMarkdownFile(path, text);
595
+ const type = file.frontmatter?.type;
596
+ return {
597
+ path,
598
+ text: file.text,
599
+ frontmatter: file.frontmatter,
600
+ hasFrontmatter: file.hasFrontmatter,
601
+ ...file.frontmatterError ? { frontmatterError: file.frontmatterError } : {},
602
+ ...typeof type === "string" && type.trim() !== "" ? { name: type } : {},
603
+ locate: file.locate
604
+ };
605
+ }
576
606
  /** Where `JSON.parse` stopped, from the offset in its message ("Expected ','
577
607
  * after property value in JSON at position 42"); the start when it gives
578
608
  * none ("Unexpected end of JSON input"). */
@@ -596,4 +626,4 @@ function positionAt(source, offset) {
596
626
  column: (before.at(-1)?.length ?? 0) + 1
597
627
  };
598
628
  }
599
- export { normalizeText as _, isTypeSchemaPath as a, readSettings as c, deriveTrustTier as d, isStaleAt as f, globToRegExp as g, normalizeVerified as h, ignoreMatcher as i, readTypeSchema as l, normalizeSources as m, SETTINGS_PATH as n, outlineTree as o, isStatus as p, TYPES_FOLDER as r, parseTree as s, MERMAID_RENDERERS as t, deriveStatus as u, isRecord as v, visit as y };
629
+ export { visit as S, normalizeSources as _, isTypeFilePath as a, normalizeText as b, outlineTree as c, readTypeSchema as d, readTypeTemplate as f, isStatus as g, isStaleAt as h, ignoreMatcher as i, parseTree as l, deriveTrustTier as m, SETTINGS_PATH as n, isTypeSchemaPath as o, deriveStatus as p, TYPES_FOLDER as r, isTypeTemplatePath as s, MERMAID_RENDERERS as t, readSettings as u, normalizeVerified as v, isRecord as x, globToRegExp as y };
@@ -177,9 +177,28 @@ interface TypeSchema {
177
177
  /** Where a key of the schema is written, if present. */
178
178
  locate(path: KeyPath): Position | undefined;
179
179
  }
180
+ /** A type's starter page, at `.okforest/types/<type>.template.md` (an
181
+ * OKForest convention, not OKF): what a new concept of the type starts as,
182
+ * front matter and body, in the template's own order. Never a concept. */
183
+ interface TypeTemplate {
184
+ path: string;
185
+ /** The file's text with any byte-order mark removed and CRLF normalized to LF. */
186
+ text: string;
187
+ /** Its front matter, as a concept's is read; `undefined` when there is no
188
+ * block or it isn't a mapping. */
189
+ frontmatter: Record<string, unknown> | undefined;
190
+ /** Whether it starts with a `---` front matter block (parseable or not). */
191
+ hasFrontmatter: boolean;
192
+ /** Why its front matter could not be read, if it couldn't. */
193
+ frontmatterError?: Diagnostic;
194
+ /** The type it's for: its `type`, when that is non-blank text. */
195
+ name?: string;
196
+ /** Where a key of its front matter is written, if present. */
197
+ locate(path: KeyPath): Position | undefined;
198
+ }
180
199
  /**
181
200
  * A tree without its documents: every path in it, the markdown files that are
182
- * part of it, its settings and its type schemas, worked out from paths alone
201
+ * part of it, its settings, type schemas, and type templates, worked out from paths alone
183
202
  * (and the text of those files). A tree too large to hold parsed at once is read one file at a
184
203
  * time with {@link TreeOutline.read}; {@link Tree} is the same, read whole.
185
204
  */
@@ -194,6 +213,8 @@ interface TreeOutline {
194
213
  settings?: TreeSettings;
195
214
  /** Its type schemas whose text was given, sorted by path. */
196
215
  types: TypeSchema[];
216
+ /** Its type templates whose text was given, sorted by path. */
217
+ templates: TypeTemplate[];
197
218
  /** Read one of {@link markdown}, with its links resolved against the whole
198
219
  * tree, as {@link Tree} holds it. Throws for any other path. */
199
220
  read(path: string, text: string): Concept | ReservedFile;
@@ -211,6 +232,8 @@ interface Tree {
211
232
  settings?: TreeSettings;
212
233
  /** Its type schemas, sorted by path. */
213
234
  types: TypeSchema[];
235
+ /** Its type templates, sorted by path. */
236
+ templates: TypeTemplate[];
214
237
  /** The bundle-root `index.md` `okf_version` value, as written. */
215
238
  okfVersion?: unknown;
216
239
  /** Every link in every markdown file, in path and position order. */
@@ -220,4 +243,4 @@ interface Tree {
220
243
  /** Links from concepts (not from `index.md` or `log.md`) to the given concept. */
221
244
  backlinks(id: string): Link[];
222
245
  }
223
- export { TreeSettings as _, FootnoteReference as a, Verification as b, MarkdownFile as c, ReservedFile as d, Source as f, TreeOutline as g, TreeFile as h, DiagramSettings as i, MermaidRenderer as l, Tree as m, Concept as n, KeyPath as o, Status as p, Diagnostic as r, Link as s, CodeBlock as t, Position as u, TrustTier as v, TypeSchema as y };
246
+ export { TreeSettings as _, FootnoteReference as a, TypeTemplate as b, MarkdownFile as c, ReservedFile as d, Source as f, TreeOutline as g, TreeFile as h, DiagramSettings as i, MermaidRenderer as l, Tree as m, Concept as n, KeyPath as o, Status as p, Diagnostic as r, Link as s, CodeBlock as t, Position as u, TrustTier as v, Verification as x, TypeSchema as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@okforest/okf",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Read an Open Knowledge Format (OKF) v0.2 tree into a model: concepts, frontmatter, links, backlinks, trust tiers, staleness, and a metadata inventory. No SDKs or frameworks; runs in Node, browsers, and Workers.",
5
5
  "keywords": [
6
6
  "okf",