@milesroxas/design-hub 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/core/catalog.test.ts +10 -1
  2. package/core/catalog.ts +11 -0
  3. package/core/cms.test.ts +103 -0
  4. package/core/cms.ts +178 -0
  5. package/core/export.test.ts +127 -0
  6. package/core/export.ts +120 -0
  7. package/core/formats.ts +60 -0
  8. package/core/project.test.ts +71 -0
  9. package/core/project.ts +147 -0
  10. package/dist/core/catalog.d.ts +5 -0
  11. package/dist/core/catalog.js +10 -0
  12. package/dist/core/cms.d.ts +40 -0
  13. package/dist/core/cms.js +141 -0
  14. package/dist/core/export.d.ts +52 -0
  15. package/dist/core/export.js +84 -0
  16. package/dist/core/formats.d.ts +90 -0
  17. package/dist/core/formats.js +39 -0
  18. package/dist/core/project.d.ts +56 -0
  19. package/dist/core/project.js +121 -0
  20. package/dist/scripts/cli.js +4 -0
  21. package/dist/scripts/commands.js +4 -0
  22. package/dist/scripts/export.d.ts +42 -0
  23. package/dist/scripts/export.js +192 -0
  24. package/dist/scripts/fixtures-pull.d.ts +31 -19
  25. package/dist/scripts/fixtures-pull.js +102 -62
  26. package/dist/scripts/lib/cdp.d.ts +11 -0
  27. package/dist/scripts/lib/cdp.js +110 -0
  28. package/dist/scripts/new.d.ts +13 -1
  29. package/dist/scripts/new.js +43 -4
  30. package/dist/scripts/tracks.d.ts +40 -0
  31. package/dist/scripts/tracks.js +93 -0
  32. package/dist/server/paths.d.ts +2 -0
  33. package/dist/server/paths.js +2 -0
  34. package/dist/server/project.d.ts +7 -0
  35. package/dist/server/project.js +29 -0
  36. package/kit/Artboard.tsx +160 -0
  37. package/kit/artboard.css +47 -0
  38. package/kit/dials.tsx +2 -1
  39. package/package.json +1 -1
  40. package/shell/Index.tsx +49 -4
  41. package/shell/main.tsx +6 -2
  42. package/shell/shell.css +7 -3
  43. package/skills/miles-brand/SKILL.md +52 -0
  44. package/skills/miles-design-hub/SKILL.md +60 -25
  45. package/skills/miles-get-hostile/SKILL.md +7 -5
  46. package/skills/miles-new-feature/SKILL.md +8 -7
  47. package/skills/miles-port/SKILL.md +14 -2
  48. package/skills/miles-port/references/emdash.md +43 -0
  49. package/skills/miles-port/references/payload.md +31 -0
  50. package/skills/miles-port/references/wordpress.md +31 -0
  51. package/skills/miles-prototype/SKILL.md +2 -2
  52. package/templates/app/README.md +1 -0
  53. package/templates/brand/README.md +48 -0
  54. package/templates/brand/index.tsx +16 -0
  55. package/templates/brand/styles.css +5 -0
  56. package/templates/site/README.md +42 -0
  57. package/templates/site/index.tsx +22 -0
  58. package/templates/site/styles.css +6 -0
  59. package/templates/space/README.md +1 -0
@@ -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 a Webflow CMS collection.";
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-list';
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 required: true;
15
- readonly description: 'The Webflow collection id.';
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 fieldData path it comes from (thumbnail.url). Omit to list fields.';
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 staged items (drafts included) instead of published ones.';
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 Webflow id, then each mapped field; a path that is not there is null. */
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
- field: string;
51
- type: string;
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 a Webflow CMS collection, with
4
- // only the fields the component renders, so a pull spends nothing on fields
5
- // nobody reads. Pages through the Data API (100 items a request) for any
6
- // --limit. Every other key in fixtures.json is kept. Run with no --map to
7
- // list the collection's fields. Needs WEBFLOW_TOKEN (cms:read) in .env.
8
- // API: https://developers.webflow.com/data/reference/cms/collection-items
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 a Webflow CMS collection.",
18
- positionals: [{ name: 'prototype', description: 'The prototype folder, e.g. sample-list', required: true }],
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: { type: 'string', required: true, description: 'The Webflow collection id.' },
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 fieldData path it comes from (thumbnail.url). Omit to list fields.',
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 Webflow id, then each mapped field; a path that is not there is null. */
45
- export function pick(item, maps) {
46
- const out = { id: item.id };
47
- for (const { key, path } of maps) {
48
- let value = item.fieldData;
49
- for (const part of path)
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
- async function get(token, path) {
56
- const response = await fetch(`${API}${path}`, {
57
- headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
58
- signal: AbortSignal.timeout(TIMEOUT_MS),
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(`Webflow answered ${response.status} for ${path}.`, {
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` unarchived items are in, or it runs out. */
78
- async function pullItems(token, collection, limit, staged) {
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
- const listing = staged ? 'items' : 'items/live';
81
- for (let offset = 0; items.length < limit; offset += PAGE) {
82
- const page = await get(token, `/collections/${collection}/${listing}?offset=${offset}&limit=${PAGE}`);
83
- items.push(...page.items.filter((i) => !i.isArchived));
84
- if (offset + PAGE >= page.pagination.total || !page.items.length)
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 real = (await pullItems(token, collection, flags.limit, flags.staged)).map((i) => pick(i, maps));
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
+ }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { type Track } from '../core/project.ts';
2
3
  import { type Args } from './lib/cli.ts';
3
4
  export declare const spec: {
4
5
  readonly name: 'new';
@@ -11,7 +12,12 @@ export declare const spec: {
11
12
  readonly flags: {
12
13
  readonly app: {
13
14
  readonly type: 'boolean';
14
- readonly description: 'Inside the product or site shell instead of the Space.';
15
+ readonly description: "Inside the track's shell (AppShell for product, SiteShell for website) instead of the Space.";
16
+ };
17
+ readonly track: {
18
+ readonly type: 'string';
19
+ readonly choices: readonly ["product", "website", "brand"];
20
+ readonly description: "The track it belongs to. Default: the project's only track; required when it has several.";
15
21
  };
16
22
  readonly sprint: {
17
23
  readonly type: 'boolean';
@@ -37,6 +43,12 @@ export declare const spec: {
37
43
  readonly output: '{ ok, created, url, next }';
38
44
  };
39
45
  type Kind = 'sprint' | 'alternate' | 'exploration';
46
+ /**
47
+ * The template folder: brand collateral is always a board of artboards;
48
+ * otherwise the Space, or the shell of the prototype's track. A project
49
+ * without tracks gets the product shell, as before.
50
+ */
51
+ export declare function templateFor(track: Track | '', app: boolean): string;
40
52
  /** The kind the flags ask for, refused when the feature's state does not allow it. */
41
53
  export declare function kindFor(flags: Pick<Args<typeof spec>['flags'], 'sprint' | 'alternate'>, feature: string, primary?: (f: string) => string | undefined): Kind;
42
54
  export declare function main(args: Args<typeof spec>): {
@@ -1,14 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  /// <reference types="node" />
3
3
  // Scaffolds a prototype from the package's templates/ (a Space, or --app inside the
4
- // shell), or a feature's walkthrough at docs/sprints/<feature>/guide.md.
4
+ // track's shell: AppShell for a product, SiteShell for a website), or a
5
+ // feature's walkthrough at docs/sprints/<feature>/guide.md.
5
6
  // A feature has one primary prototype (--sprint); --alternate is refused
6
7
  // until it exists, so the index always has a primary to show first.
7
8
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
8
9
  import { dirname, join, relative } from 'node:path';
9
10
  import { featureTitle, guideHref, SLUG } from '../core/feature.js';
11
+ import { TRACKS, trackFor } from '../core/project.js';
10
12
  import { devPort, readEnv } from '../server/env.js';
11
13
  import { DOCS, PROTOTYPES, ROOT, TEMPLATES } from '../server/paths.js';
14
+ import { readProject } from '../server/project.js';
12
15
  import { primaryOf } from './lib/catalog.js';
13
16
  import { CliError } from './lib/cli.js';
14
17
  export const spec = {
@@ -18,7 +21,15 @@ export const spec = {
18
21
  { name: 'slug', description: 'kebab-case folder name (with --guide: the feature)', required: true },
19
22
  ],
20
23
  flags: {
21
- app: { type: 'boolean', description: 'Inside the product or site shell instead of the Space.' },
24
+ app: {
25
+ type: 'boolean',
26
+ description: "Inside the track's shell (AppShell for product, SiteShell for website) instead of the Space.",
27
+ },
28
+ track: {
29
+ type: 'string',
30
+ choices: TRACKS,
31
+ description: "The track it belongs to. Default: the project's only track; required when it has several.",
32
+ },
22
33
  sprint: { type: 'boolean', description: "The feature's one primary prototype. Needs --feature." },
23
34
  alternate: {
24
35
  type: 'boolean',
@@ -61,6 +72,31 @@ function guide(feature) {
61
72
  next: `Write it from the States table. Screenshots go in docs/sprints/${feature}/assets/guide/.`,
62
73
  };
63
74
  }
75
+ /**
76
+ * The template folder: brand collateral is always a board of artboards;
77
+ * otherwise the Space, or the shell of the prototype's track. A project
78
+ * without tracks gets the product shell, as before.
79
+ */
80
+ export function templateFor(track, app) {
81
+ if (track === 'brand')
82
+ return 'brand';
83
+ if (!app)
84
+ return 'space';
85
+ return track === 'website' ? 'site' : 'app';
86
+ }
87
+ /** The prototype's track from --track and project.json, refused when the project cannot take it. */
88
+ function resolveTrack(asked) {
89
+ const { project, problems } = readProject();
90
+ if (problems.length)
91
+ throw new CliError('.design-hub/project.json is invalid.', {
92
+ problems,
93
+ fix: 'Rewrite it with design-hub tracks set --track <track>.',
94
+ });
95
+ const resolved = trackFor(project, asked);
96
+ if ('problem' in resolved)
97
+ throw new CliError(resolved.problem);
98
+ return resolved.track;
99
+ }
64
100
  /** The kind the flags ask for, refused when the feature's state does not allow it. */
65
101
  export function kindFor(flags, feature, primary = (f) => primaryOf(f)?.slug) {
66
102
  if (flags.sprint && flags.alternate)
@@ -90,17 +126,20 @@ function prototype(slug, { flags }) {
90
126
  if (feature && !SLUG.test(feature))
91
127
  throw new CliError('--feature takes a kebab-case slug.', { got: feature });
92
128
  const kind = kindFor(flags, feature);
93
- const context = flags.app ? 'app' : 'space';
94
- scaffold(join(TEMPLATES, context), join(PROTOTYPES, slug), {
129
+ const track = resolveTrack(flags.track);
130
+ const context = track === 'brand' ? 'board' : flags.app ? 'app' : 'space';
131
+ scaffold(join(TEMPLATES, templateFor(track, flags.app)), join(PROTOTYPES, slug), {
95
132
  title: flags.title ?? featureTitle(slug),
96
133
  slug,
97
134
  created: created(),
98
135
  kind,
99
136
  feature,
137
+ track,
100
138
  });
101
139
  return {
102
140
  created: `prototypes/${slug}/`,
103
141
  context,
142
+ track,
104
143
  kind,
105
144
  feature,
106
145
  url: localUrl(`/${slug}/`),
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { type Track } from '../core/project.ts';
3
+ import { type Args } from './lib/cli.ts';
4
+ export declare const spec: {
5
+ readonly name: 'tracks';
6
+ readonly summary: "Show or set the project's tracks (product, website, brand) and its website platform.";
7
+ readonly positionals: [{
8
+ readonly name: 'action';
9
+ readonly description: 'show (default): what project.json says. set: write it.';
10
+ }];
11
+ readonly flags: {
12
+ readonly track: {
13
+ readonly type: 'list';
14
+ readonly description: `For set: a track, repeated for several. One of: ${string}.`;
15
+ };
16
+ readonly platform: {
17
+ readonly type: 'string';
18
+ readonly choices: readonly ["webflow", "payload", "wordpress", "emdash"];
19
+ readonly description: 'For set, with the website track: where the site is built.';
20
+ };
21
+ readonly frontend: {
22
+ readonly type: 'string';
23
+ readonly choices: readonly ["astro", "next"];
24
+ readonly description: 'For set: the front end, for Payload or WordPress. Webflow takes none; EmDash is always Astro.';
25
+ };
26
+ readonly 'remove-samples': {
27
+ readonly type: 'boolean';
28
+ readonly description: 'For set: delete the sample prototype and walkthrough of every track not set. Setup only.';
29
+ };
30
+ };
31
+ readonly output: '{ ok, tracks, website?, file, removed?, warnings }';
32
+ };
33
+ /** Deletes the samples of the tracks a project does not keep; returns what went, relative to the project. */
34
+ export declare function removeSamples(keep: readonly Track[], prototypes?: string, docs?: string, root?: string): string[];
35
+ export declare function main(args: Args<typeof spec>): {
36
+ tracks: Track[];
37
+ website?: import("../core/project.ts").Website;
38
+ file: string;
39
+ warnings: string[];
40
+ };