@milesroxas/design-hub 0.2.0 → 0.4.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/README.md +1 -1
- package/core/catalog.test.ts +10 -1
- package/core/catalog.ts +11 -0
- package/core/cms.test.ts +103 -0
- package/core/cms.ts +178 -0
- package/core/export.test.ts +127 -0
- package/core/export.ts +120 -0
- package/core/formats.ts +60 -0
- package/core/project.test.ts +71 -0
- package/core/project.ts +147 -0
- package/dist/core/catalog.d.ts +5 -0
- package/dist/core/catalog.js +10 -0
- package/dist/core/cms.d.ts +40 -0
- package/dist/core/cms.js +141 -0
- package/dist/core/export.d.ts +52 -0
- package/dist/core/export.js +84 -0
- package/dist/core/formats.d.ts +90 -0
- package/dist/core/formats.js +39 -0
- package/dist/core/project.d.ts +56 -0
- package/dist/core/project.js +121 -0
- package/dist/scripts/bootstrap.d.ts +1 -1
- package/dist/scripts/bootstrap.js +38 -6
- package/dist/scripts/cli.js +8 -0
- package/dist/scripts/commands.js +8 -0
- package/dist/scripts/export.d.ts +42 -0
- package/dist/scripts/export.js +192 -0
- package/dist/scripts/fixtures-pull.d.ts +31 -19
- package/dist/scripts/fixtures-pull.js +102 -62
- package/dist/scripts/lib/cdp.d.ts +11 -0
- package/dist/scripts/lib/cdp.js +110 -0
- package/dist/scripts/lib/deploy.d.ts +76 -0
- package/dist/scripts/lib/deploy.js +94 -0
- package/dist/scripts/lib/vercel.d.ts +5 -0
- package/dist/scripts/lib/vercel.js +24 -0
- package/dist/scripts/new.d.ts +13 -1
- package/dist/scripts/new.js +43 -4
- package/dist/scripts/share.d.ts +63 -0
- package/dist/scripts/share.js +181 -0
- package/dist/scripts/signin.d.ts +31 -0
- package/dist/scripts/signin.js +119 -0
- package/dist/scripts/tracks.d.ts +40 -0
- package/dist/scripts/tracks.js +93 -0
- package/dist/server/paths.d.ts +2 -0
- package/dist/server/paths.js +2 -0
- package/dist/server/project.d.ts +7 -0
- package/dist/server/project.js +29 -0
- package/kit/Artboard.tsx +160 -0
- package/kit/artboard.css +47 -0
- package/kit/dials.tsx +2 -1
- package/package.json +1 -1
- package/shell/Index.tsx +49 -4
- package/shell/main.tsx +6 -2
- package/shell/shell.css +7 -3
- package/skills/miles-brand/SKILL.md +52 -0
- package/skills/miles-deploy/SKILL.md +26 -19
- package/skills/miles-design-hub/SKILL.md +77 -25
- package/skills/miles-get-hostile/SKILL.md +7 -5
- package/skills/miles-new-feature/SKILL.md +8 -7
- package/skills/miles-port/SKILL.md +14 -2
- package/skills/miles-port/references/emdash.md +43 -0
- package/skills/miles-port/references/payload.md +31 -0
- package/skills/miles-port/references/wordpress.md +31 -0
- package/skills/miles-prototype/SKILL.md +2 -2
- package/templates/app/README.md +1 -0
- package/templates/brand/README.md +48 -0
- package/templates/brand/index.tsx +16 -0
- package/templates/brand/styles.css +5 -0
- package/templates/site/README.md +42 -0
- package/templates/site/index.tsx +22 -0
- package/templates/site/styles.css +6 -0
- package/templates/space/README.md +1 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/// <reference types="node" />
|
|
3
|
+
// `design-hub export <slug>`: a brand prototype's artboards as files. It
|
|
4
|
+
// starts the hub on a free port, opens the prototype in headless Chrome with
|
|
5
|
+
// ?export (artboards only, real size, motion off), waits for fonts and
|
|
6
|
+
// images, then writes each artboard as a PNG or the presented ones into one
|
|
7
|
+
// PDF. The format decides by default: posts, stories, previews and banners
|
|
8
|
+
// are PNG; slides and print are PDF.
|
|
9
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { join, relative, resolve } from 'node:path';
|
|
11
|
+
import { createServer } from 'vite';
|
|
12
|
+
import { chromeCandidates, exportUrl, fileNames, pdfFiles, plan, } from '../core/export.js';
|
|
13
|
+
import { PROTOTYPES, ROOT } from '../server/paths.js';
|
|
14
|
+
import { hubConfig } from '../vite/plugin.js';
|
|
15
|
+
import { launch, within } from './lib/cdp.js';
|
|
16
|
+
import { CliError } from './lib/cli.js';
|
|
17
|
+
export const spec = {
|
|
18
|
+
name: 'export',
|
|
19
|
+
summary: "Write a prototype's artboards to files: PNG for posts, PDF for slides and print.",
|
|
20
|
+
positionals: [
|
|
21
|
+
{ name: 'prototype', description: 'The prototype folder, e.g. sample-social', required: true },
|
|
22
|
+
],
|
|
23
|
+
flags: {
|
|
24
|
+
as: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
choices: ['auto', 'png', 'pdf'],
|
|
27
|
+
default: 'auto',
|
|
28
|
+
description: "auto: each artboard's format decides. png: every artboard a PNG. pdf: every artboard into one PDF.",
|
|
29
|
+
},
|
|
30
|
+
scale: {
|
|
31
|
+
type: 'number',
|
|
32
|
+
default: 1,
|
|
33
|
+
description: 'PNG pixel density: 1 for the exact size platforms ask for, 2 for retina.',
|
|
34
|
+
},
|
|
35
|
+
dials: {
|
|
36
|
+
type: 'string',
|
|
37
|
+
description: 'The dial state to export, as JSON by panel: {"Review":{"fixtures":"longest"}}. Default: the committed defaults.',
|
|
38
|
+
},
|
|
39
|
+
theme: {
|
|
40
|
+
type: 'string',
|
|
41
|
+
choices: ['light', 'dark'],
|
|
42
|
+
description: 'The theme, when the artboards follow it.',
|
|
43
|
+
},
|
|
44
|
+
out: { type: 'string', description: 'Folder for the files. Default: exports/<prototype>/.' },
|
|
45
|
+
},
|
|
46
|
+
output: '{ ok, files: [path], artboards }',
|
|
47
|
+
};
|
|
48
|
+
const READY_TIMEOUT_MS = 30_000;
|
|
49
|
+
const POLL_MS = 150;
|
|
50
|
+
const SERVER_CLOSE_MS = 5_000;
|
|
51
|
+
const VIEWPORT = { width: 2400, height: 1600 };
|
|
52
|
+
const READ_BOARDS = `JSON.stringify([...document.querySelectorAll('[data-artboard]')].map((el, index) => {
|
|
53
|
+
el.dataset.index = String(index);
|
|
54
|
+
const r = el.getBoundingClientRect();
|
|
55
|
+
return { index, name: el.dataset.name, format: el.dataset.format, output: el.dataset.output,
|
|
56
|
+
x: r.x + scrollX, y: r.y + scrollY, width: r.width, height: r.height };
|
|
57
|
+
}))`;
|
|
58
|
+
function findChrome() {
|
|
59
|
+
const found = chromeCandidates(process.platform, process.env).find((p) => existsSync(p));
|
|
60
|
+
if (!found)
|
|
61
|
+
throw new CliError('No Chrome, Chromium or Edge found to render the artboards.', {
|
|
62
|
+
fix: 'Install Google Chrome, or set CHROME_PATH to a Chromium-based browser.',
|
|
63
|
+
});
|
|
64
|
+
return found;
|
|
65
|
+
}
|
|
66
|
+
/** The hub on a free port, for this one export. */
|
|
67
|
+
async function startHub() {
|
|
68
|
+
const config = hubConfig({ root: ROOT }, 'build');
|
|
69
|
+
const server = await createServer({
|
|
70
|
+
...config,
|
|
71
|
+
logLevel: 'error',
|
|
72
|
+
// One page, read once: no file watcher, no hot reload, so nothing outlives the export.
|
|
73
|
+
server: { ...config.server, port: 0, strictPort: false, hmr: false, open: false, watch: null, ws: false },
|
|
74
|
+
});
|
|
75
|
+
await server.listen();
|
|
76
|
+
const address = server.httpServer?.address();
|
|
77
|
+
if (!address)
|
|
78
|
+
throw new CliError('The hub did not start for export.');
|
|
79
|
+
return { server, origin: `http://localhost:${address.port}` };
|
|
80
|
+
}
|
|
81
|
+
async function evaluate(browser, expression) {
|
|
82
|
+
const { result } = await browser.send('Runtime.evaluate', {
|
|
83
|
+
expression,
|
|
84
|
+
returnByValue: true,
|
|
85
|
+
awaitPromise: true,
|
|
86
|
+
});
|
|
87
|
+
return result.value;
|
|
88
|
+
}
|
|
89
|
+
async function waitReady(browser) {
|
|
90
|
+
const until = Date.now() + READY_TIMEOUT_MS;
|
|
91
|
+
while (Date.now() < until) {
|
|
92
|
+
if (await evaluate(browser, "document.documentElement.dataset.exportReady === '1'"))
|
|
93
|
+
return;
|
|
94
|
+
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
95
|
+
}
|
|
96
|
+
throw new CliError('The prototype never finished loading for export.', {
|
|
97
|
+
errors: browser.errors.slice(0, 5),
|
|
98
|
+
fix: 'Open the prototype with ?export in the browser and fix what its console says. Export needs a Board from @kit/Artboard.',
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** One PNG per artboard; the page's device scale (--scale) sets the pixel density. */
|
|
102
|
+
async function writePngs(browser, slug, boards, dir) {
|
|
103
|
+
const names = fileNames(slug, boards, 'png');
|
|
104
|
+
const files = [];
|
|
105
|
+
for (const [i, b] of boards.entries()) {
|
|
106
|
+
const { data } = await browser.send('Page.captureScreenshot', {
|
|
107
|
+
format: 'png',
|
|
108
|
+
clip: { x: b.x, y: b.y, width: b.width, height: b.height, scale: 1 },
|
|
109
|
+
captureBeyondViewport: true,
|
|
110
|
+
});
|
|
111
|
+
const file = join(dir, names[i]);
|
|
112
|
+
writeFileSync(file, Buffer.from(data, 'base64'));
|
|
113
|
+
files.push(file);
|
|
114
|
+
}
|
|
115
|
+
return files;
|
|
116
|
+
}
|
|
117
|
+
/** One PDF per format: every other artboard is hidden while that format prints. */
|
|
118
|
+
async function writePdfs(browser, slug, boards, dir) {
|
|
119
|
+
// Print lays out at each page's own size; the screenshot viewport would shrink it.
|
|
120
|
+
await browser.send('Emulation.clearDeviceMetricsOverride');
|
|
121
|
+
const files = [];
|
|
122
|
+
for (const { format, file } of pdfFiles(slug, boards)) {
|
|
123
|
+
await evaluate(browser, `document.querySelectorAll('[data-artboard]').forEach((el) => {
|
|
124
|
+
el.style.display = el.dataset.format === ${JSON.stringify(format)} && ${JSON.stringify(boards.map((b) => b.index))}.includes(Number(el.dataset.index)) ? '' : 'none';
|
|
125
|
+
})`);
|
|
126
|
+
const { data } = await browser.send('Page.printToPDF', {
|
|
127
|
+
printBackground: true,
|
|
128
|
+
preferCSSPageSize: true,
|
|
129
|
+
marginTop: 0,
|
|
130
|
+
marginBottom: 0,
|
|
131
|
+
marginLeft: 0,
|
|
132
|
+
marginRight: 0,
|
|
133
|
+
});
|
|
134
|
+
const path = join(dir, file);
|
|
135
|
+
writeFileSync(path, Buffer.from(data, 'base64'));
|
|
136
|
+
files.push(path);
|
|
137
|
+
}
|
|
138
|
+
return files;
|
|
139
|
+
}
|
|
140
|
+
function checkFlags(slug, flags) {
|
|
141
|
+
if (!existsSync(join(PROTOTYPES, slug, 'index.tsx')))
|
|
142
|
+
throw new CliError(`No prototype called ${slug}.`);
|
|
143
|
+
if (!(flags.scale >= 1 && flags.scale <= 4))
|
|
144
|
+
throw new CliError('--scale takes 1 to 4.');
|
|
145
|
+
if (flags.dials) {
|
|
146
|
+
try {
|
|
147
|
+
JSON.parse(flags.dials);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
throw new CliError('--dials takes JSON by panel name.', {
|
|
151
|
+
example: '{"Review":{"fixtures":"longest"}}',
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function render(browser, url, flags, slug, dir) {
|
|
157
|
+
await browser.send('Emulation.setDeviceMetricsOverride', {
|
|
158
|
+
...VIEWPORT,
|
|
159
|
+
deviceScaleFactor: flags.scale,
|
|
160
|
+
mobile: false,
|
|
161
|
+
});
|
|
162
|
+
await browser.send('Page.navigate', { url });
|
|
163
|
+
await waitReady(browser);
|
|
164
|
+
const boards = JSON.parse(await evaluate(browser, READ_BOARDS));
|
|
165
|
+
if (!boards.length)
|
|
166
|
+
throw new CliError(`${slug} has no artboards to export.`, {
|
|
167
|
+
fix: 'Export reads <Artboard> elements inside a <Board> from @kit/Artboard.',
|
|
168
|
+
});
|
|
169
|
+
const { png, pdf } = plan(boards, flags.as);
|
|
170
|
+
mkdirSync(dir, { recursive: true });
|
|
171
|
+
const files = await writePngs(browser, slug, png, dir);
|
|
172
|
+
if (pdf.length)
|
|
173
|
+
files.push(...(await writePdfs(browser, slug, pdf, dir)));
|
|
174
|
+
return { files, artboards: boards.length };
|
|
175
|
+
}
|
|
176
|
+
export async function main({ positionals: [slug], flags }) {
|
|
177
|
+
checkFlags(slug, flags);
|
|
178
|
+
const chrome = findChrome();
|
|
179
|
+
const dir = resolve(ROOT, flags.out ?? join('exports', slug));
|
|
180
|
+
const { server, origin } = await startHub();
|
|
181
|
+
let browser;
|
|
182
|
+
try {
|
|
183
|
+
browser = await launch(chrome);
|
|
184
|
+
const url = exportUrl(origin, slug, { dials: flags.dials, theme: flags.theme });
|
|
185
|
+
const { files, artboards } = await render(browser, url, flags, slug, dir);
|
|
186
|
+
return { files: files.map((f) => relative(ROOT, f)), artboards };
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
await browser?.close();
|
|
190
|
+
await within(server.close(), SERVER_CLOSE_MS);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -1,22 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { type Item, type Source } from '../core/cms.ts';
|
|
2
3
|
import { type Args } from './lib/cli.ts';
|
|
3
4
|
export declare const spec: {
|
|
4
5
|
readonly name: 'fixtures-pull';
|
|
5
|
-
readonly summary: "Write a prototype's real fixtures from
|
|
6
|
+
readonly summary: "Write a prototype's real fixtures from the project's CMS: Webflow, Payload, WordPress, or a JSON file.";
|
|
6
7
|
readonly positionals: [{
|
|
7
8
|
readonly name: 'prototype';
|
|
8
|
-
readonly description: 'The prototype folder, e.g. sample-
|
|
9
|
+
readonly description: 'The prototype folder, e.g. sample-page';
|
|
9
10
|
readonly required: true;
|
|
10
11
|
}];
|
|
11
12
|
readonly flags: {
|
|
12
13
|
readonly collection: {
|
|
13
14
|
readonly type: 'string';
|
|
14
|
-
readonly
|
|
15
|
-
|
|
15
|
+
readonly description: 'The collection: a Webflow collection id, a Payload collection slug, or a WordPress REST base (posts, pages).';
|
|
16
|
+
};
|
|
17
|
+
readonly from: {
|
|
18
|
+
readonly type: 'string';
|
|
19
|
+
readonly description: 'A JSON file of items instead of an API. EmDash: npx emdash content list <collection> --json > items.json.';
|
|
20
|
+
};
|
|
21
|
+
readonly source: {
|
|
22
|
+
readonly type: 'string';
|
|
23
|
+
readonly choices: readonly ["webflow", "payload", "wordpress", "file"];
|
|
24
|
+
readonly description: 'Default: the website platform in .design-hub/project.json, else webflow; file with --from.';
|
|
16
25
|
};
|
|
17
26
|
readonly map: {
|
|
18
27
|
readonly type: 'list';
|
|
19
|
-
readonly description: 'key=field.path: the fixture key and the
|
|
28
|
+
readonly description: 'key=field.path: the fixture key and the path it comes from (title.rendered). Omit to list fields.';
|
|
20
29
|
};
|
|
21
30
|
readonly limit: {
|
|
22
31
|
readonly type: 'number';
|
|
@@ -25,36 +34,39 @@ export declare const spec: {
|
|
|
25
34
|
};
|
|
26
35
|
readonly staged: {
|
|
27
36
|
readonly type: 'boolean';
|
|
28
|
-
readonly description: 'Read
|
|
37
|
+
readonly description: 'Read drafts too, not only published items.';
|
|
29
38
|
};
|
|
30
39
|
};
|
|
31
|
-
readonly output: '{ ok, file, items, contacts } or, without --map, { ok: false, fields }';
|
|
32
|
-
};
|
|
33
|
-
type Item = {
|
|
34
|
-
id: string;
|
|
35
|
-
isDraft?: boolean;
|
|
36
|
-
isArchived?: boolean;
|
|
37
|
-
fieldData: Record<string, unknown>;
|
|
40
|
+
readonly output: '{ ok, source, file, items, contacts } or, without --map, { ok: false, fields }';
|
|
38
41
|
};
|
|
39
42
|
export type FieldMap = {
|
|
40
43
|
key: string;
|
|
41
44
|
path: string[];
|
|
42
45
|
};
|
|
43
46
|
export declare function parseMap(raw: string): FieldMap;
|
|
44
|
-
/** One fixture item: the
|
|
45
|
-
export declare function pick(item: Item, maps: FieldMap[]): Record<string, unknown>;
|
|
47
|
+
/** One fixture item: the source's id, then each mapped field; a path that is not there is null. */
|
|
48
|
+
export declare function pick(source: Source, item: Item, maps: FieldMap[]): Record<string, unknown>;
|
|
49
|
+
/** The source: --from means a file; else the flag, else the website platform, else Webflow. */
|
|
50
|
+
export declare function sourceFor(flag: string | undefined, from: string | undefined, platform: string | undefined): Source;
|
|
46
51
|
export declare function main({ positionals: [slug], flags }: Args<typeof spec>): Promise<{
|
|
47
52
|
ok: boolean;
|
|
53
|
+
source: "file" | "payload" | "webflow" | "wordpress";
|
|
48
54
|
error: string;
|
|
49
55
|
fields: {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
displayName: string;
|
|
56
|
+
path: string;
|
|
57
|
+
sample: string;
|
|
53
58
|
}[];
|
|
59
|
+
file?: undefined;
|
|
60
|
+
items?: undefined;
|
|
61
|
+
contacts?: undefined;
|
|
62
|
+
next?: undefined;
|
|
54
63
|
} | {
|
|
64
|
+
ok?: undefined;
|
|
65
|
+
error?: undefined;
|
|
66
|
+
fields?: undefined;
|
|
67
|
+
source: "file" | "payload" | "webflow" | "wordpress";
|
|
55
68
|
file: string;
|
|
56
69
|
items: number;
|
|
57
70
|
contacts: number;
|
|
58
71
|
next: string;
|
|
59
72
|
}>;
|
|
60
|
-
export {};
|
|
@@ -1,38 +1,49 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/// <reference types="node" />
|
|
3
|
-
// Writes a prototype's `real` fixtures from
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
3
|
+
// Writes a prototype's `real` fixtures from the project's CMS, with only the
|
|
4
|
+
// fields the component renders, so a pull spends nothing on fields nobody
|
|
5
|
+
// reads. The source follows the website platform in .design-hub/project.json
|
|
6
|
+
// (Webflow, Payload, WordPress) or --source; EmDash, and any CMS without one
|
|
7
|
+
// of those APIs, comes in as a JSON file (--from). Every other key in
|
|
8
|
+
// fixtures.json is kept. Run with no --map to list the fields. core/cms.ts
|
|
9
|
+
// holds each source's requests and responses.
|
|
9
10
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
10
|
-
import { join, relative } from 'node:path';
|
|
11
|
+
import { join, relative, resolve } from 'node:path';
|
|
12
|
+
import { fieldPaths, fieldRoot, itemsInFile, missingEnv, NEEDS, pageRequest, readPage, SOURCES, valueAt, } from '../core/cms.js';
|
|
11
13
|
import { contactsInJson } from '../core/contacts.js';
|
|
12
14
|
import { readEnv } from '../server/env.js';
|
|
13
15
|
import { PROTOTYPES, ROOT } from '../server/paths.js';
|
|
16
|
+
import { readProject } from '../server/project.js';
|
|
14
17
|
import { CliError } from './lib/cli.js';
|
|
15
18
|
export const spec = {
|
|
16
19
|
name: 'fixtures-pull',
|
|
17
|
-
summary: "Write a prototype's real fixtures from
|
|
18
|
-
positionals: [{ name: 'prototype', description: 'The prototype folder, e.g. sample-
|
|
20
|
+
summary: "Write a prototype's real fixtures from the project's CMS: Webflow, Payload, WordPress, or a JSON file.",
|
|
21
|
+
positionals: [{ name: 'prototype', description: 'The prototype folder, e.g. sample-page', required: true }],
|
|
19
22
|
flags: {
|
|
20
|
-
collection: {
|
|
23
|
+
collection: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'The collection: a Webflow collection id, a Payload collection slug, or a WordPress REST base (posts, pages).',
|
|
26
|
+
},
|
|
27
|
+
from: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
description: 'A JSON file of items instead of an API. EmDash: npx emdash content list <collection> --json > items.json.',
|
|
30
|
+
},
|
|
31
|
+
source: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
choices: SOURCES,
|
|
34
|
+
description: 'Default: the website platform in .design-hub/project.json, else webflow; file with --from.',
|
|
35
|
+
},
|
|
21
36
|
map: {
|
|
22
37
|
type: 'list',
|
|
23
|
-
description: 'key=field.path: the fixture key and the
|
|
38
|
+
description: 'key=field.path: the fixture key and the path it comes from (title.rendered). Omit to list fields.',
|
|
24
39
|
},
|
|
25
40
|
limit: { type: 'number', default: 20, description: 'How many items to keep.' },
|
|
26
|
-
staged: {
|
|
27
|
-
type: 'boolean',
|
|
28
|
-
description: 'Read staged items (drafts included) instead of published ones.',
|
|
29
|
-
},
|
|
41
|
+
staged: { type: 'boolean', description: 'Read drafts too, not only published items.' },
|
|
30
42
|
},
|
|
31
|
-
output: '{ ok, file, items, contacts } or, without --map, { ok: false, fields }',
|
|
43
|
+
output: '{ ok, source, file, items, contacts } or, without --map, { ok: false, fields }',
|
|
32
44
|
};
|
|
33
|
-
const API = 'https://api.webflow.com/v2';
|
|
34
|
-
const PAGE = 100;
|
|
35
45
|
const TIMEOUT_MS = 15_000;
|
|
46
|
+
const SAMPLE_ITEMS = 1;
|
|
36
47
|
export function parseMap(raw) {
|
|
37
48
|
const at = raw.indexOf('=');
|
|
38
49
|
const key = at > 0 ? raw.slice(0, at).trim() : '';
|
|
@@ -41,76 +52,105 @@ export function parseMap(raw) {
|
|
|
41
52
|
throw new CliError(`--map ${raw}: write it as key=field.path.`, { example: '--map cover=thumbnail.url' });
|
|
42
53
|
return { key, path: path.split('.') };
|
|
43
54
|
}
|
|
44
|
-
/** One fixture item: the
|
|
45
|
-
export function pick(item, maps) {
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
value = value && typeof value === 'object' ? value[part] : undefined;
|
|
51
|
-
out[key] = value ?? null;
|
|
52
|
-
}
|
|
55
|
+
/** One fixture item: the source's id, then each mapped field; a path that is not there is null. */
|
|
56
|
+
export function pick(source, item, maps) {
|
|
57
|
+
const root = fieldRoot(source, item);
|
|
58
|
+
const out = { id: String(item.id ?? root.id ?? '') };
|
|
59
|
+
for (const { key, path } of maps)
|
|
60
|
+
out[key] = valueAt(root, path) ?? null;
|
|
53
61
|
return out;
|
|
54
62
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
63
|
+
/** The source: --from means a file; else the flag, else the website platform, else Webflow. */
|
|
64
|
+
export function sourceFor(flag, from, platform) {
|
|
65
|
+
if (from)
|
|
66
|
+
return 'file';
|
|
67
|
+
if (flag)
|
|
68
|
+
return flag;
|
|
69
|
+
if (platform === 'payload' || platform === 'wordpress')
|
|
70
|
+
return platform;
|
|
71
|
+
if (platform === 'emdash')
|
|
72
|
+
throw new CliError('EmDash has no pull API here; read it from a file.', {
|
|
73
|
+
fix: 'npx emdash content list <collection> --json > items.json, then --from items.json.',
|
|
74
|
+
});
|
|
75
|
+
return 'webflow';
|
|
76
|
+
}
|
|
77
|
+
async function get(source, url, headers) {
|
|
78
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
60
79
|
if (!response.ok)
|
|
61
|
-
throw new CliError(
|
|
80
|
+
throw new CliError(`${source} answered ${response.status} for ${url}.`, {
|
|
62
81
|
body: (await response.text()).slice(0, 300),
|
|
63
|
-
fix: response.status === 401 || response.status === 403
|
|
64
|
-
? 'WEBFLOW_TOKEN needs the cms:read scope.'
|
|
65
|
-
: undefined,
|
|
82
|
+
fix: response.status === 401 || response.status === 403 ? NEEDS[source].fix : undefined,
|
|
66
83
|
});
|
|
67
|
-
return (await response.json());
|
|
68
|
-
}
|
|
69
|
-
async function listFields(token, collection) {
|
|
70
|
-
const schema = await get(token, `/collections/${collection}`);
|
|
71
|
-
return {
|
|
72
|
-
ok: false,
|
|
73
|
-
error: `Name the fields the component renders with --map, from ${schema.displayName}'s fields.`,
|
|
74
|
-
fields: schema.fields.map(({ slug: field, type, displayName }) => ({ field, type, displayName })),
|
|
75
|
-
};
|
|
84
|
+
return { body: (await response.json()), totalPages: response.headers.get('x-wp-totalpages') };
|
|
76
85
|
}
|
|
77
|
-
/** Pages through the collection until `limit`
|
|
78
|
-
async function
|
|
86
|
+
/** Pages through the collection until `limit` items are in, or it runs out. */
|
|
87
|
+
async function pullApi(source, env, collection, limit, staged) {
|
|
79
88
|
const items = [];
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
for (let page = 1; items.length < limit; page++) {
|
|
90
|
+
const { url, headers } = pageRequest(source, env, collection, page, staged);
|
|
91
|
+
const { body, totalPages } = await get(source, url, headers);
|
|
92
|
+
const read = readPage(source, body, page, totalPages);
|
|
93
|
+
items.push(...read.items);
|
|
94
|
+
if (!read.more)
|
|
85
95
|
break;
|
|
86
96
|
}
|
|
87
97
|
return items.slice(0, limit);
|
|
88
98
|
}
|
|
99
|
+
function readFile(path) {
|
|
100
|
+
const file = resolve(ROOT, path);
|
|
101
|
+
if (!existsSync(file))
|
|
102
|
+
throw new CliError(`${path} does not exist.`);
|
|
103
|
+
let json;
|
|
104
|
+
try {
|
|
105
|
+
json = JSON.parse(readFileSync(file, 'utf8'));
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
throw new CliError(`${path} is not JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
109
|
+
}
|
|
110
|
+
const items = itemsInFile(json);
|
|
111
|
+
if (!items)
|
|
112
|
+
throw new CliError(`${path} has no array of items at the top or under items, entries, docs or data.`);
|
|
113
|
+
return items;
|
|
114
|
+
}
|
|
89
115
|
/** Replaces `real` and keeps every other set, adding an empty `missing` for the hand-written cases. */
|
|
90
116
|
function writeReal(file, real) {
|
|
91
117
|
const current = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
|
|
92
118
|
writeFileSync(file, `${JSON.stringify({ ...current, real, missing: current.missing ?? [] }, null, 2)}\n`);
|
|
93
119
|
}
|
|
120
|
+
async function items(source, flags, limit) {
|
|
121
|
+
if (source === 'file')
|
|
122
|
+
return readFile(flags.from ?? '').slice(0, limit);
|
|
123
|
+
const env = readEnv(ROOT);
|
|
124
|
+
const missing = missingEnv(source, env);
|
|
125
|
+
if (missing.length)
|
|
126
|
+
throw new CliError(`${missing.join(' and ')} not in .env.`, { fix: NEEDS[source].fix });
|
|
127
|
+
if (!flags.collection)
|
|
128
|
+
throw new CliError(`--collection names the ${source} collection.`);
|
|
129
|
+
return pullApi(source, env, flags.collection, limit, flags.staged);
|
|
130
|
+
}
|
|
94
131
|
export async function main({ positionals: [slug], flags }) {
|
|
95
|
-
const token = readEnv(ROOT).WEBFLOW_TOKEN;
|
|
96
|
-
if (!token)
|
|
97
|
-
throw new CliError('WEBFLOW_TOKEN is not in .env.', {
|
|
98
|
-
fix: 'Create a site token with cms:read in Webflow (Site settings, Apps & integrations) and add WEBFLOW_TOKEN=<token> to .env.',
|
|
99
|
-
});
|
|
100
132
|
const dir = join(PROTOTYPES, slug);
|
|
101
133
|
if (!existsSync(join(dir, 'README.md')))
|
|
102
134
|
throw new CliError(`No prototype called ${slug}.`);
|
|
103
|
-
const collection = encodeURIComponent(flags.collection);
|
|
104
|
-
if (!flags.map.length)
|
|
105
|
-
return listFields(token, collection);
|
|
106
|
-
const maps = flags.map.map(parseMap);
|
|
107
135
|
if (!Number.isInteger(flags.limit) || flags.limit < 1)
|
|
108
136
|
throw new CliError('--limit takes a whole number above 0.');
|
|
109
|
-
const
|
|
137
|
+
const source = sourceFor(flags.source, flags.from, readProject().project?.website?.platform);
|
|
138
|
+
if (!flags.map.length) {
|
|
139
|
+
const [first] = await items(source, flags, SAMPLE_ITEMS);
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
source,
|
|
143
|
+
error: 'Name the fields the component renders with --map key=path, from these paths.',
|
|
144
|
+
fields: first ? fieldPaths(fieldRoot(source, first)) : [],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const maps = flags.map.map(parseMap);
|
|
148
|
+
const real = (await items(source, flags, flags.limit)).map((i) => pick(source, i, maps));
|
|
110
149
|
const file = join(dir, 'fixtures.json');
|
|
111
150
|
writeReal(file, real);
|
|
112
151
|
const contacts = contactsInJson(real).length;
|
|
113
152
|
return {
|
|
153
|
+
source,
|
|
114
154
|
file: relative(ROOT, file),
|
|
115
155
|
items: real.length,
|
|
116
156
|
contacts,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** A promise that settles by `ms` at the latest; for shutdown steps that may never answer. */
|
|
2
|
+
export declare const within: <T>(promise: Promise<T>, ms: number) => Promise<void | Awaited<T>>;
|
|
3
|
+
export type Browser = {
|
|
4
|
+
/** Sends a command to the open page and resolves with its result. */
|
|
5
|
+
send: <T = Record<string, unknown>>(method: string, params?: Record<string, unknown>) => Promise<T>;
|
|
6
|
+
/** Exceptions the page threw, for the error report. */
|
|
7
|
+
errors: string[];
|
|
8
|
+
close: () => Promise<void>;
|
|
9
|
+
};
|
|
10
|
+
/** Starts headless Chrome and attaches to one fresh page. */
|
|
11
|
+
export declare function launch(chrome: string): Promise<Browser>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// Just enough of the Chrome DevTools Protocol to export artboards: start a
|
|
3
|
+
// headless browser on a throwaway profile, open one page, send commands to
|
|
4
|
+
// it, and close everything. Node's own WebSocket carries it, so the package
|
|
5
|
+
// adds no browser-automation dependency; the user's installed Chrome does the
|
|
6
|
+
// rendering.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { devtoolsUrl, readDevtools } from '../../core/export.js';
|
|
12
|
+
import { CliError } from './cli.js';
|
|
13
|
+
const START_TIMEOUT_MS = 20_000;
|
|
14
|
+
const CLOSE_TIMEOUT_MS = 2_000;
|
|
15
|
+
/** A promise that settles by `ms` at the latest; for shutdown steps that may never answer. */
|
|
16
|
+
export const within = (promise, ms) => Promise.race([promise, new Promise((resolve) => setTimeout(resolve, ms).unref())]);
|
|
17
|
+
function waitForDevtools(child) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
let text = '';
|
|
20
|
+
const timer = setTimeout(() => reject(new CliError('Chrome did not start in time.', { stderr: text.slice(-400) })), START_TIMEOUT_MS);
|
|
21
|
+
child.stderr?.on('data', (d) => {
|
|
22
|
+
text += d;
|
|
23
|
+
const url = devtoolsUrl(text);
|
|
24
|
+
if (url) {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
resolve(url);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
child.on('exit', (code) => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
reject(new CliError(`Chrome exited (${code}) before it was ready.`, { stderr: text.slice(-400) }));
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** Starts headless Chrome and attaches to one fresh page. */
|
|
36
|
+
export async function launch(chrome) {
|
|
37
|
+
const profile = mkdtempSync(join(tmpdir(), 'design-hub-export-'));
|
|
38
|
+
const child = spawn(chrome, [
|
|
39
|
+
'--headless=new',
|
|
40
|
+
'--remote-debugging-port=0',
|
|
41
|
+
`--user-data-dir=${profile}`,
|
|
42
|
+
'--no-first-run',
|
|
43
|
+
'--no-default-browser-check',
|
|
44
|
+
'--hide-scrollbars',
|
|
45
|
+
'--mute-audio',
|
|
46
|
+
'--force-color-profile=srgb',
|
|
47
|
+
'about:blank',
|
|
48
|
+
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
49
|
+
const exited = new Promise((resolve) => child.once('exit', () => resolve()));
|
|
50
|
+
// The profile goes once Chrome has let go of it; a leftover temp folder is not worth failing an export over.
|
|
51
|
+
const cleanup = async () => {
|
|
52
|
+
if (child.exitCode === null)
|
|
53
|
+
child.kill('SIGKILL');
|
|
54
|
+
await within(exited, CLOSE_TIMEOUT_MS);
|
|
55
|
+
try {
|
|
56
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// The OS clears its temp folder.
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
let ws;
|
|
63
|
+
try {
|
|
64
|
+
ws = new WebSocket(await waitForDevtools(child));
|
|
65
|
+
await new Promise((resolve, reject) => {
|
|
66
|
+
ws.onopen = resolve;
|
|
67
|
+
ws.onerror = () => reject(new CliError('Could not reach Chrome over DevTools.'));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
await cleanup();
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
let next = 0;
|
|
75
|
+
let sessionId;
|
|
76
|
+
const pending = new Map();
|
|
77
|
+
const errors = [];
|
|
78
|
+
ws.onmessage = (event) => {
|
|
79
|
+
const msg = readDevtools(String(event.data));
|
|
80
|
+
if (msg.kind === 'exception')
|
|
81
|
+
errors.push(msg.text);
|
|
82
|
+
if (msg.kind !== 'reply')
|
|
83
|
+
return;
|
|
84
|
+
const waiting = pending.get(msg.id);
|
|
85
|
+
pending.delete(msg.id);
|
|
86
|
+
if (msg.error)
|
|
87
|
+
waiting?.reject(new CliError(`Chrome refused: ${msg.error}`));
|
|
88
|
+
else
|
|
89
|
+
waiting?.resolve(msg.result);
|
|
90
|
+
};
|
|
91
|
+
const raw = (method, params = {}, session) => new Promise((resolve, reject) => {
|
|
92
|
+
const id = ++next;
|
|
93
|
+
pending.set(id, { resolve: resolve, reject });
|
|
94
|
+
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
|
|
95
|
+
});
|
|
96
|
+
const { targetId } = await raw('Target.createTarget', { url: 'about:blank' });
|
|
97
|
+
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
|
98
|
+
await raw('Runtime.enable', {}, sessionId);
|
|
99
|
+
await raw('Page.enable', {}, sessionId);
|
|
100
|
+
return {
|
|
101
|
+
send: (method, params) => raw(method, params, sessionId),
|
|
102
|
+
errors,
|
|
103
|
+
close: async () => {
|
|
104
|
+
// Chrome often drops the socket before it answers Browser.close.
|
|
105
|
+
await within(raw('Browser.close').catch(() => undefined), CLOSE_TIMEOUT_MS);
|
|
106
|
+
ws.close();
|
|
107
|
+
await cleanup();
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|