@okforest/okf 0.15.0 → 0.16.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/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # @okforest/okf
2
2
 
3
- Read an [Open Knowledge Format (OKF)](https://github.com/GoogleCloudPlatform/open-knowledge-format)
4
- v0.2 tree into a model: concepts (path, concept ID, frontmatter, body as
3
+ Read an [Open Knowledge Format (OKF)](https://github.com/open-knowledge-format/open-knowledge-format)
4
+ tree, 0.2 or 0.3, into a model: concepts (path, concept ID, frontmatter, body as
5
5
  [mdast](https://github.com/syntax-tree/mdast)), reserved `index.md` and
6
6
  `log.md` files, links in both absolute and relative forms, backlinks, and the
7
- v0.2 fields with their derived values: trust tier, lifecycle status, and
8
- staleness. Also builds the metadata inventory: every type, tag, and
7
+ OKF fields with their derived values: trust tier, lifecycle status, and
8
+ staleness, read as OKF 0.3 says to read every version. Also builds the metadata inventory: every type, tag, and
9
9
  frontmatter key in use, with near-duplicates.
10
10
 
11
11
  No SDKs or frameworks: the core is pure and runs in Node, browsers, and
package/dist/index.d.mts CHANGED
@@ -1,12 +1,12 @@
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";
1
+ import { S as Verification, _ as TreeOutline, a as DiagramSettings, b as TypeSchema, c as Link, d as Position, f as ReservedFile, g as TreeFile, h as Tree, i as Diagnostic, l as MarkdownFile, m as Status, n as CodeBlock, o as FootnoteReference, p as Source, r as Concept, s as KeyPath, t as BundleMetadata, u as MermaidRenderer, v as TreeSettings, x as TypeTemplate, y as TrustTier } from "./types-CvO9HuOI.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;
5
5
  /** Strip a byte-order mark and normalize line endings to LF. */
6
6
  export declare function normalizeText(text: string): string;
7
- /** The frontmatter keys OKF defines (§4.1, §5, §10.2). A type's schema
8
- * describes the type's own fields, so these are left out of it unless it
9
- * names them. */
7
+ /** The frontmatter keys OKF defines for a concept (§4.1, §5, §10.2). A
8
+ * type's schema describes the type's own fields, so these are left out of
9
+ * it unless it names them; any other key is an extension key (§4.1). */
10
10
  export declare const OKF_FIELDS: readonly string[];
11
11
  /** A value in use and how many concepts use it. */
12
12
  interface Count {
@@ -31,7 +31,8 @@ interface Inventory {
31
31
  tags: Count[];
32
32
  /** Top-level frontmatter keys. */
33
33
  keys: Count[];
34
- statuses: Record<Status, number>;
34
+ /** Concepts by status; `unrecognized` counts values OKF doesn't define. */
35
+ statuses: Record<Status | "unrecognized", number>;
35
36
  trustTiers: Record<TrustTier, number>;
36
37
  /** Concepts past their `stale_after` instant. */
37
38
  stale: number;
@@ -102,8 +103,9 @@ export declare function isTypeFilePath(path: string): boolean;
102
103
  * reading a directory). Never throws on malformed content; problems are
103
104
  * recorded on the files for `@okforest/validate` to report.
104
105
  *
105
- * Every markdown file is part of the tree except those under `.okforest/` and
106
- * `.git/`, as OKF says; settings `ignore:` globs leave out others.
106
+ * Every markdown file is part of the tree except those in a file or folder
107
+ * whose name starts with `.` (`.okforest/`, `.git/`, `.github/`), as OKF
108
+ * says (§3.2); settings `ignore:` globs leave out others.
107
109
  */
108
110
  export declare function parseTree(input: Iterable<TreeFile>): Tree;
109
111
  /**
@@ -112,27 +114,79 @@ export declare function parseTree(input: Iterable<TreeFile>): Tree;
112
114
  * schemas and templates by path ({@link isTypeFilePath}), without reading its markdown:
113
115
  * a tree too large to hold parsed at once is then read one file at a time
114
116
  * with {@link TreeOutline.read}, each file as {@link parseTree} reads it.
117
+ * `okfVersion`, the root `index.md`'s, decides how path fields resolve (a
118
+ * bundle on 0.2 or no version may resolve them from the bundle root, §6.2).
115
119
  */
116
- export declare function outlineTree(paths: Iterable<string>, settingsText?: string, typeTexts?: ReadonlyMap<string, string>): TreeOutline;
120
+ export declare function outlineTree(paths: Iterable<string>, settingsText?: string, typeTexts?: ReadonlyMap<string, string>, options?: {
121
+ okfVersion?: unknown;
122
+ }): TreeOutline;
123
+ /** A bundle's metadata from its root `index.md`'s frontmatter (spec §8.1):
124
+ * `title`, `description`, and `license`, when they're non-blank text. */
125
+ export declare function readBundleMetadata(frontmatter: Record<string, unknown> | undefined): BundleMetadata | undefined;
126
+ /** The `okf_version` a bundle-root `index.md`'s text declares, as written
127
+ * (spec §8.1), for {@link outlineTree}: undefined when it declares none. */
128
+ export declare function declaredOkfVersion(rootIndexText: string | undefined): unknown;
117
129
  /** A type schema file, read leniently: what the `okforest/type-schema` rule
118
130
  * reports (text that isn't JSON) leaves `data` undefined. Keys are located
119
131
  * by reading the text as YAML, which JSON is. */
120
132
  export declare function readTypeSchema(path: string, text: string): TypeSchema;
121
133
  /** A type template, its front matter read as a concept's is. */
122
134
  export declare function readTypeTemplate(path: string, text: string): TypeTemplate;
123
- /** Lifecycle status (spec §5.4): absent, or not a recognized value, means `stable`. */
124
- export declare function deriveStatus(value: unknown): Status;
135
+ /** Lifecycle status (spec §5.4): absent (or null, or blank, §11.2) means
136
+ * `stable`; a value OKF doesn't define is `unrecognized`, which isn't
137
+ * `stable`, so filters to current knowledge leave it out. */
138
+ export declare function deriveStatus(value: unknown): Status | "unrecognized";
139
+ /** Whether a value is one of the statuses OKF defines. */
125
140
  export declare function isStatus(value: unknown): value is Status;
141
+ /**
142
+ * A timestamp as OKF writes it (spec §5): an RFC 3339 date-time with an
143
+ * offset, or a date only, which is the start of that day in UTC. Milliseconds
144
+ * since the epoch, or undefined for any other form (a date-time without an
145
+ * offset, a date that doesn't exist, a number).
146
+ */
147
+ export declare function parseTimestamp(value: unknown): number | undefined;
126
148
  /**
127
149
  * Verification events (spec §5.2). A bare `{ by, at }` mapping is a
128
- * one-element list; entries without a string `by` are skipped.
150
+ * one-element list; entries without a string `by` are skipped. `at` is kept
151
+ * as written: {@link currentVerifications} needs it to count an event.
129
152
  */
130
153
  export declare function normalizeVerified(value: unknown): Verification[];
131
- /** Trust tier (spec §5.3): `human:` verifiers ⇒ human-reviewed; any other
132
- * verifier ⇒ machine-confirmed; none ⇒ unverified. */
133
- export declare function deriveTrustTier(verified: readonly Verification[]): TrustTier;
134
- /** Whether `now >= staleAfter` (spec §5.5). Unparseable instants are never stale. */
135
- export declare function isStaleAt(staleAfter: string | undefined, now: Date): boolean;
154
+ /**
155
+ * The verification events that count (spec §5.3): those with a timestamp
156
+ * `at` on or after `generated.at`, the last change to the content, or every
157
+ * timed event when there's no such change to compare with. An event without
158
+ * a readable `at` never counts (§5.2).
159
+ */
160
+ export declare function currentVerifications(verified: readonly Verification[], generatedAt?: unknown): Verification[];
161
+ /** Trust tier (spec §5.3), from the current verification events only, so a
162
+ * page an agent rewrote after a person's review isn't human-reviewed until
163
+ * someone confirms it again: a current `human:` verifier ⇒ human-reviewed;
164
+ * other current verifiers only ⇒ machine-confirmed; none ⇒ unverified. */
165
+ export declare function deriveTrustTier(verified: readonly Verification[], generatedAt?: unknown): TrustTier;
166
+ /** Whether `now >= staleAfter` (spec §5.5). Absent (or null, or blank) is
167
+ * never stale; a value that isn't a timestamp is never fresh, since it can't
168
+ * say the content is still current. */
169
+ export declare function isStaleAt(staleAfter: unknown, now: Date): boolean;
170
+ /** `sources` entries (spec §5.1): a bare mapping is a one-element list
171
+ * (§11.2). Fields hold the values as written when they have the expected
172
+ * type. */
136
173
  export declare function normalizeSources(value: unknown): Source[];
174
+ /** Whether a value counts as absent (spec §11.2): undefined, null, an empty
175
+ * or blank string, or an empty list. */
176
+ export declare function isAbsent(value: unknown): boolean;
177
+ /** The newest OKF version this package reads (spec §12). */
178
+ export declare const LATEST_OKF_VERSION = "0.3";
179
+ /** An OKF version, `<major>.<minor>` (spec §12). */
180
+ interface OkfVersion {
181
+ major: number;
182
+ minor: number;
183
+ }
184
+ /** The OKF version an `okf_version` value names, or undefined when it names
185
+ * none. A number counts as written (`okf_version: 0.3`, unquoted). */
186
+ export declare function parseOkfVersion(value: unknown): OkfVersion | undefined;
187
+ /** Whether an `okf_version` value names `version` or a later one. A bundle
188
+ * that declares no version reads as 0.2 or earlier (spec §12.1), so this is
189
+ * false for it. */
190
+ export declare function okfVersionAtLeast(value: unknown, version: string): boolean;
137
191
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
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 };
192
+ export type { BundleMetadata, CodeBlock, Concept, Count, Diagnostic, DiagramSettings, FootnoteReference, Inventory, KeyPath, Link, MarkdownFile, MermaidRenderer, NearDuplicates, OkfVersion, PageStart, Position, ReservedFile, Source, Status, Tree, TreeFile, TreeOutline, TreeSettings, TrustTier, TypeSchema, TypeTemplate, Verification };
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
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";
1
+ import { A as visit, C as isStatus, D as globToRegExp, E as parseTimestamp, O as normalizeText, S as isStaleAt, T as normalizeVerified, _ as parseOkfVersion, b as deriveTrustTier, c as isTypeTemplatePath, d as readBundleMetadata, g as okfVersionAtLeast, h as LATEST_OKF_VERSION, i as declaredOkfVersion, k as isRecord, l as outlineTree, m as readTypeTemplate, n as SETTINGS_PATH, o as isTypeFilePath, p as readTypeSchema, r as TYPES_FOLDER, s as isTypeSchemaPath, t as MERMAID_RENDERERS, u as parseTree, v as currentVerifications, w as normalizeSources, x as isAbsent, y as deriveStatus } from "./tree-BYjzYhx7.mjs";
2
2
  import { isMap, isScalar, parseDocument, stringify } from "yaml";
3
3
  // src/fields.ts
4
- /** The frontmatter keys OKF defines (§4.1, §5, §10.2). A type's schema
5
- * describes the type's own fields, so these are left out of it unless it
6
- * names them. */
4
+ /** The frontmatter keys OKF defines for a concept (§4.1, §5, §10.2). A
5
+ * type's schema describes the type's own fields, so these are left out of
6
+ * it unless it names them; any other key is an extension key (§4.1). */
7
7
  const OKF_FIELDS = [
8
8
  "type",
9
9
  "title",
@@ -15,6 +15,7 @@ const OKF_FIELDS = [
15
15
  "generated",
16
16
  "verified",
17
17
  "status",
18
+ "superseded_by",
18
19
  "stale_after",
19
20
  "runtime",
20
21
  "parameters",
@@ -32,7 +33,8 @@ function buildInventory(tree, options = {}) {
32
33
  const statuses = {
33
34
  draft: 0,
34
35
  stable: 0,
35
- deprecated: 0
36
+ deprecated: 0,
37
+ unrecognized: 0
36
38
  };
37
39
  const trustTiers = {
38
40
  unverified: 0,
@@ -231,4 +233,4 @@ function topLevelPairs(yaml) {
231
233
  function range(node) {
232
234
  return node.range;
233
235
  }
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 };
236
+ export { LATEST_OKF_VERSION, MERMAID_RENDERERS, OKF_FIELDS, SETTINGS_PATH, TYPES_FOLDER, buildInventory, currentVerifications, declaredOkfVersion, deriveStatus, deriveTrustTier, editDistance, findNearDuplicates, globToRegExp, isAbsent, isRecord, isStaleAt, isStatus, isTypeFilePath, isTypeSchemaPath, isTypeTemplatePath, normalizeSources, normalizeText, normalizeVerified, okfVersionAtLeast, outlineTree, parseOkfVersion, parseTimestamp, parseTree, readBundleMetadata, readTypeSchema, readTypeTemplate, startPage, visit };
package/dist/node.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { h as TreeFile, m as Tree } from "./types-DhAXCb-h.mjs";
1
+ import { g as TreeFile, h as Tree } from "./types-CvO9HuOI.mjs";
2
2
  /**
3
3
  * Read a tree from disk and build its model with {@link parseTree}. Reads the
4
4
  * text of `.okforest/settings.yaml`, of its type schemas and templates, and of markdown
package/dist/node.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as isTypeFilePath, i as ignoreMatcher, l as parseTree, n as SETTINGS_PATH, u as readSettings } from "./tree-D-UhzEOI.mjs";
1
+ import { a as ignoreMatcher, f as readSettings, n as SETTINGS_PATH, o as isTypeFilePath, u as parseTree } from "./tree-BYjzYhx7.mjs";
2
2
  import { readFile, readdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  // src/node.ts
@@ -254,21 +254,46 @@ function globToRegExp(glob) {
254
254
  return new RegExp(`^${source}$`);
255
255
  }
256
256
  // src/trust.ts
257
+ /** The statuses OKF defines (spec §5.4). */
257
258
  const STATUSES = [
258
259
  "draft",
259
260
  "stable",
260
261
  "deprecated"
261
262
  ];
262
- /** Lifecycle status (spec §5.4): absent, or not a recognized value, means `stable`. */
263
+ /** Lifecycle status (spec §5.4): absent (or null, or blank, §11.2) means
264
+ * `stable`; a value OKF doesn't define is `unrecognized`, which isn't
265
+ * `stable`, so filters to current knowledge leave it out. */
263
266
  function deriveStatus(value) {
264
- return STATUSES.includes(value) ? value : "stable";
267
+ if (isAbsent(value)) return "stable";
268
+ return STATUSES.includes(value) ? value : "unrecognized";
265
269
  }
270
+ /** Whether a value is one of the statuses OKF defines. */
266
271
  function isStatus(value) {
267
272
  return STATUSES.includes(value);
268
273
  }
269
274
  /**
275
+ * A timestamp as OKF writes it (spec §5): an RFC 3339 date-time with an
276
+ * offset, or a date only, which is the start of that day in UTC. Milliseconds
277
+ * since the epoch, or undefined for any other form (a date-time without an
278
+ * offset, a date that doesn't exist, a number).
279
+ */
280
+ function parseTimestamp(value) {
281
+ if (typeof value !== "string") return void 0;
282
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2}))?$/.exec(value.trim());
283
+ if (!match) return void 0;
284
+ const [, year, month, day, hour, minute, second] = match;
285
+ const date = Date.UTC(Number(year), Number(month) - 1, Number(day));
286
+ const check = new Date(date);
287
+ if (check.getUTCMonth() !== Number(month) - 1 || check.getUTCDate() !== Number(day)) return;
288
+ if (hour === void 0) return date;
289
+ if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 60) return void 0;
290
+ const instant = Date.parse(value.trim().replace(" ", "T"));
291
+ return Number.isNaN(instant) ? void 0 : instant;
292
+ }
293
+ /**
270
294
  * Verification events (spec §5.2). A bare `{ by, at }` mapping is a
271
- * one-element list; entries without a string `by` are skipped.
295
+ * one-element list; entries without a string `by` are skipped. `at` is kept
296
+ * as written: {@link currentVerifications} needs it to count an event.
272
297
  */
273
298
  function normalizeVerified(value) {
274
299
  return (Array.isArray(value) ? value : value === void 0 ? [] : [value]).flatMap((entry) => isRecord(entry) && typeof entry.by === "string" && entry.by !== "" ? [{
@@ -276,21 +301,41 @@ function normalizeVerified(value) {
276
301
  ...typeof entry.at === "string" ? { at: entry.at } : {}
277
302
  }] : []);
278
303
  }
279
- /** Trust tier (spec §5.3): `human:` verifiers ⇒ human-reviewed; any other
280
- * verifier ⇒ machine-confirmed; none ⇒ unverified. */
281
- function deriveTrustTier(verified) {
282
- if (verified.some((v) => v.by.startsWith("human:"))) return "human-reviewed";
283
- return verified.length > 0 ? "machine-confirmed" : "unverified";
304
+ /**
305
+ * The verification events that count (spec §5.3): those with a timestamp
306
+ * `at` on or after `generated.at`, the last change to the content, or every
307
+ * timed event when there's no such change to compare with. An event without
308
+ * a readable `at` never counts (§5.2).
309
+ */
310
+ function currentVerifications(verified, generatedAt) {
311
+ const changed = parseTimestamp(generatedAt);
312
+ return verified.filter((v) => {
313
+ const at = parseTimestamp(v.at);
314
+ return at !== void 0 && (changed === void 0 || at >= changed);
315
+ });
316
+ }
317
+ /** Trust tier (spec §5.3), from the current verification events only, so a
318
+ * page an agent rewrote after a person's review isn't human-reviewed until
319
+ * someone confirms it again: a current `human:` verifier ⇒ human-reviewed;
320
+ * other current verifiers only ⇒ machine-confirmed; none ⇒ unverified. */
321
+ function deriveTrustTier(verified, generatedAt) {
322
+ const current = currentVerifications(verified, generatedAt);
323
+ if (current.some((v) => v.by.startsWith("human:"))) return "human-reviewed";
324
+ return current.length > 0 ? "machine-confirmed" : "unverified";
284
325
  }
285
- /** Whether `now >= staleAfter` (spec §5.5). Unparseable instants are never stale. */
326
+ /** Whether `now >= staleAfter` (spec §5.5). Absent (or null, or blank) is
327
+ * never stale; a value that isn't a timestamp is never fresh, since it can't
328
+ * say the content is still current. */
286
329
  function isStaleAt(staleAfter, now) {
287
- if (staleAfter === void 0) return false;
288
- const instant = Date.parse(staleAfter);
289
- return !Number.isNaN(instant) && now.getTime() >= instant;
330
+ if (isAbsent(staleAfter)) return false;
331
+ const instant = parseTimestamp(staleAfter);
332
+ return instant === void 0 || now.getTime() >= instant;
290
333
  }
334
+ /** `sources` entries (spec §5.1): a bare mapping is a one-element list
335
+ * (§11.2). Fields hold the values as written when they have the expected
336
+ * type. */
291
337
  function normalizeSources(value) {
292
- if (!Array.isArray(value)) return [];
293
- return value.filter(isRecord).map((entry) => {
338
+ return (Array.isArray(value) ? value : isRecord(value) ? [value] : []).filter(isRecord).map((entry) => {
294
339
  const source = {};
295
340
  if (typeof entry.id === "string") source.id = entry.id;
296
341
  if (typeof entry.resource === "string") source.resource = entry.resource;
@@ -301,6 +346,33 @@ function normalizeSources(value) {
301
346
  return source;
302
347
  });
303
348
  }
349
+ /** Whether a value counts as absent (spec §11.2): undefined, null, an empty
350
+ * or blank string, or an empty list. */
351
+ function isAbsent(value) {
352
+ return value === void 0 || value === null || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0;
353
+ }
354
+ // src/version.ts
355
+ /** The newest OKF version this package reads (spec §12). */
356
+ const LATEST_OKF_VERSION = "0.3";
357
+ /** The OKF version an `okf_version` value names, or undefined when it names
358
+ * none. A number counts as written (`okf_version: 0.3`, unquoted). */
359
+ function parseOkfVersion(value) {
360
+ const text = typeof value === "number" ? String(value) : typeof value === "string" ? value : "";
361
+ const match = /^(\d+)\.(\d+)$/.exec(text.trim());
362
+ return match ? {
363
+ major: Number(match[1]),
364
+ minor: Number(match[2])
365
+ } : void 0;
366
+ }
367
+ /** Whether an `okf_version` value names `version` or a later one. A bundle
368
+ * that declares no version reads as 0.2 or earlier (spec §12.1), so this is
369
+ * false for it. */
370
+ function okfVersionAtLeast(value, version) {
371
+ const declared = parseOkfVersion(value);
372
+ const wanted = parseOkfVersion(version);
373
+ if (!declared || !wanted) return false;
374
+ return declared.major > wanted.major || declared.major === wanted.major && declared.minor >= wanted.minor;
375
+ }
304
376
  // src/tree.ts
305
377
  /** Where OKForest keeps a bundle's settings (an OKForest convention, not OKF). */
306
378
  const SETTINGS_PATH = ".okforest/settings.yaml";
@@ -325,8 +397,6 @@ function isTypeTemplatePath(path) {
325
397
  function isTypeFilePath(path) {
326
398
  return isTypeSchemaPath(path) || isTypeTemplatePath(path);
327
399
  }
328
- /** Folders never part of a tree: OKForest's own and version control's. */
329
- const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([".okforest", ".git"]);
330
400
  const RESERVED = /* @__PURE__ */ new Set(["index.md", "log.md"]);
331
401
  /**
332
402
  * Build a {@link Tree} from files. Pure: no file system access, so the same
@@ -334,8 +404,9 @@ const RESERVED = /* @__PURE__ */ new Set(["index.md", "log.md"]);
334
404
  * reading a directory). Never throws on malformed content; problems are
335
405
  * recorded on the files for `@okforest/validate` to report.
336
406
  *
337
- * Every markdown file is part of the tree except those under `.okforest/` and
338
- * `.git/`, as OKF says; settings `ignore:` globs leave out others.
407
+ * Every markdown file is part of the tree except those in a file or folder
408
+ * whose name starts with `.` (`.okforest/`, `.git/`, `.github/`), as OKF
409
+ * says (§3.2); settings `ignore:` globs leave out others.
339
410
  */
340
411
  function parseTree(input) {
341
412
  const texts = /* @__PURE__ */ new Map();
@@ -345,7 +416,8 @@ function parseTree(input) {
345
416
  }
346
417
  const typeTexts = /* @__PURE__ */ new Map();
347
418
  for (const [path, text] of texts) if (text !== void 0 && isTypeFilePath(path)) typeTexts.set(path, text);
348
- const outline = outlineTree(texts.keys(), texts.get(SETTINGS_PATH), typeTexts);
419
+ const okfVersion = declaredOkfVersion(texts.get("index.md"));
420
+ const outline = outlineTree(texts.keys(), texts.get(SETTINGS_PATH), typeTexts, { okfVersion });
349
421
  const concepts = [];
350
422
  const reserved = [];
351
423
  for (const path of outline.markdown) {
@@ -355,13 +427,14 @@ function parseTree(input) {
355
427
  }
356
428
  const byId = new Map(concepts.map((c) => [c.id, c]));
357
429
  const backlinks = /* @__PURE__ */ new Map();
358
- for (const concept of concepts) for (const link of concept.links) {
430
+ for (const concept of concepts) for (const link of [...concept.links, ...concept.paths]) {
359
431
  if (!link.concept) continue;
360
432
  const list = backlinks.get(link.concept) ?? [];
361
433
  list.push(link);
362
434
  backlinks.set(link.concept, list);
363
435
  }
364
436
  const rootIndex = reserved.find((r) => r.path === "index.md");
437
+ const metadata = readBundleMetadata(rootIndex?.frontmatter);
365
438
  return {
366
439
  files: outline.files,
367
440
  concepts,
@@ -371,6 +444,7 @@ function parseTree(input) {
371
444
  types: outline.types,
372
445
  templates: outline.templates,
373
446
  ...rootIndex?.frontmatter && "okf_version" in rootIndex.frontmatter ? { okfVersion: rootIndex.frontmatter.okf_version } : {},
447
+ ...metadata ? { metadata } : {},
374
448
  links: [...concepts, ...reserved].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).flatMap((doc) => doc.links),
375
449
  concept: (id) => byId.get(id),
376
450
  backlinks: (id) => backlinks.get(id) ?? []
@@ -382,8 +456,10 @@ function parseTree(input) {
382
456
  * schemas and templates by path ({@link isTypeFilePath}), without reading its markdown:
383
457
  * a tree too large to hold parsed at once is then read one file at a time
384
458
  * with {@link TreeOutline.read}, each file as {@link parseTree} reads it.
459
+ * `okfVersion`, the root `index.md`'s, decides how path fields resolve (a
460
+ * bundle on 0.2 or no version may resolve them from the bundle root, §6.2).
385
461
  */
386
- function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map()) {
462
+ function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map(), options = {}) {
387
463
  const unique = /* @__PURE__ */ new Set();
388
464
  for (const raw of paths) {
389
465
  const path = normalize(raw.replaceAll("\\", "/"));
@@ -399,7 +475,7 @@ function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map())
399
475
  const markdown = [];
400
476
  for (const path of files) {
401
477
  if (!path.endsWith(".md")) continue;
402
- if (path.split("/").some((s) => SKIPPED_FOLDERS.has(s))) continue;
478
+ if (path.split("/").some((segment) => segment.startsWith("."))) continue;
403
479
  if (isIgnored(path)) ignored.push(path);
404
480
  else markdown.push(path);
405
481
  }
@@ -421,15 +497,28 @@ function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map())
421
497
  ...settings ? { settings } : {},
422
498
  types,
423
499
  templates,
500
+ ...options.okfVersion !== void 0 ? { okfVersion: options.okfVersion } : {},
424
501
  read(path, text) {
425
502
  if (!inTree.has(path)) throw new Error(`${path} is not one of the tree's markdown files.`);
426
503
  const { rawLinks, ...rest } = readMarkdownFile(path, text);
427
- const links = rawLinks.map((raw) => resolveLink(raw, path, fileSet, directories, conceptIds));
504
+ const resolve = (raw, from = path) => resolveLink(raw, from, fileSet, directories, conceptIds);
505
+ const links = rawLinks.map((raw) => resolve(raw));
428
506
  const name = basename(path);
429
- if (!RESERVED.has(name)) return buildConcept({
430
- ...rest,
431
- links
432
- });
507
+ if (!RESERVED.has(name)) {
508
+ const legacy = !okfVersionAtLeast(options.okfVersion, "0.3");
509
+ return buildConcept({
510
+ ...rest,
511
+ links
512
+ }, (raw) => {
513
+ const link = resolve(raw);
514
+ if (!legacy || link.kind !== "internal" || link.form !== "relative" || link.exists) return link;
515
+ const rooted = resolve(raw, basename(path));
516
+ return rooted.exists ? {
517
+ ...rooted,
518
+ from: path
519
+ } : link;
520
+ });
521
+ }
433
522
  return {
434
523
  ...rest,
435
524
  links,
@@ -439,29 +528,36 @@ function outlineTree(paths, settingsText, typeTexts = /* @__PURE__ */ new Map())
439
528
  }
440
529
  };
441
530
  }
442
- function buildConcept(file) {
531
+ function buildConcept(file, resolvePath) {
443
532
  const fm = file.frontmatter ?? {};
444
533
  const str = (key) => {
445
534
  const value = fm[key];
446
535
  return typeof value === "string" && value.trim() !== "" ? value : void 0;
447
536
  };
448
537
  const verified = normalizeVerified(fm.verified);
449
- const staleAfter = str("stale_after");
538
+ const staleAfter = isAbsent(fm.stale_after) ? void 0 : String(fm.stale_after);
450
539
  const generated = isRecord(fm.generated) ? {
451
540
  ...typeof fm.generated.by === "string" ? { by: fm.generated.by } : {},
452
541
  ...typeof fm.generated.at === "string" ? { at: fm.generated.at } : {}
453
542
  } : void 0;
454
- const tags = Array.isArray(fm.tags) ? fm.tags.filter((t) => typeof t === "string") : typeof fm.tags === "string" ? [fm.tags] : [];
543
+ const tags = (Array.isArray(fm.tags) ? fm.tags : [fm.tags]).filter((t) => typeof t === "string" && t.trim() !== "");
544
+ const status = deriveStatus(fm.status);
545
+ const current = new Set(currentVerifications(verified, generated?.at));
455
546
  const fields = {
456
547
  kind: "concept",
457
548
  id: file.path.slice(0, -3),
458
549
  tags,
459
- status: deriveStatus(fm.status),
550
+ status,
460
551
  verified,
461
- trustTier: deriveTrustTier(verified),
552
+ verifiedBefore: verified.filter((v) => !current.has(v) && v.at !== void 0),
553
+ trustTier: deriveTrustTier(verified, generated?.at),
462
554
  sources: normalizeSources(fm.sources),
555
+ paths: pathFields(fm, file.locate).map(resolvePath),
463
556
  isStale: (now = /* @__PURE__ */ new Date()) => isStaleAt(staleAfter, now)
464
557
  };
558
+ if (status === "unrecognized") fields.statusValue = String(fm.status);
559
+ const supersededBy = str("superseded_by");
560
+ if (supersededBy !== void 0) fields.supersededBy = supersededBy;
465
561
  for (const key of [
466
562
  "type",
467
563
  "title",
@@ -478,13 +574,70 @@ function buildConcept(file) {
478
574
  ...fields
479
575
  };
480
576
  }
577
+ /**
578
+ * A concept's path fields (spec §6.2), unresolved, each with its key and
579
+ * where it's written. A `sources` entry's `resource` may describe a scope
580
+ * (`all queries in project X`) rather than name a file (§5.1): one with
581
+ * whitespace isn't a path, since a path percent-encodes its spaces (§6).
582
+ */
583
+ function pathFields(fm, locate) {
584
+ const found = [];
585
+ const add = (keys, value, field) => {
586
+ if (typeof value !== "string" || value.trim() === "") return;
587
+ const at = locate(keys) ?? {
588
+ line: 1,
589
+ column: 1
590
+ };
591
+ found.push({
592
+ target: value,
593
+ line: at.line,
594
+ column: at.column,
595
+ image: false,
596
+ field
597
+ });
598
+ };
599
+ for (const key of [
600
+ "resource",
601
+ "superseded_by",
602
+ "computation"
603
+ ]) add([key], fm[key], key);
604
+ for (const key of ["executor", "attester"]) {
605
+ const value = fm[key];
606
+ if (isRecord(value)) add([key, "resource"], value.resource, `${key}.resource`);
607
+ }
608
+ const sources = fm.sources;
609
+ (Array.isArray(sources) ? sources : isRecord(sources) ? [sources] : []).forEach((entry, i) => {
610
+ if (!isRecord(entry) || typeof entry.resource !== "string" || /\s/.test(entry.resource.trim())) return;
611
+ add(Array.isArray(sources) ? [
612
+ "sources",
613
+ i,
614
+ "resource"
615
+ ] : ["sources", "resource"], entry.resource, Array.isArray(sources) ? `sources[${i}].resource` : "sources.resource");
616
+ });
617
+ return found;
618
+ }
619
+ /** A bundle's metadata from its root `index.md`'s frontmatter (spec §8.1):
620
+ * `title`, `description`, and `license`, when they're non-blank text. */
621
+ function readBundleMetadata(frontmatter) {
622
+ const metadata = {};
623
+ for (const key of [
624
+ "title",
625
+ "description",
626
+ "license"
627
+ ]) {
628
+ const value = frontmatter?.[key];
629
+ if (typeof value === "string" && value.trim() !== "") metadata[key] = value;
630
+ }
631
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
632
+ }
481
633
  function resolveLink(raw, from, files, directories, conceptIds) {
482
634
  const base = {
483
635
  from,
484
636
  target: raw.target,
485
637
  line: raw.line,
486
638
  column: raw.column,
487
- image: raw.image
639
+ image: raw.image,
640
+ ...raw.field !== void 0 ? { field: raw.field } : {}
488
641
  };
489
642
  const target = raw.target.trim();
490
643
  if (isExternal(target)) return {
@@ -521,6 +674,11 @@ function resolveLink(raw, from, files, directories, conceptIds) {
521
674
  ...id !== void 0 && conceptIds.has(id) ? { concept: id } : {}
522
675
  };
523
676
  }
677
+ /** The `okf_version` a bundle-root `index.md`'s text declares, as written
678
+ * (spec §8.1), for {@link outlineTree}: undefined when it declares none. */
679
+ function declaredOkfVersion(rootIndexText) {
680
+ return rootIndexText === void 0 ? void 0 : readMarkdownFile("index.md", rootIndexText).frontmatter?.okf_version;
681
+ }
524
682
  /** Whether a bundle path matches one of the settings' `ignore:` globs. */
525
683
  function ignoreMatcher(globs) {
526
684
  const patterns = globs.map(globToRegExp);
@@ -626,4 +784,4 @@ function positionAt(source, offset) {
626
784
  column: (before.at(-1)?.length ?? 0) + 1
627
785
  };
628
786
  }
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 };
787
+ export { visit as A, isStatus as C, globToRegExp as D, parseTimestamp as E, normalizeText as O, isStaleAt as S, normalizeVerified as T, parseOkfVersion as _, ignoreMatcher as a, deriveTrustTier as b, isTypeTemplatePath as c, readBundleMetadata as d, readSettings as f, okfVersionAtLeast as g, LATEST_OKF_VERSION as h, declaredOkfVersion as i, isRecord as k, outlineTree as l, readTypeTemplate as m, SETTINGS_PATH as n, isTypeFilePath as o, readTypeSchema as p, TYPES_FOLDER as r, isTypeSchemaPath as s, MERMAID_RENDERERS as t, parseTree as u, currentVerifications as v, normalizeSources as w, isAbsent as x, deriveStatus as y };
@@ -12,9 +12,9 @@ interface Diagnostic {
12
12
  }
13
13
  /** A path into a YAML mapping: keys, or indexes into sequences. */
14
14
  type KeyPath = readonly (string | number)[];
15
- /** OKF v0.2 trust tier, derived from `verified` (spec §5.3). */
15
+ /** Trust tier, derived from a concept's current `verified` events (spec §5.3). */
16
16
  type TrustTier = "unverified" | "machine-confirmed" | "human-reviewed";
17
- /** OKF v0.2 lifecycle status (spec §5.4). */
17
+ /** A lifecycle status OKF defines (spec §5.4). */
18
18
  type Status = "draft" | "stable" | "deprecated";
19
19
  /** A file handed to {@link parseTree}: a bundle-relative POSIX path and, for
20
20
  * markdown and settings files, its text. Other files only need a path, so
@@ -49,6 +49,10 @@ interface Link {
49
49
  outside?: boolean;
50
50
  /** For internal links to a concept: its concept ID. */
51
51
  concept?: string;
52
+ /** For a path field (spec §6.2) rather than a link in the body: the
53
+ * frontmatter key it's written in, such as `superseded_by` or
54
+ * `sources[0].resource`. */
55
+ field?: string;
52
56
  }
53
57
  /** A markdown footnote reference (`[^label]`), the join key into `sources` ids. */
54
58
  interface FootnoteReference {
@@ -99,11 +103,19 @@ interface Source {
99
103
  usageCount?: number;
100
104
  lastModified?: string;
101
105
  }
102
- /** A verification event (spec §5.2). */
106
+ /** A verification event (spec §5.2). Only an event with a timestamp `at`
107
+ * counts toward the trust tier. */
103
108
  interface Verification {
104
109
  by: string;
105
110
  at?: string;
106
111
  }
112
+ /** A bundle's own metadata, from its root `index.md` (spec §8.1, OKF 0.3). */
113
+ interface BundleMetadata {
114
+ title?: string;
115
+ description?: string;
116
+ /** An SPDX expression, or a path to a license file in the bundle. */
117
+ license?: string;
118
+ }
107
119
  /** A concept document: any non-reserved `.md` file. */
108
120
  interface Concept extends MarkdownFile {
109
121
  kind: "concept";
@@ -114,18 +126,37 @@ interface Concept extends MarkdownFile {
114
126
  description?: string;
115
127
  resource?: string;
116
128
  tags: string[];
117
- /** Lifecycle status; `stable` when absent or not a recognized value. */
118
- status: Status;
129
+ /** Lifecycle status (spec §5.4): `stable` when absent; `unrecognized`
130
+ * for a value OKF doesn't define, which isn't `stable` ({@link statusValue}
131
+ * has it as written). */
132
+ status: Status | "unrecognized";
133
+ /** The `status` as written, when it's one OKF doesn't define. */
134
+ statusValue?: string;
135
+ /** The concept that replaces this one, as written (spec §5.4); it means
136
+ * something only with `status: deprecated`. {@link paths} resolves it. */
137
+ supersededBy?: string;
119
138
  generated?: {
120
139
  by?: string;
121
140
  at?: string;
122
141
  };
123
142
  /** Verification events, with a bare mapping treated as a one-element list. */
124
143
  verified: Verification[];
144
+ /** The events from before the content last changed (`generated.at`):
145
+ * history, which no longer counts toward the trust tier (spec §5.3). */
146
+ verifiedBefore: Verification[];
147
+ /** From the current verification events only (spec §5.3). */
125
148
  trustTier: TrustTier;
149
+ /** `stale_after` as written, when it isn't absent. */
126
150
  staleAfter?: string;
127
151
  sources: Source[];
128
- /** Whether `now >= stale_after` (spec §5.5). False when there is no valid `stale_after`. */
152
+ /** Its path fields (spec §6.2): `resource`, `sources[].resource`,
153
+ * `superseded_by`, `computation`, `executor.resource`, and
154
+ * `attester.resource`, resolved as links are, each with its `field`. Those
155
+ * that resolve to a concept are edges of the bundle graph (§6.4), as body
156
+ * links are. */
157
+ paths: Link[];
158
+ /** Whether `now >= stale_after` (spec §5.5). False when it's absent; true
159
+ * when it isn't a timestamp, which can't say the content is still current. */
129
160
  isStale(now?: Date): boolean;
130
161
  }
131
162
  /** A reserved file: `index.md` (spec §8) or `log.md` (spec §9). */
@@ -215,6 +246,9 @@ interface TreeOutline {
215
246
  types: TypeSchema[];
216
247
  /** Its type templates whose text was given, sorted by path. */
217
248
  templates: TypeTemplate[];
249
+ /** The bundle-root `index.md` `okf_version` value, as written, when it
250
+ * was given (spec §12): it decides which version's rules apply. */
251
+ okfVersion?: unknown;
218
252
  /** Read one of {@link markdown}, with its links resolved against the whole
219
253
  * tree, as {@link Tree} holds it. Throws for any other path. */
220
254
  read(path: string, text: string): Concept | ReservedFile;
@@ -236,11 +270,15 @@ interface Tree {
236
270
  templates: TypeTemplate[];
237
271
  /** The bundle-root `index.md` `okf_version` value, as written. */
238
272
  okfVersion?: unknown;
273
+ /** The bundle's metadata from its root `index.md` (spec §8.1), when it
274
+ * gives any. */
275
+ metadata?: BundleMetadata;
239
276
  /** Every link in every markdown file, in path and position order. */
240
277
  links: Link[];
241
278
  /** Look up a concept by its concept ID. */
242
279
  concept(id: string): Concept | undefined;
243
- /** Links from concepts (not from `index.md` or `log.md`) to the given concept. */
280
+ /** Links and path fields from concepts (not from `index.md` or `log.md`)
281
+ * to the given concept: its incoming edges in the bundle graph (spec §6.4). */
244
282
  backlinks(id: string): Link[];
245
283
  }
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 };
284
+ export { Verification as S, TreeOutline as _, DiagramSettings as a, TypeSchema as b, Link as c, Position as d, ReservedFile as f, TreeFile as g, Tree as h, Diagnostic as i, MarkdownFile as l, Status as m, CodeBlock as n, FootnoteReference as o, Source as p, Concept as r, KeyPath as s, BundleMetadata as t, MermaidRenderer as u, TreeSettings as v, TypeTemplate as x, TrustTier as y };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@okforest/okf",
3
- "version": "0.15.0",
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.",
3
+ "version": "0.16.0",
4
+ "description": "Read an Open Knowledge Format (OKF) tree, 0.2 or 0.3, 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",
7
7
  "open-knowledge-format",