okforest 0.7.0 → 0.9.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.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.mjs +120 -29
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -10,6 +10,7 @@ npx okforest validate . --format json # for CI and tools
10
10
  npx okforest inventory . # types, tags, keys, near-duplicates
11
11
  npx okforest init sales-okf --template company --name "Sales knowledge"
12
12
  npx okforest rule okf/type # why a rule exists, and how to fix it
13
+ npx okforest types init . # draft a JSON Schema for each type
13
14
  ```
14
15
 
15
16
  `npx` runs it without installing anything. It needs Node.js 22 or later. To
package/dist/cli.mjs CHANGED
@@ -4,10 +4,10 @@ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
4
  import { basename, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { parseArgs, styleText } from "node:util";
7
- import { buildInventory } from "@okforest/okf";
7
+ import { TYPES_FOLDER, buildInventory } from "@okforest/okf";
8
8
  import { readTree } from "@okforest/okf/node";
9
- import { defaultRules, okfRules, ruleDocs, ruleUrl, toReport, validate } from "@okforest/validate";
10
- //#region src/io.ts
9
+ import { defaultRules, draftTypeSchema, okfRules, ruleDocs, ruleUrl, toReport, validate } from "@okforest/validate";
10
+ // src/io.ts
11
11
  /** Exit codes: 0 success, 1 validation errors, 2 usage or read problems. */
12
12
  const EXIT = {
13
13
  ok: 0,
@@ -22,8 +22,7 @@ function paint(io, style, text) {
22
22
  const packageRoot = new URL("../", import.meta.url);
23
23
  const VERSION = createRequire(import.meta.url)("../package.json").version;
24
24
  const TEMPLATES_DIR = new URL("templates/", packageRoot);
25
- //#endregion
26
- //#region src/args.ts
25
+ // src/args.ts
27
26
  /** Parse a command's arguments: options plus at most one positional path. */
28
27
  function parseCommand(args, options) {
29
28
  const { values, positionals } = parseArgs({
@@ -49,9 +48,8 @@ function formatOption(value) {
49
48
  if (value === "json") return "json";
50
49
  throw new UsageError(`--format must be \`text\` or \`json\` (got \`${String(value)}\`).`);
51
50
  }
52
- //#endregion
53
- //#region src/commands/init.ts
54
- const HELP$4 = `Usage: okforest init [path] --template <name> [--name <name>]
51
+ // src/commands/init.ts
52
+ const HELP$5 = `Usage: okforest init [path] --template <name> [--name <name>]
55
53
 
56
54
  Create a new OKF v0.2 tree at path (default: the current directory, which must
57
55
  be empty apart from .git) from a starter template. Starter concepts are drafts
@@ -68,7 +66,7 @@ async function initCommand(args, io) {
68
66
  name: { type: "string" }
69
67
  });
70
68
  if (values.help) {
71
- io.stdout(HELP$4);
69
+ io.stdout(HELP$5);
72
70
  return EXIT.ok;
73
71
  }
74
72
  const templates = await listTemplates();
@@ -77,7 +75,7 @@ async function initCommand(args, io) {
77
75
  const target = resolve(io.cwd, path);
78
76
  const blocking = (await readdir(target).catch(() => [])).filter((name) => name !== ".git" && name !== ".DS_Store");
79
77
  if (blocking.length > 0) throw new UsageError(`${path} is not empty (${blocking.slice(0, 3).join(", ")}${blocking.length > 3 ? ", ..." : ""}).`);
80
- const name = typeof values.name === "string" ? values.name.trim() : `${capitalize(slug(basename(target).replace(/-okf$/, "")) || "company")} knowledge`;
78
+ const name = typeof values.name === "string" ? values.name.trim() : `${capitalize(slug$1(basename(target).replace(/-okf$/, "")) || "company")} knowledge`;
81
79
  if (name === "" || [...name].length > 100) throw new UsageError(`--name must be 1 to 100 characters (got ${[...name].length.toLocaleString("en-US")}).`);
82
80
  const now = /* @__PURE__ */ new Date();
83
81
  const tokens = {
@@ -119,14 +117,13 @@ async function copyTemplate(from, to, tokens) {
119
117
  await walk("");
120
118
  return written;
121
119
  }
122
- function slug(value) {
120
+ function slug$1(value) {
123
121
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
124
122
  }
125
123
  function capitalize(value) {
126
124
  return value.charAt(0).toUpperCase() + value.slice(1).replaceAll("-", " ");
127
125
  }
128
- //#endregion
129
- //#region src/tree.ts
126
+ // src/tree.ts
130
127
  /** Read the tree at a user-supplied path, or explain why not. */
131
128
  async function loadTree(path, io) {
132
129
  const dir = resolve(io.cwd, path);
@@ -139,9 +136,8 @@ async function loadTree(path, io) {
139
136
  throw new UsageError(`Could not read ${path}: ${error.message}`);
140
137
  }
141
138
  }
142
- //#endregion
143
- //#region src/commands/inventory.ts
144
- const HELP$3 = `Usage: okforest inventory [path] [--format text|json]
139
+ // src/commands/inventory.ts
140
+ const HELP$4 = `Usage: okforest inventory [path] [--format text|json]
145
141
 
146
142
  List every type, tag, and frontmatter key in use in the tree at path (default:
147
143
  the current directory), with counts, lifecycle and trust totals, and likely
@@ -153,7 +149,7 @@ Options
153
149
  async function inventoryCommand(args, io) {
154
150
  const { values, path } = parseCommand(args, { format: { type: "string" } });
155
151
  if (values.help) {
156
- io.stdout(HELP$3);
152
+ io.stdout(HELP$4);
157
153
  return EXIT.ok;
158
154
  }
159
155
  const format = formatOption(values.format);
@@ -197,9 +193,8 @@ function inventoryText(inventory, io) {
197
193
  }
198
194
  return `${out.join("\n")}\n`;
199
195
  }
200
- //#endregion
201
- //#region src/commands/rule.ts
202
- const HELP$2 = `Usage: okforest rule [rule] [--format text|json]
196
+ // src/commands/rule.ts
197
+ const HELP$3 = `Usage: okforest rule [rule] [--format text|json]
203
198
 
204
199
  Explain a rule: why it exists, an example that breaks it, what
205
200
  \`okforest validate\` reports for it, and the fix. Without a rule, list every
@@ -233,7 +228,7 @@ async function ruleCommand(args, io) {
233
228
  strict: true
234
229
  });
235
230
  if (values.help) {
236
- io.stdout(HELP$2);
231
+ io.stdout(HELP$3);
237
232
  return EXIT.ok;
238
233
  }
239
234
  if (positionals.length > 1) throw new UsageError(`Expected one rule, got ${positionals.length}: ${positionals.join(" ")}`);
@@ -361,8 +356,103 @@ function edits(a, b) {
361
356
  }
362
357
  return previous[b.length];
363
358
  }
364
- //#endregion
365
- //#region src/commands/validate.ts
359
+ // src/commands/types.ts
360
+ const HELP$2 = `Usage: okforest types <command> [path]
361
+
362
+ Work with the tree's type schemas: a JSON Schema for each type's frontmatter
363
+ in ${TYPES_FOLDER}, which \`okforest validate\` checks concepts against.
364
+
365
+ Commands
366
+ init Draft a schema for each type in use that has none.
367
+
368
+ Run \`okforest types <command> --help\` for its options.
369
+ `;
370
+ const INIT_HELP = `Usage: okforest types init [path] [--type <type>]... [--dry-run]
371
+
372
+ Draft a JSON Schema for each type the tree at path (default: the current
373
+ directory) uses that has no schema yet, as ${TYPES_FOLDER}<type>.schema.json.
374
+ Each draft holds the fields the type's concepts use beyond OKF's, typed by
375
+ their values, with a format, allowed values, or required fields where every
376
+ concept agrees, so they all match it. Review and tighten each one; no file is
377
+ ever overwritten.
378
+
379
+ Options
380
+ --type <type> Only this type (repeatable), as concepts write it.
381
+ --dry-run Print the drafts instead of writing them.
382
+ `;
383
+ const COMMANDS$1 = { init: typesInit };
384
+ async function typesCommand(args, io) {
385
+ const [command, ...rest] = args;
386
+ if (command === void 0 || command === "-h" || command === "--help") {
387
+ io.stdout(HELP$2);
388
+ return command === void 0 ? EXIT.usage : EXIT.ok;
389
+ }
390
+ if (!Object.hasOwn(COMMANDS$1, command)) throw new UsageError(`Unknown command \`types ${command}\`. Run \`okforest types --help\` for usage.`);
391
+ return await COMMANDS$1[command](rest, io);
392
+ }
393
+ async function typesInit(args, io) {
394
+ const { values, path } = parseCommand(args, {
395
+ type: {
396
+ type: "string",
397
+ multiple: true
398
+ },
399
+ "dry-run": { type: "boolean" }
400
+ });
401
+ if (values.help) {
402
+ io.stdout(INIT_HELP);
403
+ return EXIT.ok;
404
+ }
405
+ const tree = await loadTree(path, io);
406
+ const byType = /* @__PURE__ */ new Map();
407
+ for (const concept of tree.concepts) {
408
+ if (concept.type === void 0) continue;
409
+ byType.set(concept.type, [...byType.get(concept.type) ?? [], concept]);
410
+ }
411
+ const wanted = values.type ?? [...byType.keys()].sort();
412
+ const unknown = wanted.filter((type) => !byType.has(type));
413
+ if (unknown.length > 0) throw new UsageError(`No concept has type ${unknown.map((t) => `\`${t}\``).join(", ")}. Run \`okforest inventory ${path}\` to list the types in use.`);
414
+ const schemas = new Set(tree.types.flatMap((schema) => schema.name ? [schema.name] : []));
415
+ const files = new Set(tree.files);
416
+ const lines = [];
417
+ let drafted = 0;
418
+ for (const type of wanted) {
419
+ const concepts = byType.get(type);
420
+ const file = `${TYPES_FOLDER}${slug(type)}.schema.json`;
421
+ if (schemas.has(type)) {
422
+ lines.push(` skipped ${type}: it has a schema already`);
423
+ continue;
424
+ }
425
+ if (files.has(file)) {
426
+ lines.push(` skipped ${type}: ${file} exists, for another type`);
427
+ continue;
428
+ }
429
+ const { $schema, ...draft } = draftTypeSchema(type, concepts);
430
+ const schema = {
431
+ $schema,
432
+ $comment: `Drafted by okforest ${VERSION} types init from ${concepts.length} ${concepts.length === 1 ? "concept" : "concepts"}: tighten it (required fields, allowed values, formats).`,
433
+ ...draft
434
+ };
435
+ const text = `${JSON.stringify(schema, null, 2)}\n`;
436
+ drafted++;
437
+ if (values["dry-run"]) {
438
+ lines.push(` ${file}`, ...text.trimEnd().split("\n").map((line) => ` ${line}`));
439
+ continue;
440
+ }
441
+ const target = resolve(io.cwd, path, file);
442
+ await mkdir(join(target, ".."), { recursive: true });
443
+ await writeFile(target, text, { flag: "wx" });
444
+ lines.push(` wrote ${file} (${type}, from ${concepts.length})`);
445
+ }
446
+ const verb = values["dry-run"] ? "Would draft" : "Drafted";
447
+ io.stdout(`${verb} ${drafted} type ${drafted === 1 ? "schema" : "schemas"} in ${path}.\n` + (lines.length > 0 ? `${lines.join("\n")}\n` : "") + (drafted > 0 && !values["dry-run"] ? `\nNext: review each draft, then check the tree with \`okforest validate ${path}\`.\n` : ""));
448
+ return EXIT.ok;
449
+ }
450
+ /** `BigQuery Table` → `bigquery-table`, `顧客` → `顧客`; `type` when no
451
+ * letter or digit is left. */
452
+ function slug(type) {
453
+ return type.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "") || "type";
454
+ }
455
+ // src/commands/validate.ts
366
456
  const HELP$1 = `Usage: okforest validate [path] [--format text|json]
367
457
 
368
458
  Check the OKF v0.2 tree at path (default: the current directory) against the
@@ -439,8 +529,7 @@ function summary(result, io) {
439
529
  const counts = `${plural(result.errors, "error")}, ${plural(result.warnings, "warning")}, ${result.infos} info`;
440
530
  return result.ok ? `${paint(io, "green", "✔")} ${counts} · ${scope}` : `${paint(io, "red", "✖")} ${counts} · ${scope}`;
441
531
  }
442
- //#endregion
443
- //#region src/main.ts
532
+ // src/main.ts
444
533
  const HELP = `okforest ${VERSION}: validate, inventory, and scaffold Open Knowledge Format (OKF) v0.2 trees
445
534
 
446
535
  Usage
@@ -448,6 +537,7 @@ Usage
448
537
  okforest inventory [path] [--format text|json]
449
538
  okforest init [path] --template company [--name <name>]
450
539
  okforest rule [rule] [--format text|json]
540
+ okforest types init [path] [--type <type>]... [--dry-run]
451
541
 
452
542
  Commands
453
543
  validate Check a tree against OKF v0.2 and OKForest conventions.
@@ -457,6 +547,8 @@ Commands
457
547
  init Create a new tree from a starter template (templates: company).
458
548
  rule Explain a rule: why it exists, an example, and the fix.
459
549
  Without a rule, list every rule.
550
+ types Work with the tree's type schemas (.okforest/types/):
551
+ \`types init\` drafts one for each type in use that has none.
460
552
 
461
553
  Options
462
554
  -h, --help Show help (also: okforest <command> --help)
@@ -472,7 +564,8 @@ const COMMANDS = {
472
564
  validate: validateCommand,
473
565
  inventory: inventoryCommand,
474
566
  init: initCommand,
475
- rule: ruleCommand
567
+ rule: ruleCommand,
568
+ types: typesCommand
476
569
  };
477
570
  /** Run the CLI and return its exit code. */
478
571
  async function main(argv, io) {
@@ -500,8 +593,7 @@ function isArgsError(error) {
500
593
  const code = error?.code;
501
594
  return typeof code === "string" && code.startsWith("ERR_PARSE_ARGS_");
502
595
  }
503
- //#endregion
504
- //#region src/cli.ts
596
+ // src/cli.ts
505
597
  const env = process.env;
506
598
  const color = env.FORCE_COLOR !== void 0 ? env.FORCE_COLOR !== "0" : Boolean(process.stdout.isTTY) && env.NO_COLOR === void 0 && env.TERM !== "dumb";
507
599
  process.exitCode = await main(process.argv.slice(2), {
@@ -510,5 +602,4 @@ process.exitCode = await main(process.argv.slice(2), {
510
602
  color,
511
603
  cwd: process.cwd()
512
604
  });
513
- //#endregion
514
605
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okforest",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "The OKForest CLI: validate Open Knowledge Format (OKF) v0.2 trees, inventory their metadata, and scaffold new trees from templates.",
5
5
  "keywords": [
6
6
  "okf",
@@ -32,13 +32,13 @@
32
32
  "node": ">=22"
33
33
  },
34
34
  "dependencies": {
35
- "@okforest/okf": "0.7.0",
36
- "@okforest/validate": "0.7.0"
35
+ "@okforest/okf": "0.9.0",
36
+ "@okforest/validate": "0.9.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@types/node": "^26.6.5",
39
+ "@types/node": "^26.6.6",
40
40
  "@vitest/coverage-v8": "^5.0.5",
41
- "tsdown": "^0.23.0",
41
+ "tsdown": "^0.23.4",
42
42
  "typescript": "^7.0.2",
43
43
  "vitest": "^5.0.5"
44
44
  },