@cagov/ca-ds 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +600 -2
- package/bin/ca-ds.js +5 -0
- package/package.json +62 -4
- package/src/cli/add.js +134 -0
- package/src/cli/build.js +15 -0
- package/src/cli/diff.js +39 -0
- package/src/cli/eject.js +112 -0
- package/src/cli/exit.js +22 -0
- package/src/cli/format.js +52 -0
- package/src/cli/init.js +148 -0
- package/src/cli/install.js +178 -0
- package/src/cli/items.js +10 -0
- package/src/cli/login.js +331 -0
- package/src/cli/main.js +108 -0
- package/src/cli/new.js +230 -0
- package/src/cli/outdated.js +74 -0
- package/src/cli/pack.js +75 -0
- package/src/cli/preview.js +31 -0
- package/src/cli/publish.js +295 -0
- package/src/cli/pull.js +208 -0
- package/src/cli/remote.js +52 -0
- package/src/cli/remove.js +69 -0
- package/src/cli/update.js +223 -0
- package/src/cli/validate.js +131 -0
- package/src/lib/browser.js +12 -0
- package/src/lib/build.js +249 -0
- package/src/lib/bundle.js +148 -0
- package/src/lib/catalog.js +44 -0
- package/src/lib/checks.js +31 -0
- package/src/lib/collection.js +65 -0
- package/src/lib/emblem.js +29 -0
- package/src/lib/fixtures.js +59 -0
- package/src/lib/floor.js +79 -0
- package/src/lib/glyph.js +148 -0
- package/src/lib/image.js +138 -0
- package/src/lib/json-text.js +213 -0
- package/src/lib/keys.js +322 -0
- package/src/lib/links.js +321 -0
- package/src/lib/markdown.js +408 -0
- package/src/lib/merge.js +93 -0
- package/src/lib/pack.js +30 -0
- package/src/lib/page-schema.js +368 -0
- package/src/lib/page.js +372 -0
- package/src/lib/patch.js +9 -0
- package/src/lib/regions.js +173 -0
- package/src/lib/registry.js +371 -0
- package/src/lib/release.js +119 -0
- package/src/lib/repoints.js +120 -0
- package/src/lib/resolve.js +32 -0
- package/src/lib/schema.js +28 -0
- package/src/lib/serial.js +4 -0
- package/src/lib/serialize.js +444 -0
- package/src/lib/structured.js +72 -0
- package/src/lib/system.js +13 -0
- package/src/lib/targets.js +85 -0
- package/src/lib/terms.js +11 -0
- package/src/lib/token-view.js +289 -0
- package/src/lib/tokens.js +247 -0
- package/src/lib/version.js +34 -0
- package/src/preview/frame.js +75 -0
- package/src/preview/pages.js +128 -0
- package/src/preview/preview.css +58 -0
- package/src/preview/screenshots.js +72 -0
- package/src/preview/server.js +378 -0
- package/src/preview/shell.js +153 -0
- package/src/schema/a11y.schema.json +56 -0
- package/src/schema/collection.lock.schema.json +58 -0
- package/src/schema/collection.schema.json +65 -0
- package/src/schema/composition.schema.json +98 -0
- package/src/schema/contract.schema.json +116 -0
- package/src/schema/interface.schema.json +257 -0
- package/src/schema/item.schema.json +362 -0
- package/src/schema/release.schema.json +39 -0
- package/src/schema/system.schema.json +75 -0
- package/src/schema/variants.schema.json +60 -0
- package/src/validate/collection.js +19 -0
- package/src/validate/collisions.js +124 -0
- package/src/validate/context.js +357 -0
- package/src/validate/facts.js +253 -0
- package/src/validate/files.js +103 -0
- package/src/validate/findings.js +19 -0
- package/src/validate/glyphs.js +126 -0
- package/src/validate/html.js +215 -0
- package/src/validate/imports.js +29 -0
- package/src/validate/index.js +75 -0
- package/src/validate/item.js +47 -0
- package/src/validate/links.js +113 -0
- package/src/validate/manifest.js +147 -0
- package/src/validate/media.js +65 -0
- package/src/validate/page.js +74 -0
- package/src/validate/prefixes.js +58 -0
- package/src/validate/relations.js +310 -0
- package/src/validate/release.js +109 -0
- package/src/validate/skill.js +122 -0
- package/src/validate/structured.js +335 -0
- package/src/validate/tasc.js +80 -0
- package/src/validate/template.js +129 -0
- package/src/validate/tokens.js +154 -0
- package/src/validate/zip.js +40 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { glob, readdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import { join, sep } from 'node:path';
|
|
3
|
+
import { framedBody } from './frame.js';
|
|
4
|
+
|
|
5
|
+
export const PAGE_SKIP = new Set(['node_modules', '.git', 'build']);
|
|
6
|
+
|
|
7
|
+
function marker(src, name) {
|
|
8
|
+
const m = src.match(new RegExp(`<!--\\s*${name}:\\s*(.+?)\\s*-->`));
|
|
9
|
+
return m ? m[1].trim() : null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// A <ca-layout> page brings its own gutter; any other takes the demo gutter.
|
|
13
|
+
function insetFor(src) {
|
|
14
|
+
const declared = marker(src, 'preview-inset');
|
|
15
|
+
if (declared) return declared === 'on';
|
|
16
|
+
return !/<ca-layout[\s/>]/i.test(src);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');
|
|
20
|
+
|
|
21
|
+
export const itemAssetUrl = (name, path) => `/assets/item/${name}/${encodePath(path)}`;
|
|
22
|
+
|
|
23
|
+
// A two-segment entry names a file of the page's own item; otherwise the first two segments are a scoped name.
|
|
24
|
+
function stylesFor(value, scope, names) {
|
|
25
|
+
if (!value) return null;
|
|
26
|
+
return value.split(',').map((entry) => {
|
|
27
|
+
const parts = entry.trim().split('/');
|
|
28
|
+
const local = scope && names.has(`${scope}/${parts[0]}`);
|
|
29
|
+
const [name, path] = local ? [`${scope}/${parts[0]}`, parts.slice(1)] : [parts.slice(0, 2).join('/'), parts.slice(2)];
|
|
30
|
+
return itemAssetUrl(name, path.join('/'));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const isDocument = (src) => /<html[\s>]/i.test(src);
|
|
35
|
+
|
|
36
|
+
function toPage({ group, route, file, kind, src, entry = null, scope = null, names }) {
|
|
37
|
+
const document = kind === 'page' && isDocument(src);
|
|
38
|
+
const body = document ? src : framedBody(src, entry?.frame);
|
|
39
|
+
return {
|
|
40
|
+
group,
|
|
41
|
+
route,
|
|
42
|
+
file,
|
|
43
|
+
kind,
|
|
44
|
+
title: entry?.title || marker(src, 'preview-title') || route,
|
|
45
|
+
description: entry?.description ?? null,
|
|
46
|
+
styles: stylesFor(marker(src, 'preview-styles'), scope, names),
|
|
47
|
+
inset: insetFor(body),
|
|
48
|
+
document,
|
|
49
|
+
body,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const scopeOf = (name) => name.slice(0, name.indexOf('/'));
|
|
54
|
+
const namesOf = (collection) => new Set(collection.items.map((i) => i.manifest.name));
|
|
55
|
+
|
|
56
|
+
async function checkFiles(root, item) {
|
|
57
|
+
try {
|
|
58
|
+
const names = await readdir(join(root, item.dir, 'checks'));
|
|
59
|
+
return names.filter((n) => n.endsWith('.html')).sort().map((n) => `checks/${n}`);
|
|
60
|
+
} catch {
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function itemPage(collection, item, file, entry, names) {
|
|
66
|
+
const { name } = item.manifest;
|
|
67
|
+
const src = await readFile(join(collection.root, item.dir, file), 'utf8');
|
|
68
|
+
const kind = entry ? 'example' : 'check';
|
|
69
|
+
return toPage({ group: name, route: `item/${name}/${encodePath(file)}`, file, kind, src, entry, scope: scopeOf(name), names });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const examplesOf = (item) => (item.manifest.files ?? []).filter((f) => f.role === 'reference-html');
|
|
73
|
+
|
|
74
|
+
// Manifest order, so the default example comes first.
|
|
75
|
+
async function pagesOf(collection, item, names) {
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const entry of examplesOf(item)) out.push(await itemPage(collection, item, entry.path, entry, names));
|
|
78
|
+
for (const file of await checkFiles(collection.root, item)) out.push(await itemPage(collection, item, file, null, names));
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function pageFiles(collection) {
|
|
83
|
+
const patterns = collection.config?.pages ?? [];
|
|
84
|
+
if (patterns.length === 0) return [];
|
|
85
|
+
const skip = new Set([...PAGE_SKIP, (collection.config.dist ?? 'dist').split('/')[0]]);
|
|
86
|
+
const found = new Set();
|
|
87
|
+
const exclude = (path) => skip.has(String(path).split(/[\\/]/).pop());
|
|
88
|
+
for await (const path of glob(patterns, { cwd: collection.root, exclude })) {
|
|
89
|
+
if (path.endsWith('.html')) found.add(path.split(sep).join('/'));
|
|
90
|
+
}
|
|
91
|
+
return [...found].sort();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function collectionPage(collection, file, names = namesOf(collection)) {
|
|
95
|
+
const src = await readFile(join(collection.root, file), 'utf8');
|
|
96
|
+
return toPage({ group: 'Pages', route: `page/${encodePath(file)}`, file, kind: 'page', src, names });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const rank = (item) => (item.manifest.kind === 'template' ? 0 : 1);
|
|
100
|
+
|
|
101
|
+
// Re-run per request, so an added or deleted page shows with no restart.
|
|
102
|
+
export async function discover(collection) {
|
|
103
|
+
const names = namesOf(collection);
|
|
104
|
+
const groups = new Map();
|
|
105
|
+
const own = [];
|
|
106
|
+
for (const file of await pageFiles(collection)) own.push(await collectionPage(collection, file, names));
|
|
107
|
+
if (own.length) groups.set('Pages', own);
|
|
108
|
+
const items = [...collection.items].sort((a, b) => rank(a) - rank(b) || a.manifest.name.localeCompare(b.manifest.name));
|
|
109
|
+
for (const item of items) {
|
|
110
|
+
const pages = await pagesOf(collection, item, names);
|
|
111
|
+
if (pages.length) groups.set(item.manifest.name, pages);
|
|
112
|
+
}
|
|
113
|
+
return groups;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A lookup by manifest and checks/, never a filesystem walk from file.
|
|
117
|
+
export async function findItemPage(collection, name, file) {
|
|
118
|
+
const item = collection.items.find((i) => i.manifest.name === name);
|
|
119
|
+
if (!item) return null;
|
|
120
|
+
const entry = examplesOf(item).find((f) => f.path === file) ?? null;
|
|
121
|
+
if (!entry && !(await checkFiles(collection.root, item)).includes(file)) return null;
|
|
122
|
+
return itemPage(collection, item, file, entry, namesOf(collection));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function findCollectionPage(collection, file) {
|
|
126
|
+
if (!(await pageFiles(collection)).includes(file)) return null;
|
|
127
|
+
return collectionPage(collection, file);
|
|
128
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/* Demo chrome. It sets no type on bare elements, so the bundle's own output shows. */
|
|
2
|
+
|
|
3
|
+
/* Padding, not margin, so the body's background reaches the frame edge. */
|
|
4
|
+
body[data-preview-inset] {
|
|
5
|
+
padding: 1.5rem;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
@media screen and (min-width: 1024px) {
|
|
9
|
+
body[data-preview-inset] {
|
|
10
|
+
padding: 2.5rem;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
.role {
|
|
15
|
+
color: #8e8e8e;
|
|
16
|
+
font-family: ui-monospace, monospace;
|
|
17
|
+
font-size: 0.75rem;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
.demo-note {
|
|
21
|
+
color: #555;
|
|
22
|
+
font-size: 0.875rem;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/* Check pages only; an example renders as a consumer's page would. */
|
|
26
|
+
body:not([data-preview-example]) section {
|
|
27
|
+
padding-block: 1rem;
|
|
28
|
+
border-block-end: 1px solid #ddd;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/* A class, since a bare hr rule would outrank divider's :where(hr). */
|
|
32
|
+
.demo-rule {
|
|
33
|
+
border: 0;
|
|
34
|
+
border-block-start: 1px solid #d9d9d9;
|
|
35
|
+
margin-block: 3rem;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
.demo-label {
|
|
39
|
+
color: #8e8e8e;
|
|
40
|
+
font-family: ui-monospace, monospace;
|
|
41
|
+
font-size: 0.75rem;
|
|
42
|
+
margin-block: 2.5rem 0.5rem;
|
|
43
|
+
margin-inline: 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
ca-layout .demo-label {
|
|
47
|
+
margin-inline: var(--ca-well-inset);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
.demo-label-warn {
|
|
51
|
+
color: #a5391f;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
.demo-well {
|
|
55
|
+
background: #eef4f8;
|
|
56
|
+
outline: 1px dashed #7fa7c4;
|
|
57
|
+
padding-block: 0.5rem;
|
|
58
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs';
|
|
2
|
+
import { join, relative } from 'node:path';
|
|
3
|
+
import { createPreview } from './server.js';
|
|
4
|
+
|
|
5
|
+
const VIEWPORT = { width: 1440, height: 900 };
|
|
6
|
+
const QUALITY = 0.82;
|
|
7
|
+
|
|
8
|
+
export function shots(items, root, names = []) {
|
|
9
|
+
const out = [];
|
|
10
|
+
for (const { dir, manifest } of items) {
|
|
11
|
+
if (names.length && !names.includes(manifest.name)) continue;
|
|
12
|
+
for (const f of (manifest.files ?? []).filter((x) => x.role === 'reference-html' && x.site === 'image')) {
|
|
13
|
+
for (const theme of ['light', 'dark']) {
|
|
14
|
+
if (f.image?.[theme]) out.push({ name: manifest.name, route: `item/${manifest.name}/${f.path}`, theme, out: join(root, dir, f.image[theme]) });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function chromium() {
|
|
22
|
+
try {
|
|
23
|
+
return (await import('playwright-core')).chromium;
|
|
24
|
+
} catch (err) {
|
|
25
|
+
if (err?.code !== 'ERR_MODULE_NOT_FOUND' || !String(err.message).includes('playwright-core')) throw err;
|
|
26
|
+
throw new Error('ca-ds preview --screenshots needs playwright-core, which is not installed. Install it beside @cagov/ca-ds with npm install --save-dev playwright-core, and run it again.');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function screenshots(collection, { names = [], log = console.log } = {}) {
|
|
31
|
+
const todo = shots(collection.items, collection.root, names);
|
|
32
|
+
if (todo.length === 0) {
|
|
33
|
+
log('No example sets site to image.');
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
const launch = await chromium();
|
|
37
|
+
const preview = createPreview({ root: collection.root });
|
|
38
|
+
await new Promise((done) => preview.server.listen(0, done));
|
|
39
|
+
const base = `http://localhost:${preview.server.address().port}`;
|
|
40
|
+
const browser = await launch.launch(process.env.CA_DS_CHROME ? { executablePath: process.env.CA_DS_CHROME } : { channel: 'chrome' });
|
|
41
|
+
try {
|
|
42
|
+
const page = await browser.newPage({ viewport: VIEWPORT });
|
|
43
|
+
const encoder = await browser.newPage();
|
|
44
|
+
for (const shot of todo) {
|
|
45
|
+
const res = await page.goto(`${base}/frame/${shot.route}`, { waitUntil: 'networkidle' });
|
|
46
|
+
if (!res?.ok()) throw new Error(`${shot.route} answered ${res?.status()}, not a page.`);
|
|
47
|
+
await page.evaluate(async (theme) => {
|
|
48
|
+
document.documentElement.style.colorScheme = theme;
|
|
49
|
+
await document.fonts.ready;
|
|
50
|
+
}, shot.theme);
|
|
51
|
+
const png = (await page.screenshot({ type: 'png' })).toString('base64');
|
|
52
|
+
// Chrome encodes the WebP from its own PNG capture, so no image library is needed.
|
|
53
|
+
const webp = await encoder.evaluate(
|
|
54
|
+
async ({ png, quality }) => {
|
|
55
|
+
const img = new Image();
|
|
56
|
+
img.src = `data:image/png;base64,${png}`;
|
|
57
|
+
await img.decode();
|
|
58
|
+
const canvas = Object.assign(document.createElement('canvas'), { width: img.naturalWidth, height: img.naturalHeight });
|
|
59
|
+
canvas.getContext('2d').drawImage(img, 0, 0);
|
|
60
|
+
return canvas.toDataURL('image/webp', quality).split(',')[1];
|
|
61
|
+
},
|
|
62
|
+
{ png, quality: QUALITY },
|
|
63
|
+
);
|
|
64
|
+
writeFileSync(shot.out, Buffer.from(webp, 'base64'));
|
|
65
|
+
log(`Wrote ${relative(collection.root, shot.out)} (${shot.name}, ${shot.theme})`);
|
|
66
|
+
}
|
|
67
|
+
} finally {
|
|
68
|
+
await browser.close();
|
|
69
|
+
await preview.close();
|
|
70
|
+
}
|
|
71
|
+
return todo;
|
|
72
|
+
}
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import { createServer, get } from 'node:http';
|
|
2
|
+
import { statSync, watch } from 'node:fs';
|
|
3
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
4
|
+
import { extname, join, relative, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { buildTokens, readTokenSources } from '../lib/tokens.js';
|
|
7
|
+
import { buildSet, diskSource, buildCss, buildJs, fontAssets, copied } from '../lib/build.js';
|
|
8
|
+
import { fixtureFolders } from '../lib/fixtures.js';
|
|
9
|
+
import { openUrl } from '../lib/browser.js';
|
|
10
|
+
import { openCollection, COLLECTION } from '../lib/collection.js';
|
|
11
|
+
import { discover, findItemPage, findCollectionPage, pageFiles, PAGE_SKIP } from './pages.js';
|
|
12
|
+
import { renderFrame } from './frame.js';
|
|
13
|
+
import { renderIndex, renderShell, renderDocument } from './shell.js';
|
|
14
|
+
|
|
15
|
+
export const IDENTITY = 'ca-ds-preview';
|
|
16
|
+
const PREVIEW_CSS = fileURLToPath(new URL('./preview.css', import.meta.url));
|
|
17
|
+
const { version } = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
18
|
+
|
|
19
|
+
const TYPES = {
|
|
20
|
+
'.html': 'text/html',
|
|
21
|
+
'.css': 'text/css',
|
|
22
|
+
'.js': 'text/javascript',
|
|
23
|
+
'.mjs': 'text/javascript',
|
|
24
|
+
'.json': 'application/json',
|
|
25
|
+
'.map': 'application/json',
|
|
26
|
+
'.svg': 'image/svg+xml',
|
|
27
|
+
'.png': 'image/png',
|
|
28
|
+
'.jpg': 'image/jpeg',
|
|
29
|
+
'.jpeg': 'image/jpeg',
|
|
30
|
+
'.gif': 'image/gif',
|
|
31
|
+
'.webp': 'image/webp',
|
|
32
|
+
'.avif': 'image/avif',
|
|
33
|
+
'.ico': 'image/x-icon',
|
|
34
|
+
'.woff2': 'font/woff2',
|
|
35
|
+
'.woff': 'font/woff',
|
|
36
|
+
'.ttf': 'font/ttf',
|
|
37
|
+
'.otf': 'font/otf',
|
|
38
|
+
'.txt': 'text/plain',
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const WATCH_SKIP = new Set(['node_modules', 'build', 'dist', '.git']);
|
|
42
|
+
|
|
43
|
+
function send(res, status, type, body) {
|
|
44
|
+
res.writeHead(status, { 'content-type': type });
|
|
45
|
+
res.end(body);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const notFound = (res) => send(res, 404, 'text/plain', 'Not found');
|
|
49
|
+
|
|
50
|
+
// Null for any segment that could leave the folder it's joined to once decoded.
|
|
51
|
+
function segments(rest) {
|
|
52
|
+
try {
|
|
53
|
+
const parts = rest.split('/').map(decodeURIComponent);
|
|
54
|
+
return parts.every((p) => p && p !== '.' && p !== '..' && !/[/\\\0]/.test(p)) ? parts : null;
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The fixtures collection's members win a folder-name clash.
|
|
61
|
+
function mediaFolders(collection) {
|
|
62
|
+
const byName = new Map(collection.items.map((i) => [i.manifest.name, i]));
|
|
63
|
+
const fixtures = byName.get(collection.system?.fixtures)?.manifest ?? null;
|
|
64
|
+
const folders = fixtureFolders(fixtures, byName);
|
|
65
|
+
for (const item of collection.items) {
|
|
66
|
+
const slug = item.dir.split('/').pop();
|
|
67
|
+
if (item.manifest.kind !== 'media' || item.dir === '.' || folders.has(slug)) continue;
|
|
68
|
+
folders.set(slug, { name: item.manifest.name, item, files: new Set((item.manifest.files ?? []).map((f) => f.path)) });
|
|
69
|
+
}
|
|
70
|
+
return folders;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createPreview({ root, identity = {} }) {
|
|
74
|
+
let collection = null;
|
|
75
|
+
let cache = {};
|
|
76
|
+
let media = null;
|
|
77
|
+
let fonts = null;
|
|
78
|
+
let setSource = null;
|
|
79
|
+
let linked = null;
|
|
80
|
+
const clients = new Set();
|
|
81
|
+
|
|
82
|
+
const current = () => (collection ??= openCollection(root));
|
|
83
|
+
const label = () => current().config?.namespaces?.join(', ') || root;
|
|
84
|
+
|
|
85
|
+
function broadcast(event, data = '') {
|
|
86
|
+
const payload = `event: ${event}\ndata: ${String(data).replace(/\n/g, '\\n')}\n\n`;
|
|
87
|
+
for (const res of clients) {
|
|
88
|
+
try {
|
|
89
|
+
res.write(payload);
|
|
90
|
+
} catch {
|
|
91
|
+
/* the socket is gone, and its close handler reaps it */
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function events(req, res) {
|
|
97
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
|
|
98
|
+
res.write(': connected\n\n');
|
|
99
|
+
clients.add(res);
|
|
100
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 30000);
|
|
101
|
+
const drop = () => {
|
|
102
|
+
clearInterval(ping);
|
|
103
|
+
clients.delete(res);
|
|
104
|
+
};
|
|
105
|
+
req.on('close', drop);
|
|
106
|
+
res.on('error', drop);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// /assets/ stands for this folder, which the build's url()s and maps resolve against.
|
|
110
|
+
const out = join(root, 'assets');
|
|
111
|
+
const source = () => (setSource ??= diskSource(root, buildSet(current())));
|
|
112
|
+
|
|
113
|
+
async function asset(name) {
|
|
114
|
+
if (name in cache) return cache[name];
|
|
115
|
+
if (name === 'tokens.css') {
|
|
116
|
+
cache[name] = { type: 'text/css', body: await buildTokens({ sources: readTokenSources(root) }) };
|
|
117
|
+
} else if (name === 'bundle.css' || name === 'bundle.css.map') {
|
|
118
|
+
const { code, map, assets } = await buildCss(source(), { out, locate: copied(source(), out) });
|
|
119
|
+
cache['bundle.css'] = { type: 'text/css', body: `${code}\n/*# sourceMappingURL=bundle.css.map */\n` };
|
|
120
|
+
cache['bundle.css.map'] = { type: 'application/json', body: JSON.stringify(map) };
|
|
121
|
+
linked = assets;
|
|
122
|
+
} else if (name === 'bundle.js' || name === 'bundle.js.map') {
|
|
123
|
+
const { code, map } = await buildJs(source(), { out, file: 'bundle.js' });
|
|
124
|
+
cache['bundle.js'] = { type: 'text/javascript', body: code };
|
|
125
|
+
cache['bundle.js.map'] = { type: 'application/json', body: JSON.stringify(map) };
|
|
126
|
+
} else {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
return cache[name] ?? null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function fontFiles() {
|
|
133
|
+
if (fonts) return fonts;
|
|
134
|
+
if (!linked) await asset('bundle.css');
|
|
135
|
+
fonts = new Map([...fontAssets(source(), out), ...linked].map((a) => [relative(out, a.to).split(sep).join('/'), a.from]));
|
|
136
|
+
return fonts;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function page(res, kind, rest, render) {
|
|
140
|
+
const parts = segments(rest);
|
|
141
|
+
if (!parts) return send(res, 400, 'text/plain', 'Bad path');
|
|
142
|
+
let found = null;
|
|
143
|
+
if (kind === 'item' && parts.length >= 3) {
|
|
144
|
+
found = await findItemPage(current(), `${parts[0]}/${parts[1]}`, parts.slice(2).join('/'));
|
|
145
|
+
} else if (kind === 'page') {
|
|
146
|
+
found = await findCollectionPage(current(), parts.join('/'));
|
|
147
|
+
if (!found && render === renderFrame) return pageAsset(res, parts);
|
|
148
|
+
}
|
|
149
|
+
if (!found) return send(res, 404, 'text/plain', 'No such page');
|
|
150
|
+
const html = render === renderFrame && found.document ? renderDocument(found) : render(found);
|
|
151
|
+
send(res, 200, 'text/html', html);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Only beside a collection page, and only a type TYPES lists.
|
|
155
|
+
async function pageAsset(res, parts) {
|
|
156
|
+
const file = parts.join('/');
|
|
157
|
+
const type = TYPES[extname(file).toLowerCase()];
|
|
158
|
+
if (!type || parts.some((p) => PAGE_SKIP.has(p))) return notFound(res);
|
|
159
|
+
const dirs = (await pageFiles(current())).map((p) => p.slice(0, p.lastIndexOf('/') + 1));
|
|
160
|
+
if (!dirs.some((d) => file.startsWith(d))) return notFound(res);
|
|
161
|
+
try {
|
|
162
|
+
return send(res, 200, type, await readFile(join(root, ...parts)));
|
|
163
|
+
} catch {
|
|
164
|
+
return notFound(res);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function itemAsset(res, parts) {
|
|
169
|
+
const item = current().items.find((i) => i.manifest.name === `${parts[0]}/${parts[1]}`);
|
|
170
|
+
const path = parts.slice(2).join('/');
|
|
171
|
+
const type = TYPES[extname(path).toLowerCase()];
|
|
172
|
+
if (!item || !type || !(item.manifest.files ?? []).some((f) => f.path === path)) return notFound(res);
|
|
173
|
+
try {
|
|
174
|
+
return send(res, 200, type, await readFile(join(root, item.dir, ...parts.slice(2))));
|
|
175
|
+
} catch {
|
|
176
|
+
return notFound(res);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function mediaFile(res, parts) {
|
|
181
|
+
const type = TYPES[extname(parts[1]).toLowerCase()];
|
|
182
|
+
if (!type) return send(res, 400, 'text/plain', 'Bad path');
|
|
183
|
+
media ??= mediaFolders(current());
|
|
184
|
+
const member = media.get(parts[0]);
|
|
185
|
+
if (!member?.files.has(parts[1])) return notFound(res);
|
|
186
|
+
try {
|
|
187
|
+
return send(res, 200, type, await readFile(join(root, member.item.dir, parts[1])));
|
|
188
|
+
} catch {
|
|
189
|
+
return notFound(res);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const server = createServer(async (req, res) => {
|
|
194
|
+
try {
|
|
195
|
+
const path = new URL(req.url, 'http://localhost').pathname;
|
|
196
|
+
let m;
|
|
197
|
+
if (path === '/') return send(res, 200, 'text/html', renderIndex(await discover(current()), label()));
|
|
198
|
+
if (path === '/events') return events(req, res);
|
|
199
|
+
if (path === '/__preview__') {
|
|
200
|
+
const port = server.address()?.port ?? null;
|
|
201
|
+
return send(res, 200, 'application/json', JSON.stringify({ ...identity, name: IDENTITY, root, pid: process.pid, port, version }));
|
|
202
|
+
}
|
|
203
|
+
if ((m = path.match(/^\/(preview|frame)\/(item|page)\/(.+)$/))) {
|
|
204
|
+
return page(res, m[2], m[3], m[1] === 'preview' ? renderShell : renderFrame);
|
|
205
|
+
}
|
|
206
|
+
if (path === '/assets/preview.css') return send(res, 200, 'text/css', await readFile(PREVIEW_CSS));
|
|
207
|
+
if ((m = path.match(/^\/assets\/item\/(.+)$/))) {
|
|
208
|
+
const parts = segments(m[1]);
|
|
209
|
+
if (!parts || parts.length < 3) return send(res, 400, 'text/plain', 'Bad path');
|
|
210
|
+
return itemAsset(res, parts);
|
|
211
|
+
}
|
|
212
|
+
if ((m = path.match(/^\/assets\/(.+)$/))) {
|
|
213
|
+
try {
|
|
214
|
+
const built = await asset(m[1]);
|
|
215
|
+
if (built) return send(res, 200, built.type, built.body);
|
|
216
|
+
const font = (await fontFiles()).get(m[1]);
|
|
217
|
+
return font ? send(res, 200, TYPES[extname(font).toLowerCase()] ?? 'application/octet-stream', await readFile(font)) : notFound(res);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
// Shown in the shell's overlay, never as stale output.
|
|
220
|
+
broadcast('builderror', err?.message ?? String(err));
|
|
221
|
+
return send(res, 500, 'text/css', `/* build error: ${err?.message ?? err} */`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if ((m = path.match(/^\/media\/([^/]+)\/([^/]+)$/))) {
|
|
225
|
+
const parts = segments(`${m[1]}/${m[2]}`);
|
|
226
|
+
if (!parts) return send(res, 400, 'text/plain', 'Bad path');
|
|
227
|
+
return mediaFile(res, parts);
|
|
228
|
+
}
|
|
229
|
+
notFound(res);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
send(res, 500, 'text/plain', String(err?.stack ?? err));
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
// One watcher per top-level folder, since Linux's recursive watch would walk node_modules.
|
|
236
|
+
const watchers = new Map();
|
|
237
|
+
let timer;
|
|
238
|
+
const changed = () => {
|
|
239
|
+
clearTimeout(timer);
|
|
240
|
+
timer = setTimeout(() => {
|
|
241
|
+
collection = null;
|
|
242
|
+
cache = {};
|
|
243
|
+
media = null;
|
|
244
|
+
fonts = null;
|
|
245
|
+
setSource = null;
|
|
246
|
+
linked = null;
|
|
247
|
+
broadcast('reload');
|
|
248
|
+
}, 75);
|
|
249
|
+
};
|
|
250
|
+
let distPath = 'dist';
|
|
251
|
+
const readDist = () => {
|
|
252
|
+
try {
|
|
253
|
+
distPath = (openCollection(root).config?.dist ?? 'dist').replace(/\\/g, '/').replace(/^\.\/|\/$/g, '');
|
|
254
|
+
} catch {
|
|
255
|
+
distPath = 'dist';
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const skipped = (name) => WATCH_SKIP.has(name) || name === distPath;
|
|
259
|
+
const ignored = (path) => path.split('/').some((p) => WATCH_SKIP.has(p)) || path.startsWith(`${distPath}/`);
|
|
260
|
+
function watchFolder(name) {
|
|
261
|
+
if (watchers.has(name) || skipped(name)) return;
|
|
262
|
+
try {
|
|
263
|
+
if (!statSync(join(root, name)).isDirectory()) return;
|
|
264
|
+
const w = watch(join(root, name), { recursive: true }, (event, file) => {
|
|
265
|
+
if (!file || !ignored(`${name}/${String(file).replace(/\\/g, '/')}`)) changed();
|
|
266
|
+
});
|
|
267
|
+
w.on('error', () => {
|
|
268
|
+
w.close();
|
|
269
|
+
watchers.delete(name);
|
|
270
|
+
});
|
|
271
|
+
watchers.set(name, w);
|
|
272
|
+
} catch {
|
|
273
|
+
/* the folder went away before its watcher started */
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function watchRoot() {
|
|
277
|
+
if (watchers.size) return;
|
|
278
|
+
readDist();
|
|
279
|
+
const top = watch(root, (event, file) => {
|
|
280
|
+
if (String(file) === COLLECTION) readDist();
|
|
281
|
+
if (!file || skipped(String(file))) return;
|
|
282
|
+
watchFolder(String(file));
|
|
283
|
+
changed();
|
|
284
|
+
});
|
|
285
|
+
watchers.set('', top);
|
|
286
|
+
for (const entry of await readdir(root, { withFileTypes: true })) if (entry.isDirectory()) watchFolder(entry.name);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function close() {
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
for (const w of watchers.values()) w.close();
|
|
292
|
+
for (const res of clients) res.end();
|
|
293
|
+
const closed = new Promise((done) => server.close(() => done()));
|
|
294
|
+
server.closeAllConnections();
|
|
295
|
+
return closed;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return { server, root, watch: watchRoot, close };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const WALK = 10;
|
|
302
|
+
|
|
303
|
+
function probe(port, root) {
|
|
304
|
+
return new Promise((resolve) => {
|
|
305
|
+
let done = false;
|
|
306
|
+
const finish = (value) => {
|
|
307
|
+
if (!done) resolve(value);
|
|
308
|
+
done = true;
|
|
309
|
+
};
|
|
310
|
+
const req = get(`http://localhost:${port}/__preview__`, { timeout: 250, agent: false }, (res) => {
|
|
311
|
+
let body = '';
|
|
312
|
+
res.on('data', (chunk) => (body += chunk));
|
|
313
|
+
res.on('end', () => {
|
|
314
|
+
try {
|
|
315
|
+
const id = JSON.parse(body);
|
|
316
|
+
finish(id?.name === IDENTITY && id?.root === root ? id : null);
|
|
317
|
+
} catch {
|
|
318
|
+
finish(null);
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
res.on('error', () => finish(null));
|
|
322
|
+
});
|
|
323
|
+
req.on('timeout', () => {
|
|
324
|
+
req.destroy();
|
|
325
|
+
finish(null);
|
|
326
|
+
});
|
|
327
|
+
req.on('error', () => finish(null));
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// A winner of a startup race may need a moment before it answers.
|
|
332
|
+
async function probeAgain(port, root, attempts = 3, delay = 150) {
|
|
333
|
+
for (let i = 0; i < attempts; i++) {
|
|
334
|
+
const id = await probe(port, root);
|
|
335
|
+
if (id) return id;
|
|
336
|
+
if (i < attempts - 1) await new Promise((r) => setTimeout(r, delay));
|
|
337
|
+
}
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export async function startPreview({ root, port = 3000, explicit = false, openBrowser = null, log = console.log }) {
|
|
342
|
+
const ports = explicit ? [port] : Array.from({ length: WALK + 1 }, (_, i) => port + i);
|
|
343
|
+
const found = await Promise.all(ports.map((p) => probe(p, root).then((id) => id && p)));
|
|
344
|
+
const incumbent = found.find(Boolean);
|
|
345
|
+
if (incumbent) {
|
|
346
|
+
const url = `http://localhost:${incumbent}`;
|
|
347
|
+
log(`ca-ds preview already running at ${url}`);
|
|
348
|
+
return { url, running: true };
|
|
349
|
+
}
|
|
350
|
+
const preview = createPreview({ root, identity: { startedAt: new Date().toISOString() } });
|
|
351
|
+
for (const p of ports) {
|
|
352
|
+
const bound = await new Promise((resolve, reject) => {
|
|
353
|
+
const onError = (err) => (err.code === 'EADDRINUSE' ? resolve(false) : reject(err));
|
|
354
|
+
// A failed listen's callback never fires or removes itself, so it would fire beside the next.
|
|
355
|
+
preview.server.removeAllListeners('listening');
|
|
356
|
+
preview.server.once('error', onError);
|
|
357
|
+
preview.server.listen(p, () => {
|
|
358
|
+
preview.server.removeListener('error', onError);
|
|
359
|
+
resolve(true);
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
if (bound) {
|
|
363
|
+
const url = `http://localhost:${p}`;
|
|
364
|
+
log(`ca-ds preview running at ${url}`);
|
|
365
|
+
await preview.watch();
|
|
366
|
+
if (openBrowser ?? process.stdout.isTTY) openUrl(url);
|
|
367
|
+
return { url, running: false, preview };
|
|
368
|
+
}
|
|
369
|
+
if (await probeAgain(p, root)) {
|
|
370
|
+
await preview.close();
|
|
371
|
+
const url = `http://localhost:${p}`;
|
|
372
|
+
log(`ca-ds preview already running at ${url}`);
|
|
373
|
+
return { url, running: true };
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
await preview.close();
|
|
377
|
+
throw new Error(explicit ? `Port ${port} is in use by another process, not this collection's previewer.` : `Ports ${port} to ${port + WALK} are all in use.`);
|
|
378
|
+
}
|