fragmentor 0.1.0 → 0.2.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 (42) hide show
  1. package/dist/src/api/asset.d.ts +3 -0
  2. package/dist/src/api/asset.js +3 -0
  3. package/dist/src/api/component.d.ts +3 -0
  4. package/dist/src/api/component.js +3 -0
  5. package/dist/src/api/document.d.ts +4 -0
  6. package/dist/src/api/document.js +4 -0
  7. package/dist/src/api/path.d.ts +3 -0
  8. package/dist/src/api/path.js +3 -0
  9. package/dist/src/api/schema.d.ts +3 -0
  10. package/dist/src/api/schema.js +3 -0
  11. package/dist/src/build/compile/directives.d.ts +11 -6
  12. package/dist/src/build/compile/directives.js +16 -15
  13. package/dist/src/build/compile/index.d.ts +4 -1
  14. package/dist/src/build/compile/index.js +33 -7
  15. package/dist/src/build/compile/memo.d.ts +44 -0
  16. package/dist/src/build/compile/memo.js +73 -0
  17. package/dist/src/build/compile/render.d.ts +5 -1
  18. package/dist/src/build/compile/render.js +22 -2
  19. package/dist/src/build/lint/index.js +2 -2
  20. package/dist/src/build/resolve/index.d.ts +15 -1
  21. package/dist/src/build/resolve/index.js +33 -9
  22. package/dist/src/build/source/index.d.ts +1 -1
  23. package/dist/src/build/source/index.js +1 -1
  24. package/dist/src/build/validate/document.js +12 -3
  25. package/dist/src/build/validate/schema.js +25 -6
  26. package/dist/src/cli/build.js +4 -3
  27. package/dist/src/cli/color.d.ts +9 -0
  28. package/dist/src/cli/color.js +12 -0
  29. package/dist/src/cli/dev.js +66 -22
  30. package/dist/src/cli/fs.d.ts +8 -1
  31. package/dist/src/cli/fs.js +25 -3
  32. package/dist/src/cli/index.js +2 -1
  33. package/dist/src/cli/pull.js +2 -1
  34. package/dist/src/cli/push.js +2 -1
  35. package/dist/src/cli/target.js +2 -1
  36. package/dist/src/index.d.ts +10 -3
  37. package/dist/src/index.js +13 -6
  38. package/dist/src/utils/expression.d.ts +6 -0
  39. package/dist/src/utils/expression.js +44 -3
  40. package/dist/src/utils/path.d.ts +4 -4
  41. package/dist/src/utils/path.js +4 -4
  42. package/package.json +2 -2
@@ -75,7 +75,14 @@ export function validateProp({ value, field, schemas, reset = false, depth = 0,
75
75
  /* A missing nullable field is off: `write` deletes a key set to null, so this is how a toggled-off field reads back */
76
76
  if (value === undefined)
77
77
  return field.nullable ? null : def_;
78
- /* An out-of-range min/max is kept when errors are collected (a draft the editor warns about), only strict checks like compile reject it */
78
+ /* An out-of-range min/max is kept when errors are collected (a draft the editor warns about, a build that reports it and fails), only a strict read (a write) throws */
79
+ const sized = (list, min, max) => {
80
+ if (min !== undefined && list.length < min)
81
+ return fail(`List length ${list.length} is below minimum ${min}`, list);
82
+ if (max !== undefined && list.length > max)
83
+ return fail(`List length ${list.length} exceeds maximum ${max}`, list);
84
+ return list;
85
+ };
79
86
  if (field.type === "string" || field.type === "email") {
80
87
  if (typeof value !== "string")
81
88
  return fail(`Expected string, got ${typeof value}`, def_);
@@ -116,11 +123,12 @@ export function validateProp({ value, field, schemas, reset = false, depth = 0,
116
123
  else if (field.type === "references") {
117
124
  if (!Array.isArray(value))
118
125
  return fail(`Expected array for references field, got ${typeof value}`, def_);
119
- return value.flatMap((item, i) => {
126
+ const refs = value.flatMap((item, i) => {
120
127
  if (!isReference(item))
121
128
  return fail(`Expected a reference ({ _ref: string }) in references array, got ${kind(item)}`, [], [...path, String(i)]);
122
129
  return [{ _ref: item._ref }];
123
130
  });
131
+ return sized(refs, field.min, field.max);
124
132
  }
125
133
  else if (field.type === "date" || field.type === "datetime") {
126
134
  if (typeof value !== "string")
@@ -149,7 +157,8 @@ export function validateProp({ value, field, schemas, reset = false, depth = 0,
149
157
  else if (field.type === "fragments" || field.type === "richtext" || field.type === "text") {
150
158
  if (!Array.isArray(value))
151
159
  return fail(`Expected array for ${field.type}, got ${typeof value}`, def_);
152
- return value.flatMap((item, i) => fragment(item, [...path, String(i)], `in ${field.type} array`, [], (result) => [result]));
160
+ const list = value.flatMap((item, i) => fragment(item, [...path, String(i)], `in ${field.type} array`, [], (result) => [result]));
161
+ return (field.type === "text" ? list : sized(list, field.min, field.max));
153
162
  }
154
163
  return fail(`Unknown field type "${field.type}"`, def_);
155
164
  }
@@ -2,6 +2,7 @@ import { EmailSchema, FieldSchema, isFragment, isFragments, isReserved, Identifi
2
2
  import { error, warning } from "../../utils/report.js";
3
3
  import { empty } from "../../model/schema.js";
4
4
  import { rejects } from "./document.js";
5
+ import { DEFAULT_MAX_REFERENCES } from "../resolve/index.js";
5
6
  /**
6
7
  * Validates a single field value considering all schemas.
7
8
  * @param field The field to validate.
@@ -27,14 +28,19 @@ export function validateField({ field, path = [], errors, warnings }) {
27
28
  return field;
28
29
  field.default = fail(`Field default can only be null when the field is nullable`, empty(field));
29
30
  }
31
+ /* `complete` fills such a field, when left null, with up to DEFAULT_MAX_REFERENCES documents: on a site-wide fragment that's that many cards on every page */
32
+ if (field.type === "references" && !field.nullable && field.max === undefined) {
33
+ const at = path.length ? `${path.join(".")}: ` : "";
34
+ warning(`${at}Left empty, this references field is filled with up to ${DEFAULT_MAX_REFERENCES} matching documents. Set a max to choose how many, or nullable`, null, warnings);
35
+ }
30
36
  if ("min" in field && "max" in field && field.min !== undefined && field.max !== undefined && field.min > field.max) {
31
37
  field.min = fail(`Field min ${field.min} is greater than max ${field.max}`, field.max);
32
38
  }
33
39
  if (field.type === "string") {
34
- if (field.min && field.default.length < field.min) {
40
+ if (field.min !== undefined && field.default.length < field.min) {
35
41
  field.default = fail(`Field default length ${field.default.length} is less than min ${field.min}`, field.default.padEnd(field.min, " "));
36
42
  }
37
- if (field.max && field.default.length > field.max) {
43
+ if (field.max !== undefined && field.default.length > field.max) {
38
44
  field.default = fail(`Field default length ${field.default.length} is greater than max ${field.max}`, field.default.substring(0, field.max));
39
45
  }
40
46
  }
@@ -44,10 +50,10 @@ export function validateField({ field, path = [], errors, warnings }) {
44
50
  }
45
51
  }
46
52
  else if (field.type === "number") {
47
- if (field.min && field.default < field.min) {
53
+ if (field.min !== undefined && field.default < field.min) {
48
54
  field.default = fail(`Field default ${field.default} is less than min ${field.min}`, field.min);
49
55
  }
50
- if (field.max && field.default > field.max) {
56
+ if (field.max !== undefined && field.default > field.max) {
51
57
  field.default = fail(`Field default ${field.default} is greater than max ${field.max}`, field.max);
52
58
  }
53
59
  }
@@ -70,14 +76,27 @@ export function validateField({ field, path = [], errors, warnings }) {
70
76
  const first = list.map(reason).find(Boolean);
71
77
  if (first)
72
78
  list = fail(`Field default: ${first}`, list.filter((f) => !reason(f)));
73
- if (field.type === "fragments" && field.min && list.length < field.min) {
79
+ if (field.type === "fragments" && field.min !== undefined && list.length < field.min) {
74
80
  list = fail(`Field default length ${list.length} is less than min ${field.min}`, [...list, ...Array.from({ length: field.min - list.length }, () => ({ _type: field.allow[0] ?? "" }))]);
75
81
  }
76
- if (field.max && list.length > field.max) {
82
+ /* Rich text has no one type to pad with, so a short default is only reported */
83
+ if (field.type === "richtext" && field.min !== undefined && list.length < field.min) {
84
+ list = fail(`Field default length ${list.length} is less than min ${field.min}`, list);
85
+ }
86
+ if (field.max !== undefined && list.length > field.max) {
77
87
  list = fail(`Field default length ${list.length} is greater than max ${field.max}`, list.slice(0, field.max));
78
88
  }
79
89
  field.default = list;
80
90
  }
91
+ else if (field.type === "references" && field.default) {
92
+ /* A short default is only reported: there's no id to pad it with */
93
+ if (field.min !== undefined && field.default.length < field.min) {
94
+ field.default = fail(`Field default length ${field.default.length} is less than min ${field.min}`, field.default);
95
+ }
96
+ if (field.max !== undefined && field.default.length > field.max) {
97
+ field.default = fail(`Field default length ${field.default.length} is greater than max ${field.max}`, field.default.slice(0, field.max));
98
+ }
99
+ }
81
100
  return field;
82
101
  }
83
102
  export function validateFields({ fields, errors, warnings }) {
@@ -4,6 +4,7 @@ import { compile } from "../build/compile/index.js";
4
4
  import { optimize } from "../build/optimize/index.js";
5
5
  import { plural } from "../utils/text.js";
6
6
  import { asset, flags, read, write } from "./fs.js";
7
+ import { error, warn } from "./color.js";
7
8
  export async function run(args) {
8
9
  const opts = flags(args);
9
10
  if (opts["help"]) {
@@ -25,16 +26,16 @@ export async function run(args) {
25
26
  const published = new Date();
26
27
  const { output, errors, warnings } = compile(sources, { parse, url, published });
27
28
  for (const w of warnings)
28
- console.warn(` warning: ${w.path}: ${w.message}`);
29
+ warn(` warning: ${w.path}: ${w.message}`);
29
30
  for (const e of errors)
30
- console.error(` error: ${e.path}: ${e.message}`);
31
+ error(` error: ${e.path}: ${e.message}`);
31
32
  /* Binary assets have null data, their bytes are copied from /assets/ */
32
33
  const bytes = asset(root);
33
34
  if (!noOptimize) {
34
35
  const files = Object.fromEntries(output.map((s) => [s.path, s.data]));
35
36
  const { files: optimized, warnings: optWarnings } = await optimize(files, { parse, read: async (path) => bytes(path) });
36
37
  for (const w of optWarnings)
37
- console.warn(` warning: ${w}`);
38
+ warn(` warning: ${w}`);
38
39
  write(Object.entries(optimized).map(([path, data]) => ({ path, data })), outDir, bytes);
39
40
  }
40
41
  else {
@@ -0,0 +1,9 @@
1
+ /** Text in red, for stderr. */
2
+ export declare const red: (text: string) => string;
3
+ /** Text in orange (256-color 208, which terminals without it show as their closest color), for stderr. */
4
+ export declare const orange: (text: string) => string;
5
+ /** Prints an error in red. */
6
+ export declare const error: (message: string) => void;
7
+ /** Prints a warning in orange. */
8
+ export declare const warn: (message: string) => void;
9
+ //# sourceMappingURL=color.d.ts.map
@@ -0,0 +1,12 @@
1
+ /* Colors for the CLI's problems: errors red, warnings orange. Only on a terminal, and never with NO_COLOR set (https://no-color.org) */
2
+ const enabled = (stream) => Boolean(stream.isTTY) && !process.env["NO_COLOR"];
3
+ const paint = (code, text, stream) => (enabled(stream) ? `\x1b[${code}m${text}\x1b[0m` : text);
4
+ /** Text in red, for stderr. */
5
+ export const red = (text) => paint("31", text, process.stderr);
6
+ /** Text in orange (256-color 208, which terminals without it show as their closest color), for stderr. */
7
+ export const orange = (text) => paint("38;5;208", text, process.stderr);
8
+ /** Prints an error in red. */
9
+ export const error = (message) => console.error(red(message));
10
+ /** Prints a warning in orange. */
11
+ export const warn = (message) => console.warn(orange(message));
12
+ //# sourceMappingURL=color.js.map
@@ -7,6 +7,21 @@ import { parse as parsePath } from "../utils/path.js";
7
7
  import { MIME } from "../utils/mime.js";
8
8
  import { plural } from "../utils/text.js";
9
9
  import { FOLDERS, asset, flags, read } from "./fs.js";
10
+ import { error, warn } from "./color.js";
11
+ /* Answers the number of the current build, which every served page polls to reload once it changes */
12
+ const BUILD = "/__fragmentor/build";
13
+ /* How long to wait for more file events before rebuilding, so one save (often a write, a rename and a change) rebuilds once */
14
+ const SETTLE = 30;
15
+ /*
16
+ * Polls instead of holding an EventSource open: each open stream takes one of the browser's 6 connections per host, so a few tabs stalled navigation.
17
+ * Hidden tabs don't poll, and catch up as soon as they're shown again.
18
+ */
19
+ const reloader = (build) => `<script>(()=>{const c=()=>{if(!document.hidden)fetch("${BUILD}",{cache:"no-store"}).then(r=>r.text()).then(b=>{if(b!=="${build}")location.reload()},()=>{})};setInterval(c,1000);document.addEventListener("visibilitychange",c)})()</script>`;
20
+ /** Adds the live reload script to a page, before `</body>` (or at the end, for a page without one). */
21
+ function inject(html, build) {
22
+ const at = html.lastIndexOf("</body>");
23
+ return at === -1 ? html + reloader(build) : html.slice(0, at) + reloader(build) + html.slice(at);
24
+ }
10
25
  export async function run(args) {
11
26
  const opts = flags(args);
12
27
  if (opts["help"]) {
@@ -23,58 +38,87 @@ export async function run(args) {
23
38
  const host = opts["host"] ?? "localhost";
24
39
  const parse = (html) => parseHTML(html).document;
25
40
  const bytes = asset(root);
26
- let output = [];
41
+ const cache = new Map();
42
+ let output = new Map();
43
+ let build = 0;
44
+ let sources = [];
45
+ /* The problems last printed, so a rebuild only prints them again when they change */
46
+ let reported = "";
47
+ /** Recompiles when a file changed since the last build (an editor touching a file without changing it doesn't count), and bumps `build` so open pages reload. */
27
48
  function rebuild() {
28
49
  try {
29
- const sources = read(root);
50
+ const next = read(root, cache);
51
+ if (build && next.length === sources.length && next.every((s, i) => s === sources[i]))
52
+ return;
53
+ sources = next;
30
54
  const result = compile(sources, { parse, dev: true });
31
- output = result.output;
32
- for (const e of result.errors)
33
- console.error(` error: ${e.path}: ${e.message}`);
34
- for (const w of result.warnings)
35
- console.warn(` warning: ${w.path}: ${w.message}`);
36
- console.log(` rebuilt (${plural(output.filter((s) => s.path.endsWith(".html")).length, "page")})`);
55
+ output = new Map(result.output.map((s) => [s.path, s]));
56
+ build++;
57
+ const errors = result.errors.map((e) => ` error: ${e.path}: ${e.message}`);
58
+ const warnings = result.warnings.map((w) => ` warning: ${w.path}: ${w.message}`);
59
+ const problems = [...errors, ...warnings].join("\n");
60
+ if (problems !== reported) {
61
+ if (!problems)
62
+ console.log(" all problems fixed");
63
+ errors.forEach(error);
64
+ warnings.forEach(warn);
65
+ }
66
+ reported = problems;
37
67
  }
38
68
  catch (e) {
39
- console.error(` build error: ${e.message}`);
69
+ error(` build error: ${e.message}`);
70
+ reported = "";
40
71
  }
41
72
  }
42
73
  rebuild();
43
- /* Watch for changes in all project folders */
74
+ console.log(`Built ${plural([...output.keys()].filter((p) => p.endsWith(".html")).length, "page")}`);
75
+ /* Watch every project folder, rebuilding once the events of a save have settled */
76
+ let timer;
44
77
  for (const folder of FOLDERS) {
45
78
  const dir = join(root, folder);
46
79
  if (!existsSync(dir))
47
80
  continue;
48
81
  watch(dir, { recursive: true }, () => {
49
- process.stdout.write(` change detected, `);
50
- rebuild();
82
+ clearTimeout(timer);
83
+ timer = setTimeout(rebuild, SETTLE);
51
84
  });
52
85
  }
53
86
  const server = createServer((req, res) => {
54
87
  let path = new URL(req.url ?? "/", `http://localhost`).pathname;
88
+ if (path === BUILD) {
89
+ res.writeHead(200, { "Content-Type": "text/plain", "Cache-Control": "no-store" });
90
+ res.end(String(build));
91
+ return;
92
+ }
55
93
  if (path.endsWith("/"))
56
94
  path += "index.html";
57
- const file = output.find((s) => s.path === path);
95
+ /* A page's route has no trailing slash ("/about", its `_slug`), but is built at "/about/index.html" */
96
+ const file = output.get(path) ?? output.get(`${path}/index.html`);
58
97
  if (file) {
59
98
  try {
60
99
  /* A binary asset's bytes are on disk, in /assets/ */
61
- const data = file.data ?? bytes(path);
62
- res.writeHead(200, { "Content-Type": MIME[parsePath(path).extension] ?? "application/octet-stream" });
63
- res.end(data);
100
+ const data = file.data ?? bytes(file.path);
101
+ const extension = parsePath(file.path).extension;
102
+ res.writeHead(200, { "Content-Type": MIME[extension] ?? "application/octet-stream", "Cache-Control": "no-store" });
103
+ res.end(extension === "html" && typeof data === "string" ? inject(data, build) : data);
64
104
  return;
65
105
  }
66
106
  catch {
67
107
  /* Gone since the last build: a 404 */
68
108
  }
69
109
  }
70
- /* 404 page */
71
- const notFound = output.find((s) => s.path === "/404.html");
72
- res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
73
- res.end(notFound?.data ?? "<h1>404 Not Found</h1>");
110
+ /* 404 page, which reloads too, so it turns into the page once that's created */
111
+ const notFound = output.get("/404.html")?.data;
112
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
113
+ res.end(inject(typeof notFound === "string" ? notFound : "<h1>404 Not Found</h1>", build));
114
+ });
115
+ server.on("error", (e) => {
116
+ error(e.code === "EADDRINUSE" ? `Port ${port} is already in use, try another with --port <port>` : `Dev server error: ${e.message}`);
117
+ process.exit(1);
74
118
  });
75
119
  server.listen(port, host, () => {
76
- console.log(`\nDev server running at http://${host}:${port}`);
77
- console.log("Press Ctrl+C to stop.\n");
120
+ console.log(`Dev server running at http://${host}:${port}`);
121
+ console.log("Press Ctrl+C to stop.");
78
122
  });
79
123
  }
80
124
  //# sourceMappingURL=dev.js.map
@@ -1,10 +1,17 @@
1
1
  import type { Source } from "../model/types/index.js";
2
2
  export declare const FOLDERS: string[];
3
+ export type Cache = Map<string, {
4
+ mtime: number;
5
+ size: number;
6
+ source: Source;
7
+ }>;
3
8
  /**
4
9
  * Reads all files in a project `root` into Source objects with the right paths. A file that isn't UTF-8 text (an image, a font, ...)
5
10
  * gets `data: null`, its bytes staying on disk (see `asset`), since decoding it as text would corrupt it.
11
+ * @param cache Reuses the Source of a file whose mtime and size are unchanged, so it isn't read again and is the same object (`dev` compares them to skip
12
+ * rebuilds when nothing changed). Files gone since are dropped from it.
6
13
  */
7
- export declare function read(root: string): Source[];
14
+ export declare function read(root: string, cache?: Cache): Source[];
8
15
  /** Reads the bytes of a project's asset by its output path ("/images/logo.png" is "<root>/assets/images/logo.png"), for a binary file with null `data`. */
9
16
  export declare function asset(root: string): (path: string) => Buffer;
10
17
  /**
@@ -9,20 +9,42 @@ export const FOLDERS = Object.keys(PROJECT);
9
9
  /**
10
10
  * Reads all files in a project `root` into Source objects with the right paths. A file that isn't UTF-8 text (an image, a font, ...)
11
11
  * gets `data: null`, its bytes staying on disk (see `asset`), since decoding it as text would corrupt it.
12
+ * @param cache Reuses the Source of a file whose mtime and size are unchanged, so it isn't read again and is the same object (`dev` compares them to skip
13
+ * rebuilds when nothing changed). Files gone since are dropped from it.
12
14
  */
13
- export function read(root) {
15
+ export function read(root, cache) {
14
16
  const out = [];
17
+ const seen = new Set();
15
18
  for (const folder of FOLDERS) {
16
19
  const dir = join(root, folder);
17
20
  if (!existsSync(dir))
18
21
  continue;
19
22
  for (const file of walk(dir)) {
20
- const rel = relative(dir, file).replace(/\\/g, "/");
23
+ const stat = statSync(file);
24
+ const hit = cache?.get(file);
25
+ seen.add(file);
26
+ if (hit && hit.mtime === stat.mtimeMs && hit.size === stat.size) {
27
+ out.push(hit.source);
28
+ continue;
29
+ }
21
30
  const bytes = readFileSync(file);
22
31
  const data = extension(bytes) === "txt" ? bytes.toString("utf8") : null;
23
- out.push(source({ path: `/${folder}/${rel}`, data, size: bytes.length }));
32
+ /* Touched but not changed (an editor saving without edits, a git checkout): still the same Source */
33
+ if (hit && hit.size === stat.size && hit.source.data !== null && hit.source.data === data) {
34
+ cache.set(file, { ...hit, mtime: stat.mtimeMs });
35
+ out.push(hit.source);
36
+ continue;
37
+ }
38
+ const rel = relative(dir, file).replace(/\\/g, "/");
39
+ const s = source({ path: `/${folder}/${rel}`, data, size: bytes.length, created_at: stat.birthtime.toISOString(), updated_at: stat.mtime.toISOString() });
40
+ cache?.set(file, { mtime: stat.mtimeMs, size: stat.size, source: s });
41
+ out.push(s);
24
42
  }
25
43
  }
44
+ if (cache)
45
+ for (const file of cache.keys())
46
+ if (!seen.has(file))
47
+ cache.delete(file);
26
48
  return out;
27
49
  }
28
50
  /** Reads the bytes of a project's asset by its output path ("/images/logo.png" is "<root>/assets/images/logo.png"), for a binary file with null `data`. */
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
+ import { red } from "./color.js";
4
5
  const [, , command, ...args] = process.argv;
5
6
  const commands = {
6
7
  build: "./build.js",
@@ -21,7 +22,7 @@ if (!command || command === "--help" || command === "-h") {
21
22
  process.exit(0);
22
23
  }
23
24
  if (!(command in commands)) {
24
- console.error(`Unknown command: ${command}`);
25
+ console.error(red(`Unknown command: ${command}`));
25
26
  console.error("Run `fragmentor --help` for available commands.");
26
27
  process.exit(1);
27
28
  }
@@ -4,12 +4,13 @@ import { pull } from "../sync/pull/index.js";
4
4
  import { plural } from "../utils/text.js";
5
5
  import { write } from "./fs.js";
6
6
  import { target } from "./target.js";
7
+ import { error } from "./color.js";
7
8
  export async function run(args) {
8
9
  const { root, sources, schemas, schema, document } = target(args, "pull");
9
10
  console.log(`Pulling "${schema._type}"...`);
10
11
  const { pulled, pruned, failed } = await pull({ schema, schemas, sources, document, fetch });
11
12
  for (const f of failed)
12
- console.error(` error: ${f.path}: ${f.error}`);
13
+ error(` error: ${f.path}: ${f.error}`);
13
14
  write(pulled, root);
14
15
  for (const s of pruned) {
15
16
  try {
@@ -1,12 +1,13 @@
1
1
  import { push } from "../sync/push/index.js";
2
2
  import { plural } from "../utils/text.js";
3
3
  import { target } from "./target.js";
4
+ import { error } from "./color.js";
4
5
  export async function run(args) {
5
6
  const { sources, schemas, schema, document } = target(args, "push");
6
7
  console.log(`Pushing "${schema._type}"...`);
7
8
  const { pushed, failed } = await push({ schema, schemas, sources, document, fetch });
8
9
  for (const f of failed)
9
- console.error(` error: ${f.path}: ${f.error}`);
10
+ error(` error: ${f.path}: ${f.error}`);
10
11
  console.log(`Pushed ${plural(pushed.length, "document")}${failed.length ? `, ${failed.length} failed` : ""}`);
11
12
  if (failed.length)
12
13
  process.exit(1);
@@ -3,6 +3,7 @@ import { resolve, join } from "node:path";
3
3
  import { schemas as readSchemas } from "../build/source/read.js";
4
4
  import { getSchema } from "../model/schema.js";
5
5
  import { flags, read } from "./fs.js";
6
+ import { error } from "./color.js";
6
7
  /**
7
8
  * Parses a `pull` or `push` command's arguments ("<schema> [--root <dir>] [--document <path>]") and reads its project.
8
9
  * Prints the usage and exits on --help or without a schema, and exits with an error when the schema doesn't exist, has no `verb` spec, or --document isn't a file.
@@ -34,7 +35,7 @@ export function target(args, verb) {
34
35
  return { root, sources, schemas, schema, document };
35
36
  }
36
37
  function fail(message) {
37
- console.error(message);
38
+ error(message);
38
39
  process.exit(1);
39
40
  }
40
41
  //# sourceMappingURL=target.js.map
@@ -1,10 +1,17 @@
1
1
  export { compile, type Parser } from "./build/compile/index.js";
2
2
  export { optimize } from "./build/optimize/index.js";
3
3
  export { lint } from "./build/lint/index.js";
4
- export { source, read, write } from "./build/source/index.js";
5
- export { decode } from "./build/decode/index.js";
6
- export { encode } from "./build/encode/index.js";
7
4
  export { pull } from "./sync/pull/index.js";
8
5
  export { push } from "./sync/push/index.js";
6
+ export { builtins } from "./build/builtins.js";
7
+ export { source } from "./build/source/index.js";
8
+ export { decode } from "./build/decode/index.js";
9
+ export { encode } from "./build/encode/index.js";
10
+ export { patch, type Patch } from "./build/source/patch.js";
11
+ export * as path from "./api/path.js";
12
+ export * as document from "./api/document.js";
13
+ export * as schema from "./api/schema.js";
14
+ export * as component from "./api/component.js";
15
+ export * as asset from "./api/asset.js";
9
16
  export type { Source, Schema, Document, Fragment, Entry } from "./model/types/index.js";
10
17
  //# sourceMappingURL=index.d.ts.map
package/dist/src/index.js CHANGED
@@ -1,12 +1,19 @@
1
- /* Build: turn a project's sources into a site */
1
+ /* Pipeline: turn a project's sources into a site, and sync documents with external APIs */
2
2
  export { compile } from "./build/compile/index.js";
3
3
  export { optimize } from "./build/optimize/index.js";
4
4
  export { lint } from "./build/lint/index.js";
5
- /* Content: move between raw files and structured entries */
6
- export { source, read, write } from "./build/source/index.js";
7
- export { decode } from "./build/decode/index.js";
8
- export { encode } from "./build/encode/index.js";
9
- /* Sync: exchange documents with external APIs */
10
5
  export { pull } from "./sync/pull/index.js";
11
6
  export { push } from "./sync/push/index.js";
7
+ export { builtins } from "./build/builtins.js";
8
+ /* Sources: move between raw files and structured entries */
9
+ export { source } from "./build/source/index.js";
10
+ export { decode } from "./build/decode/index.js";
11
+ export { encode } from "./build/encode/index.js";
12
+ export { patch } from "./build/source/patch.js";
13
+ /* Namespaces: everything you can do with one kind of thing */
14
+ export * as path from "./api/path.js";
15
+ export * as document from "./api/document.js";
16
+ export * as schema from "./api/schema.js";
17
+ export * as component from "./api/component.js";
18
+ export * as asset from "./api/asset.js";
12
19
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Whether an expression reads `$`, the top-level value, so its result can differ between pages that render the same data.
3
+ * @example isRooted("$.site.name") // true
4
+ * @example isRooted("title") // false
5
+ */
6
+ export declare function isRooted(expr: string): boolean;
1
7
  /**
2
8
  * Evaluates a directive's expression against `data`, safely (see the supported grammar above).
3
9
  * @param root The top-level value being rendered (the document or fragment passed to `render`, usually a page), reachable as
@@ -32,6 +32,11 @@ const UNARY = {
32
32
  "+": (a) => +num(a),
33
33
  typeof: (a) => typeof a,
34
34
  };
35
+ /*
36
+ * Array methods that change the array in place. They're called on a copy instead, so they give the same result ("a/b".split("/").pop()
37
+ * is still "b") without changing the data, which may be shared by every page of a build (see `render`).
38
+ */
39
+ const MUTATING = new Set(["sort", "reverse", "splice", "push", "pop", "shift", "unshift", "fill", "copyWithin"]);
35
40
  /** Reads `obj[key]`, blocking prototype escapes like `x.constructor.constructor("return process")()`. */
36
41
  function member(obj, key) {
37
42
  return obj == null || BLOCKED.has(String(key)) ? undefined : obj[String(key)];
@@ -54,8 +59,10 @@ function node(n, scope) {
54
59
  const args = c.arguments.map((a) => node(a, scope));
55
60
  if (c.callee.type === "MemberExpression") {
56
61
  const m = c.callee;
57
- const obj = node(m.object, scope);
58
- const fn = member(obj, m.computed ? node(m.property, scope) : m.property.name);
62
+ const target = node(m.object, scope);
63
+ const name = m.computed ? node(m.property, scope) : m.property.name;
64
+ const obj = Array.isArray(target) && MUTATING.has(String(name)) ? [...target] : target;
65
+ const fn = member(obj, name);
59
66
  return typeof fn === "function" ? fn.call(obj, ...args) : undefined;
60
67
  }
61
68
  const fn = node(c.callee, scope);
@@ -86,6 +93,37 @@ function node(n, scope) {
86
93
  return undefined;
87
94
  }
88
95
  }
96
+ /*
97
+ * Every expression parsed so far by its source (null when it doesn't parse), and whether it reads `$`: a template's few expressions
98
+ * are evaluated thousands of times. Emptied past MAX_PARSED, so a long-running server building many projects doesn't grow it forever.
99
+ */
100
+ const MAX_PARSED = 10_000;
101
+ const parsed = new Map();
102
+ /* Whether an AST reads `$` anywhere */
103
+ const roots = (n) => n !== null && typeof n === "object" && (n.type === "Identifier" ? n.name === "$" : Object.values(n).some(roots));
104
+ /* The parsed expression, from `parsed` after the first time */
105
+ function parse(expr) {
106
+ if (!parsed.has(expr)) {
107
+ if (parsed.size >= MAX_PARSED)
108
+ parsed.clear();
109
+ try {
110
+ const ast = jsep(expr);
111
+ parsed.set(expr, { ast, rooted: roots(ast) });
112
+ }
113
+ catch {
114
+ parsed.set(expr, null);
115
+ }
116
+ }
117
+ return parsed.get(expr);
118
+ }
119
+ /**
120
+ * Whether an expression reads `$`, the top-level value, so its result can differ between pages that render the same data.
121
+ * @example isRooted("$.site.name") // true
122
+ * @example isRooted("title") // false
123
+ */
124
+ export function isRooted(expr) {
125
+ return parse(expr)?.rooted ?? false;
126
+ }
89
127
  /**
90
128
  * Evaluates a directive's expression against `data`, safely (see the supported grammar above).
91
129
  * @param root The top-level value being rendered (the document or fragment passed to `render`, usually a page), reachable as
@@ -96,8 +134,11 @@ function node(n, scope) {
96
134
  * @example evaluate("$.title", {}, { title: "Home" }) // "Home"
97
135
  */
98
136
  export function evaluate(expr, data, root) {
137
+ const expression = parse(expr);
138
+ if (!expression)
139
+ return undefined;
99
140
  try {
100
- return node(jsep(expr), root ? { ...data, $: root } : data);
141
+ return node(expression.ast, root ? { ...data, $: root } : data);
101
142
  }
102
143
  catch {
103
144
  return undefined;
@@ -48,11 +48,11 @@ export declare function slug(path: string): string;
48
48
  /**
49
49
  * The "/index" file path for a slug, the counterpart of `slug`. A slug can also live at the path itself
50
50
  * ("/about" may be "/about" or "/about/index"), so check which one exists when looking a file up.
51
- * @example path("/about") // "/about/index"
52
- * @example path("/") // "/index"
53
- * @example path("/about/index") // "/about/index"
51
+ * @example file("/about") // "/about/index"
52
+ * @example file("/") // "/index"
53
+ * @example file("/about/index") // "/about/index"
54
54
  */
55
- export declare function path(slug: string): string;
55
+ export declare function file(slug: string): string;
56
56
  /**
57
57
  * The `_type` a schema or component file path names: its file name without extension, hidden dot or prefix,
58
58
  * since a component's name may be prefixed with the types it lives in ("Product.Faq" renders "Faq" inside "Product").
@@ -80,11 +80,11 @@ export function slug(path) {
80
80
  /**
81
81
  * The "/index" file path for a slug, the counterpart of `slug`. A slug can also live at the path itself
82
82
  * ("/about" may be "/about" or "/about/index"), so check which one exists when looking a file up.
83
- * @example path("/about") // "/about/index"
84
- * @example path("/") // "/index"
85
- * @example path("/about/index") // "/about/index"
83
+ * @example file("/about") // "/about/index"
84
+ * @example file("/") // "/index"
85
+ * @example file("/about/index") // "/about/index"
86
86
  */
87
- export function path(slug) {
87
+ export function file(slug) {
88
88
  return slug.endsWith("/index") ? slug : `${slug.replace(/\/$/, "")}/index`;
89
89
  }
90
90
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fragmentor",
3
- "version": "0.1.0",
4
- "description": "The open-source build engine for Fragmentor — compile, optimize and deploy content-driven sites.",
3
+ "version": "0.2.0",
4
+ "description": "The open-source build engine for Fragmentor.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/src/index.js",