fragmentor 0.0.0-stage → 0.1.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 (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/dist/src/build/builtins.d.ts +16 -0
  4. package/dist/src/build/builtins.js +57 -0
  5. package/dist/src/build/compile/annotate.d.ts +27 -0
  6. package/dist/src/build/compile/annotate.js +76 -0
  7. package/dist/src/build/compile/assets.d.ts +30 -0
  8. package/dist/src/build/compile/assets.js +74 -0
  9. package/dist/src/build/compile/directives.d.ts +18 -0
  10. package/dist/src/build/compile/directives.js +93 -0
  11. package/dist/src/build/compile/generate.d.ts +24 -0
  12. package/dist/src/build/compile/generate.js +42 -0
  13. package/dist/src/build/compile/index.d.ts +43 -0
  14. package/dist/src/build/compile/index.js +75 -0
  15. package/dist/src/build/compile/render.d.ts +72 -0
  16. package/dist/src/build/compile/render.js +116 -0
  17. package/dist/src/build/decode/html.d.ts +13 -0
  18. package/dist/src/build/decode/html.js +21 -0
  19. package/dist/src/build/decode/index.d.ts +23 -0
  20. package/dist/src/build/decode/index.js +63 -0
  21. package/dist/src/build/decode/json.d.ts +3 -0
  22. package/dist/src/build/decode/json.js +12 -0
  23. package/dist/src/build/decode/markdown.d.ts +21 -0
  24. package/dist/src/build/decode/markdown.js +121 -0
  25. package/dist/src/build/decode/tag.d.ts +8 -0
  26. package/dist/src/build/decode/tag.js +85 -0
  27. package/dist/src/build/decode/yaml.d.ts +3 -0
  28. package/dist/src/build/decode/yaml.js +47 -0
  29. package/dist/src/build/encode/html.d.ts +8 -0
  30. package/dist/src/build/encode/html.js +36 -0
  31. package/dist/src/build/encode/index.d.ts +12 -0
  32. package/dist/src/build/encode/index.js +27 -0
  33. package/dist/src/build/encode/json.d.ts +3 -0
  34. package/dist/src/build/encode/json.js +10 -0
  35. package/dist/src/build/encode/markdown.d.ts +8 -0
  36. package/dist/src/build/encode/markdown.js +49 -0
  37. package/dist/src/build/encode/node.d.ts +19 -0
  38. package/dist/src/build/encode/node.js +44 -0
  39. package/dist/src/build/encode/tag.d.ts +3 -0
  40. package/dist/src/build/encode/tag.js +28 -0
  41. package/dist/src/build/encode/yaml.d.ts +3 -0
  42. package/dist/src/build/encode/yaml.js +11 -0
  43. package/dist/src/build/lint/index.d.ts +20 -0
  44. package/dist/src/build/lint/index.js +67 -0
  45. package/dist/src/build/optimize/index.d.ts +28 -0
  46. package/dist/src/build/optimize/index.js +125 -0
  47. package/dist/src/build/resolve/index.d.ts +37 -0
  48. package/dist/src/build/resolve/index.js +102 -0
  49. package/dist/src/build/sanitize/asset.d.ts +11 -0
  50. package/dist/src/build/sanitize/asset.js +11 -0
  51. package/dist/src/build/sanitize/component.d.ts +12 -0
  52. package/dist/src/build/sanitize/component.js +14 -0
  53. package/dist/src/build/sanitize/document.d.ts +15 -0
  54. package/dist/src/build/sanitize/document.js +21 -0
  55. package/dist/src/build/sanitize/index.d.ts +5 -0
  56. package/dist/src/build/sanitize/index.js +5 -0
  57. package/dist/src/build/sanitize/schema.d.ts +13 -0
  58. package/dist/src/build/sanitize/schema.js +15 -0
  59. package/dist/src/build/source/folders.d.ts +8 -0
  60. package/dist/src/build/source/folders.js +8 -0
  61. package/dist/src/build/source/index.d.ts +35 -0
  62. package/dist/src/build/source/index.js +103 -0
  63. package/dist/src/build/source/patch.d.ts +19 -0
  64. package/dist/src/build/source/patch.js +108 -0
  65. package/dist/src/build/source/read.d.ts +56 -0
  66. package/dist/src/build/source/read.js +103 -0
  67. package/dist/src/build/source/write.d.ts +28 -0
  68. package/dist/src/build/source/write.js +32 -0
  69. package/dist/src/build/validate/document.d.ts +56 -0
  70. package/dist/src/build/validate/document.js +192 -0
  71. package/dist/src/build/validate/index.d.ts +4 -0
  72. package/dist/src/build/validate/index.js +4 -0
  73. package/dist/src/build/validate/schema.d.ts +33 -0
  74. package/dist/src/build/validate/schema.js +141 -0
  75. package/dist/src/cli/build.d.ts +2 -0
  76. package/dist/src/cli/build.js +47 -0
  77. package/dist/src/cli/dev.d.ts +2 -0
  78. package/dist/src/cli/dev.js +80 -0
  79. package/dist/src/cli/fs.d.ts +20 -0
  80. package/dist/src/cli/fs.js +76 -0
  81. package/dist/src/cli/index.d.ts +3 -0
  82. package/dist/src/cli/index.js +31 -0
  83. package/dist/src/cli/pull.d.ts +2 -0
  84. package/dist/src/cli/pull.js +27 -0
  85. package/dist/src/cli/push.d.ts +2 -0
  86. package/dist/src/cli/push.js +14 -0
  87. package/dist/src/cli/target.d.ts +13 -0
  88. package/dist/src/cli/target.js +40 -0
  89. package/dist/src/index.d.ts +10 -0
  90. package/dist/src/index.js +12 -0
  91. package/dist/src/model/entry.d.ts +11 -0
  92. package/dist/src/model/entry.js +16 -0
  93. package/dist/src/model/fragment.d.ts +28 -0
  94. package/dist/src/model/fragment.js +43 -0
  95. package/dist/src/model/schema.d.ts +23 -0
  96. package/dist/src/model/schema.js +49 -0
  97. package/dist/src/model/types/asset.d.ts +13 -0
  98. package/dist/src/model/types/asset.js +3 -0
  99. package/dist/src/model/types/component.d.ts +15 -0
  100. package/dist/src/model/types/component.js +11 -0
  101. package/dist/src/model/types/document.d.ts +24 -0
  102. package/dist/src/model/types/document.js +16 -0
  103. package/dist/src/model/types/fields.d.ts +428 -0
  104. package/dist/src/model/types/fields.js +118 -0
  105. package/dist/src/model/types/fragment.d.ts +56 -0
  106. package/dist/src/model/types/fragment.js +41 -0
  107. package/dist/src/model/types/index.d.ts +9 -0
  108. package/dist/src/model/types/index.js +9 -0
  109. package/dist/src/model/types/primitives.d.ts +17 -0
  110. package/dist/src/model/types/primitives.js +59 -0
  111. package/dist/src/model/types/schema.d.ts +255 -0
  112. package/dist/src/model/types/schema.js +39 -0
  113. package/dist/src/model/types/source.d.ts +34 -0
  114. package/dist/src/model/types/source.js +28 -0
  115. package/dist/src/sync/api/index.d.ts +94 -0
  116. package/dist/src/sync/api/index.js +343 -0
  117. package/dist/src/sync/pull/index.d.ts +34 -0
  118. package/dist/src/sync/pull/index.js +202 -0
  119. package/dist/src/sync/push/index.d.ts +27 -0
  120. package/dist/src/sync/push/index.js +76 -0
  121. package/dist/src/utils/expression.d.ts +11 -0
  122. package/dist/src/utils/expression.js +106 -0
  123. package/dist/src/utils/hash.d.ts +8 -0
  124. package/dist/src/utils/hash.js +18 -0
  125. package/dist/src/utils/mime.d.ts +10 -0
  126. package/dist/src/utils/mime.js +47 -0
  127. package/dist/src/utils/object.d.ts +22 -0
  128. package/dist/src/utils/object.js +40 -0
  129. package/dist/src/utils/path.d.ts +71 -0
  130. package/dist/src/utils/path.js +109 -0
  131. package/dist/src/utils/report.d.ts +20 -0
  132. package/dist/src/utils/report.js +29 -0
  133. package/dist/src/utils/text.d.ts +17 -0
  134. package/dist/src/utils/text.js +41 -0
  135. package/package.json +71 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fragmentor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ <img alt="Fragmentor — plain files in, static HTML out" src="https://raw.githubusercontent.com/fragmentorio/fragmentor/main/.github/assets/banner.png" width="100%">
2
+
3
+ <br/>
4
+ <p align="center">
5
+ <a href="https://fragmentor.io">Fragmentor</a> is an AI website builder with a builtin CMS.<br/>
6
+ Its open-source build engine turns your content and HTML templates into fast, static HTML.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/fragmentorio/fragmentor/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue"></a>
11
+ <a href="https://www.npmjs.com/package/fragmentor"><img alt="npm package" src="https://img.shields.io/npm/v/fragmentor?label=npm%20package"></a>
12
+ </p>
13
+
14
+ ## Install
15
+
16
+ Install Fragmentor in your project by running the command below:
17
+
18
+ ```bash
19
+ npm install fragmentor
20
+ ```
21
+
22
+ For minified CSS/JS and responsive WebP images in production builds, also install the optional optimizers:
23
+
24
+ ```bash
25
+ npm install --save-dev esbuild sharp
26
+ ```
27
+
28
+ Looking for help? Start with the [documentation](https://fragmentor.io/docs).
29
+
30
+ ## Commands
31
+
32
+ ```bash
33
+ npx fragmentor dev # start a dev server at http://localhost:3000
34
+ npx fragmentor build # build the site to dist/
35
+ ```
36
+
37
+ Run `npx fragmentor --help` to see all commands and options.
38
+
39
+ ## Links
40
+
41
+ - [Website](https://fragmentor.io)
42
+ - [Documentation](https://fragmentor.io/docs)
43
+ - [Changelog](https://fragmentor.io/changelog)
44
+ - [Blog](https://fragmentor.io/blog)
45
+ - [Discord](https://discord.gg/9aH7gRhcyQ)
46
+ - [License (MIT)](https://github.com/fragmentorio/fragmentor/blob/main/LICENSE)
2
47
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,16 @@
1
+ import type { Schema, SchemaFragment } from "../model/types/index.js";
2
+ export declare const text: SchemaFragment;
3
+ export declare const img: SchemaFragment;
4
+ export declare const a: SchemaFragment;
5
+ export declare const h1: SchemaFragment;
6
+ export declare const h2: SchemaFragment;
7
+ export declare const h3: SchemaFragment;
8
+ export declare const h4: SchemaFragment;
9
+ export declare const h5: SchemaFragment;
10
+ export declare const h6: SchemaFragment;
11
+ export declare const p: SchemaFragment;
12
+ export declare const li: SchemaFragment;
13
+ export declare const ul: SchemaFragment;
14
+ export declare const ol: SchemaFragment;
15
+ export declare const builtins: Schema[];
16
+ //# sourceMappingURL=builtins.d.ts.map
@@ -0,0 +1,57 @@
1
+ import { validateFields } from "./validate/schema.js";
2
+ function builtin({ _type, label, fields }) {
3
+ const now = new Date().toISOString();
4
+ return { _type, label, _path: `/${_type}.json`, _extension: "json", _hidden: false, _data: "", _size: 0, _raw: null, _updated_at: now, _created_at: now, fields: validateFields({ fields }) };
5
+ }
6
+ const TEXT = { _type: "text", text: "" };
7
+ const ITEM = { _type: "li", children: [TEXT] };
8
+ const inline = (label, _type) => builtin({ _type, label, fields: { children: { type: "fragments", allow: ["text", "a"], default: [TEXT] } } });
9
+ export const text = builtin({
10
+ _type: "text",
11
+ label: "Text",
12
+ fields: {
13
+ text: { type: "string" },
14
+ bold: { type: "boolean", nullable: true },
15
+ italic: { type: "boolean", nullable: true },
16
+ underline: { type: "boolean", nullable: true },
17
+ code: { type: "boolean", nullable: true },
18
+ },
19
+ });
20
+ export const img = builtin({
21
+ _type: "img",
22
+ label: "Image",
23
+ fields: {
24
+ src: { type: "url" },
25
+ alt: { type: "string" },
26
+ },
27
+ });
28
+ export const a = builtin({
29
+ _type: "a",
30
+ label: "Link",
31
+ fields: {
32
+ href: { type: "url" },
33
+ children: { type: "fragments", allow: ["text"], default: [TEXT] },
34
+ target: { type: "string", nullable: true },
35
+ rel: { type: "string", nullable: true },
36
+ },
37
+ });
38
+ export const h1 = inline("Heading 1", "h1");
39
+ export const h2 = inline("Heading 2", "h2");
40
+ export const h3 = inline("Heading 3", "h3");
41
+ export const h4 = inline("Heading 4", "h4");
42
+ export const h5 = inline("Heading 5", "h5");
43
+ export const h6 = inline("Heading 6", "h6");
44
+ export const p = inline("Paragraph", "p");
45
+ export const li = inline("List Item", "li");
46
+ export const ul = builtin({
47
+ _type: "ul",
48
+ label: "Unordered List",
49
+ fields: { children: { type: "fragments", allow: ["li"], default: [ITEM] } },
50
+ });
51
+ export const ol = builtin({
52
+ _type: "ol",
53
+ label: "Ordered List",
54
+ fields: { children: { type: "fragments", allow: ["li"], default: [ITEM] } },
55
+ });
56
+ export const builtins = [text, img, a, h1, h2, h3, h4, h5, h6, p, li, ul, ol];
57
+ //# sourceMappingURL=builtins.js.map
@@ -0,0 +1,27 @@
1
+ import type { Schema } from "../../model/types/index.js";
2
+ /**
3
+ * Tags every element in a raw template with `x-src="file:line:n"`, pointing back to where it was authored, so the editor
4
+ * can map a rendered element to its template. Runs on raw text before parsing, since no DOM parser keeps line numbers.
5
+ * `<script>`/`<style>` bodies are copied verbatim: tag-like text inside JS/CSS isn't markup.
6
+ * @param html Raw template HTML.
7
+ * @param file Name recorded in each x-src, e.g. the component's _type.
8
+ * @example annotate("<div>\n<p>Hi</p></div>", "faq") // '<div x-src="faq:1:0">\n<p x-src="faq:2:1">Hi</p></div>'
9
+ */
10
+ export declare function annotate(html: string, file: string): string;
11
+ /**
12
+ * Every object reachable from `document`, mapped to its field path (getFragment/setFragment shape), so a rendered fragment's
13
+ * path is where it lives, however the template reached it ("hero", "$.site.footer", "items.slice(0, 3)"). The shortest path
14
+ * wins when an object is reachable several ways (a document referenced twice, or a loop back through a reference).
15
+ * @example paths({ _type: "page", sections: [hero] }).get(hero) // ["sections", "0"]
16
+ */
17
+ export declare function paths(document: Record<string, unknown>): Map<object, string[]>;
18
+ /**
19
+ * The editor's pointers for the fragment at `path` in `document`: always its `x-path`, the field path (getFragment/setFragment
20
+ * shape) so the editor can map a rendered element back to the field that produced it, plus its `x-type` and `x-allow` (the
21
+ * types its field accepts, space separated) when `schemas` describe the field it sits in with an `allow` list (a fragment,
22
+ * fragments, reference or references field). The root needs no pointers.
23
+ * An array item's path ends with its index ("sections.1"), a single field's with the field ("hero.media").
24
+ * @example pointers(page, ["sections", "1"], schemas) // { "x-path": "sections.1", "x-type": "hero", "x-allow": "hero cta" }
25
+ */
26
+ export declare function pointers(document: Record<string, unknown>, path: string[], schemas?: Schema[]): Record<string, string>;
27
+ //# sourceMappingURL=annotate.d.ts.map
@@ -0,0 +1,76 @@
1
+ import { locate } from "../../model/fragment.js";
2
+ import { getSchema } from "../../model/schema.js";
3
+ /* An opening tag with its attributes, quoted values may contain ">" */
4
+ const TAG_OPEN = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
5
+ /**
6
+ * Tags every element in a raw template with `x-src="file:line:n"`, pointing back to where it was authored, so the editor
7
+ * can map a rendered element to its template. Runs on raw text before parsing, since no DOM parser keeps line numbers.
8
+ * `<script>`/`<style>` bodies are copied verbatim: tag-like text inside JS/CSS isn't markup.
9
+ * @param html Raw template HTML.
10
+ * @param file Name recorded in each x-src, e.g. the component's _type.
11
+ * @example annotate("<div>\n<p>Hi</p></div>", "faq") // '<div x-src="faq:1:0">\n<p x-src="faq:2:1">Hi</p></div>'
12
+ */
13
+ export function annotate(html, file) {
14
+ let n = 0;
15
+ let line = 1;
16
+ let cursor = 0;
17
+ let out = "";
18
+ const lines = (from, to) => html.slice(from, to).split("\n").length - 1;
19
+ TAG_OPEN.lastIndex = 0;
20
+ for (let match = TAG_OPEN.exec(html); match; match = TAG_OPEN.exec(html)) {
21
+ const [full, tag, raw] = match;
22
+ line += lines(cursor, match.index);
23
+ out += html.slice(cursor, match.index);
24
+ if (/^(script|style)$/i.test(tag)) {
25
+ const close = new RegExp(`</${tag}\\s*>`, "i").exec(html.slice(match.index));
26
+ const end = close ? match.index + close.index + close[0].length : html.length;
27
+ out += html.slice(match.index, end);
28
+ line += lines(match.index, end);
29
+ cursor = TAG_OPEN.lastIndex = end;
30
+ continue;
31
+ }
32
+ const self = raw.trimEnd().endsWith("/");
33
+ const attrs = (self ? raw.trimEnd().slice(0, -1) : raw).trimEnd();
34
+ out += `<${tag}${attrs} x-src="${file}:${line}:${n++}"${self ? " /" : ""}>`;
35
+ cursor = match.index + full.length;
36
+ }
37
+ return out + html.slice(cursor);
38
+ }
39
+ /**
40
+ * Every object reachable from `document`, mapped to its field path (getFragment/setFragment shape), so a rendered fragment's
41
+ * path is where it lives, however the template reached it ("hero", "$.site.footer", "items.slice(0, 3)"). The shortest path
42
+ * wins when an object is reachable several ways (a document referenced twice, or a loop back through a reference).
43
+ * @example paths({ _type: "page", sections: [hero] }).get(hero) // ["sections", "0"]
44
+ */
45
+ export function paths(document) {
46
+ const found = new Map([[document, []]]);
47
+ const queue = [[document, []]];
48
+ for (const [value, path] of queue) {
49
+ for (const [key, child] of Object.entries(value)) {
50
+ if (!child || typeof child !== "object" || found.has(child))
51
+ continue;
52
+ found.set(child, [...path, key]);
53
+ queue.push([child, [...path, key]]);
54
+ }
55
+ }
56
+ return found;
57
+ }
58
+ /**
59
+ * The editor's pointers for the fragment at `path` in `document`: always its `x-path`, the field path (getFragment/setFragment
60
+ * shape) so the editor can map a rendered element back to the field that produced it, plus its `x-type` and `x-allow` (the
61
+ * types its field accepts, space separated) when `schemas` describe the field it sits in with an `allow` list (a fragment,
62
+ * fragments, reference or references field). The root needs no pointers.
63
+ * An array item's path ends with its index ("sections.1"), a single field's with the field ("hero.media").
64
+ * @example pointers(page, ["sections", "1"], schemas) // { "x-path": "sections.1", "x-type": "hero", "x-allow": "hero cta" }
65
+ */
66
+ export function pointers(document, path, schemas) {
67
+ if (!path.length)
68
+ return {};
69
+ const at = (p) => p.reduce((value, key) => value?.[key], document);
70
+ const { parent, key } = locate(path);
71
+ const field = getSchema({ schemas, type: at(parent)?._type })?.fields[key];
72
+ if (!field || !("allow" in field))
73
+ return { "x-path": path.join(".") };
74
+ return { "x-path": path.join("."), "x-type": at(path)._type, "x-allow": field.allow.join(" ") };
75
+ }
76
+ //# sourceMappingURL=annotate.js.map
@@ -0,0 +1,30 @@
1
+ import type { Parser, Rendered } from "./render.js";
2
+ import { hash } from "../../utils/hash.js";
3
+ export { hash };
4
+ export declare const STYLES = "/_styles";
5
+ export declare const SCRIPTS = "/_scripts";
6
+ /**
7
+ * Pulls every non-empty `<style>` and inline `<script>` out of a template and turns each into a file named after its
8
+ * content hash, so two instances of the same component collapse into one file. A `<script src>` is already external and stays,
9
+ * and so does a data block like `<script type="application/ld+json">`, which only works inside the page.
10
+ * @returns The template without those tags, and `assets` mapping each file's path ("/_styles/<hash>.css") to its content.
11
+ */
12
+ export declare function extract(html: string, parse: Parser): Rendered;
13
+ /**
14
+ * The inverse of `extract`: puts a page's assets back into its HTML, styles before `</head>` and scripts before `</body>`
15
+ * (or prepended/appended for a bare fragment).
16
+ * @param options.inline Embeds each asset's content instead of linking its path, for HTML with no server behind it (e.g. an iframe srcdoc).
17
+ */
18
+ export declare function inject({ html, assets }: Rendered, options?: {
19
+ inline?: boolean;
20
+ }): string;
21
+ /**
22
+ * Prepares a rendered page for the site: joins its styles, in render order, into one stylesheet (a single render-blocking
23
+ * file, shared by pages with the same components), then links every asset into the HTML (see `inject`).
24
+ * @returns The final HTML, and the files to write next to it: one "/_styles/<hash>.css", and each script as it was.
25
+ * @example bundle({ html: "<h1></h1>", assets: { "/_styles/a.css": "h1 {}", "/_styles/b.css": "p {}" } }) // { html: '<link rel="stylesheet" href="/_styles/<hash>.css"><h1></h1>', assets: { "/_styles/<hash>.css": "h1 {}\np {}" } }
26
+ */
27
+ export declare function bundle({ html, assets }: Rendered): Rendered;
28
+ /** The index of the real `</tag>` in `html`, skipping comments and `<script>`/`<style>` bodies, or -1 when there's none. */
29
+ export declare function close(html: string, tag: string): number;
30
+ //# sourceMappingURL=assets.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { hash } from "../../utils/hash.js";
2
+ export { hash };
3
+ /* Where extracted styles and scripts are served from */
4
+ export const STYLES = "/_styles";
5
+ export const SCRIPTS = "/_scripts";
6
+ /* Script types the browser runs as JavaScript: any other type (application/ld+json, importmap, ...) is a data block and stays in place */
7
+ const EXECUTABLE = new Set(["", "text/javascript", "application/javascript", "module"]);
8
+ /**
9
+ * Pulls every non-empty `<style>` and inline `<script>` out of a template and turns each into a file named after its
10
+ * content hash, so two instances of the same component collapse into one file. A `<script src>` is already external and stays,
11
+ * and so does a data block like `<script type="application/ld+json">`, which only works inside the page.
12
+ * @returns The template without those tags, and `assets` mapping each file's path ("/_styles/<hash>.css") to its content.
13
+ */
14
+ export function extract(html, parse) {
15
+ const document = parse(html);
16
+ const assets = {};
17
+ for (const el of document.querySelectorAll("style, script")) {
18
+ const content = el.textContent ?? "";
19
+ if (!content.trim() || el.getAttribute("src"))
20
+ continue;
21
+ if (el.tagName.toLowerCase() === "script" && !EXECUTABLE.has((el.getAttribute("type") ?? "").trim().toLowerCase()))
22
+ continue;
23
+ assets[el.tagName.toLowerCase() === "style" ? `${STYLES}/${hash(content)}.css` : `${SCRIPTS}/${hash(content)}.js`] = content;
24
+ /* The line break after the tag goes too, or every extracted tag leaves a blank line behind */
25
+ const next = el.nextSibling;
26
+ if (next?.nodeType === 3 && !next.textContent?.trim() && next.textContent?.includes("\n"))
27
+ next.remove();
28
+ el.remove();
29
+ }
30
+ return { html: document.toString(), assets };
31
+ }
32
+ /**
33
+ * The inverse of `extract`: puts a page's assets back into its HTML, styles before `</head>` and scripts before `</body>`
34
+ * (or prepended/appended for a bare fragment).
35
+ * @param options.inline Embeds each asset's content instead of linking its path, for HTML with no server behind it (e.g. an iframe srcdoc).
36
+ */
37
+ export function inject({ html, assets }, options = {}) {
38
+ const files = Object.entries(assets);
39
+ const styles = files.filter(([path]) => path.endsWith(".css")).map(([path, css]) => (options.inline ? `<style>${css}</style>` : `<link rel="stylesheet" href="${path}">`)).join("");
40
+ const scripts = files.filter(([path]) => path.endsWith(".js")).map(([path, js]) => (options.inline ? `<script type="module">${js}</script>` : `<script type="module" src="${path}"></script>`)).join("");
41
+ const head = close(html, "head");
42
+ const out = head === -1 ? styles + html : html.slice(0, head) + styles + html.slice(head);
43
+ const body = close(out, "body");
44
+ return body === -1 ? out + scripts : out.slice(0, body) + scripts + out.slice(body);
45
+ }
46
+ /**
47
+ * Prepares a rendered page for the site: joins its styles, in render order, into one stylesheet (a single render-blocking
48
+ * file, shared by pages with the same components), then links every asset into the HTML (see `inject`).
49
+ * @returns The final HTML, and the files to write next to it: one "/_styles/<hash>.css", and each script as it was.
50
+ * @example bundle({ html: "<h1></h1>", assets: { "/_styles/a.css": "h1 {}", "/_styles/b.css": "p {}" } }) // { html: '<link rel="stylesheet" href="/_styles/<hash>.css"><h1></h1>', assets: { "/_styles/<hash>.css": "h1 {}\np {}" } }
51
+ */
52
+ export function bundle({ html, assets }) {
53
+ const files = Object.entries(assets);
54
+ const css = files.filter(([path]) => path.endsWith(".css")).map(([, data]) => data).join("\n");
55
+ const bundled = Object.fromEntries(files.filter(([path]) => !path.endsWith(".css")));
56
+ if (css)
57
+ bundled[`${STYLES}/${hash(css)}.css`] = css;
58
+ return { html: inject({ html, assets: bundled }), assets: bundled };
59
+ }
60
+ /** The index of the real `</tag>` in `html`, skipping comments and `<script>`/`<style>` bodies, or -1 when there's none. */
61
+ export function close(html, tag) {
62
+ const skip = /<!--[\s\S]*?(?:-->|$)|<(script|style)\b[^>]*>[\s\S]*?(?:<\/\1>|$)/gi;
63
+ const end = new RegExp(`</${tag}\\s*>`, "i");
64
+ let cursor = 0;
65
+ for (let match = skip.exec(html); match; match = skip.exec(html)) {
66
+ const found = end.exec(html.slice(cursor, match.index));
67
+ if (found)
68
+ return cursor + found.index;
69
+ cursor = match.index + match[0].length;
70
+ }
71
+ const found = end.exec(html.slice(cursor));
72
+ return found ? cursor + found.index : -1;
73
+ }
74
+ //# sourceMappingURL=assets.js.map
@@ -0,0 +1,18 @@
1
+ import { evaluate } from "../../utils/expression.js";
2
+ import type { Root } from "./render.js";
3
+ export { evaluate };
4
+ /**
5
+ * Applies a template's directives to `root` in place, in this order:
6
+ * 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.
7
+ * 2. `x-if` removes the element when falsy.
8
+ * 3. `x-bind` sets the element's text, or renders a fragment (or array of fragments) value through `render` into it.
9
+ * 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
+ * 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.
14
+ */
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;
18
+ //# sourceMappingURL=directives.d.ts.map
@@ -0,0 +1,93 @@
1
+ import { isFragment, unsafeUrl } from "../../model/types/index.js";
2
+ import { evaluate } from "../../utils/expression.js";
3
+ /* The expression evaluator lives in utils/expression.ts (pull and push use it too), re-exported here where it started */
4
+ export { evaluate };
5
+ /* Attributes a browser loads or navigates to, so a bound value with a javascript:, vbscript: or data: url is dropped from them (see `unsafeUrl`), whatever the field's type */
6
+ const URL_ATTRIBUTES = new Set(["href", "src", "action", "formaction", "xlink:href", "poster", "cite", "background"]);
7
+ /**
8
+ * Applies a template's directives to `root` in place, in this order:
9
+ * 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.
10
+ * 2. `x-if` removes the element when falsy.
11
+ * 3. `x-bind` sets the element's text, or renders a fragment (or array of fragments) value through `render` into it.
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
+ * 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.
17
+ */
18
+ export function apply(root, data, render, mark, top = data) {
19
+ for (const el of root.querySelectorAll("[x-for]")) {
20
+ const expr = el.getAttribute("x-for");
21
+ el.removeAttribute("x-for");
22
+ /* x-bind on the same element wins */
23
+ if (el.getAttribute("x-bind") != null)
24
+ continue;
25
+ const items = evaluate(expr, data, top);
26
+ if (Array.isArray(items)) {
27
+ /* Every clone after the first gets the whitespace before the original, so items keep the template's indentation */
28
+ const before = el.previousSibling;
29
+ const indent = before?.nodeType === 3 && !before.textContent?.trim() ? before.textContent ?? "" : "";
30
+ el.replaceWith(...items.flatMap((item, i) => {
31
+ const clone = el.cloneNode(true);
32
+ if (isFragment(item))
33
+ mark(clone, item);
34
+ /* 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);
37
+ return i && indent ? [indent, clone] : [clone];
38
+ }));
39
+ }
40
+ else if (items != null) {
41
+ bind(el, items, top);
42
+ apply(el, items, render, mark, top);
43
+ }
44
+ }
45
+ /*
46
+ * A <template>'s markup is authored like the rest of the component (e.g. a line a script clones per basket item), so its
47
+ * directives get the same data. Queries from outside never reach template content, so each template is applied on its own.
48
+ * Parsers keep that content in different places: linkedom (server) as the template's own children, with `.content` only
49
+ * a copy whose changes are never serialized, the browser only in `.content`. Hence the children when there are any.
50
+ * Runs after x-for, so a template inside a repeated element is applied with that item's data first.
51
+ */
52
+ for (const el of root.querySelectorAll("template")) {
53
+ const template = el;
54
+ const content = template.firstElementChild ? template : template.content;
55
+ if (content)
56
+ apply(content, data, render, mark, top);
57
+ }
58
+ for (const el of root.querySelectorAll("[x-if]")) {
59
+ if (evaluate(el.getAttribute("x-if"), data, top))
60
+ el.removeAttribute("x-if");
61
+ else
62
+ el.remove();
63
+ }
64
+ for (const el of root.querySelectorAll("[x-bind]")) {
65
+ const expr = el.getAttribute("x-bind");
66
+ const value = evaluate(expr, data, top);
67
+ const unresolved = (f) => `<!-- unresolved type: ${f._type} -->`;
68
+ if (isFragment(value))
69
+ el.innerHTML = render(value) ?? unresolved(value);
70
+ else if (Array.isArray(value) && value.every(isFragment))
71
+ el.innerHTML = value.map((v) => render(v) ?? unresolved(v)).join("");
72
+ else
73
+ el.textContent = value == null ? "" : String(value);
74
+ el.removeAttribute("x-bind");
75
+ }
76
+ for (const el of root.querySelectorAll("*"))
77
+ bind(el, data, top);
78
+ }
79
+ /* Applies an element's own `x-bind:attr` directives against `data` (see `apply`, step 4) */
80
+ function bind(el, data, top) {
81
+ for (const { name, value } of [...el.attributes]) {
82
+ if (!name.startsWith("x-bind:") || name === "x-bind:")
83
+ continue;
84
+ const result = evaluate(value, data, top);
85
+ const attr = name.slice("x-bind:".length);
86
+ if (result == null || (URL_ATTRIBUTES.has(attr.toLowerCase()) && unsafeUrl(String(result))))
87
+ el.removeAttribute(attr);
88
+ else
89
+ el.setAttribute(attr, String(result));
90
+ el.removeAttribute(name);
91
+ }
92
+ }
93
+ //# sourceMappingURL=directives.js.map
@@ -0,0 +1,24 @@
1
+ import type { Source } from "../../model/types/index.js";
2
+ /**
3
+ * Builds "/sitemap.xml", listing every .html file among the output files at the URL it's served at:
4
+ * "/blog/index.html" at "/blog/", any other .html file at its own path, with its `updated_at` as `<lastmod>`. Hidden files (a leading ".") are left out.
5
+ * @param url The site's base URL, e.g. "https://example.com".
6
+ * @param sources The build's output files.
7
+ * @example sitemap("https://example.com", output).data // '<?xml version="1.0" ...<loc>https://example.com/blog/</loc>...'
8
+ */
9
+ export declare function sitemap(url: string, sources: Source[]): Source;
10
+ /**
11
+ * Stamps a page with a "Made with Fragmentor" HTML comment and optional published date, right after the doctype when there is one.
12
+ * @param options.published When the site went live, printed in UTC.
13
+ * @example stamp("<!doctype html><html></html>", { published: new Date("2026-11-02T10:00:00Z") })
14
+ */
15
+ export declare function stamp(html: string, { published }?: {
16
+ published?: Date;
17
+ }): string;
18
+ /**
19
+ * Builds "/robots.txt", allowing every crawler and pointing it at the sitemap.
20
+ * @param url The site's base URL, e.g. "https://example.com".
21
+ * @example robots("https://example.com").data // "User-agent: *\nAllow: /\n\nSitemap: https://example.com/sitemap.xml\n"
22
+ */
23
+ export declare function robots(url: string): Source;
24
+ //# sourceMappingURL=generate.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { source } from "../source/index.js";
2
+ import { parse } from "../../utils/path.js";
3
+ /* The absolute URL of a route on the site, e.g. ("https://example.com/", "/blog") -> "https://example.com/blog" */
4
+ const absolute = (url, route) => url.replace(/\/+$/, "") + encodeURI(route);
5
+ /**
6
+ * Builds "/sitemap.xml", listing every .html file among the output files at the URL it's served at:
7
+ * "/blog/index.html" at "/blog/", any other .html file at its own path, with its `updated_at` as `<lastmod>`. Hidden files (a leading ".") are left out.
8
+ * @param url The site's base URL, e.g. "https://example.com".
9
+ * @param sources The build's output files.
10
+ * @example sitemap("https://example.com", output).data // '<?xml version="1.0" ...<loc>https://example.com/blog/</loc>...'
11
+ */
12
+ export function sitemap(url, sources) {
13
+ const pages = sources.filter((s) => s.path.endsWith(".html") && !parse(s.path).hidden);
14
+ const entries = pages.map((s) => {
15
+ const loc = absolute(url, s.path.replace(/(^|\/)index\.html$/, "$1")).replace(/&/g, "&amp;").replace(/'/g, "&apos;");
16
+ return ` <url><loc>${loc}</loc><lastmod>${s.updated_at}</lastmod></url>`;
17
+ });
18
+ return source({
19
+ path: "/sitemap.xml",
20
+ data: `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.join("\n")}\n</urlset>\n`,
21
+ });
22
+ }
23
+ /**
24
+ * Stamps a page with a "Made with Fragmentor" HTML comment and optional published date, right after the doctype when there is one.
25
+ * @param options.published When the site went live, printed in UTC.
26
+ * @example stamp("<!doctype html><html></html>", { published: new Date("2026-11-02T10:00:00Z") })
27
+ */
28
+ export function stamp(html, { published } = {}) {
29
+ const date = published?.toLocaleString("en-US", { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
30
+ const comment = `<!-- Made with Fragmentor - fragmentor.io -->\n${date ? `<!-- Published ${date} UTC -->\n` : ""}`;
31
+ const doctype = /^\s*<!doctype[^>]*>\s*/i.exec(html)?.[0] ?? "";
32
+ return `${doctype.trimEnd()}${doctype ? "\n" : ""}${comment}${html.slice(doctype.length)}`;
33
+ }
34
+ /**
35
+ * Builds "/robots.txt", allowing every crawler and pointing it at the sitemap.
36
+ * @param url The site's base URL, e.g. "https://example.com".
37
+ * @example robots("https://example.com").data // "User-agent: *\nAllow: /\n\nSitemap: https://example.com/sitemap.xml\n"
38
+ */
39
+ export function robots(url) {
40
+ return source({ path: "/robots.txt", data: `User-agent: *\nAllow: /\n\nSitemap: ${absolute(url, "/sitemap.xml")}\n` });
41
+ }
42
+ //# sourceMappingURL=generate.js.map
@@ -0,0 +1,43 @@
1
+ import type { Source } from "../../model/types/index.js";
2
+ import { type Parser } from "./render.js";
3
+ export type Compiled = {
4
+ output: Source[];
5
+ errors: {
6
+ path: string;
7
+ message: string;
8
+ }[];
9
+ warnings: {
10
+ path: string;
11
+ message: string;
12
+ }[];
13
+ };
14
+ /**
15
+ * Compiles a project's sources into the files of its site, with no filesystem access so it runs anywhere:
16
+ * 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
+ * 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
+ * 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.
20
+ * 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
+ * 5. Stamps each page (see `stamp`): a "Made with Fragmentor" comment at the top, with `published` when it was published.
22
+ * 6. With a `url`, generates "/sitemap.xml" and "/robots.txt" (see `sitemap` and `robots`).
23
+ * 7. Passes assets through with "/assets" stripped ("/assets/images/logo" -> "/images/logo"). An asset wins over a page or generated file at the same path. One with an extension assets can't have is left out (and listed in `errors`).
24
+ * @param sources Every source of the project, with its full path ("/documents/blog/hello", "/components/page", ...).
25
+ * @param options.parse Parses HTML: linkedom on the server, the native DOM in the browser.
26
+ * @param options.dev Adds the editor's `x-src`/`x-path` pointers to every page, and keeps hidden documents (a leading ".") so drafts can be previewed.
27
+ * @param options.url The site's base URL ("https://example.com"), needed for the absolute URLs in the generated files.
28
+ * @param options.route Renders only the page at this route ("/blog"), for a preview that shows one page at a time and recompiles on every edit.
29
+ * @param options.published When the site goes live, stamped on every page. Passed by the caller so the build stays deterministic.
30
+ * @returns The output files as Sources (write each to its `path`), and every error and warning by file.
31
+ * @example compile(sources, { parse: (html) => parseHTML(html).document })
32
+ */
33
+ export declare function compile(sources: Source[], { parse, dev, url, route, published }: {
34
+ parse: Parser;
35
+ dev?: boolean;
36
+ url?: string;
37
+ route?: string;
38
+ published?: Date;
39
+ }): Compiled;
40
+ export { render, lookup, type Parser, type Parsed, type Rendered } from "./render.js";
41
+ export { bundle, extract, inject } from "./assets.js";
42
+ export { annotate } from "./annotate.js";
43
+ //# sourceMappingURL=index.d.ts.map