@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
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ A speculation rule in `shell/index.html` prefetches a prototype's page when its
|
|
|
68
68
|
|
|
69
69
|
## Deploying, and the password
|
|
70
70
|
|
|
71
|
-
`miles-deploy` owns the steps; this is what they rest on.
|
|
71
|
+
`miles-deploy` owns the steps; this is what they rest on. `design-hub signin` starts `vercel login`'s device sign-in in the background and returns its link, so the user clicks instead of typing. `design-hub bootstrap --vercel <project>` links the project, connects it to the `origin` repo when Vercel can reach it, turns Vercel Authentication off and sets the env. `design-hub share` runs the pre-flight, then deploys: a push of a clean production branch when the project is connected to the repo (following the build for that commit), else `vercel deploy --prod`; then it requests the production URL signed out and fails unless the password page answers with `noindex`. Every path on the deployed site sits behind one password, enforced on the server by Vercel Routing Middleware (`vercel/proxy.ts`, exported as `createProxy` and default-exported by the project's one-line `proxy.ts`, which `vercel.json` names as `proxy.entrypoint`): a visitor who opens a deep link, `/sample-list/#/items` included, sees the password page first and lands on that link after. A client-side gate was rejected because the bundle and the state behind it would still download.
|
|
72
72
|
|
|
73
73
|
The middleware reads two environment variables, set in the Vercel project for Production and Preview and never committed (`.env.example` names them): `GATE_PASSWORD`, the word a reviewer types, and `GATE_SECRET`, at least 32 random characters (`openssl rand -base64 32`) that sign the session cookie. With either missing the gate answers 503 on every path, so a misconfigured deploy never serves the prototypes open. The cookie is `__Host-`-prefixed, `HttpOnly`, `Secure`, `SameSite=Lax`, lasts 30 days, and its signature covers the password, so changing `GATE_PASSWORD` signs every visitor out. A wrong password waits 800ms before answering; add a Vercel Firewall rate-limit rule on `POST` for anything stronger. The password page ships a hash-based Content Security Policy with no `unsafe-inline`, plus `font-src 'self'` and `img-src 'self'`. It wears the hub's neutral look in Geist, so two files pass the gate without a session: `/_gate/geist.woff2` (the latin subset, emitted by `vite/plugin.ts` at that fixed path) and `/favicon.svg`. Nothing else does. Every response carries `X-Robots-Tag: noindex`, so no search engine lists the site. The page's title is the `siteName` the project's `proxy.ts` passes to `createProxy`.
|
|
74
74
|
|
package/core/catalog.test.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
2
|
import { test } from 'node:test';
|
|
3
|
-
import { byIndexOrder, isLive, readMeta } from './catalog.ts';
|
|
3
|
+
import { byIndexOrder, isLive, placeLabel, readMeta } from './catalog.ts';
|
|
4
4
|
import { frontmatter } from './frontmatter.ts';
|
|
5
5
|
|
|
6
6
|
const readme = (fm: string, body = '') => `---\n${fm}\n---\n\n# X\n${body}`;
|
|
@@ -42,3 +42,12 @@ test('open questions sort above answered ones, newest first, then by title', ()
|
|
|
42
42
|
);
|
|
43
43
|
assert.equal(isLive({ status: 'archived' }), false);
|
|
44
44
|
});
|
|
45
|
+
|
|
46
|
+
test('the track is read when known, and names the shell a prototype stands in', () => {
|
|
47
|
+
assert.equal(readMeta('x', readme('track: website')).track, 'website');
|
|
48
|
+
assert.equal(readMeta('x', readme('track: app')).track, '');
|
|
49
|
+
assert.equal(placeLabel({ context: 'app', track: 'website' }), 'Site shell');
|
|
50
|
+
assert.equal(placeLabel({ context: 'app', track: '' }), 'App shell');
|
|
51
|
+
assert.equal(placeLabel({ context: 'space', track: 'website' }), 'Space');
|
|
52
|
+
assert.equal(placeLabel({ context: 'board', track: 'brand' }), 'Artboards');
|
|
53
|
+
});
|
package/core/catalog.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// (shell/registry.ts) and the Node scripts (scripts/lib/catalog.ts), so
|
|
4
4
|
// they never disagree about what a prototype is.
|
|
5
5
|
import { frontmatter } from './frontmatter.ts';
|
|
6
|
+
import { TRACKS, type Track } from './project.ts';
|
|
6
7
|
import { parseStates, type State } from './states.ts';
|
|
7
8
|
|
|
8
9
|
export type Kind = 'sprint' | 'alternate' | 'exploration';
|
|
@@ -12,6 +13,8 @@ export type Meta = {
|
|
|
12
13
|
title: string;
|
|
13
14
|
summary: string;
|
|
14
15
|
context: string;
|
|
16
|
+
/** The track it belongs to; empty in a project made before tracks. */
|
|
17
|
+
track: Track | '';
|
|
15
18
|
status: string;
|
|
16
19
|
kind: Kind;
|
|
17
20
|
feature: string;
|
|
@@ -27,6 +30,7 @@ export function readMeta(slug: string, readme: string): Meta {
|
|
|
27
30
|
title: data.title || slug,
|
|
28
31
|
summary: data.summary || '',
|
|
29
32
|
context: data.context || 'space',
|
|
33
|
+
track: TRACKS.includes(data.track as Track) ? (data.track as Track) : '',
|
|
30
34
|
status: data.status || 'exploring',
|
|
31
35
|
kind: data.kind === 'sprint' || data.kind === 'alternate' ? data.kind : 'exploration',
|
|
32
36
|
feature: data.feature || '',
|
|
@@ -41,3 +45,10 @@ export const isLive = (m: Pick<Meta, 'status'>) => m.status !== 'archived';
|
|
|
41
45
|
const rank = (status: string) => (status === 'exploring' ? 0 : 1);
|
|
42
46
|
export const byIndexOrder = (a: Meta, b: Meta) =>
|
|
43
47
|
rank(a.status) - rank(b.status) || b.created.localeCompare(a.created) || a.title.localeCompare(b.title);
|
|
48
|
+
|
|
49
|
+
/** Where a prototype stands, in words: the Space, the shell its track draws, or a board of artboards. */
|
|
50
|
+
export function placeLabel(m: Pick<Meta, 'context' | 'track'>): string {
|
|
51
|
+
if (m.context === 'board') return 'Artboards';
|
|
52
|
+
if (m.context !== 'app') return 'Space';
|
|
53
|
+
return m.track === 'website' ? 'Site shell' : 'App shell';
|
|
54
|
+
}
|
package/core/cms.test.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { test } from 'node:test';
|
|
3
|
+
import {
|
|
4
|
+
fieldPaths,
|
|
5
|
+
fieldRoot,
|
|
6
|
+
itemsInFile,
|
|
7
|
+
missingEnv,
|
|
8
|
+
pageRequest,
|
|
9
|
+
plainText,
|
|
10
|
+
readPage,
|
|
11
|
+
valueAt,
|
|
12
|
+
} from './cms.ts';
|
|
13
|
+
|
|
14
|
+
test('each source builds its page request', () => {
|
|
15
|
+
const webflow = pageRequest('webflow', { WEBFLOW_TOKEN: 't' }, 'abc', 2, false);
|
|
16
|
+
assert.equal(webflow.url, 'https://api.webflow.com/v2/collections/abc/items/live?offset=100&limit=100');
|
|
17
|
+
assert.equal(webflow.headers.authorization, 'Bearer t');
|
|
18
|
+
assert.match(pageRequest('webflow', {}, 'abc', 1, true).url, /\/items\?offset=0/);
|
|
19
|
+
|
|
20
|
+
const payload = pageRequest(
|
|
21
|
+
'payload',
|
|
22
|
+
{ PAYLOAD_URL: 'https://cms.x/', PAYLOAD_API_KEY: 'k' },
|
|
23
|
+
'posts',
|
|
24
|
+
1,
|
|
25
|
+
true,
|
|
26
|
+
);
|
|
27
|
+
assert.equal(payload.url, 'https://cms.x/api/posts?limit=100&page=1&depth=1&draft=true');
|
|
28
|
+
assert.equal(payload.headers.authorization, 'users API-Key k');
|
|
29
|
+
assert.equal(
|
|
30
|
+
pageRequest(
|
|
31
|
+
'payload',
|
|
32
|
+
{ PAYLOAD_URL: 'https://cms.x', PAYLOAD_API_KEY: 'k', PAYLOAD_AUTH_COLLECTION: 'admins' },
|
|
33
|
+
'posts',
|
|
34
|
+
1,
|
|
35
|
+
false,
|
|
36
|
+
).headers.authorization,
|
|
37
|
+
'admins API-Key k',
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
const wp = pageRequest('wordpress', { WORDPRESS_URL: 'https://site.x' }, 'posts', 3, false);
|
|
41
|
+
assert.equal(wp.url, 'https://site.x/wp-json/wp/v2/posts?per_page=100&page=3&_embed=1');
|
|
42
|
+
assert.equal(wp.headers.authorization, undefined);
|
|
43
|
+
const wpDrafts = pageRequest(
|
|
44
|
+
'wordpress',
|
|
45
|
+
{ WORDPRESS_URL: 'https://site.x', WORDPRESS_USER: 'ed', WORDPRESS_APP_PASSWORD: 'p w' },
|
|
46
|
+
'posts',
|
|
47
|
+
1,
|
|
48
|
+
true,
|
|
49
|
+
);
|
|
50
|
+
assert.match(wpDrafts.url, /status=any/);
|
|
51
|
+
assert.equal(wpDrafts.headers.authorization, `Basic ${btoa('ed:p w')}`);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('each source reads its page and says whether another follows', () => {
|
|
55
|
+
const wf = readPage(
|
|
56
|
+
'webflow',
|
|
57
|
+
{ items: [{ id: 'a' }, { id: 'b', isArchived: true }], pagination: { total: 150, offset: 0 } },
|
|
58
|
+
1,
|
|
59
|
+
);
|
|
60
|
+
assert.deepEqual(wf, { items: [{ id: 'a' }], more: true });
|
|
61
|
+
assert.equal(
|
|
62
|
+
readPage('webflow', { items: [{ id: 'a' }], pagination: { total: 150, offset: 100 } }, 2).more,
|
|
63
|
+
false,
|
|
64
|
+
);
|
|
65
|
+
assert.deepEqual(readPage('payload', { docs: [{ id: 1 }], hasNextPage: false }, 1), {
|
|
66
|
+
items: [{ id: 1 }],
|
|
67
|
+
more: false,
|
|
68
|
+
});
|
|
69
|
+
assert.equal(readPage('wordpress', [{ id: 1 }], 1, '2').more, true);
|
|
70
|
+
assert.equal(readPage('wordpress', [{ id: 1 }], 2, '2').more, false);
|
|
71
|
+
assert.equal(readPage('wordpress', [], 1, '5').more, false);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('a file holds its items in an array, at the top or under a common key', () => {
|
|
75
|
+
assert.deepEqual(itemsInFile([{ a: 1 }]), [{ a: 1 }]);
|
|
76
|
+
assert.deepEqual(itemsInFile({ entries: [{ a: 1 }] }), [{ a: 1 }]);
|
|
77
|
+
assert.deepEqual(itemsInFile({ data: { items: [{ a: 1 }] } }), [{ a: 1 }]);
|
|
78
|
+
assert.equal(itemsInFile({ nothing: 1 }), null);
|
|
79
|
+
assert.equal(itemsInFile('x'), null);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('fields are read by path, with WordPress HTML made plain', () => {
|
|
83
|
+
const item = {
|
|
84
|
+
id: 7,
|
|
85
|
+
title: { rendered: 'Café & <em>bar</em> ’s' },
|
|
86
|
+
_embedded: { 'wp:featuredmedia': [{ source_url: 'https://x/y.jpg' }] },
|
|
87
|
+
};
|
|
88
|
+
assert.equal(valueAt(item, ['_embedded', 'wp:featuredmedia', '0', 'source_url']), 'https://x/y.jpg');
|
|
89
|
+
assert.equal(valueAt(item, ['title', 'rendered']), 'Café & bar ’s');
|
|
90
|
+
assert.equal(valueAt(item, ['author', 'name']), undefined);
|
|
91
|
+
assert.equal(plainText('<p>One\n two</p> '), 'One two');
|
|
92
|
+
assert.deepEqual(fieldRoot('webflow', { id: 'a', fieldData: { name: 'x' } }), { name: 'x' });
|
|
93
|
+
assert.deepEqual(fieldRoot('payload', { id: 'a' }), { id: 'a' });
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('field paths list every leaf with a sample', () => {
|
|
97
|
+
assert.deepEqual(fieldPaths({ title: 'Hi', image: { url: 'u' }, tags: ['a', 'b'] }), [
|
|
98
|
+
{ path: 'title', sample: '"Hi"' },
|
|
99
|
+
{ path: 'image.url', sample: '"u"' },
|
|
100
|
+
{ path: 'tags.0', sample: '"a"' },
|
|
101
|
+
]);
|
|
102
|
+
assert.deepEqual(missingEnv('payload', { PAYLOAD_URL: 'x' }), ['PAYLOAD_API_KEY']);
|
|
103
|
+
});
|
package/core/cms.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Where real fixtures come from: a CMS's own API, read page by page, or a
|
|
2
|
+
// JSON file another tool wrote. Pure: this module builds each request and
|
|
3
|
+
// reads each response; the caller fetches and passes the environment in, so
|
|
4
|
+
// every source is tested without a network.
|
|
5
|
+
//
|
|
6
|
+
// Webflow: Data API v2, https://developers.webflow.com/data/reference/cms/collection-items
|
|
7
|
+
// Payload: REST, GET <url>/api/<collection>, `Authorization: <auth collection> API-Key <key>`
|
|
8
|
+
// WordPress: REST, GET <url>/wp-json/wp/v2/<rest base>, application passwords for drafts
|
|
9
|
+
// File: any JSON with an array of items (EmDash: `npx emdash content list <collection> --json`)
|
|
10
|
+
|
|
11
|
+
export const SOURCES = ['webflow', 'payload', 'wordpress', 'file'] as const;
|
|
12
|
+
export type Source = (typeof SOURCES)[number];
|
|
13
|
+
|
|
14
|
+
export type Item = Record<string, unknown>;
|
|
15
|
+
export type Request = { url: string; headers: Record<string, string> };
|
|
16
|
+
export type Page = { items: Item[]; more: boolean };
|
|
17
|
+
export type Env = Record<string, string | undefined>;
|
|
18
|
+
|
|
19
|
+
/** The env a source needs, as `.env` lines, and why. */
|
|
20
|
+
export const NEEDS: Record<Exclude<Source, 'file'>, { keys: string[]; fix: string }> = {
|
|
21
|
+
webflow: {
|
|
22
|
+
keys: ['WEBFLOW_TOKEN'],
|
|
23
|
+
fix: 'Create a site token with cms:read in Webflow (Site settings, Apps & integrations) and add WEBFLOW_TOKEN=<token> to .env.',
|
|
24
|
+
},
|
|
25
|
+
payload: {
|
|
26
|
+
keys: ['PAYLOAD_URL', 'PAYLOAD_API_KEY'],
|
|
27
|
+
fix: 'Add PAYLOAD_URL=<site origin> and PAYLOAD_API_KEY=<key> to .env. The key comes from a user in an auth collection with useAPIKey on; set PAYLOAD_AUTH_COLLECTION when that collection is not users.',
|
|
28
|
+
},
|
|
29
|
+
wordpress: {
|
|
30
|
+
keys: ['WORDPRESS_URL'],
|
|
31
|
+
fix: 'Add WORDPRESS_URL=<site origin> to .env. For drafts (--staged), add WORDPRESS_USER and WORDPRESS_APP_PASSWORD (Users, Profile, Application Passwords).',
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const PAGE_SIZE = 100;
|
|
36
|
+
|
|
37
|
+
/** The env keys a source still lacks. */
|
|
38
|
+
export const missingEnv = (source: Exclude<Source, 'file'>, env: Env) =>
|
|
39
|
+
NEEDS[source].keys.filter((k) => !env[k]);
|
|
40
|
+
|
|
41
|
+
const origin = (url: string) => url.replace(/\/+$/, '');
|
|
42
|
+
|
|
43
|
+
/** The request for one page (`page` counts from 1) of a collection. */
|
|
44
|
+
export function pageRequest(
|
|
45
|
+
source: Exclude<Source, 'file'>,
|
|
46
|
+
env: Env,
|
|
47
|
+
collection: string,
|
|
48
|
+
page: number,
|
|
49
|
+
staged: boolean,
|
|
50
|
+
): Request {
|
|
51
|
+
const c = encodeURIComponent(collection);
|
|
52
|
+
if (source === 'webflow') {
|
|
53
|
+
const listing = staged ? 'items' : 'items/live';
|
|
54
|
+
return {
|
|
55
|
+
url: `https://api.webflow.com/v2/collections/${c}/${listing}?offset=${(page - 1) * PAGE_SIZE}&limit=${PAGE_SIZE}`,
|
|
56
|
+
headers: { authorization: `Bearer ${env.WEBFLOW_TOKEN}`, accept: 'application/json' },
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (source === 'payload') {
|
|
60
|
+
const auth = env.PAYLOAD_AUTH_COLLECTION || 'users';
|
|
61
|
+
return {
|
|
62
|
+
url: `${origin(env.PAYLOAD_URL ?? '')}/api/${c}?limit=${PAGE_SIZE}&page=${page}&depth=1${staged ? '&draft=true' : ''}`,
|
|
63
|
+
headers: { authorization: `${auth} API-Key ${env.PAYLOAD_API_KEY}`, accept: 'application/json' },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const headers: Record<string, string> = { accept: 'application/json' };
|
|
67
|
+
if (env.WORDPRESS_USER && env.WORDPRESS_APP_PASSWORD)
|
|
68
|
+
headers.authorization = `Basic ${btoa(`${env.WORDPRESS_USER}:${env.WORDPRESS_APP_PASSWORD}`)}`;
|
|
69
|
+
return {
|
|
70
|
+
url: `${origin(env.WORDPRESS_URL ?? '')}/wp-json/wp/v2/${c}?per_page=${PAGE_SIZE}&page=${page}&_embed=1${staged ? '&status=any' : ''}`,
|
|
71
|
+
headers,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type WebflowPage = {
|
|
76
|
+
items: (Item & { isArchived?: boolean })[];
|
|
77
|
+
pagination: { total: number; offset: number };
|
|
78
|
+
};
|
|
79
|
+
type PayloadPage = { docs: Item[]; hasNextPage: boolean };
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* One page's items and whether another follows. Webflow's archived items
|
|
83
|
+
* are dropped, since they are not on the site. WordPress answers with a bare
|
|
84
|
+
* array and puts the page count in X-WP-TotalPages.
|
|
85
|
+
*/
|
|
86
|
+
export function readPage(
|
|
87
|
+
source: Exclude<Source, 'file'>,
|
|
88
|
+
body: unknown,
|
|
89
|
+
page: number,
|
|
90
|
+
totalPages?: string | null,
|
|
91
|
+
): Page {
|
|
92
|
+
if (source === 'webflow') {
|
|
93
|
+
const { items, pagination } = body as WebflowPage;
|
|
94
|
+
return {
|
|
95
|
+
items: items.filter((i) => !i.isArchived),
|
|
96
|
+
more: items.length > 0 && pagination.offset + PAGE_SIZE < pagination.total,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (source === 'payload') {
|
|
100
|
+
const { docs, hasNextPage } = body as PayloadPage;
|
|
101
|
+
return { items: docs, more: hasNextPage };
|
|
102
|
+
}
|
|
103
|
+
const items = body as Item[];
|
|
104
|
+
return { items, more: items.length > 0 && page < Number(totalPages ?? 1) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Where a file keeps its items: a bare array, or the first array under a common key. */
|
|
108
|
+
export function itemsInFile(json: unknown): Item[] | null {
|
|
109
|
+
if (Array.isArray(json)) return json as Item[];
|
|
110
|
+
if (!json || typeof json !== 'object') return null;
|
|
111
|
+
for (const key of ['items', 'entries', 'docs', 'data', 'results']) {
|
|
112
|
+
const value = (json as Record<string, unknown>)[key];
|
|
113
|
+
if (Array.isArray(value)) return value as Item[];
|
|
114
|
+
if (value && typeof value === 'object') {
|
|
115
|
+
const nested = itemsInFile(value);
|
|
116
|
+
if (nested) return nested;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Where an item's fields start: Webflow nests them under fieldData; every other source maps from the item itself. */
|
|
123
|
+
export const fieldRoot = (source: Source, item: Item): Item =>
|
|
124
|
+
source === 'webflow' ? ((item.fieldData as Item | undefined) ?? {}) : item;
|
|
125
|
+
|
|
126
|
+
/** The named entities CMS output carries in practice; anything else is left as written. */
|
|
127
|
+
const NAMED: Record<string, string> = {
|
|
128
|
+
quot: '"',
|
|
129
|
+
apos: "'",
|
|
130
|
+
lt: '<',
|
|
131
|
+
gt: '>',
|
|
132
|
+
nbsp: ' ',
|
|
133
|
+
hellip: '…',
|
|
134
|
+
mdash: '—',
|
|
135
|
+
ndash: '–',
|
|
136
|
+
lsquo: '‘',
|
|
137
|
+
rsquo: '’',
|
|
138
|
+
ldquo: '“',
|
|
139
|
+
rdquo: '”',
|
|
140
|
+
eacute: 'é',
|
|
141
|
+
copy: '©',
|
|
142
|
+
reg: '®',
|
|
143
|
+
trade: '™',
|
|
144
|
+
amp: '&',
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const decode = (s: string) =>
|
|
148
|
+
s
|
|
149
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
|
150
|
+
.replace(/&#x([\da-f]+);/gi, (_, n) => String.fromCodePoint(Number.parseInt(n, 16)))
|
|
151
|
+
.replace(/&([a-z]+);/gi, (match, name: string) => NAMED[name.toLowerCase()] ?? match);
|
|
152
|
+
|
|
153
|
+
/** WordPress's `rendered` fields are HTML; a fixture holds the text a reader sees. */
|
|
154
|
+
export const plainText = (html: string) =>
|
|
155
|
+
decode(html.replace(/<[^>]*>/g, ''))
|
|
156
|
+
.replace(/\s+/g, ' ')
|
|
157
|
+
.trim();
|
|
158
|
+
|
|
159
|
+
/** The value at a dotted path (`title.rendered`, `_embedded.wp:featuredmedia.0.source_url`); undefined when it is not there. */
|
|
160
|
+
export function valueAt(root: unknown, path: string[]): unknown {
|
|
161
|
+
let value = root;
|
|
162
|
+
for (const part of path)
|
|
163
|
+
value = value && typeof value === 'object' ? (value as Record<string, unknown>)[part] : undefined;
|
|
164
|
+
if (typeof value === 'string' && path.at(-1) === 'rendered') return plainText(value);
|
|
165
|
+
return value;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const MAX_DEPTH = 3;
|
|
169
|
+
|
|
170
|
+
/** Every leaf path in an item, with a short sample, so the user can pick what to map. */
|
|
171
|
+
export function fieldPaths(item: unknown, prefix = '', depth = 0): { path: string; sample: string }[] {
|
|
172
|
+
if (!item || typeof item !== 'object' || depth > MAX_DEPTH)
|
|
173
|
+
return prefix ? [{ path: prefix, sample: JSON.stringify(item ?? null).slice(0, 60) }] : [];
|
|
174
|
+
const entries = Array.isArray(item)
|
|
175
|
+
? item.slice(0, 1).map((v, i) => [String(i), v] as const)
|
|
176
|
+
: Object.entries(item);
|
|
177
|
+
return entries.flatMap(([key, value]) => fieldPaths(value, prefix ? `${prefix}.${key}` : key, depth + 1));
|
|
178
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { test } from 'node:test';
|
|
3
|
+
import {
|
|
4
|
+
type Board,
|
|
5
|
+
chromeCandidates,
|
|
6
|
+
devtoolsUrl,
|
|
7
|
+
exportUrl,
|
|
8
|
+
fileNames,
|
|
9
|
+
pdfFiles,
|
|
10
|
+
plan,
|
|
11
|
+
readDevtools,
|
|
12
|
+
} from './export.ts';
|
|
13
|
+
import { fitZoom, pageSize, sizeLabel, zoomFor } from './formats.ts';
|
|
14
|
+
|
|
15
|
+
const board = (name: string, format: string, output: 'png' | 'pdf'): Board => ({
|
|
16
|
+
index: 0,
|
|
17
|
+
name,
|
|
18
|
+
format,
|
|
19
|
+
output,
|
|
20
|
+
x: 0,
|
|
21
|
+
y: 0,
|
|
22
|
+
width: 1,
|
|
23
|
+
height: 1,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('formats know their size, page and screen zoom', () => {
|
|
27
|
+
assert.equal(sizeLabel('story'), '1080 × 1920');
|
|
28
|
+
assert.equal(pageSize('a4'), '210mm 297mm');
|
|
29
|
+
assert.equal(pageSize('slide'), '1920px 1080px');
|
|
30
|
+
assert.equal(fitZoom('post-square', { width: 2000, height: 2000 }), 1);
|
|
31
|
+
assert.equal(fitZoom('post-square', { width: 540, height: 2000 }), 0.5);
|
|
32
|
+
assert.equal(fitZoom('story', { width: 2000, height: 960 }), 0.5);
|
|
33
|
+
assert.equal(zoomFor('fit', 'post-square', { width: 540, height: 2000 }), 0.5);
|
|
34
|
+
assert.equal(zoomFor('25%', 'slide', { width: 1, height: 1 }), 0.25);
|
|
35
|
+
assert.equal(zoomFor('odd', 'slide', { width: 1, height: 1 }), 1);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('Chrome is looked for where each system keeps it, $CHROME_PATH first', () => {
|
|
39
|
+
assert.equal(chromeCandidates('darwin', { CHROME_PATH: '/x/chrome' })[0], '/x/chrome');
|
|
40
|
+
assert.match(chromeCandidates('darwin', {})[0], /Google Chrome\.app/);
|
|
41
|
+
assert.ok(chromeCandidates('linux', {}).includes('/usr/bin/chromium'));
|
|
42
|
+
assert.match(chromeCandidates('win32', { PROGRAMFILES: 'C:\\PF' })[0], /^C:\\PF\\Google/);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("the DevTools address comes from Chrome's start line", () => {
|
|
46
|
+
assert.equal(
|
|
47
|
+
devtoolsUrl('x\nDevTools listening on ws://127.0.0.1:5555/devtools/browser/ab-cd\n'),
|
|
48
|
+
'ws://127.0.0.1:5555/devtools/browser/ab-cd',
|
|
49
|
+
);
|
|
50
|
+
assert.equal(devtoolsUrl('nothing yet'), null);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('auto follows each format; png or pdf sends everything one way', () => {
|
|
54
|
+
const boards = [board('a', 'post-square', 'png'), board('b', 'slide', 'pdf')];
|
|
55
|
+
assert.deepEqual(
|
|
56
|
+
plan(boards, 'auto').png.map((b) => b.name),
|
|
57
|
+
['a'],
|
|
58
|
+
);
|
|
59
|
+
assert.deepEqual(
|
|
60
|
+
plan(boards, 'auto').pdf.map((b) => b.name),
|
|
61
|
+
['b'],
|
|
62
|
+
);
|
|
63
|
+
assert.equal(plan(boards, 'pdf').pdf.length, 2);
|
|
64
|
+
assert.equal(plan(boards, 'png').png.length, 2);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('file names are the slug and the artboard name, unique, with the format when unnamed', () => {
|
|
68
|
+
assert.deepEqual(
|
|
69
|
+
fileNames(
|
|
70
|
+
'launch',
|
|
71
|
+
[
|
|
72
|
+
board('Square', 'post-square', 'png'),
|
|
73
|
+
board('Square', 'post-square', 'png'),
|
|
74
|
+
board('', 'story', 'png'),
|
|
75
|
+
],
|
|
76
|
+
'png',
|
|
77
|
+
),
|
|
78
|
+
['launch-square.png', 'launch-square-2.png', 'launch-story-3.png'],
|
|
79
|
+
);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('the export URL carries the dial state and theme', () => {
|
|
83
|
+
assert.equal(exportUrl('http://localhost:1', 'launch', {}), 'http://localhost:1/launch/?export=1');
|
|
84
|
+
assert.equal(
|
|
85
|
+
exportUrl('http://localhost:1', 'launch', { dials: '{"Review":{"fixtures":"longest"}}', theme: 'dark' }),
|
|
86
|
+
'http://localhost:1/launch/?export=1&dials=%7B%22Review%22%3A%7B%22fixtures%22%3A%22longest%22%7D%7D&theme=dark',
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('one PDF per format, named after the format only when there are several', () => {
|
|
91
|
+
assert.deepEqual(pdfFiles('deck', [board('a', 'slide', 'pdf'), board('b', 'slide', 'pdf')]), [
|
|
92
|
+
{ format: 'slide', file: 'deck.pdf' },
|
|
93
|
+
]);
|
|
94
|
+
assert.deepEqual(
|
|
95
|
+
pdfFiles('deck', [board('a', 'slide', 'pdf'), board('b', 'a4', 'pdf'), board('c', 'slide', 'pdf')]),
|
|
96
|
+
[
|
|
97
|
+
{ format: 'slide', file: 'deck-slide.pdf' },
|
|
98
|
+
{ format: 'a4', file: 'deck-a4.pdf' },
|
|
99
|
+
],
|
|
100
|
+
);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('DevTools messages are replies, page exceptions, or ignored', () => {
|
|
104
|
+
assert.deepEqual(readDevtools('{"id":3,"result":{"a":1}}'), {
|
|
105
|
+
kind: 'reply',
|
|
106
|
+
id: 3,
|
|
107
|
+
result: { a: 1 },
|
|
108
|
+
error: undefined,
|
|
109
|
+
});
|
|
110
|
+
assert.deepEqual(readDevtools('{"id":4,"error":{"message":"No target"}}'), {
|
|
111
|
+
kind: 'reply',
|
|
112
|
+
id: 4,
|
|
113
|
+
result: undefined,
|
|
114
|
+
error: 'No target',
|
|
115
|
+
});
|
|
116
|
+
assert.deepEqual(
|
|
117
|
+
readDevtools(
|
|
118
|
+
'{"method":"Runtime.exceptionThrown","params":{"exceptionDetails":{"exception":{"description":"TypeError: x"}}}}',
|
|
119
|
+
),
|
|
120
|
+
{ kind: 'exception', text: 'TypeError: x' },
|
|
121
|
+
);
|
|
122
|
+
assert.deepEqual(readDevtools('{"method":"Runtime.exceptionThrown","params":{}}'), {
|
|
123
|
+
kind: 'exception',
|
|
124
|
+
text: 'An exception',
|
|
125
|
+
});
|
|
126
|
+
assert.deepEqual(readDevtools('{"method":"Page.loadEventFired"}'), { kind: 'other' });
|
|
127
|
+
});
|
package/core/export.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// The decisions `design-hub export` makes, kept pure: which browser to drive,
|
|
2
|
+
// what each artboard becomes, and what its file is called. The command
|
|
3
|
+
// (scripts/export.ts) does the driving.
|
|
4
|
+
import { isFormat, type Output } from './formats.ts';
|
|
5
|
+
|
|
6
|
+
/** An artboard as the page reports it: its name, format, and box in page pixels. */
|
|
7
|
+
export type Board = {
|
|
8
|
+
/** Its place on the page, so the exporter can show or hide exactly this one. */
|
|
9
|
+
index: number;
|
|
10
|
+
name: string;
|
|
11
|
+
format: string;
|
|
12
|
+
output: Output;
|
|
13
|
+
x: number;
|
|
14
|
+
y: number;
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type As = 'auto' | Output;
|
|
20
|
+
|
|
21
|
+
/** Where Chrome, Chromium or Edge usually lives; $CHROME_PATH first. */
|
|
22
|
+
export function chromeCandidates(platform: string, env: Record<string, string | undefined>): string[] {
|
|
23
|
+
const own = env.CHROME_PATH ? [env.CHROME_PATH] : [];
|
|
24
|
+
if (platform === 'darwin')
|
|
25
|
+
return [
|
|
26
|
+
...own,
|
|
27
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
28
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
29
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
30
|
+
];
|
|
31
|
+
if (platform === 'win32') {
|
|
32
|
+
const roots = [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean);
|
|
33
|
+
return [
|
|
34
|
+
...own,
|
|
35
|
+
...roots.flatMap((r) => [
|
|
36
|
+
`${r}\\Google\\Chrome\\Application\\chrome.exe`,
|
|
37
|
+
`${r}\\Microsoft\\Edge\\Application\\msedge.exe`,
|
|
38
|
+
]),
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
return [
|
|
42
|
+
...own,
|
|
43
|
+
'/usr/bin/google-chrome',
|
|
44
|
+
'/usr/bin/google-chrome-stable',
|
|
45
|
+
'/usr/bin/chromium',
|
|
46
|
+
'/usr/bin/chromium-browser',
|
|
47
|
+
'/snap/bin/chromium',
|
|
48
|
+
];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The browser's DevTools address, from the line headless Chrome prints on start. */
|
|
52
|
+
export const devtoolsUrl = (stderr: string) =>
|
|
53
|
+
stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1] ?? null;
|
|
54
|
+
|
|
55
|
+
/** What one DevTools message means to the exporter: a reply to a command, a page exception, or nothing. */
|
|
56
|
+
export type DevtoolsMessage =
|
|
57
|
+
| { kind: 'reply'; id: number; result: unknown; error?: string }
|
|
58
|
+
| { kind: 'exception'; text: string }
|
|
59
|
+
| { kind: 'other' };
|
|
60
|
+
|
|
61
|
+
type RawMessage = {
|
|
62
|
+
id?: number;
|
|
63
|
+
result?: unknown;
|
|
64
|
+
error?: { message: string };
|
|
65
|
+
method?: string;
|
|
66
|
+
params?: { exceptionDetails?: { exception?: { description?: string }; text?: string } };
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export function readDevtools(data: string): DevtoolsMessage {
|
|
70
|
+
const msg = JSON.parse(data) as RawMessage;
|
|
71
|
+
if (msg.id !== undefined)
|
|
72
|
+
return { kind: 'reply', id: msg.id, result: msg.result, error: msg.error?.message };
|
|
73
|
+
if (msg.method !== 'Runtime.exceptionThrown') return { kind: 'other' };
|
|
74
|
+
const d = msg.params?.exceptionDetails;
|
|
75
|
+
return { kind: 'exception', text: d?.exception?.description ?? d?.text ?? 'An exception' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Which artboards become PNG files and which go into the one PDF. */
|
|
79
|
+
export function plan(boards: Board[], as: As): { png: Board[]; pdf: Board[] } {
|
|
80
|
+
const output = (b: Board): Output => (as === 'auto' ? b.output : as);
|
|
81
|
+
return { png: boards.filter((b) => output(b) === 'png'), pdf: boards.filter((b) => output(b) === 'pdf') };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const slugify = (s: string) =>
|
|
85
|
+
s
|
|
86
|
+
.toLowerCase()
|
|
87
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
88
|
+
.replace(/^-|-$/g, '');
|
|
89
|
+
|
|
90
|
+
/** `<slug>-<name>.png`, unique within one export: a repeated name gets -2, -3. */
|
|
91
|
+
export function fileNames(slug: string, boards: Board[], ext: string): string[] {
|
|
92
|
+
const seen = new Map<string, number>();
|
|
93
|
+
return boards.map((b, i) => {
|
|
94
|
+
const base = slugify(b.name) || (isFormat(b.format) ? `${b.format}-${i + 1}` : `artboard-${i + 1}`);
|
|
95
|
+
const count = (seen.get(base) ?? 0) + 1;
|
|
96
|
+
seen.set(base, count);
|
|
97
|
+
return `${slug}-${count > 1 ? `${base}-${count}` : base}.${ext}`;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The PDFs an export writes: one per format, in the order the formats first
|
|
103
|
+
* appear. Chrome lays out one PDF at a single width, so a deck and an A4 page
|
|
104
|
+
* in the same file would shrink each other.
|
|
105
|
+
*/
|
|
106
|
+
export function pdfFiles(slug: string, boards: Board[]): { format: string; file: string }[] {
|
|
107
|
+
const formats = [...new Set(boards.map((b) => b.format))];
|
|
108
|
+
return formats.map((format) => ({
|
|
109
|
+
format,
|
|
110
|
+
file: formats.length > 1 ? `${slug}-${format}.pdf` : `${slug}.pdf`,
|
|
111
|
+
}));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The page the browser opens: the prototype in export mode, with the dial state and theme asked for. */
|
|
115
|
+
export function exportUrl(origin: string, slug: string, opts: { dials?: string; theme?: string }): string {
|
|
116
|
+
const params = new URLSearchParams({ export: '1' });
|
|
117
|
+
if (opts.dials) params.set('dials', opts.dials);
|
|
118
|
+
if (opts.theme) params.set('theme', opts.theme);
|
|
119
|
+
return `${origin}/${slug}/?${params}`;
|
|
120
|
+
}
|
package/core/formats.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// The fixed sizes brand collateral is made in. An artboard is designed at its
|
|
2
|
+
// real pixel size, so type and spacing are the values that ship, and
|
|
3
|
+
// `design-hub export` writes it at that size: PNG for anything posted, PDF for
|
|
4
|
+
// anything presented or printed. One list for the kit (the browser) and the
|
|
5
|
+
// export command (Node).
|
|
6
|
+
|
|
7
|
+
export type Output = 'png' | 'pdf';
|
|
8
|
+
|
|
9
|
+
export type Format = {
|
|
10
|
+
label: string;
|
|
11
|
+
width: number;
|
|
12
|
+
height: number;
|
|
13
|
+
output: Output;
|
|
14
|
+
/** The CSS page size for PDF; pixel formats print at their pixel size. */
|
|
15
|
+
page?: string;
|
|
16
|
+
/** Bands a platform's own interface covers; type and logos stay out of them. */
|
|
17
|
+
safe?: { top: number; bottom: number };
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const FORMATS = {
|
|
21
|
+
'post-square': { label: 'Post, square', width: 1080, height: 1080, output: 'png' },
|
|
22
|
+
'post-portrait': { label: 'Post, portrait', width: 1080, height: 1350, output: 'png' },
|
|
23
|
+
story: { label: 'Story', width: 1080, height: 1920, output: 'png', safe: { top: 250, bottom: 250 } },
|
|
24
|
+
'link-preview': { label: 'Link preview', width: 1200, height: 630, output: 'png' },
|
|
25
|
+
banner: { label: 'Banner', width: 1584, height: 396, output: 'png' },
|
|
26
|
+
slide: { label: 'Slide', width: 1920, height: 1080, output: 'pdf' },
|
|
27
|
+
a4: { label: 'A4', width: 794, height: 1123, output: 'pdf', page: '210mm 297mm' },
|
|
28
|
+
letter: { label: 'Letter', width: 816, height: 1056, output: 'pdf', page: '8.5in 11in' },
|
|
29
|
+
} as const satisfies Record<string, Format>;
|
|
30
|
+
|
|
31
|
+
export type FormatName = keyof typeof FORMATS;
|
|
32
|
+
|
|
33
|
+
export const FORMAT_NAMES = Object.keys(FORMATS) as FormatName[];
|
|
34
|
+
|
|
35
|
+
export const isFormat = (v: unknown): v is FormatName => typeof v === 'string' && v in FORMATS;
|
|
36
|
+
|
|
37
|
+
/** `1080 × 1350`, as a label under an artboard. */
|
|
38
|
+
export const sizeLabel = (name: FormatName) => `${FORMATS[name].width} × ${FORMATS[name].height}`;
|
|
39
|
+
|
|
40
|
+
/** The CSS `@page` size a format prints at: its paper size, or its pixel size. */
|
|
41
|
+
export const pageSize = (name: FormatName) => {
|
|
42
|
+
const f: Format = FORMATS[name];
|
|
43
|
+
return f.page ?? `${f.width}px ${f.height}px`;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** The screen scale for the Board's zoom dial: `fit`, or a percentage. */
|
|
47
|
+
export function zoomFor(zoom: string, name: FormatName, room: { width: number; height: number }): number {
|
|
48
|
+
if (zoom === 'fit') return fitZoom(name, room);
|
|
49
|
+
const percent = Number.parseFloat(zoom);
|
|
50
|
+
return Number.isFinite(percent) && percent > 0 ? percent / 100 : 1;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How large an artboard draws on screen: its real size at most, else what
|
|
55
|
+
* fits the board's width and a comfortable height. Export always draws at 1.
|
|
56
|
+
*/
|
|
57
|
+
export function fitZoom(name: FormatName, room: { width: number; height: number }): number {
|
|
58
|
+
const { width, height } = FORMATS[name];
|
|
59
|
+
return Math.min(1, room.width / width, room.height / height);
|
|
60
|
+
}
|