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
@@ -0,0 +1,3 @@
1
+ export { asset as read } from "../build/source/read.js";
2
+ export { asset as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=asset.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { asset as read } from "../build/source/read.js";
2
+ export { asset as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=asset.js.map
@@ -0,0 +1,3 @@
1
+ export { component as read } from "../build/source/read.js";
2
+ export { component as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=component.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { component as read } from "../build/source/read.js";
2
+ export { component as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=component.js.map
@@ -0,0 +1,4 @@
1
+ export { document as read } from "../build/source/read.js";
2
+ export { document as write } from "../build/source/write.js";
3
+ export { resolve, complete } from "../build/resolve/index.js";
4
+ //# sourceMappingURL=document.d.ts.map
@@ -0,0 +1,4 @@
1
+ export { document as read } from "../build/source/read.js";
2
+ export { document as write } from "../build/source/write.js";
3
+ export { resolve, complete } from "../build/resolve/index.js";
4
+ //# sourceMappingURL=document.js.map
@@ -0,0 +1,3 @@
1
+ export { normalize, parse, format, folder, slug, file } from "../utils/path.js";
2
+ export { allowed } from "../build/source/index.js";
3
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { normalize, parse, format, folder, slug, file } from "../utils/path.js";
2
+ export { allowed } from "../build/source/index.js";
3
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1,3 @@
1
+ export { schema as read } from "../build/source/read.js";
2
+ export { schema as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { schema as read } from "../build/source/read.js";
2
+ export { schema as write } from "../build/source/write.js";
3
+ //# sourceMappingURL=schema.js.map
@@ -1,6 +1,13 @@
1
1
  import { evaluate } from "../../utils/expression.js";
2
2
  import type { Root } from "./render.js";
3
3
  export { evaluate };
4
+ export type Context = {
5
+ evaluate: (expr: string, data: Record<string, unknown>) => unknown;
6
+ render: (fragment: Record<string, unknown>) => string | undefined;
7
+ mark: (el: {
8
+ setAttribute(name: string, value: string): void;
9
+ }, fragment: Record<string, unknown>) => void;
10
+ };
4
11
  /**
5
12
  * Applies a template's directives to `root` in place, in this order:
6
13
  * 1. `x-for` rescopes an element to the value: an array repeats it once per item, any other non-null value is its new scope.
@@ -8,11 +15,9 @@ export { evaluate };
8
15
  * 3. `x-bind` sets the element's text, or renders a fragment (or array of fragments) value through `render` into it.
9
16
  * 4. `x-bind:attr` sets an attribute, removing it when the value is null or undefined, or an unsafe url in a url attribute (href, src, ..., see `unsafeUrl`).
10
17
  * A `<template>`'s contents get the same directives and data (applied right after `x-for`, see below).
11
- * @param render Renders a nested fragment (see render.ts).
12
- * @param mark Marks a fragment's root element with the editor's pointers (a no-op outside dev, see `pointers`).
13
- * @param top The top-level value being rendered, `$` in every expression (see `evaluate`). Defaults to `data`, which is the top level when called from it.
18
+ * @param context Evaluates expressions (with `$` already bound by the caller, see `evaluate`), renders nested fragments and marks their root
19
+ * elements with the editor's pointers (a no-op outside dev, see `pointers`). See render.ts.
20
+ * @example apply(parsed, { title: "Hi" }, { evaluate: (expr, data) => evaluate(expr, data), render: () => "", mark: () => {} })
14
21
  */
15
- export declare function apply(root: Root, data: Record<string, unknown>, render: (fragment: Record<string, unknown>) => string | undefined, mark: (el: {
16
- setAttribute(name: string, value: string): void;
17
- }, fragment: Record<string, unknown>) => void, top?: Record<string, unknown>): void;
22
+ export declare function apply(root: Root, data: Record<string, unknown>, context: Context): void;
18
23
  //# sourceMappingURL=directives.d.ts.map
@@ -11,18 +11,19 @@ const URL_ATTRIBUTES = new Set(["href", "src", "action", "formaction", "xlink:hr
11
11
  * 3. `x-bind` sets the element's text, or renders a fragment (or array of fragments) value through `render` into it.
12
12
  * 4. `x-bind:attr` sets an attribute, removing it when the value is null or undefined, or an unsafe url in a url attribute (href, src, ..., see `unsafeUrl`).
13
13
  * A `<template>`'s contents get the same directives and data (applied right after `x-for`, see below).
14
- * @param render Renders a nested fragment (see render.ts).
15
- * @param mark Marks a fragment's root element with the editor's pointers (a no-op outside dev, see `pointers`).
16
- * @param top The top-level value being rendered, `$` in every expression (see `evaluate`). Defaults to `data`, which is the top level when called from it.
14
+ * @param context Evaluates expressions (with `$` already bound by the caller, see `evaluate`), renders nested fragments and marks their root
15
+ * elements with the editor's pointers (a no-op outside dev, see `pointers`). See render.ts.
16
+ * @example apply(parsed, { title: "Hi" }, { evaluate: (expr, data) => evaluate(expr, data), render: () => "", mark: () => {} })
17
17
  */
18
- export function apply(root, data, render, mark, top = data) {
18
+ export function apply(root, data, context) {
19
+ const { evaluate, render, mark } = context;
19
20
  for (const el of root.querySelectorAll("[x-for]")) {
20
21
  const expr = el.getAttribute("x-for");
21
22
  el.removeAttribute("x-for");
22
23
  /* x-bind on the same element wins */
23
24
  if (el.getAttribute("x-bind") != null)
24
25
  continue;
25
- const items = evaluate(expr, data, top);
26
+ const items = evaluate(expr, data);
26
27
  if (Array.isArray(items)) {
27
28
  /* Every clone after the first gets the whitespace before the original, so items keep the template's indentation */
28
29
  const before = el.previousSibling;
@@ -32,14 +33,14 @@ export function apply(root, data, render, mark, top = data) {
32
33
  if (isFragment(item))
33
34
  mark(clone, item);
34
35
  /* The repeated element's own x-bind:attr reads the item, like its children do (querySelectorAll never matches the root itself) */
35
- bind(clone, item, top);
36
- apply(clone, item, render, mark, top);
36
+ bind(clone, item, evaluate);
37
+ apply(clone, item, context);
37
38
  return i && indent ? [indent, clone] : [clone];
38
39
  }));
39
40
  }
40
41
  else if (items != null) {
41
- bind(el, items, top);
42
- apply(el, items, render, mark, top);
42
+ bind(el, items, evaluate);
43
+ apply(el, items, context);
43
44
  }
44
45
  }
45
46
  /*
@@ -53,17 +54,17 @@ export function apply(root, data, render, mark, top = data) {
53
54
  const template = el;
54
55
  const content = template.firstElementChild ? template : template.content;
55
56
  if (content)
56
- apply(content, data, render, mark, top);
57
+ apply(content, data, context);
57
58
  }
58
59
  for (const el of root.querySelectorAll("[x-if]")) {
59
- if (evaluate(el.getAttribute("x-if"), data, top))
60
+ if (evaluate(el.getAttribute("x-if"), data))
60
61
  el.removeAttribute("x-if");
61
62
  else
62
63
  el.remove();
63
64
  }
64
65
  for (const el of root.querySelectorAll("[x-bind]")) {
65
66
  const expr = el.getAttribute("x-bind");
66
- const value = evaluate(expr, data, top);
67
+ const value = evaluate(expr, data);
67
68
  const unresolved = (f) => `<!-- unresolved type: ${f._type} -->`;
68
69
  if (isFragment(value))
69
70
  el.innerHTML = render(value) ?? unresolved(value);
@@ -74,14 +75,14 @@ export function apply(root, data, render, mark, top = data) {
74
75
  el.removeAttribute("x-bind");
75
76
  }
76
77
  for (const el of root.querySelectorAll("*"))
77
- bind(el, data, top);
78
+ bind(el, data, evaluate);
78
79
  }
79
80
  /* Applies an element's own `x-bind:attr` directives against `data` (see `apply`, step 4) */
80
- function bind(el, data, top) {
81
+ function bind(el, data, evaluate) {
81
82
  for (const { name, value } of [...el.attributes]) {
82
83
  if (!name.startsWith("x-bind:") || name === "x-bind:")
83
84
  continue;
84
- const result = evaluate(value, data, top);
85
+ const result = evaluate(value, data);
85
86
  const attr = name.slice("x-bind:".length);
86
87
  if (result == null || (URL_ATTRIBUTES.has(attr.toLowerCase()) && unsafeUrl(String(result))))
87
88
  el.removeAttribute(attr);
@@ -1,5 +1,6 @@
1
1
  import type { Source } from "../../model/types/index.js";
2
2
  import { type Parser } from "./render.js";
3
+ export declare const MAX_ELEMENTS = 1400;
3
4
  export type Compiled = {
4
5
  output: Source[];
5
6
  errors: {
@@ -15,8 +16,10 @@ export type Compiled = {
15
16
  * Compiles a project's sources into the files of its site, with no filesystem access so it runs anywhere:
16
17
  * 1. Reads schemas, documents, components and assets (`read.*`). Every problem `lint` finds in a file is listed in `errors` or `warnings` (except for a document
17
18
  * without `_type`, which is plain data), but the file is still read leniently (invalid values replaced by defaults) so one bad field doesn't drop a page.
18
- * 2. Links each document's references (`complete`, then `resolve`). Its `_slug` is its route ("/blog/index.yml" -> "/blog").
19
+ * 2. Links each document's references (`complete`, then `resolver`, shared by every page). Its `_slug` is its route ("/blog/index.yml" -> "/blog").
19
20
  * 3. Renders a page for every visible document (every document in dev) whose _type has a component (see `render`), at "<slug>/index.html". With a `route`, only that one.
21
+ * A page with more than MAX_ELEMENTS elements gets a warning (see `heaviness`).
22
+ * Outside dev, a fragment that several pages render the same way is rendered once (see `Memo`).
20
23
  * 4. Bundles each page (see `bundle`): its styles joined into one "/_styles/<hash>.css", its scripts each at "/_scripts/<hash>.js", all linked from the page.
21
24
  * 5. Stamps each page (see `stamp`): a "Made with Fragmentor" comment at the top, with `published` when it was published.
22
25
  * 6. With a `url`, generates "/sitemap.xml" and "/robots.txt" (see `sitemap` and `robots`).
@@ -1,22 +1,36 @@
1
1
  import { declared } from "../decode/index.js";
2
2
  import { builtins } from "../builtins.js";
3
3
  import { read, source } from "../source/index.js";
4
- import { folder, parse as parsePath, path, slug } from "../../utils/path.js";
4
+ import { file, folder, parse as parsePath, slug } from "../../utils/path.js";
5
5
  import { lint } from "../lint/index.js";
6
- import { complete, resolve } from "../resolve/index.js";
6
+ import { complete, resolver } from "../resolve/index.js";
7
7
  import { bundle } from "./assets.js";
8
8
  import { robots, sitemap, stamp } from "./generate.js";
9
9
  import { render } from "./render.js";
10
+ import { Memo } from "./memo.js";
10
11
  /** Whether a source is a document file without `_type`: plain data that references can still point at, so it's no error to build with (even though `write.document` refuses to write one). */
11
12
  function plain(source) {
12
13
  return folder(source.path) === "documents" && declared(source) === undefined;
13
14
  }
15
+ /* Lighthouse flags a page with more elements than this ("Avoid an excessive DOM size"), and it's usually a data mistake, like a large references field on a fragment shown on every page */
16
+ export const MAX_ELEMENTS = 1400;
17
+ /* A warning when a page's HTML has more than MAX_ELEMENTS elements (counted by their opening tags), else null */
18
+ function heaviness(html) {
19
+ let elements = 0;
20
+ for (const _ of html.matchAll(/<[a-zA-Z]/g))
21
+ elements++;
22
+ if (elements <= MAX_ELEMENTS)
23
+ return null;
24
+ return `The page has ${elements} elements, over the ${MAX_ELEMENTS} Lighthouse flags, which slows the page and the build. Check for a large references field on a fragment shown on every page`;
25
+ }
14
26
  /**
15
27
  * Compiles a project's sources into the files of its site, with no filesystem access so it runs anywhere:
16
28
  * 1. Reads schemas, documents, components and assets (`read.*`). Every problem `lint` finds in a file is listed in `errors` or `warnings` (except for a document
17
29
  * without `_type`, which is plain data), but the file is still read leniently (invalid values replaced by defaults) so one bad field doesn't drop a page.
18
- * 2. Links each document's references (`complete`, then `resolve`). Its `_slug` is its route ("/blog/index.yml" -> "/blog").
30
+ * 2. Links each document's references (`complete`, then `resolver`, shared by every page). Its `_slug` is its route ("/blog/index.yml" -> "/blog").
19
31
  * 3. Renders a page for every visible document (every document in dev) whose _type has a component (see `render`), at "<slug>/index.html". With a `route`, only that one.
32
+ * A page with more than MAX_ELEMENTS elements gets a warning (see `heaviness`).
33
+ * Outside dev, a fragment that several pages render the same way is rendered once (see `Memo`).
20
34
  * 4. Bundles each page (see `bundle`): its styles joined into one "/_styles/<hash>.css", its scripts each at "/_scripts/<hash>.js", all linked from the page.
21
35
  * 5. Stamps each page (see `stamp`): a "Made with Fragmentor" comment at the top, with `published` when it was published.
22
36
  * 6. With a `url`, generates "/sitemap.xml" and "/robots.txt" (see `sitemap` and `robots`).
@@ -44,15 +58,27 @@ export function compile(sources, { parse, dev = false, url, route, published })
44
58
  const warnings = linted.flatMap(({ path, warnings }) => warnings.map((message) => ({ path, message })));
45
59
  const types = [...builtins, ...schemas];
46
60
  /* Completed up front so null references fill in on referenced documents too (e.g. a Site's navigation), not only on the page */
47
- const completed = documents.map((d) => complete({ document: d, schemas: types, references: documents }));
61
+ const completed = documents.map((d) => {
62
+ const cut = [];
63
+ const document = complete({ document: d, schemas: types, references: documents, warnings: cut });
64
+ for (const message of cut)
65
+ warnings.push({ path: `/documents${d._path}`, message });
66
+ return document;
67
+ });
48
68
  const pages = completed.filter((d) => (!route || d._slug === slug(route)) && components.some((c) => c._type === d._type));
69
+ /* Resolved through one resolver, a document reached from many pages is one object, so the memo renders it once (see `Memo`) */
70
+ const resolve = resolver({ references: completed });
71
+ const memo = dev ? undefined : new Memo();
49
72
  const output = new Map();
50
73
  const emit = (file) => output.set(file.path, file);
51
74
  for (const document of pages) {
52
75
  try {
53
- const page = resolve({ document, references: completed });
54
- const { html, assets } = bundle(render(page, components, parse, { dev, schemas }));
55
- emit(source({ path: `${path(document._slug)}.html`, data: stamp(html, { published }) }));
76
+ const page = resolve(document);
77
+ const { html, assets } = bundle(render(page, components, parse, { dev, schemas, memo }));
78
+ const heavy = heaviness(html);
79
+ if (heavy)
80
+ warnings.push({ path: `/documents${document._path}`, message: heavy });
81
+ emit(source({ path: `${file(document._slug)}.html`, data: stamp(html, { published }) }));
56
82
  for (const [at, data] of Object.entries(assets))
57
83
  emit(source({ path: at, data }));
58
84
  }
@@ -0,0 +1,44 @@
1
+ type Read = {
2
+ expr: string;
3
+ data: Record<string, unknown>;
4
+ value: unknown;
5
+ };
6
+ /**
7
+ * Remembers what rendering a fragment produced, so another page of the same build that renders the same fragment at the same
8
+ * place reuses it instead of rendering again (a site's navigation and footer, rendered once instead of once per page).
9
+ *
10
+ * A fragment is "the same" when it's the same object, which `resolver` guarantees for every document a build reaches, and
11
+ * "at the same place" when the _types it's nested in (`ancestors`) match, since those pick its components (see `lookup`).
12
+ * Its fields can't differ, but `$` can: the page being rendered. So every expression reading `$` is recorded while a fragment
13
+ * renders, nested renders included, and a recording is reused only when each of them still gives the same value.
14
+ *
15
+ * Rendering is synchronous, so recordings nest like the renders they record (see `run`).
16
+ * @example const memo = new Memo(); render(home, components, parse, { memo }); render(about, components, parse, { memo }) // the footer renders once
17
+ */
18
+ export declare class Memo {
19
+ private recordings;
20
+ private open;
21
+ /**
22
+ * Renders `fragment` through `draw`, or reuses a recording whose `$` reads all give the same value again (checked with `check`).
23
+ * Either way, what it read and added is passed on to the render around it, so that one depends on it too.
24
+ * @param check Evaluates a recorded `$` expression for the page being rendered now.
25
+ * @example memo.run(fragment, ancestors, (read) => evaluate(read.expr, read.data, page), () => draw(fragment))
26
+ */
27
+ run(fragment: object, ancestors: string[], check: (read: Read) => unknown, draw: () => string | undefined): {
28
+ html: string | undefined;
29
+ assets: Record<string, string>[];
30
+ };
31
+ /**
32
+ * Records a `$` expression evaluated by the render running now (a no-op outside one).
33
+ * @example memo.read({ expr: "$.title", data, value: "Home" })
34
+ */
35
+ read(read: Read): void;
36
+ /**
37
+ * Records assets added by the render running now (a no-op outside one).
38
+ * @example memo.add({ "/_styles/a1b2.css": "h1 {}" })
39
+ */
40
+ add(assets: Record<string, string>): void;
41
+ private pass;
42
+ }
43
+ export {};
44
+ //# sourceMappingURL=memo.d.ts.map
@@ -0,0 +1,73 @@
1
+ /*
2
+ * How many recordings are kept per fragment and place. Each differs in what its `$` reads gave, so a fragment that shows the
3
+ * page's own title gets one per page: past this it isn't worth keeping (and checking) them all.
4
+ */
5
+ const MAX_RECORDINGS = 4;
6
+ /**
7
+ * Remembers what rendering a fragment produced, so another page of the same build that renders the same fragment at the same
8
+ * place reuses it instead of rendering again (a site's navigation and footer, rendered once instead of once per page).
9
+ *
10
+ * A fragment is "the same" when it's the same object, which `resolver` guarantees for every document a build reaches, and
11
+ * "at the same place" when the _types it's nested in (`ancestors`) match, since those pick its components (see `lookup`).
12
+ * Its fields can't differ, but `$` can: the page being rendered. So every expression reading `$` is recorded while a fragment
13
+ * renders, nested renders included, and a recording is reused only when each of them still gives the same value.
14
+ *
15
+ * Rendering is synchronous, so recordings nest like the renders they record (see `run`).
16
+ * @example const memo = new Memo(); render(home, components, parse, { memo }); render(about, components, parse, { memo }) // the footer renders once
17
+ */
18
+ export class Memo {
19
+ recordings = new WeakMap();
20
+ /* The recordings of the renders running right now, innermost last */
21
+ open = [];
22
+ /**
23
+ * Renders `fragment` through `draw`, or reuses a recording whose `$` reads all give the same value again (checked with `check`).
24
+ * Either way, what it read and added is passed on to the render around it, so that one depends on it too.
25
+ * @param check Evaluates a recorded `$` expression for the page being rendered now.
26
+ * @example memo.run(fragment, ancestors, (read) => evaluate(read.expr, read.data, page), () => draw(fragment))
27
+ */
28
+ run(fragment, ancestors, check, draw) {
29
+ const key = ancestors.join("\u0000");
30
+ const list = this.recordings.get(fragment)?.get(key) ?? [];
31
+ const found = list.find((r) => r.reads.every((read) => Object.is(check(read), read.value)));
32
+ if (found) {
33
+ this.pass(found);
34
+ return found;
35
+ }
36
+ const recording = { html: undefined, assets: [], reads: [] };
37
+ this.open.push(recording);
38
+ try {
39
+ recording.html = draw();
40
+ }
41
+ finally {
42
+ this.open.pop();
43
+ }
44
+ this.pass(recording);
45
+ if (list.length < MAX_RECORDINGS) {
46
+ const byKey = this.recordings.get(fragment) ?? new Map();
47
+ byKey.set(key, [...list, recording]);
48
+ this.recordings.set(fragment, byKey);
49
+ }
50
+ return recording;
51
+ }
52
+ /**
53
+ * Records a `$` expression evaluated by the render running now (a no-op outside one).
54
+ * @example memo.read({ expr: "$.title", data, value: "Home" })
55
+ */
56
+ read(read) {
57
+ this.open.at(-1)?.reads.push(read);
58
+ }
59
+ /**
60
+ * Records assets added by the render running now (a no-op outside one).
61
+ * @example memo.add({ "/_styles/a1b2.css": "h1 {}" })
62
+ */
63
+ add(assets) {
64
+ this.open.at(-1)?.assets.push(assets);
65
+ }
66
+ /* Hands what a finished or reused render read and added to the render around it */
67
+ pass(recording) {
68
+ const outer = this.open.at(-1);
69
+ outer?.reads.push(...recording.reads);
70
+ outer?.assets.push(...recording.assets);
71
+ }
72
+ }
73
+ //# sourceMappingURL=memo.js.map
@@ -1,4 +1,5 @@
1
1
  import type { Component, Schema } from "../../model/types/index.js";
2
+ import type { Memo } from "./memo.js";
2
3
  export interface Root {
3
4
  querySelectorAll(selector: string): Iterable<Elem>;
4
5
  }
@@ -63,10 +64,13 @@ export declare const MAX_DEPTH = 32;
63
64
  * @param options.dev Adds the editor's pointers: `x-src` on every template element, and on every fragment's root element its
64
65
  * `x-path` (where it lives in `document`, see `paths`), plus `x-type`/`x-allow` when `schemas` describe its field (see `pointers`).
65
66
  * @param options.schemas The project's schemas, for `x-type`/`x-allow`.
67
+ * @param options.memo Shared by the pages of a build, so a fragment they all render (a navigation, a footer) renders once (see `Memo`).
68
+ * Left out in dev, where every fragment's pointers depend on the page.
66
69
  * @returns The HTML, or an `<!-- unresolved type -->` comment when the root has no component, and the extracted assets.
67
70
  */
68
- export declare function render(document: Record<string, unknown>, components: Component[], parse: Parser, { dev, schemas }?: {
71
+ export declare function render(document: Record<string, unknown>, components: Component[], parse: Parser, { dev, schemas, memo }?: {
69
72
  dev?: boolean;
70
73
  schemas?: Schema[];
74
+ memo?: Memo;
71
75
  }): Rendered;
72
76
  //# sourceMappingURL=render.d.ts.map
@@ -6,6 +6,7 @@ import { list } from "../../utils/object.js";
6
6
  import { annotate, paths, pointers } from "./annotate.js";
7
7
  import { extract } from "./assets.js";
8
8
  import { apply } from "./directives.js";
9
+ import { evaluate, isRooted } from "../../utils/expression.js";
9
10
  /** Escapes text so it can't be read as markup. */
10
11
  function escape(text) {
11
12
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
@@ -75,9 +76,11 @@ const templates = [new WeakMap(), new WeakMap()];
75
76
  * @param options.dev Adds the editor's pointers: `x-src` on every template element, and on every fragment's root element its
76
77
  * `x-path` (where it lives in `document`, see `paths`), plus `x-type`/`x-allow` when `schemas` describe its field (see `pointers`).
77
78
  * @param options.schemas The project's schemas, for `x-type`/`x-allow`.
79
+ * @param options.memo Shared by the pages of a build, so a fragment they all render (a navigation, a footer) renders once (see `Memo`).
80
+ * Left out in dev, where every fragment's pointers depend on the page.
78
81
  * @returns The HTML, or an `<!-- unresolved type -->` comment when the root has no component, and the extracted assets.
79
82
  */
80
- export function render(document, components, parse, { dev = false, schemas } = {}) {
83
+ export function render(document, components, parse, { dev = false, schemas, memo } = {}) {
81
84
  const assets = {};
82
85
  /* A fragment's path is looked up from where it lives, so it's right however the template reached it. One that's not in the document (built by an expression) has none */
83
86
  const found = dev ? paths(document) : null;
@@ -89,7 +92,23 @@ export function render(document, components, parse, { dev = false, schemas } = {
89
92
  for (const [name, value] of Object.entries(point(fragment)))
90
93
  el.setAttribute(name, value);
91
94
  };
95
+ /* Every expression sees `document` as `$`, and one that reads it is recorded for the memo, since it can differ on another page */
96
+ const scoped = (expr, data) => {
97
+ const value = evaluate(expr, data, document);
98
+ if (memo && isRooted(expr))
99
+ memo.read({ expr, data, value });
100
+ return value;
101
+ };
102
+ /* A nested fragment is rendered once per build when a memo is given (see `Memo`), the page itself always, since no other page renders it */
92
103
  const go = (fragment, ancestors) => {
104
+ if (!memo || !ancestors.length)
105
+ return draw(fragment, ancestors);
106
+ const done = memo.run(fragment, ancestors, (read) => evaluate(read.expr, read.data, document), () => draw(fragment, ancestors));
107
+ for (const added of done.assets)
108
+ Object.assign(assets, added);
109
+ return done.html;
110
+ };
111
+ const draw = (fragment, ancestors) => {
93
112
  const type = String(fragment._type);
94
113
  if (ancestors.length >= MAX_DEPTH)
95
114
  return `<!-- too deep: ${type} -->`;
@@ -105,8 +124,9 @@ export function render(document, components, parse, { dev = false, schemas } = {
105
124
  if (!template)
106
125
  cache.set(component, (template = extract(dev ? annotate(component._data, type) : component._data, parse)));
107
126
  Object.assign(assets, template.assets);
127
+ memo?.add(template.assets);
108
128
  const parsed = parse(template.html);
109
- apply(parsed, fragment, nested, mark, document); /* the top-level value, `$` in every expression of every nested fragment */
129
+ apply(parsed, fragment, { evaluate: scoped, render: nested, mark });
110
130
  for (const el of parsed.children)
111
131
  mark(el, fragment);
112
132
  return parsed.toString();
@@ -1,5 +1,5 @@
1
1
  import { read } from "../source/index.js";
2
- import { folder, path } from "../../utils/path.js";
2
+ import { file, folder } from "../../utils/path.js";
3
3
  import { refs } from "../../model/fragment.js";
4
4
  import { keyOf, getSchema } from "../../model/schema.js";
5
5
  /**
@@ -20,7 +20,7 @@ export function lint({ sources, paths }) {
20
20
  for (const c of claims(d, schemas))
21
21
  holders.set(c.id, [...(holders.get(c.id) ?? []), `/documents${d._path}`]);
22
22
  const ids = new Set(documents.map((d) => d._id));
23
- const pages = new Map(documents.map((d) => [`${path(d._slug)}.html`, `/documents${d._path}`]));
23
+ const pages = new Map(documents.map((d) => [`${file(d._slug)}.html`, `/documents${d._path}`]));
24
24
  return sources.filter((s) => !paths || paths.includes(s.path)).map((source) => {
25
25
  const errors = [];
26
26
  const warnings = [];
@@ -18,6 +18,18 @@ export declare function resolve({ document, references }: {
18
18
  errors?: string[];
19
19
  warnings?: string[];
20
20
  }): Resolve<Document>;
21
+ /**
22
+ * Like `resolve`, for many documents that share their resolved objects: a document resolved for one page is the same object on
23
+ * every other page that reaches it. That makes a fragment's identity mean "the same data" across a build, which `render` relies on
24
+ * to reuse what it rendered (see `Memo`). Resolved objects are never changed afterwards (expressions can't, see `evaluate`).
25
+ * @param references The list of all documents, used to look up each `_ref`.
26
+ * @returns A function resolving one document, as `resolve` does.
27
+ * @example const resolve = resolver({ references: documents }); resolve(home).site === resolve(about).site // true
28
+ */
29
+ export declare function resolver({ references }: {
30
+ references: Document[];
31
+ }): (document: Document) => Resolve<Document>;
32
+ export declare const DEFAULT_MAX_REFERENCES = 20;
21
33
  /**
22
34
  * Fills in every non-nullable `reference`/`references` field left `null` on a document with matching
23
35
  * candidates from `references`, so the document validates and `resolve` has something to resolve. Meant to run before
@@ -25,9 +37,11 @@ export declare function resolve({ document, references }: {
25
37
  * @param document The document to complete.
26
38
  * @param schemas The list of all schemas, used to look up field definitions.
27
39
  * @param references The candidate documents to fill non-nullable null references with.
40
+ * @param warnings Collects a warning for every `references` field without a `max` that had more matching documents than DEFAULT_MAX_REFERENCES.
28
41
  * @returns The document with eligible null references filled in.
42
+ * @example complete({ document, schemas, references: documents, warnings }) // warnings: ["related: Left empty, so filled with the first 20 of 143 matching documents. ..."]
29
43
  */
30
- export declare function complete({ document, schemas, references }: {
44
+ export declare function complete({ document, schemas, references, warnings }: {
31
45
  document: Document;
32
46
  schemas: Schema[];
33
47
  references: Document[];
@@ -1,5 +1,6 @@
1
1
  import { isFragment, isReference } from "../../model/types/index.js";
2
2
  import { getSchema } from "../../model/schema.js";
3
+ import { warning } from "../../utils/report.js";
3
4
  /**
4
5
  * Resolves a document's references, replacing every `{ _ref }` with the document it points to (looked up by `_id` in
5
6
  * `references`). Unresolved refs are removed: a single reference becomes `null`, an entry in a references array is dropped.
@@ -14,6 +15,17 @@ import { getSchema } from "../../model/schema.js";
14
15
  * @returns The document with every `_ref` replaced by its resolved document.
15
16
  */
16
17
  export function resolve({ document, references }) {
18
+ return resolver({ references })(document);
19
+ }
20
+ /**
21
+ * Like `resolve`, for many documents that share their resolved objects: a document resolved for one page is the same object on
22
+ * every other page that reaches it. That makes a fragment's identity mean "the same data" across a build, which `render` relies on
23
+ * to reuse what it rendered (see `Memo`). Resolved objects are never changed afterwards (expressions can't, see `evaluate`).
24
+ * @param references The list of all documents, used to look up each `_ref`.
25
+ * @returns A function resolving one document, as `resolve` does.
26
+ * @example const resolve = resolver({ references: documents }); resolve(home).site === resolve(about).site // true
27
+ */
28
+ export function resolver({ references }) {
17
29
  const byId = new Map(references.map(d => [d._id, d]));
18
30
  const resolved = new Map();
19
31
  /* The object is registered before its fields are filled, so a reference back to it, at any depth, gets this same object */
@@ -38,20 +50,25 @@ export function resolve({ document, references }) {
38
50
  return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, walk(v)]));
39
51
  return value;
40
52
  };
41
- return link(document);
53
+ /* A document reached earlier through a reference is already linked, so it comes back as that same object */
54
+ return (document) => link(document);
42
55
  }
56
+ /* How many documents `complete` fills a non-nullable `references` field without a `max` with. Set a max to get more (or fewer) */
57
+ export const DEFAULT_MAX_REFERENCES = 20;
43
58
  /**
44
59
  * Walks a value against its field definitions, filling in any non-nullable `reference`/`references` field
45
60
  * left `null` with matching candidates from `references` (matching `field.allow` when set, capped at
46
- * `field.max` for `references`), so `resolve` has something to resolve. Fragments are walked recursively
61
+ * `field.max` for `references`, or DEFAULT_MAX_REFERENCES without one), so `resolve` has something to resolve. Fragments are walked recursively
47
62
  * using `schemas` to find their field definitions.
48
63
  * @param value The value to walk (document or fragment).
49
64
  * @param fields The field definitions for `value`.
50
65
  * @param schemas The list of all schemas, used for nested fragments.
51
66
  * @param references The candidate documents to fill non-nullable null references with.
67
+ * @param path The keys from the document to `value`, to say where a field is in a warning.
68
+ * @param warnings Collects a warning for every field DEFAULT_MAX_REFERENCES cut short.
52
69
  * @returns The value with eligible null references filled in.
53
70
  */
54
- function completeProp(value, fields, schemas, references) {
71
+ function completeProp(value, fields, schemas, references, path, warnings) {
55
72
  const result = { ...value };
56
73
  for (const [key, field] of Object.entries(fields)) {
57
74
  const prop = result[key];
@@ -65,20 +82,25 @@ function completeProp(value, fields, schemas, references) {
65
82
  else if (field.type === "references") {
66
83
  if (prop === null && !field.nullable) {
67
84
  const candidates = references.filter(r => !field.allow.length || field.allow.includes(r._type));
68
- result[key] = (field.max !== undefined ? candidates.slice(0, field.max) : candidates).map(r => ({ _ref: r._id }));
85
+ const max = field.max ?? DEFAULT_MAX_REFERENCES;
86
+ result[key] = candidates.slice(0, max).map(r => ({ _ref: r._id }));
87
+ /* A field's own max is a choice, so only the default cap cutting documents off is worth a warning */
88
+ if (field.max === undefined && candidates.length > max) {
89
+ warning(`${[...path, key].join(".")}: Left empty, so filled with the first ${max} of ${candidates.length} matching documents. Set a max to choose how many, or nullable`, null, warnings);
90
+ }
69
91
  }
70
92
  }
71
93
  else if (field.type === "fragment" && isFragment(prop)) {
72
94
  const def = getSchema({ schemas, type: prop._type });
73
95
  if (def)
74
- result[key] = completeProp(prop, def.fields, schemas, references);
96
+ result[key] = completeProp(prop, def.fields, schemas, references, [...path, key], warnings);
75
97
  }
76
98
  else if (field.type === "fragments" && Array.isArray(prop)) {
77
- result[key] = prop.map(item => {
99
+ result[key] = prop.map((item, i) => {
78
100
  if (!isFragment(item))
79
101
  return item;
80
102
  const def = getSchema({ schemas, type: item._type });
81
- return def ? completeProp(item, def.fields, schemas, references) : item;
103
+ return def ? completeProp(item, def.fields, schemas, references, [...path, key, String(i)], warnings) : item;
82
104
  });
83
105
  }
84
106
  }
@@ -91,12 +113,14 @@ function completeProp(value, fields, schemas, references) {
91
113
  * @param document The document to complete.
92
114
  * @param schemas The list of all schemas, used to look up field definitions.
93
115
  * @param references The candidate documents to fill non-nullable null references with.
116
+ * @param warnings Collects a warning for every `references` field without a `max` that had more matching documents than DEFAULT_MAX_REFERENCES.
94
117
  * @returns The document with eligible null references filled in.
118
+ * @example complete({ document, schemas, references: documents, warnings }) // warnings: ["related: Left empty, so filled with the first 20 of 143 matching documents. ..."]
95
119
  */
96
- export function complete({ document, schemas, references }) {
120
+ export function complete({ document, schemas, references, warnings }) {
97
121
  const def = getSchema({ schemas, type: document._type });
98
122
  if (!def)
99
123
  return document;
100
- return completeProp(document, def.fields, schemas, references);
124
+ return completeProp(document, def.fields, schemas, references, [], warnings);
101
125
  }
102
126
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import { Fields, Source } from "../../model/types/index.js";
2
2
  import * as read from "./read.js";
3
3
  import * as write from "./write.js";
4
- export { parse, format, folder, inside, slug, path, type, chain } from "../../utils/path.js";
4
+ export { parse, format, folder, inside, slug, file, type, chain } from "../../utils/path.js";
5
5
  /**
6
6
  * Builds a Source from a file's `path` and raw `data`, with no filesystem access so it runs anywhere.
7
7
  * `path` goes through `normalize` first, so any input either becomes a canonical path or throws. It's kept whole:
@@ -6,7 +6,7 @@ import * as read from "./read.js";
6
6
  import { FOLDERS } from "./folders.js";
7
7
  import * as write from "./write.js";
8
8
  /* The path helpers live in utils/path.ts, re-exported here as part of the source API */
9
- export { parse, format, folder, inside, slug, path, type, chain } from "../../utils/path.js";
9
+ export { parse, format, folder, inside, slug, file, type, chain } from "../../utils/path.js";
10
10
  /**
11
11
  * Builds a Source from a file's `path` and raw `data`, with no filesystem access so it runs anywhere.
12
12
  * `path` goes through `normalize` first, so any input either becomes a canonical path or throws. It's kept whole: