gen-llm-md 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +115 -2
- package/cli.d.ts +2 -0
- package/cli.js +50 -0
- package/entities.d.ts +15 -0
- package/entities.js +95 -0
- package/esm/cli.d.ts +2 -0
- package/esm/cli.js +48 -0
- package/esm/entities.d.ts +15 -0
- package/esm/entities.js +81 -0
- package/esm/files.d.ts +10 -0
- package/esm/files.js +106 -0
- package/esm/html.d.ts +6 -0
- package/esm/html.js +103 -0
- package/esm/index.d.ts +48 -0
- package/esm/index.js +116 -0
- package/esm/render.d.ts +12 -0
- package/esm/render.js +55 -0
- package/esm/types.d.ts +45 -0
- package/esm/types.js +1 -0
- package/files.d.ts +10 -0
- package/files.js +113 -0
- package/html.d.ts +6 -0
- package/html.js +109 -0
- package/index.d.ts +48 -0
- package/index.js +149 -0
- package/package.json +29 -3
- package/render.d.ts +12 -0
- package/render.js +63 -0
- package/types.d.ts +45 -0
- package/types.js +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
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,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gen-llm-md
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generate `llms.txt` and Markdown twins from an existing static HTML export. The
|
|
4
|
+
tool reads each page's main content, embedded JSON-LD, and HTML metadata. It
|
|
5
|
+
never crawls the site or fetches a separate JSON-LD dataset.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm exec gen-llm-md generate --dir out --site-url https://example.com --exclude /preview
|
|
9
|
+
pnpm exec gen-llm-md generate --config ./llms.config.mjs --dry-run
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Requires Node 22.12+. `--dir` defaults to `out`; paths are relative to the
|
|
13
|
+
working directory. `--exclude` is repeatable. A config is a synchronous JS
|
|
14
|
+
module exporting a config object. CLI flags override the directory and site
|
|
15
|
+
URL and add to the exclusions. Dry run lists the files without writing.
|
|
16
|
+
|
|
17
|
+
Flat and trailing-slash exports (for example, `guide.html` and
|
|
18
|
+
`guide/index.html`) both map to `guide.md`. The generator skips 404s,
|
|
19
|
+
redirects, and noindex pages (except legal pages), and resolves relative
|
|
20
|
+
content links against the page URL. Mark UI to omit with `data-llm-ignore`.
|
|
21
|
+
ARIA tables convert to Markdown tables; presentation tables are flattened.
|
|
22
|
+
An explicit primary entity can supply page metadata. A named page retains
|
|
23
|
+
its own identity when the graph lists collection members or related topics.
|
|
24
|
+
|
|
25
|
+
## Library
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { generate, flattenLayoutTables } from 'gen-llm-md';
|
|
29
|
+
|
|
30
|
+
const isIssue = ({ route }) => route.startsWith('/issues/');
|
|
31
|
+
const config = {
|
|
32
|
+
outDir: 'out',
|
|
33
|
+
siteUrl: 'https://example.com',
|
|
34
|
+
exclude: ['/preview'],
|
|
35
|
+
transforms: [
|
|
36
|
+
{ match: /^\/issues\//, apply: ({ $ }) => flattenLayoutTables($, '.issue-body table') },
|
|
37
|
+
],
|
|
38
|
+
index: {
|
|
39
|
+
sections: (pages) => [
|
|
40
|
+
{ title: 'Issues', pages: pages.filter(isIssue) },
|
|
41
|
+
{ title: 'Pages', pages: pages.filter((page) => !isIssue(page)) },
|
|
42
|
+
],
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
await generate(config);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- `planGeneration(config)` returns the site identity, twins, and artifacts
|
|
49
|
+
without writing. `generate(config)` also writes them.
|
|
50
|
+
- Use `pageContent(page)` for a page whose Markdown body is available at build
|
|
51
|
+
time but is not rendered in the HTML; return `{ body }` and optionally
|
|
52
|
+
`title` or `description` to override the defaults. Parsed pages expose
|
|
53
|
+
`html`, `$` (Cheerio), `jsonld`, `meta(name)`, the canonical `url`,
|
|
54
|
+
and the exported HTML and Markdown paths.
|
|
55
|
+
- Use `nativeMarkdown()` to supply complete twins and their index metadata.
|
|
56
|
+
A twin's `markdown` string or byte array is written as supplied, without
|
|
57
|
+
normalization or content filtering. Providers must apply site policy to
|
|
58
|
+
their native output themselves. `blockedHosts` applies to generated
|
|
59
|
+
content.
|
|
60
|
+
- Import or override the individual pipeline stages: `discoverPages`,
|
|
61
|
+
`parsePage`, `selectPageEntity`, `selectSiteIdentity`, `htmlToMarkdown`,
|
|
62
|
+
`renderTwin`, `renderIndex`, `planManifest`, and `writeArtifacts`.
|
|
63
|
+
Pass overrides under `pipeline`, or compose the functions independently.
|
|
64
|
+
|
|
65
|
+
The tool records its output in `out/.llms-markdown.json`. For deployments
|
|
66
|
+
that keep stale Markdown, pass `stale: { previousManifest: 'previous.json',
|
|
67
|
+
unavailable: true }` and carry the last deployed manifest forward before
|
|
68
|
+
each clean build. If the output directory survives builds, the default
|
|
69
|
+
previous manifest is the one already in it. A removed route gets a notice
|
|
70
|
+
twin, not an index entry. Existing files not matching the previous
|
|
71
|
+
generated bytes are left alone. You can provide a function instead of
|
|
72
|
+
`true` to render a custom notice.
|
|
73
|
+
|
|
74
|
+
Generation refuses to overwrite an existing Markdown file unless the
|
|
75
|
+
current export manifest or the configured previous manifest records its
|
|
76
|
+
exact bytes. With notices disabled, the export manifest continues to
|
|
77
|
+
track unchanged generated twins left on disk but omitted from the index.
|
|
78
|
+
On the first run over an older export without a manifest, rebuild into
|
|
79
|
+
a clean directory.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Development
|
|
84
|
+
|
|
85
|
+
### Setup
|
|
86
|
+
|
|
87
|
+
1. Clone the repository:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
git clone https://github.com/constructive-io/dev-utils.git
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
2. Install dependencies:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
cd dev-utils
|
|
97
|
+
pnpm install
|
|
98
|
+
pnpm build
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
3. Test the package of interest:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
cd packages/<packagename>
|
|
105
|
+
pnpm test:watch
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Credits
|
|
109
|
+
|
|
110
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
111
|
+
|
|
112
|
+
## Disclaimer
|
|
113
|
+
|
|
114
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
115
|
+
|
|
116
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/cli.d.ts
ADDED
package/cli.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const node_module_1 = require("node:module");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
const index_1 = require("./index");
|
|
8
|
+
const usage = 'Usage: gen-llm-md generate [--dir out] [--site-url https://example.com] [--exclude /preview] [--config ./llms.config.mjs] [--dry-run]';
|
|
9
|
+
async function main() {
|
|
10
|
+
const { values, positionals } = (0, node_util_1.parseArgs)({
|
|
11
|
+
allowPositionals: true,
|
|
12
|
+
options: {
|
|
13
|
+
dir: { type: 'string' },
|
|
14
|
+
'site-url': { type: 'string' },
|
|
15
|
+
exclude: { type: 'string', multiple: true },
|
|
16
|
+
config: { type: 'string' },
|
|
17
|
+
'dry-run': { type: 'boolean' },
|
|
18
|
+
help: { type: 'boolean', short: 'h' },
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
if (values.help) {
|
|
22
|
+
console.log(usage);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (positionals.length !== 1 || positionals[0] !== 'generate')
|
|
26
|
+
throw new Error(usage);
|
|
27
|
+
const requireConfig = (0, node_module_1.createRequire)((0, node_path_1.resolve)('package.json'));
|
|
28
|
+
const imported = values.config ? requireConfig((0, node_path_1.resolve)(values.config)) : {};
|
|
29
|
+
const options = imported.default ?? imported;
|
|
30
|
+
const siteUrl = values['site-url'] ?? options.siteUrl;
|
|
31
|
+
if (!siteUrl)
|
|
32
|
+
throw new Error(`Missing site URL. ${usage}`);
|
|
33
|
+
const config = {
|
|
34
|
+
...options, siteUrl, outDir: values.dir ?? options.outDir ?? 'out',
|
|
35
|
+
exclude: [...(options.exclude ?? []), ...(values.exclude ?? [])],
|
|
36
|
+
};
|
|
37
|
+
if (values['dry-run']) {
|
|
38
|
+
const { artifacts } = await (0, index_1.planGeneration)(config);
|
|
39
|
+
for (const artifact of artifacts)
|
|
40
|
+
console.log(artifact.file);
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const { twins } = await (0, index_1.generate)(config);
|
|
44
|
+
console.log(`Generated ${twins.length} Markdown twins and llms.txt in ${config.outDir}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
void main().catch((error) => {
|
|
48
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
49
|
+
process.exitCode = 1;
|
|
50
|
+
});
|
package/entities.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Entity, ParsedPage } from './types';
|
|
2
|
+
export declare const isEntity: (value: unknown) => value is Entity;
|
|
3
|
+
export declare const list: (value: unknown) => unknown[];
|
|
4
|
+
export declare const text: (value: unknown) => string;
|
|
5
|
+
export declare const types: (entity: Entity) => string[];
|
|
6
|
+
export declare const name: (entity?: Entity) => string;
|
|
7
|
+
export declare function entities(value: unknown): Entity[];
|
|
8
|
+
export declare function urlFor(value: unknown, base: URL): URL | undefined;
|
|
9
|
+
export declare const sameRoute: (a: URL, b: URL) => boolean;
|
|
10
|
+
export declare function sitePath(siteUrl: string, path: string): URL;
|
|
11
|
+
export declare function selectPageEntity(page: ParsedPage): Entity | undefined;
|
|
12
|
+
export declare function selectSiteIdentity(page: ParsedPage): {
|
|
13
|
+
title: string;
|
|
14
|
+
description: string;
|
|
15
|
+
};
|
package/entities.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sameRoute = exports.name = exports.types = exports.text = exports.list = exports.isEntity = void 0;
|
|
4
|
+
exports.entities = entities;
|
|
5
|
+
exports.urlFor = urlFor;
|
|
6
|
+
exports.sitePath = sitePath;
|
|
7
|
+
exports.selectPageEntity = selectPageEntity;
|
|
8
|
+
exports.selectSiteIdentity = selectSiteIdentity;
|
|
9
|
+
const isEntity = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
10
|
+
exports.isEntity = isEntity;
|
|
11
|
+
const list = (value) => Array.isArray(value) ? value : [value];
|
|
12
|
+
exports.list = list;
|
|
13
|
+
const text = (value) => typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
14
|
+
exports.text = text;
|
|
15
|
+
const types = (entity) => (0, exports.list)(entity['@type']).map(exports.text).filter(Boolean);
|
|
16
|
+
exports.types = types;
|
|
17
|
+
const name = (entity) => entity ? (0, exports.text)(entity.headline) || (0, exports.text)(entity.name) : '';
|
|
18
|
+
exports.name = name;
|
|
19
|
+
function entities(value) {
|
|
20
|
+
return (0, exports.list)(value).filter(exports.isEntity).flatMap((entity) => [
|
|
21
|
+
...(entity['@type'] ? [entity] : []),
|
|
22
|
+
...('@graph' in entity ? entities(entity['@graph']) : []),
|
|
23
|
+
]);
|
|
24
|
+
}
|
|
25
|
+
function urlFor(value, base) {
|
|
26
|
+
const address = (0, exports.text)((0, exports.isEntity)(value) ? value['@id'] || value.url : value);
|
|
27
|
+
if (!address)
|
|
28
|
+
return;
|
|
29
|
+
try {
|
|
30
|
+
return new URL(address, base);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const pathKey = (url) => url.pathname.replace(/\/$/, '');
|
|
37
|
+
const sameRoute = (a, b) => a.origin === b.origin && pathKey(a) === pathKey(b);
|
|
38
|
+
exports.sameRoute = sameRoute;
|
|
39
|
+
function sitePath(siteUrl, path) {
|
|
40
|
+
const base = new URL(siteUrl);
|
|
41
|
+
base.pathname = `${pathKey(base)}/`;
|
|
42
|
+
return new URL(`./${path.replace(/^\/+/, '')}`, base);
|
|
43
|
+
}
|
|
44
|
+
function matches(value, url) {
|
|
45
|
+
const candidate = urlFor(value, url);
|
|
46
|
+
return !!candidate && (0, exports.sameRoute)(candidate, url);
|
|
47
|
+
}
|
|
48
|
+
function references(page, value) {
|
|
49
|
+
return (0, exports.list)(value).flatMap((ref) => {
|
|
50
|
+
const id = urlFor(ref, page.url)?.href;
|
|
51
|
+
const resolved = id && page.jsonld.find((entity) => urlFor(entity['@id'], page.url)?.href === id);
|
|
52
|
+
return resolved ? [resolved] : (0, exports.isEntity)(ref) && ref['@type'] ? [ref] : [];
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function selectPageEntity(page) {
|
|
56
|
+
const { jsonld, url } = page;
|
|
57
|
+
const matchesPage = (entity) => {
|
|
58
|
+
const addresses = [...(0, exports.list)(entity.url), ...(0, exports.list)(entity.mainEntityOfPage)].filter(Boolean);
|
|
59
|
+
if (addresses.length)
|
|
60
|
+
return addresses.some((value) => matches(value, url));
|
|
61
|
+
const id = urlFor(entity['@id'], url);
|
|
62
|
+
return !!id && (0, exports.sameRoute)(id, url) &&
|
|
63
|
+
(!!pathKey(url) || ['', '#page', '#webpage', '#home', '#profilepage'].includes(id.hash.toLowerCase()));
|
|
64
|
+
};
|
|
65
|
+
const candidates = jsonld.filter(matchesPage);
|
|
66
|
+
const pageEntity = candidates.find((entity) => (0, exports.types)(entity).some((type) => /Page$/.test(type)));
|
|
67
|
+
if (pageEntity) {
|
|
68
|
+
const primary = references(page, pageEntity.mainEntity).filter((entity) => (0, exports.name)(entity));
|
|
69
|
+
if (primary.length === 1 && (!Array.isArray(pageEntity.mainEntity) || !(0, exports.name)(pageEntity)))
|
|
70
|
+
return primary[0];
|
|
71
|
+
if (!(0, exports.name)(pageEntity) && (0, exports.types)(pageEntity).includes('WebPage')) {
|
|
72
|
+
const subjects = references(page, pageEntity.about).filter((entity) => (0, exports.name)(entity));
|
|
73
|
+
if (subjects.length === 1)
|
|
74
|
+
return subjects[0];
|
|
75
|
+
}
|
|
76
|
+
return pageEntity;
|
|
77
|
+
}
|
|
78
|
+
return candidates.find((entity) => !(0, exports.types)(entity).includes('WebSite') && (0, exports.name)(entity));
|
|
79
|
+
}
|
|
80
|
+
function selectSiteIdentity(page) {
|
|
81
|
+
const { jsonld, url } = page;
|
|
82
|
+
const websites = jsonld.filter((node) => (0, exports.types)(node).includes('WebSite'));
|
|
83
|
+
const canonical = new URL('#website', url).href;
|
|
84
|
+
const website = websites.find((node) => urlFor(node['@id'], url)?.href === canonical &&
|
|
85
|
+
(!node.url || (0, exports.list)(node.url).some((value) => matches(value, url))))
|
|
86
|
+
?? websites.find((node) => (0, exports.list)(node.url).some((value) => matches(value, url)));
|
|
87
|
+
const person = references(page, website?.mainEntity).find((node) => (0, exports.types)(node).includes('Person'))
|
|
88
|
+
?? (!website ? jsonld.find((node) => (0, exports.types)(node).includes('Person') &&
|
|
89
|
+
((0, exports.list)(node.url).some((value) => matches(value, url)) ||
|
|
90
|
+
urlFor(node['@id'], url)?.href === new URL('#person', url).href)) : undefined);
|
|
91
|
+
return {
|
|
92
|
+
title: (0, exports.name)(person) || (0, exports.name)(website),
|
|
93
|
+
description: (0, exports.text)(website?.description) || (0, exports.text)(person?.description),
|
|
94
|
+
};
|
|
95
|
+
}
|
package/esm/cli.d.ts
ADDED
package/esm/cli.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { generate, planGeneration } from './index';
|
|
6
|
+
const usage = 'Usage: gen-llm-md generate [--dir out] [--site-url https://example.com] [--exclude /preview] [--config ./llms.config.mjs] [--dry-run]';
|
|
7
|
+
async function main() {
|
|
8
|
+
const { values, positionals } = parseArgs({
|
|
9
|
+
allowPositionals: true,
|
|
10
|
+
options: {
|
|
11
|
+
dir: { type: 'string' },
|
|
12
|
+
'site-url': { type: 'string' },
|
|
13
|
+
exclude: { type: 'string', multiple: true },
|
|
14
|
+
config: { type: 'string' },
|
|
15
|
+
'dry-run': { type: 'boolean' },
|
|
16
|
+
help: { type: 'boolean', short: 'h' },
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
if (values.help) {
|
|
20
|
+
console.log(usage);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (positionals.length !== 1 || positionals[0] !== 'generate')
|
|
24
|
+
throw new Error(usage);
|
|
25
|
+
const requireConfig = createRequire(resolve('package.json'));
|
|
26
|
+
const imported = values.config ? requireConfig(resolve(values.config)) : {};
|
|
27
|
+
const options = imported.default ?? imported;
|
|
28
|
+
const siteUrl = values['site-url'] ?? options.siteUrl;
|
|
29
|
+
if (!siteUrl)
|
|
30
|
+
throw new Error(`Missing site URL. ${usage}`);
|
|
31
|
+
const config = {
|
|
32
|
+
...options, siteUrl, outDir: values.dir ?? options.outDir ?? 'out',
|
|
33
|
+
exclude: [...(options.exclude ?? []), ...(values.exclude ?? [])],
|
|
34
|
+
};
|
|
35
|
+
if (values['dry-run']) {
|
|
36
|
+
const { artifacts } = await planGeneration(config);
|
|
37
|
+
for (const artifact of artifacts)
|
|
38
|
+
console.log(artifact.file);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const { twins } = await generate(config);
|
|
42
|
+
console.log(`Generated ${twins.length} Markdown twins and llms.txt in ${config.outDir}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
void main().catch((error) => {
|
|
46
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
47
|
+
process.exitCode = 1;
|
|
48
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Entity, ParsedPage } from './types';
|
|
2
|
+
export declare const isEntity: (value: unknown) => value is Entity;
|
|
3
|
+
export declare const list: (value: unknown) => unknown[];
|
|
4
|
+
export declare const text: (value: unknown) => string;
|
|
5
|
+
export declare const types: (entity: Entity) => string[];
|
|
6
|
+
export declare const name: (entity?: Entity) => string;
|
|
7
|
+
export declare function entities(value: unknown): Entity[];
|
|
8
|
+
export declare function urlFor(value: unknown, base: URL): URL | undefined;
|
|
9
|
+
export declare const sameRoute: (a: URL, b: URL) => boolean;
|
|
10
|
+
export declare function sitePath(siteUrl: string, path: string): URL;
|
|
11
|
+
export declare function selectPageEntity(page: ParsedPage): Entity | undefined;
|
|
12
|
+
export declare function selectSiteIdentity(page: ParsedPage): {
|
|
13
|
+
title: string;
|
|
14
|
+
description: string;
|
|
15
|
+
};
|
package/esm/entities.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export const isEntity = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
export const list = (value) => Array.isArray(value) ? value : [value];
|
|
3
|
+
export const text = (value) => typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
4
|
+
export const types = (entity) => list(entity['@type']).map(text).filter(Boolean);
|
|
5
|
+
export const name = (entity) => entity ? text(entity.headline) || text(entity.name) : '';
|
|
6
|
+
export function entities(value) {
|
|
7
|
+
return list(value).filter(isEntity).flatMap((entity) => [
|
|
8
|
+
...(entity['@type'] ? [entity] : []),
|
|
9
|
+
...('@graph' in entity ? entities(entity['@graph']) : []),
|
|
10
|
+
]);
|
|
11
|
+
}
|
|
12
|
+
export function urlFor(value, base) {
|
|
13
|
+
const address = text(isEntity(value) ? value['@id'] || value.url : value);
|
|
14
|
+
if (!address)
|
|
15
|
+
return;
|
|
16
|
+
try {
|
|
17
|
+
return new URL(address, base);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const pathKey = (url) => url.pathname.replace(/\/$/, '');
|
|
24
|
+
export const sameRoute = (a, b) => a.origin === b.origin && pathKey(a) === pathKey(b);
|
|
25
|
+
export function sitePath(siteUrl, path) {
|
|
26
|
+
const base = new URL(siteUrl);
|
|
27
|
+
base.pathname = `${pathKey(base)}/`;
|
|
28
|
+
return new URL(`./${path.replace(/^\/+/, '')}`, base);
|
|
29
|
+
}
|
|
30
|
+
function matches(value, url) {
|
|
31
|
+
const candidate = urlFor(value, url);
|
|
32
|
+
return !!candidate && sameRoute(candidate, url);
|
|
33
|
+
}
|
|
34
|
+
function references(page, value) {
|
|
35
|
+
return list(value).flatMap((ref) => {
|
|
36
|
+
const id = urlFor(ref, page.url)?.href;
|
|
37
|
+
const resolved = id && page.jsonld.find((entity) => urlFor(entity['@id'], page.url)?.href === id);
|
|
38
|
+
return resolved ? [resolved] : isEntity(ref) && ref['@type'] ? [ref] : [];
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export function selectPageEntity(page) {
|
|
42
|
+
const { jsonld, url } = page;
|
|
43
|
+
const matchesPage = (entity) => {
|
|
44
|
+
const addresses = [...list(entity.url), ...list(entity.mainEntityOfPage)].filter(Boolean);
|
|
45
|
+
if (addresses.length)
|
|
46
|
+
return addresses.some((value) => matches(value, url));
|
|
47
|
+
const id = urlFor(entity['@id'], url);
|
|
48
|
+
return !!id && sameRoute(id, url) &&
|
|
49
|
+
(!!pathKey(url) || ['', '#page', '#webpage', '#home', '#profilepage'].includes(id.hash.toLowerCase()));
|
|
50
|
+
};
|
|
51
|
+
const candidates = jsonld.filter(matchesPage);
|
|
52
|
+
const pageEntity = candidates.find((entity) => types(entity).some((type) => /Page$/.test(type)));
|
|
53
|
+
if (pageEntity) {
|
|
54
|
+
const primary = references(page, pageEntity.mainEntity).filter((entity) => name(entity));
|
|
55
|
+
if (primary.length === 1 && (!Array.isArray(pageEntity.mainEntity) || !name(pageEntity)))
|
|
56
|
+
return primary[0];
|
|
57
|
+
if (!name(pageEntity) && types(pageEntity).includes('WebPage')) {
|
|
58
|
+
const subjects = references(page, pageEntity.about).filter((entity) => name(entity));
|
|
59
|
+
if (subjects.length === 1)
|
|
60
|
+
return subjects[0];
|
|
61
|
+
}
|
|
62
|
+
return pageEntity;
|
|
63
|
+
}
|
|
64
|
+
return candidates.find((entity) => !types(entity).includes('WebSite') && name(entity));
|
|
65
|
+
}
|
|
66
|
+
export function selectSiteIdentity(page) {
|
|
67
|
+
const { jsonld, url } = page;
|
|
68
|
+
const websites = jsonld.filter((node) => types(node).includes('WebSite'));
|
|
69
|
+
const canonical = new URL('#website', url).href;
|
|
70
|
+
const website = websites.find((node) => urlFor(node['@id'], url)?.href === canonical &&
|
|
71
|
+
(!node.url || list(node.url).some((value) => matches(value, url))))
|
|
72
|
+
?? websites.find((node) => list(node.url).some((value) => matches(value, url)));
|
|
73
|
+
const person = references(page, website?.mainEntity).find((node) => types(node).includes('Person'))
|
|
74
|
+
?? (!website ? jsonld.find((node) => types(node).includes('Person') &&
|
|
75
|
+
(list(node.url).some((value) => matches(value, url)) ||
|
|
76
|
+
urlFor(node['@id'], url)?.href === new URL('#person', url).href)) : undefined);
|
|
77
|
+
return {
|
|
78
|
+
title: name(person) || name(website),
|
|
79
|
+
description: text(website?.description) || text(person?.description),
|
|
80
|
+
};
|
|
81
|
+
}
|
package/esm/files.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Artifact, ExportPage, Twin } from './types';
|
|
2
|
+
export declare function discoverPages(outDir: string): ExportPage[];
|
|
3
|
+
export declare function markdownArtifact(file: string, contents: Artifact['contents']): Artifact;
|
|
4
|
+
export declare function writeArtifacts(outDir: string, artifacts: readonly Artifact[], stale?: StaleOptions): void;
|
|
5
|
+
export declare const manifestFile = ".llms-markdown.json";
|
|
6
|
+
export type StaleOptions = {
|
|
7
|
+
previousManifest?: string;
|
|
8
|
+
unavailable?: boolean | ((entry: Pick<Twin, 'route' | 'file'>) => string);
|
|
9
|
+
};
|
|
10
|
+
export declare function planManifest(outDir: string, twins: readonly Twin[], stale?: StaleOptions): Artifact[];
|
package/esm/files.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, relative, sep } from 'node:path';
|
|
4
|
+
export function discoverPages(outDir) {
|
|
5
|
+
if (!existsSync(join(outDir, 'index.html')))
|
|
6
|
+
throw new Error(`Missing static export: ${outDir}/index.html`);
|
|
7
|
+
const files = readdirSync(outDir, { recursive: true, withFileTypes: true })
|
|
8
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.html'))
|
|
9
|
+
.map((entry) => relative(outDir, join(entry.parentPath, entry.name)).split(sep).join('/'))
|
|
10
|
+
.filter((file) => !file.startsWith('_next/') && file !== '404.html' && file !== '404/index.html')
|
|
11
|
+
.sort();
|
|
12
|
+
const exported = new Set(files);
|
|
13
|
+
const pages = files.filter((file) => file !== 'index.html' &&
|
|
14
|
+
(file.endsWith('/index.html') || !exported.has(`${file.slice(0, -'.html'.length)}/index.html`)));
|
|
15
|
+
return ['index.html', ...pages].map((htmlFile) => {
|
|
16
|
+
const route = htmlFile === 'index.html' ? '/' : `/${htmlFile.replace(/\/index\.html$/, '/').replace(/\.html$/, '')}`;
|
|
17
|
+
return { route, htmlFile, file: route === '/' ? 'index.md' : `${route.slice(1).replace(/\/$/, '')}.md` };
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function safePath(file) {
|
|
21
|
+
if (!file || file.includes('\\') || file.split('/').some((part) => !part || part === '.' || part === '..')) {
|
|
22
|
+
throw new Error(`Invalid artifact path: ${file}`);
|
|
23
|
+
}
|
|
24
|
+
return file;
|
|
25
|
+
}
|
|
26
|
+
function artifactPath(outDir, file) {
|
|
27
|
+
const segments = safePath(file).split('/');
|
|
28
|
+
let target = outDir;
|
|
29
|
+
for (const segment of ['', ...segments]) {
|
|
30
|
+
target = join(target, segment);
|
|
31
|
+
if (lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
32
|
+
throw new Error(`Refusing to follow artifact symlink: ${target}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return target;
|
|
36
|
+
}
|
|
37
|
+
export function markdownArtifact(file, contents) {
|
|
38
|
+
return { file, contents, markdown: true };
|
|
39
|
+
}
|
|
40
|
+
export function writeArtifacts(outDir, artifacts, stale = {}) {
|
|
41
|
+
const targets = artifacts.map((artifact) => ({ ...artifact, target: artifactPath(outDir, artifact.file) }));
|
|
42
|
+
const existingTwins = targets.filter(({ file, target, markdown }) => (markdown || /\.(?:md|markdown)$/i.test(file)) && existsSync(target));
|
|
43
|
+
if (existingTwins.length) {
|
|
44
|
+
const current = artifactPath(outDir, manifestFile);
|
|
45
|
+
const manifests = [current];
|
|
46
|
+
if (stale.previousManifest && stale.previousManifest !== current)
|
|
47
|
+
manifests.push(stale.previousManifest);
|
|
48
|
+
const owned = manifests.map((path) => new Map(readManifest(path).map(({ file, sha256 }) => [file, sha256])));
|
|
49
|
+
for (const { file, target } of existingTwins) {
|
|
50
|
+
const sha256 = lstatSync(target).isFile() ? digest(readFileSync(target)) : undefined;
|
|
51
|
+
if (!sha256 || !owned.some((manifest) => manifest.get(file) === sha256)) {
|
|
52
|
+
throw new Error(`Refusing to overwrite unowned Markdown: ${file}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const { target, contents } of targets) {
|
|
57
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
58
|
+
const handle = openSync(target, constants.O_CREAT | constants.O_TRUNC | constants.O_WRONLY | constants.O_NOFOLLOW);
|
|
59
|
+
try {
|
|
60
|
+
writeFileSync(handle, contents);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
closeSync(handle);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
68
|
+
export const manifestFile = '.llms-markdown.json';
|
|
69
|
+
function readManifest(path) {
|
|
70
|
+
if (!existsSync(path))
|
|
71
|
+
return [];
|
|
72
|
+
const manifest = JSON.parse(readFileSync(path, 'utf8'));
|
|
73
|
+
if (manifest.version !== 1 || !Array.isArray(manifest.twins))
|
|
74
|
+
throw new Error(`Invalid twin manifest: ${path}`);
|
|
75
|
+
return manifest.twins;
|
|
76
|
+
}
|
|
77
|
+
export function planManifest(outDir, twins, stale = {}) {
|
|
78
|
+
const entries = twins.map(({ route, file, markdown }) => ({ route, file, sha256: digest(markdown) }));
|
|
79
|
+
const tombstones = [];
|
|
80
|
+
const previous = (stale.unavailable && stale.previousManifest) || artifactPath(outDir, manifestFile);
|
|
81
|
+
const files = new Set(entries.map(({ file }) => file));
|
|
82
|
+
for (const entry of readManifest(previous)) {
|
|
83
|
+
const { route, file, sha256 } = entry;
|
|
84
|
+
if (typeof route !== 'string' || typeof file !== 'string') {
|
|
85
|
+
throw new Error(`Invalid twin manifest entry: ${previous}`);
|
|
86
|
+
}
|
|
87
|
+
if (files.has(file))
|
|
88
|
+
continue;
|
|
89
|
+
const path = artifactPath(outDir, file);
|
|
90
|
+
const existing = lstatSync(path, { throwIfNoEntry: false });
|
|
91
|
+
if (existing && (!existing.isFile() || digest(readFileSync(path)) !== sha256))
|
|
92
|
+
continue;
|
|
93
|
+
files.add(file);
|
|
94
|
+
if (stale.unavailable) {
|
|
95
|
+
const contents = typeof stale.unavailable === 'function'
|
|
96
|
+
? stale.unavailable({ route, file })
|
|
97
|
+
: '# Page no longer available\n\nThis page is no longer part of the site.\n';
|
|
98
|
+
entries.push({ route, file, sha256: digest(contents), unavailable: true });
|
|
99
|
+
tombstones.push(markdownArtifact(file, contents));
|
|
100
|
+
}
|
|
101
|
+
else if (existing) {
|
|
102
|
+
entries.push(entry);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return [...tombstones, { file: manifestFile, contents: `${JSON.stringify({ version: 1, twins: entries }, null, 2)}\n` }];
|
|
106
|
+
}
|
package/esm/html.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type CheerioAPI } from 'cheerio';
|
|
2
|
+
import type { ExportPage, ParsedPage } from './types';
|
|
3
|
+
export declare function parsePage(page: ExportPage, html: string, siteUrl: string): ParsedPage;
|
|
4
|
+
export declare function flattenLayoutTables($: CheerioAPI, selector?: string): void;
|
|
5
|
+
export declare function normalizeRoleTables($: CheerioAPI): void;
|
|
6
|
+
export declare function htmlToMarkdown(html: string): string;
|