@p10i/flowmatter 0.1.1 → 0.1.3

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,6 +1,6 @@
1
1
  # flowmatter
2
2
 
3
- `flowmatter` turns a folder or glob of Markdown files into one interactive
3
+ `flowmatter` turns Markdown files selected by path, folder, or glob into one interactive
4
4
  [flowjob](https://github.com/piontkovsk11andre1/flowjob) map and a mirrored tree
5
5
  of linked, standalone HTML pages.
6
6
 
@@ -16,7 +16,7 @@ npm install @p10i/flowmatter
16
16
 
17
17
  ## Markdown schema
18
18
 
19
- Each Markdown file is a flowjob submodule. Its frontmatter defines its stable
19
+ Each non-config Markdown file is a flowjob submodule. Its frontmatter defines its stable
20
20
  identity, parent module, and outgoing relations:
21
21
 
22
22
  ```markdown
@@ -43,6 +43,30 @@ Validate the order and request payment.
43
43
  flow label. `relations[].id` and `relations[].relationType` are optional; an
44
44
  omitted relation ID is generated as `<document-id>:<one-based-index>`.
45
45
 
46
+ To give a connection its own **View** page, set `viewUrl: ../notes/retry-policy.md` on the relation. The path is relative to the declaring document; include the target in the build inputs. A referenced plain Markdown file needs no frontmatter: it renders once in the output directory without becoming a graph item. Multiple connections can share the page.
47
+
48
+ Any input document can define map-wide styles in its frontmatter:
49
+
50
+ ```yaml
51
+ relationTypes:
52
+ call: { label: Call, color: "#1565c0" }
53
+ ```
54
+
55
+ A relation with `relationType: call` uses that style; its `type` remains the individual connection label. Definitions merge by type and property across documents. Identical values are allowed, and conflicting values report both paths. An undeclared type keeps the default style. Optional `color` and `previewColor` accept quoted hex colors (3, 4, 6 or 8 digits).
56
+
57
+ For a shared palette, include a Markdown file such as `styles.md`:
58
+
59
+ ```yaml
60
+ ---
61
+ flowmatter: config
62
+ relationTypes:
63
+ - { id: call, label: Call, color: "#1565c0" }
64
+ - { id: event, label: Event, color: "#c60" }
65
+ ---
66
+ ```
67
+
68
+ Either declaration form works in ordinary documents and config files. Lists are read in declaration order. A config contributes only definitions: it has no node, page, or target ID. Include at least one ordinary document.
69
+
46
70
  The following values are inferred when omitted:
47
71
 
48
72
  | Field | Default |
@@ -61,6 +85,24 @@ module: Orders
61
85
 
62
86
  ## CLI
63
87
 
88
+ ### Preview while editing
89
+
90
+ `flowmatter serve docs --port 4173` serves the map at `http://127.0.0.1:4173/` and watches the same files, directories and quoted globs accepted by `build`. Refresh the browser after editing. New and removed pages are reflected together with the rebuilt map. Invalid edits are reported in the terminal; after startup, the last successful preview stays available until the inputs are valid again. The preview is in memory. Use `build` to write a distributable site, and Ctrl+C to stop serving.
91
+
92
+ ### Module colors
93
+
94
+ A module can open its own documentation: set `module: {name: Orders, viewUrl: ./Overview.md}` on any one of its items. Include the overview in the build inputs. Plain Markdown overviews render as pages without becoming map items. Declarations for the same module must resolve to the same page.
95
+
96
+ Use `module.type` to select a graph card palette. The definition can live on the same page or in a shared config document. Like `relationTypes`, `moduleTypes` accepts a mapping or a list and merges declarations across pages.
97
+
98
+ ```yaml
99
+ module: {name: Orders, type: domain}
100
+ moduleTypes:
101
+ domain: {accent: '#287768', headerBg: '#D9F0EA', headerFg: '#123D36'}
102
+ ```
103
+
104
+ Dark mode derives the card tint from `accent`.
105
+
64
106
  Build every Markdown file under a directory:
65
107
 
66
108
  ```sh
@@ -76,17 +118,20 @@ flowmatter "docs/**/*.md" --output site --title "Order processing"
76
118
  The explicit `build` command is equivalent and is preferable in automation:
77
119
 
78
120
  ```sh
79
- flowmatter build "docs/**/*.md" --output site --title "Order processing"
121
+ flowmatter build styles.md "docs/**/*.md" --output site --title "Order processing"
80
122
  ```
81
123
 
82
124
  The default output directory is `flowmatter-dist`. It contains `flow.html`
83
- and one `.html` page per source file with the same relative path. Existing
125
+ and one `.html` page per non-config document. Each input must match Markdown;
126
+ overlapping paths are processed once. Mirrored paths, inferred IDs, and the
127
+ default title use the common ancestor of the input roots (a file's parent,
128
+ the selected directory, or the directory before a glob's first wildcard). Existing
84
129
  generated files are not overwritten unless `--force` is passed.
85
130
 
86
131
  ```text
87
- Usage: flowmatter build <folder-or-glob> [options]
88
- flowmatter <folder-or-glob> [options]
89
- flowmatter validate <folder-or-glob> [--json]
132
+ Usage: flowmatter build <path-or-glob>... [options]
133
+ flowmatter <path-or-glob>... [options]
134
+ flowmatter validate <path-or-glob>... [--json]
90
135
  flowmatter schema
91
136
  flowmatter example
92
137
  flowmatter skill
@@ -157,11 +202,12 @@ generate Markdown, run JSON validation until it succeeds, then build.
157
202
  ```js
158
203
  import { buildSite, validateSite } from "@p10i/flowmatter";
159
204
 
160
- const validation = await validateSite({ input: "docs/**/*.md" });
205
+ const input = ["styles.md", "docs/**/*.md"]; // A single string also works.
206
+ const validation = await validateSite({ input });
161
207
  if (!validation.valid) console.error(validation.errors);
162
208
 
163
209
  const result = await buildSite({
164
- input: "docs/**/*.md",
210
+ input,
165
211
  outputDir: "site",
166
212
  title: "Order processing",
167
213
  });
@@ -3,9 +3,10 @@
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { buildSite, FlowmatterError, validateSite } from "../src/index.mjs";
5
5
 
6
- const HELP = `Usage: flowmatter build <folder-or-glob> [options]
7
- flowmatter <folder-or-glob> [options]
8
- flowmatter validate <folder-or-glob> [--json]
6
+ const HELP = `Usage: flowmatter build <path-or-glob>... [options]
7
+ flowmatter <path-or-glob>... [options]
8
+ flowmatter validate <path-or-glob>... [--json]
9
+ flowmatter serve <path-or-glob>... [--port 4173] [--title <title>] [--flow <filename>]
9
10
  flowmatter schema
10
11
  flowmatter example
11
12
  flowmatter skill
@@ -32,13 +33,17 @@ function takeValue(args, index, option) {
32
33
  return value;
33
34
  }
34
35
 
35
- function parseInputOptions(args) {
36
+ function parseInputOptions(args, serve = false) {
36
37
  const options = { force: false, json: false };
37
38
  const inputs = [];
38
39
 
39
40
  for (let index = 0; index < args.length; index += 1) {
40
41
  const argument = args[index];
41
- if (argument === "-f" || argument === "--force") {
42
+ if (serve && argument === '--port') {
43
+ const raw = takeValue(args,index++,argument);
44
+ if (!/^\d+$/.test(raw) || Number(raw)>65535) throw new Error('Expected --port 0–65535');
45
+ options.port = Number(raw);
46
+ } else if (argument === "-f" || argument === "--force") {
42
47
  options.force = true;
43
48
  } else if (argument === "--json") {
44
49
  options.json = true;
@@ -58,8 +63,8 @@ function parseInputOptions(args) {
58
63
  }
59
64
  }
60
65
 
61
- if (inputs.length !== 1) throw new Error("exactly one folder or glob is required");
62
- return { input: inputs[0], ...options };
66
+ if (!inputs.length) throw new Error("at least one Markdown path or glob is required");
67
+ return { input: inputs, ...options };
63
68
  }
64
69
 
65
70
  async function printBundledJson(relativePath) {
@@ -80,6 +85,15 @@ async function main() {
80
85
  }
81
86
 
82
87
  const command = args[0];
88
+ if (command === 'serve') {
89
+ const options = parseInputOptions(args.slice(1),true);
90
+ if (options.outputDir || options.force || options.json) throw new Error('serve accepts --flow, --title and --port');
91
+ const {serveSite} = await import('../src/serve.mjs');
92
+ const preview = await serveSite(options);
93
+ console.log(`Serving ${preview.url} (watching Markdown; refresh to see changes)`);
94
+ for (const signal of ['SIGINT','SIGTERM']) process.once(signal,()=>preview.close());
95
+ return;
96
+ }
83
97
  if (["schema", "example", "skill"].includes(command)) {
84
98
  if (args.length !== 1) throw new Error(`${command} does not accept arguments or options`);
85
99
  if (command === "skill") {
@@ -103,7 +117,7 @@ async function main() {
103
117
  console.log(JSON.stringify(report));
104
118
  }
105
119
  else if (validation.valid) {
106
- console.log(`${parsed.input} is valid (${validation.stats.files} files, ${validation.stats.relations} relations)`);
120
+ console.log(`Valid: ${parsed.input.join(", ")} (${validation.stats.files} files, ${validation.stats.relations} relations)`);
107
121
  } else {
108
122
  console.log(validation.errors.map((error) => error.message).join("\n"));
109
123
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p10i/flowmatter",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Generate flowjob maps and linked HTML pages from Markdown frontmatter.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -46,7 +46,7 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@p10i/flowjob": "0.1.2",
49
+ "@p10i/flowjob": "0.1.4",
50
50
  "glob": "13.0.6",
51
51
  "glob-parent": "6.0.2",
52
52
  "gray-matter": "4.0.3",
@@ -5,6 +5,10 @@
5
5
  "description": "Frontmatter fields supported by one Flowmatter Markdown document.",
6
6
  "type": "object",
7
7
  "properties": {
8
+ "flowmatter": {
9
+ "const": "config",
10
+ "description": "Contribute global relation types without creating a document node or HTML page."
11
+ },
8
12
  "id": {
9
13
  "type": "string",
10
14
  "pattern": "\\S",
@@ -27,12 +31,39 @@
27
31
  "properties": {
28
32
  "id": { "type": "string", "pattern": "\\S" },
29
33
  "name": { "type": "string", "pattern": "\\S" },
34
+ "viewUrl": { "type": "string", "description": "Local path to a selected Markdown overview, relative to this source file." },
30
35
  "type": { "type": "string", "pattern": "\\S" }
31
36
  },
32
37
  "additionalProperties": true
33
38
  }
34
39
  ]
35
40
  },
41
+ "moduleTypes": {
42
+ "description": "Map-wide module styles selected by module.type.",
43
+ "oneOf": [
44
+ { "type": "object", "propertyNames": { "$ref": "#/$defs/typeId" }, "additionalProperties": { "$ref": "#/$defs/moduleStyle", "unevaluatedProperties": false } },
45
+ { "type": "array", "items": { "$ref": "#/$defs/moduleStyle", "properties": { "id": { "$ref": "#/$defs/typeId" } }, "required": ["id"], "unevaluatedProperties": false } }
46
+ ]
47
+ },
48
+ "relationTypes": {
49
+ "description": "Map-wide styles in a keyed mapping or an ordered list. Repeated IDs merge by property; conflicting values are errors.",
50
+ "oneOf": [
51
+ {
52
+ "type": "object",
53
+ "propertyNames": { "$ref": "#/$defs/typeId" },
54
+ "additionalProperties": { "$ref": "#/$defs/style", "unevaluatedProperties": false }
55
+ },
56
+ {
57
+ "type": "array",
58
+ "items": {
59
+ "$ref": "#/$defs/style",
60
+ "properties": { "id": { "$ref": "#/$defs/typeId" } },
61
+ "required": ["id"],
62
+ "unevaluatedProperties": false
63
+ }
64
+ }
65
+ ]
66
+ },
36
67
  "relations": {
37
68
  "type": "array",
38
69
  "description": "Directed relations from this document to documents selected by ID.",
@@ -59,11 +90,41 @@
59
90
  "type": "string",
60
91
  "pattern": "\\S",
61
92
  "description": "Optional flowjob relation styling/filter key."
93
+ },
94
+ "viewUrl": {
95
+ "type": "string",
96
+ "pattern": "^(?!/)[^\\\\:\\u0000-\\u001f]*\\.(?:[mM][dD]|html)$",
97
+ "description": "Local path relative to this Markdown file. Select an included .md file or its generated .html path; write literal filenames, not URL-encoded segments. A referenced file without Flowmatter document fields renders only as a page."
62
98
  }
63
99
  },
64
100
  "additionalProperties": true
65
101
  }
66
102
  }
67
103
  },
104
+ "$defs": {
105
+ "typeId": { "type": "string", "pattern": "^\\S(?:[\\s\\S]*\\S)?$" },
106
+ "moduleStyle": {
107
+ "type": "object",
108
+ "properties": {
109
+ "label": {"type":"string","pattern":"\\S"},
110
+ "accent": {"$ref":"#/$defs/hexColor"}, "surface": {"$ref":"#/$defs/hexColor"},
111
+ "headerBg": {"$ref":"#/$defs/hexColor"}, "headerFg": {"$ref":"#/$defs/hexColor"}, "footerFg": {"$ref":"#/$defs/hexColor"}
112
+ }
113
+ },
114
+ "style": {
115
+ "type": "object",
116
+ "properties": {
117
+ "label": { "type": "string", "pattern": "\\S" },
118
+ "hint": { "type": "string", "pattern": "\\S", "description": "Short description shown under the connection filter label." },
119
+ "color": { "$ref": "#/$defs/hexColor" },
120
+ "previewColor": { "$ref": "#/$defs/hexColor" }
121
+ }
122
+ },
123
+ "hexColor": {
124
+ "type": "string",
125
+ "description": "CSS hex color; quote it in YAML so # does not start a comment.",
126
+ "pattern": "^#(?:[0-9A-Fa-f]{3,4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$"
127
+ }
128
+ },
68
129
  "additionalProperties": true
69
130
  }
@@ -25,12 +25,13 @@ render one interactive flowjob map plus linked standalone HTML pages.
25
25
  IDs and definitions consistent across files.
26
26
  6. Define each outgoing relation in its source document with non-empty `to`
27
27
  and `type` values. The `to` value must equal a target document ID.
28
- 7. Run `flowmatter validate <folder-or-glob> --json` before building.
28
+ 7. Run `flowmatter validate <path-or-glob>... --json` with all inputs, including shared configs. Overlapping paths count once. Inferred document IDs are relative to the common input root.
29
29
  8. Resolve every item in `errors` and repeat validation until `valid` is true.
30
- 9. Run `flowmatter build <folder-or-glob> --output <directory> --json`.
30
+ 9. Run `flowmatter build <path-or-glob>... --output <directory> --json` with the same inputs.
31
31
  10. Report the generated `flowPath`, page count, and output directory.
32
32
 
33
33
  Always quote glob inputs so Flowmatter receives the pattern. Do not use
34
+ `serve` as a replacement for the final build: `flowmatter serve <inputs> --port 4173` is a loopback editing preview; refresh after changes. Do not use
34
35
  `--force` unless overwriting existing generated files is explicitly intended.
35
36
  Do not edit generated HTML when the source Markdown can be corrected instead.
36
37
 
@@ -51,3 +52,26 @@ relations:
51
52
  Fields may be inferred, but explicit stable IDs are preferable for documents
52
53
  that participate in relations. Use the schema output as the authoritative
53
54
  field reference and JSON validation diagnostics as the authoritative check.
55
+
56
+ For a colored map, declare `relationTypes` in ordinary document frontmatter, e.g. `call: {label: Call, color: "#1565c0"}` under that key. Declarations merge across the input set; do not assign conflicting values to the same property.
57
+
58
+ Alternatively, use an ordered list such as `relationTypes: [{id: call, label: Call, color: "#1565c0"}]`. For a shared palette, put either form in Markdown frontmatter with `flowmatter: config`. Config files create no node or page; never use them as relation targets.
59
+
60
+ ## View pages and module colors
61
+
62
+ Each graph item opens its own generated page. To give a module header and a connection their own **View** pages, use frontmatter like this in `orders/place.md`:
63
+
64
+ ```yaml
65
+ module: {name: Orders, type: domain, viewUrl: ./Overview.md}
66
+ moduleTypes:
67
+ domain: {accent: '#287768', headerBg: '#D9F0EA', headerFg: '#123D36'}
68
+ relations:
69
+ - to: capture-payment
70
+ type: requests payment
71
+ relationType: call
72
+ viewUrl: ../notes/payment-handoff.md
73
+ ```
74
+
75
+ - **Module:** Declare `module.viewUrl` on one item in the module. If repeated, the declarations must resolve to the same page. `module.type` selects the card palette; `moduleTypes` can also live in a shared config and merges by ID and property like `relationTypes`.
76
+ - **Connection:** `to` is the destination item's ID; `viewUrl` is the document explaining the connection. For grouped connections, use the same view URL on every member if the group should offer **View**.
77
+ - **Inputs:** Resolve view paths relative to the declaring Markdown file. Include both the overview and the connection note in validation and build inputs. Use plain Markdown without graph frontmatter for these pages: Flowmatter renders them once without adding map items. Use `flowmatter: config` only for declarations that should produce no page.
package/src/index.mjs CHANGED
@@ -7,28 +7,31 @@ import matter from "gray-matter";
7
7
  import { marked } from "marked";
8
8
 
9
9
  const PAGE_STYLE = `
10
- :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; line-height: 1.6; }
11
- body { margin: 0; background: #f4f1ea; color: #27241f; }
12
- main { width: min(52rem, calc(100% - 2rem)); margin: 0 auto; padding: 3rem 0 5rem; }
13
- header { border-bottom: 1px solid #c9c1b3; margin-bottom: 2rem; padding-bottom: 1.25rem; }
14
- h1, h2, h3 { font-family: Georgia, "Times New Roman", serif; line-height: 1.15; }
15
- h1 { font-size: clamp(2.2rem, 7vw, 4.5rem); letter-spacing: -.04em; margin: .25rem 0; }
16
- a { color: #9a3f22; text-underline-offset: .18em; }
17
- .eyebrow { color: #70685d; font-size: .78rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
18
- .relations { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); margin: 2.5rem 0; }
19
- .relation-card { background: #fffaf0; border: 1px solid #d8cebd; border-radius: .35rem; padding: 1rem 1.2rem; }
20
- .relation-card h2 { font-size: 1rem; margin: 0 0 .65rem; }
21
- .relation-card ul { margin: 0; padding-left: 1.2rem; }
10
+ :root { color-scheme: light dark; font-family: Aptos, "Segoe UI Variable", "Segoe UI", sans-serif; line-height: 1.55;
11
+ --surface: #fcfeff; --text: #142236; --muted: #58708f; --border: #b9cde9; --tint: #e7f0ff; --link: #1855aa; }
12
+ @media (prefers-color-scheme: dark) { :root {
13
+ --surface: #0a121f; --text: #e8f1ff; --muted: #9ab2d5; --border: #294266; --tint: #111d32; --link: #8ab9ff; } }
14
+ body { margin: 0; background: var(--surface); color: var(--text); }
15
+ main { box-sizing: border-box; width: 100%; min-height: 100vh; margin: 0; padding: calc(.5rem + 5px) calc(.75rem + 5px); overflow-wrap: anywhere; }
16
+ h1, h2, h3 { line-height: 1.25; }
17
+ h1 { font-size: clamp(1.5rem, 4vw, 2rem); margin: .5em 0; }
18
+ a { color: var(--link); text-underline-offset: .18em; }
19
+ a:focus-visible { outline: 2px solid var(--link); outline-offset: 2px; }
20
+ .eyebrow, .relations { font-size: .875rem; }
21
+ .eyebrow { color: var(--muted); font-weight: 600; }
22
+ .relations { border-top: 1px solid var(--border); margin-top: 2rem; padding-top: .75rem; }
23
+ .relations small, article :not(pre) > code { border-radius: .35rem; padding: .1em .4em; background: var(--tint); }
24
+ .relations small { color: var(--muted); }
25
+ .relations section { margin: .4rem 0; }
26
+ .relations h2 { font-size: inherit; margin: 0; }
27
+ .relations ul { margin: .15rem 0; padding-left: 1.25rem; }
22
28
  article img { height: auto; max-width: 100%; }
23
- article pre { overflow-x: auto; padding: 1rem; background: #25231f; color: #f9f3e8; }
29
+ article pre { overflow-x: auto; padding: .75rem; border: 1px solid var(--border); border-radius: .5rem; background: var(--tint); }
30
+ article table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
31
+ article th, article td { border: 1px solid var(--border); text-align: start; padding: .35rem .6rem; }
32
+ article th { background: var(--tint); }
33
+ article blockquote { margin-inline: 0; padding-inline: 1rem; border-inline-start: 3px solid var(--border); color: var(--muted); }
24
34
  article code { font-family: "SFMono-Regular", Consolas, monospace; }
25
- @media (prefers-color-scheme: dark) {
26
- body { background: #1d1b18; color: #eee7db; }
27
- header { border-color: #4b453c; }
28
- a { color: #ef9b7c; }
29
- .eyebrow { color: #aaa195; }
30
- .relation-card { background: #292620; border-color: #514a40; }
31
- }
32
35
  `;
33
36
 
34
37
  export class FlowmatterError extends Error {
@@ -100,6 +103,49 @@ function describeModule(value, relativePath) {
100
103
  return { id: id.trim(), name: name.trim(), ...(value.type ? { type: value.type.trim() } : {}) };
101
104
  }
102
105
 
106
+ function mergeTypes(types, source, fieldName) {
107
+ const { relativePath } = source;
108
+ const relationTypes = source[fieldName];
109
+ const modules = fieldName === 'moduleTypes';
110
+ if (relationTypes === undefined) return;
111
+ const isMapping = (value) => isObject(value) && Object.getPrototypeOf(value) === Object.prototype;
112
+ const invalid = (message) => {
113
+ throw new FlowmatterError(`${relativePath}: ${message}`, { code: modules ? 'invalid_module_types' : 'invalid_relation_types', path: relativePath });
114
+ };
115
+ const list = Array.isArray(relationTypes);
116
+ if (!list && !isMapping(relationTypes)) invalid(`${fieldName} must be a mapping or a list of definitions`);
117
+
118
+ for (const [index, definition] of Object.entries(relationTypes)) {
119
+ const location = `${fieldName}[${list ? index : JSON.stringify(index)}]`;
120
+ if (!isMapping(definition)) invalid(`${location} must be an object`);
121
+ const key = list ? definition.id : index;
122
+ if (!isNonEmptyString(key) || key !== key.trim()) invalid(`${location}${list ? '.id' : ''} needs a non-empty ID without surrounding whitespace`);
123
+ if (!types.has(key)) types.set(key, { style: {}, sources: new Map() });
124
+ const { style, sources } = types.get(key);
125
+ for (const [field, value] of Object.entries(definition)) {
126
+ if (list && field === "id") continue;
127
+ if (field === "label" || (!modules && field === "hint")) {
128
+ if (!isNonEmptyString(value)) invalid(`${location}.${field} must be a non-empty string`);
129
+ } else if ((modules ? ['accent','surface','headerBg','headerFg','footerFg'] : ['color','previewColor']).includes(field)) {
130
+ if (typeof value !== "string" || !/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(value)) {
131
+ invalid(`${location}.${field} must be a hex color with 3, 4, 6, or 8 digits`);
132
+ }
133
+ } else {
134
+ invalid(`${location}.${field} is not a supported property`);
135
+ }
136
+ if (sources.has(field) && style[field] !== value) {
137
+ throw new FlowmatterError(`${relativePath}: ${location}.${field} (${key}) conflicts with the declaration in ${sources.get(field)}`, {
138
+ code: modules ? 'conflicting_module_type' : 'conflicting_relation_type', path: relativePath,
139
+ });
140
+ }
141
+ if (!sources.has(field)) {
142
+ style[field] = value;
143
+ sources.set(field, relativePath);
144
+ }
145
+ }
146
+ }
147
+ }
148
+
103
149
  function parseRelations(value, relativePath) {
104
150
  if (value === undefined) return [];
105
151
  if (!Array.isArray(value)) {
@@ -133,11 +179,63 @@ function parseRelations(value, relativePath) {
133
179
  ...(relation.id ? { id: relation.id.trim() } : {}),
134
180
  to: relation.to.trim(),
135
181
  type: relation.type.trim(),
182
+ ...(relation.viewUrl !== undefined ? { viewPath: relation.viewUrl } : {}),
136
183
  ...(relation.relationType ? { relationType: relation.relationType.trim() } : {}),
137
184
  };
138
185
  });
139
186
  }
140
187
 
188
+ function pageUrl(relativePath) {
189
+ return `./${relativePath.split("/").map(encodeURIComponent).join("/")}`;
190
+ }
191
+
192
+ function resolveRelationViews(sources) {
193
+ const bySource = new Map(sources.map(source => [source.relativePath, source]));
194
+ const byPage = new Map();
195
+ for (const source of sources) {
196
+ if (source.config) continue;
197
+ const page = source.outputRelativePath;
198
+ if (byPage.has(page)) {
199
+ throw new FlowmatterError(`${source.relativePath} and ${byPage.get(page).relativePath} both render to ${page}`, {
200
+ code: "output_collision", path: source.relativePath,
201
+ });
202
+ }
203
+ byPage.set(page, source);
204
+ }
205
+ for (const [page, source] of byPage) {
206
+ for (let dir = path.posix.dirname(page); dir !== "."; dir = path.posix.dirname(dir)) {
207
+ if (byPage.has(dir)) throw new FlowmatterError(`${source.relativePath}: output directory ${dir} conflicts with the page for ${byPage.get(dir).relativePath}`, {
208
+ code: "output_collision", path: source.relativePath,
209
+ });
210
+ }
211
+ function resolveView(ref, field, code) {
212
+ if (ref === undefined) return;
213
+ const fail = message => {
214
+ throw new FlowmatterError(`${source.relativePath}: ${field} ${message}`, {
215
+ code, path: source.relativePath,
216
+ });
217
+ };
218
+ if (!isNonEmptyString(ref) || ref.startsWith("/") || /[\\:\x00-\x1f]/.test(ref) || !/\.(?:[mM][dD]|html)$/.test(ref)) {
219
+ fail("must be a local relative .md path or generated .html path");
220
+ }
221
+ const key = path.posix.join(path.posix.dirname(source.relativePath), ref);
222
+ if (key.startsWith("../")) fail(`points outside the input root: ${ref}`);
223
+ const target = /\.md$/i.test(ref) ? bySource.get(key) : byPage.get(key);
224
+ if (!target) fail(`does not match a page in the selected inputs: ${ref}`);
225
+ if (target.config) fail(`references a configuration file: ${ref}`);
226
+ if (/[\\:\x00-\x1f]/.test(target.outputRelativePath)) fail(`references a path Flowjob cannot display: ${key}`);
227
+ if (!target.explicitGraph) target.pageOnly = true;
228
+ return pageUrl(target.outputRelativePath);
229
+ }
230
+ if (source.moduleViewPath !== undefined) {
231
+ source.module.viewUrl = resolveView(source.moduleViewPath, 'module.viewUrl', 'invalid_module_view_url');
232
+ }
233
+ source.relations.forEach((relation, index) => {
234
+ if (relation.viewPath !== undefined) relation.viewUrl = resolveView(relation.viewPath, `relations[${index}].viewUrl`, 'invalid_relation_view_url');
235
+ });
236
+ }
237
+ }
238
+
141
239
  async function pathExists(filePath) {
142
240
  try {
143
241
  await access(filePath);
@@ -167,17 +265,32 @@ async function resolveInput(input, cwd) {
167
265
  return { baseDir, files };
168
266
  }
169
267
 
170
- async function readDocuments(input, cwd) {
171
- const { baseDir, files } = await resolveInput(input, cwd);
172
- const markdownFiles = [...new Set(files.map((file) => path.resolve(file)))]
173
- .filter((file) => /\.md$/i.test(file))
174
- .sort((left, right) => left.localeCompare(right));
175
-
176
- if (markdownFiles.length === 0) {
177
- throw new FlowmatterError(`No Markdown files matched "${input}"`, { code: "no_markdown_files", path: input });
268
+ export async function resolveMarkdownInputs(input, cwd) {
269
+ const inputs = Array.isArray(input) ? input : [input];
270
+ if (!inputs.length || !inputs.every(isNonEmptyString)) throw new FlowmatterError("One or more Markdown paths or globs are required");
271
+ const files = new Set();
272
+ let baseDir;
273
+ for (const spec of new Set(inputs)) {
274
+ const resolved = await resolveInput(spec, cwd);
275
+ const matches = resolved.files.filter((file) => /\.md$/i.test(file));
276
+ if (!matches.length) throw new FlowmatterError(`No Markdown files matched "${spec}"`, { code: "no_markdown_files", path: spec });
277
+ for (const file of matches) files.add(path.resolve(file));
278
+ baseDir ??= resolved.baseDir;
279
+ if (path.parse(baseDir).root !== path.parse(resolved.baseDir).root) throw new FlowmatterError("Inputs must share a filesystem root");
280
+ while (true) {
281
+ const relative = path.relative(baseDir, resolved.baseDir);
282
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`)) break;
283
+ baseDir = path.dirname(baseDir);
284
+ }
178
285
  }
286
+ const markdownFiles = [...files].sort((left, right) => left.localeCompare(right));
287
+ return {baseDir, markdownFiles};
288
+ }
179
289
 
180
- const documents = await Promise.all(markdownFiles.map(async (sourcePath) => {
290
+ async function readDocuments(input, cwd, resolvedInputs) {
291
+ const {baseDir, markdownFiles} = resolvedInputs ?? await resolveMarkdownInputs(input, cwd);
292
+
293
+ const sources = await Promise.all(markdownFiles.map(async (sourcePath) => {
181
294
  const relativePath = toPosix(path.relative(baseDir, sourcePath));
182
295
  if (relativePath === ".." || relativePath.startsWith("../")) {
183
296
  throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`, {
@@ -203,6 +316,8 @@ async function readDocuments(input, cwd) {
203
316
  });
204
317
  }
205
318
 
319
+ if (parsed.data.flowmatter === "config") return { config: true, relativePath, relationTypes: parsed.data.relationTypes, moduleTypes: parsed.data.moduleTypes };
320
+
206
321
  const fallbackId = relativePath.replace(/\.md$/i, "");
207
322
  const id = parsed.data.id ?? fallbackId;
208
323
  const title = parsed.data.title ?? titleFromContent(parsed.content, path.posix.basename(fallbackId));
@@ -221,8 +336,12 @@ async function readDocuments(input, cwd) {
221
336
 
222
337
  return {
223
338
  id: id.trim(),
339
+ explicitGraph: ["id", "title", "module", "relations", "relationTypes", "moduleTypes"].some(key => Object.hasOwn(parsed.data, key)),
224
340
  title: title.trim(),
225
341
  module: describeModule(parsed.data.module, relativePath),
342
+ moduleViewPath: parsed.data.module?.viewUrl,
343
+ relationTypes: parsed.data.relationTypes,
344
+ moduleTypes: parsed.data.moduleTypes,
226
345
  relations: parseRelations(parsed.data.relations, relativePath),
227
346
  content: parsed.content,
228
347
  sourcePath,
@@ -230,15 +349,25 @@ async function readDocuments(input, cwd) {
230
349
  outputRelativePath: relativePath.replace(/\.md$/i, ".html"),
231
350
  };
232
351
  }));
233
- return { baseDir, documents };
352
+ const relationTypes = new Map();
353
+ const moduleTypes = new Map();
354
+ for (const source of sources) {
355
+ mergeTypes(relationTypes, source, 'relationTypes');
356
+ mergeTypes(moduleTypes, source, 'moduleTypes');
357
+ }
358
+ const documents = sources.filter((source) => !source.config);
359
+ resolveRelationViews(sources);
360
+ if (!documents.length) throw new FlowmatterError("Inputs contain only configuration; at least one document is required", { code: "no_documents" });
361
+ return { baseDir, documents, relationTypes, moduleTypes };
234
362
  }
235
363
 
236
- function compile(documents, title) {
364
+ function compile(documents, title, relationTypes, moduleTypes) {
237
365
  const byId = new Map();
238
366
  const modules = new Map();
239
367
  const flowIds = new Map();
240
368
 
241
- for (const document of documents) {
369
+ const graphDocuments = documents.filter(document => !document.pageOnly);
370
+ for (const document of graphDocuments) {
242
371
  if (byId.has(document.id)) {
243
372
  throw new FlowmatterError(
244
373
  `${document.relativePath}: duplicate document id "${document.id}" (also used by ${byId.get(document.id).relativePath})`,
@@ -250,6 +379,7 @@ function compile(documents, title) {
250
379
  const existing = modules.get(document.module.id);
251
380
  if (existing && (
252
381
  existing.name !== document.module.name
382
+ || (existing.viewUrl && document.module.viewUrl && existing.viewUrl !== document.module.viewUrl)
253
383
  || (existing.type && document.module.type && existing.type !== document.module.type)
254
384
  )) {
255
385
  throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`, {
@@ -259,11 +389,12 @@ function compile(documents, title) {
259
389
  }
260
390
  if (!existing) modules.set(document.module.id, { ...document.module, submodules: [] });
261
391
  if (existing && !existing.type && document.module.type) existing.type = document.module.type;
262
- modules.get(document.module.id).submodules.push({ id: document.id, name: document.title });
392
+ if (existing && !existing.viewUrl && document.module.viewUrl) existing.viewUrl = document.module.viewUrl;
393
+ modules.get(document.module.id).submodules.push({ id: document.id, name: document.title, viewUrl: pageUrl(document.outputRelativePath) });
263
394
  }
264
395
 
265
396
  const flows = [];
266
- for (const document of documents) {
397
+ for (const document of graphDocuments) {
267
398
  document.relations.forEach((relation, index) => {
268
399
  const target = byId.get(relation.to);
269
400
  if (!target) {
@@ -283,6 +414,7 @@ function compile(documents, title) {
283
414
  flows.push({
284
415
  id,
285
416
  type: relation.type,
417
+ ...(relation.viewUrl ? { viewUrl: relation.viewUrl } : {}),
286
418
  ...(relation.relationType ? { relationType: relation.relationType } : {}),
287
419
  from: { module: document.module.id, submodule: document.id },
288
420
  to: { module: target.module.id, submodule: target.id },
@@ -294,6 +426,8 @@ function compile(documents, title) {
294
426
  schemaVersion: 1,
295
427
  title,
296
428
  modules: [...modules.values()],
429
+ ...(moduleTypes.size ? { moduleTypes: Object.fromEntries([...moduleTypes].map(([key,{style}])=>[key,style])) } : {}),
430
+ ...(relationTypes.size ? { relationTypes: Object.fromEntries([...relationTypes].map(([key, { style }]) => [key, style])) } : {}),
297
431
  flows,
298
432
  };
299
433
  const validation = validateFlow(flow);
@@ -306,13 +440,12 @@ function compile(documents, title) {
306
440
 
307
441
  export async function validateSite({ input, title, cwd = process.cwd() } = {}) {
308
442
  try {
309
- if (!isNonEmptyString(input)) throw new FlowmatterError("A folder or glob input is required");
310
443
  if (title !== undefined && !isNonEmptyString(title)) {
311
444
  throw new FlowmatterError("The title must be a non-empty string");
312
445
  }
313
- const { baseDir, documents } = await readDocuments(input, path.resolve(cwd));
446
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd));
314
447
  const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
315
- const { flow } = compile(documents, siteTitle);
448
+ const { flow } = compile(documents, siteTitle, relationTypes, moduleTypes);
316
449
  return {
317
450
  valid: true,
318
451
  errors: [],
@@ -357,22 +490,24 @@ function renderRelationList(title, relations, currentOutputPath) {
357
490
  return `<section class="relation-card"><h2>${escapeHtml(title)}</h2><ul>${items}</ul></section>`;
358
491
  }
359
492
 
360
- function renderPage(document, documents, byId, flowPath) {
493
+ function renderPage(document, documents, byId) {
361
494
  const outgoing = document.relations.map((relation) => ({ document: byId.get(relation.to), type: relation.type }));
362
- const incoming = documents.flatMap((candidate) => candidate.relations
495
+ const incoming = document.pageOnly ? [] : documents.flatMap((candidate) => candidate.relations
363
496
  .filter((relation) => relation.to === document.id)
364
497
  .map((relation) => ({ document: candidate, type: relation.type })));
365
498
 
366
499
  const sourceToOutput = new Map(documents.map((candidate) => [candidate.sourcePath, candidate.outputPath]));
367
- const body = marked.parse(document.content, {
368
- walkTokens(token) {
500
+ const tokens = marked.lexer(document.content);
501
+ const first = tokens.find(token => token.type !== "space");
502
+ const hasTitle = first?.type === "heading" && first.depth === 1;
503
+ marked.walkTokens(tokens, token => {
369
504
  if (token.type !== "link" || !isNonEmptyString(token.href)) return;
370
505
  const match = token.href.match(/^([^?#]+\.md)([?#].*)?$/i);
371
506
  if (!match || path.isAbsolute(match[1])) return;
372
507
  const targetOutput = sourceToOutput.get(path.resolve(path.dirname(document.sourcePath), match[1]));
373
508
  if (targetOutput) token.href = `${relativeHref(document.outputPath, targetOutput)}${match[2] ?? ""}`;
374
- },
375
509
  });
510
+ const body = marked.parser(tokens);
376
511
  const relations = [
377
512
  renderRelationList("Leads to", outgoing, document.outputPath),
378
513
  renderRelationList("Reached from", incoming, document.outputPath),
@@ -389,26 +524,24 @@ function renderPage(document, documents, byId, flowPath) {
389
524
  <body>
390
525
  <main>
391
526
  <header>
392
- <div class="eyebrow">${escapeHtml(document.module.name)} · <a href="${escapeHtml(relativeHref(document.outputPath, flowPath))}">Open flow</a></div>
393
- <h1>${escapeHtml(document.title)}</h1>
527
+ <div class="eyebrow">${escapeHtml(document.module.name)}</div>
394
528
  </header>
395
- ${relations ? `<aside class="relations" aria-label="Relations">${relations}</aside>` : ""}
396
- <article>${body}</article>
529
+ <article>${hasTitle ? "" : `<h1>${escapeHtml(document.title)}</h1>`}${body}</article>
530
+ ${relations ? `<footer class="relations" aria-label="Relations">${relations}</footer>` : ""}
397
531
  </main>
398
532
  </body>
399
533
  </html>
400
534
  `;
401
535
  }
402
536
 
403
- export async function buildSite({
537
+ export async function renderSite({
404
538
  input,
539
+ resolvedInputs,
405
540
  outputDir = "flowmatter-dist",
406
541
  flowFile = "flow.html",
407
542
  title,
408
- force = false,
409
543
  cwd = process.cwd(),
410
544
  } = {}) {
411
- if (!isNonEmptyString(input)) throw new FlowmatterError("A folder or glob input is required");
412
545
  if (!isNonEmptyString(outputDir)) throw new FlowmatterError("The output directory must be a non-empty string");
413
546
  if (!isNonEmptyString(flowFile) || path.basename(flowFile) !== flowFile || !/\.html?$/i.test(flowFile)) {
414
547
  throw new FlowmatterError("The flow filename must be an HTML filename without a directory");
@@ -417,27 +550,34 @@ export async function buildSite({
417
550
  throw new FlowmatterError("The title must be a non-empty string");
418
551
  }
419
552
 
420
- const { baseDir, documents } = await readDocuments(input, path.resolve(cwd));
553
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd), resolvedInputs);
421
554
  const outputRoot = path.resolve(cwd, outputDir);
422
555
  const flowPath = path.join(outputRoot, flowFile);
423
556
  for (const document of documents) {
424
557
  document.outputPath = path.join(outputRoot, document.outputRelativePath);
425
- if (path.resolve(document.outputPath) === path.resolve(flowPath)) {
426
- throw new FlowmatterError(`${document.relativePath}: rendered page conflicts with ${flowFile}`);
558
+ if (document.outputRelativePath === flowFile || document.outputRelativePath.startsWith(`${flowFile}/`)) {
559
+ throw new FlowmatterError(`${document.relativePath}: rendered page conflicts with ${flowFile}`, {
560
+ code: "output_collision", path: document.relativePath,
561
+ });
427
562
  }
428
563
  }
429
564
 
430
565
  const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
431
- const { byId, flow } = compile(documents, siteTitle);
566
+ const { byId, flow } = compile(documents, siteTitle, relationTypes, moduleTypes);
432
567
  const outputs = [
433
568
  { path: flowPath, content: buildFlow(flow, { title: siteTitle }) },
434
569
  ...documents.map((document) => ({
435
570
  path: document.outputPath,
436
- content: renderPage(document, documents, byId, flowPath),
571
+ content: renderPage(document, documents, byId),
437
572
  })),
438
573
  ];
439
574
 
440
- if (!force) {
575
+ return {flow, flowPath, outputDir: outputRoot, pageCount: documents.length, pages: documents.map(document => document.outputPath), outputs};
576
+ }
577
+
578
+ export async function buildSite(options = {}) {
579
+ const {outputs, ...result} = await renderSite(options);
580
+ if (!options.force) {
441
581
  for (const output of outputs) {
442
582
  if (await pathExists(output.path)) {
443
583
  throw new FlowmatterError(`${output.path} already exists; use --force to overwrite generated files`);
@@ -450,11 +590,5 @@ export async function buildSite({
450
590
  await writeFile(output.path, output.content, "utf8");
451
591
  }
452
592
 
453
- return {
454
- flow,
455
- flowPath,
456
- outputDir: outputRoot,
457
- pageCount: documents.length,
458
- pages: documents.map((document) => document.outputPath),
459
- };
593
+ return result;
460
594
  }
package/src/serve.mjs ADDED
@@ -0,0 +1,58 @@
1
+ import http from 'node:http';
2
+ import path from 'node:path';
3
+ import {stat} from 'node:fs/promises';
4
+ import {renderSite, resolveMarkdownInputs} from './index.mjs';
5
+
6
+ // Re-resolve the input set on every poll so atomic saves, additions, and removals
7
+ // work for globs as well as directories on bind-mounted filesystems.
8
+ export async function serveSite({input, cwd = process.cwd(), title, flowFile = 'flow.html', port = 4173,
9
+ interval = 500, log = console.error}) {
10
+ async function fingerprint({markdownFiles}) {
11
+ return JSON.stringify(await Promise.all(markdownFiles.map(async file => {
12
+ const s = await stat(file, {bigint:true});
13
+ return [file, String(s.ino), String(s.size), String(s.ctimeNs), String(s.mtimeNs)];
14
+ })));
15
+ }
16
+ async function render(resolvedInputs) {
17
+ const site = await renderSite({resolvedInputs,cwd,title,flowFile});
18
+ return new Map(site.outputs.map(({path:file,content}) => ['/' + path.relative(site.outputDir,file).split(path.sep).join('/'),content]));
19
+ }
20
+ // The fingerprint and rendered pages must describe the same set of files.
21
+ const initial = await resolveMarkdownInputs(input, cwd);
22
+ let seen = await fingerprint(initial), pages = await render(initial), stopped = false, timer, lastError;
23
+ async function poll() {
24
+ try {
25
+ const inputs = await resolveMarkdownInputs(input, cwd);
26
+ const next = await fingerprint(inputs);
27
+ if (next !== seen) {
28
+ seen = next;
29
+ pages = await render(inputs); // Publish the entire new generation together.
30
+ log(`Rebuilt ${pages.size - 1} pages`);
31
+ }
32
+ lastError = undefined;
33
+ } catch (error) {
34
+ if (lastError !== error.message) log(`Preview rebuild failed: ${error.message}`);
35
+ lastError = error.message;
36
+ } finally {
37
+ if (!stopped) timer = setTimeout(poll,interval);
38
+ }
39
+ }
40
+ const server = http.createServer((req,res) => {
41
+ if (!['GET','HEAD'].includes(req.method)) {res.writeHead(405,{Allow:'GET, HEAD'}).end(); return;}
42
+ let key;
43
+ try {key = decodeURIComponent(req.url.split('?')[0]);} catch {res.writeHead(400).end(); return;}
44
+ const page = pages.get(key === '/' ? '/' + flowFile : key);
45
+ if (page === undefined) {res.writeHead(404).end(); return;}
46
+ res.writeHead(200,{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'});
47
+ res.end(req.method === 'HEAD' ? undefined : page);
48
+ });
49
+ await new Promise((resolve,reject) => {
50
+ server.once('error',reject);
51
+ server.listen(port,'127.0.0.1',resolve);
52
+ });
53
+ timer = setTimeout(poll,interval);
54
+ return {url:`http://127.0.0.1:${server.address().port}/`, close() {
55
+ stopped = true; clearTimeout(timer);
56
+ return new Promise(resolve => server.close(resolve));
57
+ }};
58
+ }