decklight 0.9.0 → 0.10.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 (48) hide show
  1. package/PLATFORM.md +44 -3
  2. package/README.md +7 -5
  3. package/SPEC.md +100 -31
  4. package/cli/agent-review.mjs +5 -4
  5. package/cli/agents.mjs +11 -5
  6. package/cli/bundle-audio.mjs +10 -3
  7. package/cli/bundle-module.mjs +95 -0
  8. package/cli/bundle.mjs +58 -6
  9. package/cli/cast.mjs +41 -5
  10. package/cli/check-fixes.mjs +186 -0
  11. package/cli/check.mjs +32 -5
  12. package/cli/commit-flow.mjs +7 -3
  13. package/cli/commit-message.mjs +1 -1
  14. package/cli/commit-split.mjs +2 -2
  15. package/cli/deck-refs.mjs +8 -3
  16. package/cli/design-system-refs.mjs +263 -6
  17. package/cli/design-system.mjs +82 -14
  18. package/cli/edit-git.mjs +2 -2
  19. package/cli/edit-handover.mjs +129 -23
  20. package/cli/edit-look.mjs +248 -5
  21. package/cli/edit.mjs +504 -58
  22. package/cli/enhance.mjs +12 -10
  23. package/cli/git.mjs +13 -0
  24. package/cli/init.mjs +8 -3
  25. package/cli/marketplace-autocheck.mjs +200 -0
  26. package/cli/marketplace.mjs +250 -13
  27. package/cli/narrate.mjs +78 -3
  28. package/cli/open.mjs +24 -6
  29. package/cli/pdf.mjs +27 -8
  30. package/cli/pptx-export.mjs +7 -4
  31. package/cli/record.mjs +73 -13
  32. package/cli/remote.mjs +32 -6
  33. package/cli/serve.mjs +2 -2
  34. package/cli/skill-content.mjs +40 -3
  35. package/cli/skills.mjs +247 -3
  36. package/cli/theme-refs.mjs +14 -2
  37. package/cli/units.mjs +75 -7
  38. package/dist/build-info.json +1 -1
  39. package/dist/decklight.css +429 -32
  40. package/dist/decklight.js +169 -123
  41. package/dist/decklight.js.map +4 -4
  42. package/package.json +1 -1
  43. package/tools/design-system-format.mjs +25 -0
  44. package/tools/design-system-migrations.mjs +207 -0
  45. package/tools/exec.mjs +10 -2
  46. package/tools/narration-manifest.mjs +77 -3
  47. package/tools/site-clip.mjs +114 -0
  48. package/tools/video.mjs +69 -6
package/cli/check.mjs CHANGED
@@ -49,7 +49,10 @@ import {
49
49
  import { CLICK_MARK } from '../tools/sentences.mjs';
50
50
  import { isTemplateRef, parseTemplateRef } from '../tools/design-system-format.mjs';
51
51
  import { auditDeck } from './audit.mjs';
52
- import { designSystemRefs, packageVerdict, resolveDesignSystemRef } from './design-system-refs.mjs';
52
+ import {
53
+ designSystemRefs, packageVerdict, resolveDesignSystemRef, deckDesignSystemVersions, linkedStylesheets, migrationStatus, behindMessage,
54
+ } from './design-system-refs.mjs';
55
+ import { composeRenames, migrationsOf } from '../tools/design-system-migrations.mjs';
53
56
  import { markedSources } from './theme-refs.mjs';
54
57
  import { parseColor, toOklab } from '../tools/color.mjs';
55
58
  import { ON_PALETTE_DISTANCE, offRoleColours, nearestRole, resolveTokenColours } from '../tools/brand-palette.mjs';
@@ -389,8 +392,11 @@ export function deckDesignSystems(html) {
389
392
  /** What `check` keeps of a design system that passed its gate: its templates, and its palette and roles when it has them. */
390
393
  export function checkEntry(ref, verdict) {
391
394
  const brand = verdict?.summary?.brand;
395
+ const m = verdict?.manifest;
392
396
  return {
393
397
  ref, templates: new Map((verdict?.summary?.templates ?? []).map((l) => [l.id, l.slots])),
398
+ // what a deck behind its version is held to (SPEC DESIGN_SYSTEM_MIGRATIONS)
399
+ ...(m?.version ? { migrationManifest: { name: m.name, version: m.version, tokenPrefix: m.tokenPrefix, migrations: m.migrations } } : {}),
394
400
  // component classes its base styles also give a plain element (SPEC DESIGN_SYSTEMS)
395
401
  components: verdict?.summary?.baseStyles?.components ?? {},
396
402
  // a palette of scales and its own themes (SPEC BRAND_PALETTE): what off-palette-literal holds slides to
@@ -567,7 +573,7 @@ function diagramBuilds(svg) {
567
573
  * `dir` is what a relative asset path resolves against — the deck's own
568
574
  * directory, exactly as the browser would resolve it from the deck's URL.
569
575
  */
570
- export function staticFindings(html, { dir = '.', exists = existsSync, designSystems = deckDesignSystems } = {}) {
576
+ export function staticFindings(html, { dir = '.', exists = existsSync, designSystems = deckDesignSystems, stylesheets = linkedStylesheets, deck = '<deck.html>' } = {}) {
571
577
  const src = String(html ?? '');
572
578
  const out = [];
573
579
  const ranges = sectionRanges(src);
@@ -590,6 +596,26 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
590
596
  `design system ${sys.ref} cannot be read on this machine — ${sys.missing}; its slides' templates and slots go unchecked`));
591
597
  }
592
598
  }
599
+ // A deck behind the major this machine serves (SPEC DESIGN_SYSTEM_MIGRATIONS):
600
+ // ONE finding with the renames and what moves them, read from the deck and
601
+ // the stylesheets it links — and the names it found are not each said again
602
+ // as off-role. `renamedTo` names a renamed role wherever off-role still meets one.
603
+ const behindNames = new Set();
604
+ const renamedTo = new Map();
605
+ const versions = configured.length ? deckDesignSystemVersions(src) : {};
606
+ let linked = null;
607
+ for (const [name, sys] of systems) {
608
+ const mm = sys.migrationManifest;
609
+ if (!mm) continue;
610
+ linked ??= stylesheets(src, dir).map((x) => x.text);
611
+ const status = migrationStatus(mm, versions[sys.ref] ?? null, [src, ...linked]);
612
+ for (const [from, r] of Object.entries(composeRenames(migrationsOf(mm)).roles)) {
613
+ renamedTo.set(`${mm.tokenPrefix ?? `--${mm.name}-`}color-${from}`, `was renamed ${r.to} in ${r.version}`);
614
+ }
615
+ if (!status.behind) continue;
616
+ for (const f of status.found) behindNames.add(f.as);
617
+ out.push(finding('warn', 'ds-behind', null, 'head', `${sys.ref} — ${behindMessage(name, status, { ref: sys.ref, deck })}`));
618
+ }
593
619
  // `sectionInner`, never the raw body: a body begins mid-open-tag, so a slide
594
620
  // with no heading to fall back on would be titled ` data-markdown>` — the
595
621
  // remnant of its own tag, read as the slide's opening words.
@@ -645,7 +671,7 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
645
671
  const values = [...COLOUR_ATTRS.map((k) => [k, a[k]]).filter(([, v]) => v), ...[...(a.style ?? '').matchAll(COLOUR_DECL)].map((m) => [m[1], m[2]])];
646
672
  for (const [prop, v] of values) {
647
673
  for (const o of offRoleColours(v, roles.ctx)) {
648
- if (off.some((x) => x.name === o.name)) continue;
674
+ if (off.some((x) => x.name === o.name) || behindNames.has(o.name)) continue;
649
675
  // `border: var(--acme-rule-width) solid …`: a design-system token that is no colour is the width, not off-role
650
676
  if (o.kind === 'token' && !o.hex && SHORTHAND.test(prop)) continue;
651
677
  off.push({ ...o, near: (o.kind === 'contract' && roles.contract[o.name]) || nearestRole(roles.values, o.hex) });
@@ -653,7 +679,8 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
653
679
  }
654
680
  }
655
681
  if (off.length) {
656
- const what = (o) => `${o.name}${o.kind === 'contract' ? ' (the theme contract)' : o.kind === 'swatch' ? ' (a swatch)' : o.kind === 'token' ? ' (a design-system token)' : ''}${o.near ? ` (nearest role ${o.near})` : ''}`;
682
+ const what = (o) => `${o.name}${renamedTo.has(o.name) ? ` (${renamedTo.get(o.name)})`
683
+ : `${o.kind === 'contract' ? ' (the theme contract)' : o.kind === 'swatch' ? ' (a swatch)' : o.kind === 'token' ? ' (a design-system token)' : ''}${o.near ? ` (nearest role ${o.near})` : ''}`}`;
657
684
  push('off-role', `${off.slice(0, 3).map(what).join(', ')}${off.length > 3 ? ` and ${off.length - 3} more` : ''}`
658
685
  + ` ${off.length === 1 ? 'is' : 'are'} not one of the design system's roles — this deck colours through them, so every theme recolours it: pick a role in Colors…, or set "brandThemesOnly": false`);
659
686
  }
@@ -918,7 +945,7 @@ export async function checkMain(args = []) {
918
945
 
919
946
  const html = readFileSync(src, 'utf8');
920
947
  const slides = sectionBodies(html).length;
921
- const findings = staticFindings(html, { dir: dirname(src) });
948
+ const findings = staticFindings(html, { dir: dirname(src), deck });
922
949
 
923
950
  // The render half is skipped rather than failed when there is no browser:
924
951
  // `findChrome` and never `chromeBin`, which exits the process — half a lint
@@ -176,7 +176,11 @@ export function nagText({ lines = 0, sinceMs = 0 } = {}) {
176
176
  }
177
177
 
178
178
  /** The line `open` prints when the snapshot is what stands behind the nag. */
179
- export function wipLine(deckRel) {
180
- return ` git: committing ${deckRel} when you say so — a silent snapshot rides on`
181
- + ` ${WIP_REF.replace('refs/', '')} in between (git show decklight/wip:${deckRel})`;
179
+ export function wipLine(deckRel, { untracked = false } = {}) {
180
+ // An untracked deck is not committed until K (edit.mjs startGit), so the
181
+ // line says that rather than promising a commit nobody asked for.
182
+ const lead = untracked
183
+ ? ` git: ${deckRel} is not in git: K adds it — until then a silent snapshot rides on`
184
+ : ` git: committing ${deckRel} when you say so — a silent snapshot rides on`;
185
+ return `${lead} ${WIP_REF.replace('refs/', '')} in between (git show decklight/wip:${deckRel})`;
182
186
  }
@@ -345,7 +345,7 @@ export async function describeCommit({
345
345
 
346
346
  /**
347
347
  * A subject for work that is NOT COMMITTED YET — what the commit overlay's
348
- * "write them for me" button asks for.
348
+ * "write it for me" button asks for.
349
349
  *
350
350
  * The same prompt, the same read-only argv, the same cap and the same stated
351
351
  * truncation as `describeCommit`; three things differ, and each is because
@@ -252,7 +252,7 @@ const addedLines = (f) => {
252
252
  };
253
253
 
254
254
  /**
255
- * The commits "write them for me" proposes: `{ work, commits }`, where
255
+ * The commits "write it for me" proposes: `{ work, commits }`, where
256
256
  * `commits` is `[{ subject, units }]`, or `{ work, commits: null }` when there
257
257
  * is nothing to cut (no HEAD: a first commit is one commit; nothing changed).
258
258
  *
@@ -464,7 +464,7 @@ function commitTree(cwd, tree, parent, message, env) {
464
464
  export function commitPlan({ cwd, deckRel, also = [], base, commits, template }) {
465
465
  const now = workingUnits({ cwd, deckRel, also });
466
466
  if (!now || now.base !== base) {
467
- return { ok: false, code: 'STALE', error: 'the deck changed since these commits were proposed — write them again' };
467
+ return { ok: false, code: 'STALE', error: 'the deck changed since these commits were proposed — write it again' };
468
468
  }
469
469
  const byId = new Map(now.units.map((u) => [u.id, u]));
470
470
  const asked = (commits ?? []).map((c) => ({ subject: String(c?.message ?? ''), units: (c?.units ?? []).map(Number), skip: !!c?.skip }));
package/cli/deck-refs.mjs CHANGED
@@ -35,9 +35,14 @@ export const REFERENCE_KINDS = [
35
35
  { kind: 'font', link: linkFonts, asset: fontAsset, namespace: inFontNamespace },
36
36
  ];
37
37
 
38
- /** Every reference kind linked into a served page, in the chain's order. */
39
- export function linkReferences(html, kinds = REFERENCE_KINDS) {
40
- return kinds.reduce((out, k) => k.link(out), html);
38
+ /**
39
+ * Every reference kind linked into a served page, in the chain's order.
40
+ * `dir` is the deck's folder and `deck` its file name, for what a kind reads
41
+ * beside it and says about it (a design system's behind check reads the
42
+ * stylesheets the deck links, and names the deck in its command).
43
+ */
44
+ export function linkReferences(html, { dir = null, deck = undefined, kinds = REFERENCE_KINDS } = {}) {
45
+ return kinds.reduce((out, k) => k.link(out, undefined, { dir, deck }), html);
41
46
  }
42
47
 
43
48
  /**
@@ -32,10 +32,11 @@
32
32
  // `marketplace update` can change its bytes afterwards — remembered by a
33
33
  // stat signature so a page load re-reads nothing that has not changed.
34
34
 
35
- import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
35
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
36
36
  import { dirname, join, resolve, sep } from 'node:path';
37
37
  import { escapeHtml } from '../tools/escape.mjs';
38
- import { DESIGN_SYSTEM_API_VERSION, ASSET_EXTENSIONS } from '../tools/design-system-format.mjs';
38
+ import { DESIGN_SYSTEM_API_VERSION, ASSET_EXTENSIONS, tokenPrefixOf } from '../tools/design-system-format.mjs';
39
+ import { pendingMigrations, composeRenames, findRenamed, majorOf, applyRenames, RENAME_KINDS } from '../tools/design-system-migrations.mjs';
39
40
  import { configBlock, isDeck } from './runtime-link.mjs';
40
41
  import { configHome, loadRegistry, loadCatalog, MarketplaceError, NAME_RE } from './marketplace.mjs';
41
42
  import {
@@ -46,6 +47,247 @@ import { checkDir } from './design-system.mjs';
46
47
 
47
48
  export { DESIGN_SYSTEMS_KEY };
48
49
 
50
+ /**
51
+ * The config key a deck records the version of each design system it took
52
+ * under (SPEC DESIGN_SYSTEM_MIGRATIONS): `{ "<ref>": "5.0.0" }`, keyed by the
53
+ * deck's own spelling of the reference. The deck's fact, not this machine's:
54
+ * the ledger in ~/.decklight/ says what one machine installed, for every deck
55
+ * at once, and says nothing on the next machine.
56
+ */
57
+ export const DESIGN_SYSTEM_VERSIONS_KEY = 'designSystemVersions';
58
+
59
+ /** The versions a deck records, `{ ref: version }` — strings only. */
60
+ export function deckDesignSystemVersions(html) {
61
+ const v = configBlock(html)?.config?.[DESIGN_SYSTEM_VERSIONS_KEY];
62
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return {};
63
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === 'string'));
64
+ }
65
+
66
+ /**
67
+ * Record (or, with null, forget) the version of one design system the deck
68
+ * took, editing only that key so the author's formatting survives. A deck
69
+ * with no configuration block is returned as it is.
70
+ */
71
+ export function setDesignSystemVersion(html, ref, version) {
72
+ const block = configBlock(html);
73
+ if (!block || block.error) return html;
74
+ const versions = deckDesignSystemVersions(html);
75
+ if (version) versions[ref] = String(version);
76
+ else delete versions[ref];
77
+ const inner = withKey(block.inner, DESIGN_SYSTEM_VERSIONS_KEY, Object.keys(versions).length ? versions : null);
78
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
79
+ }
80
+
81
+ /**
82
+ * The stylesheets a deck links from its own folder (`<link rel="stylesheet"
83
+ * href="course.css">`), as `[{ href, path, text }]`: what a migration reads
84
+ * and rewrites beside the deck. A URL, a root-absolute path, a design
85
+ * system's or a theme's own link, and a file that is not there are left out.
86
+ */
87
+ export function linkedStylesheets(html, dir) {
88
+ const out = [];
89
+ const masked = String(html).replace(/<!--[\s\S]*?-->/g, '');
90
+ for (const tag of masked.match(/<link\b[^>]*>/gi) ?? []) {
91
+ if (!/\brel\s*=\s*["']?stylesheet/i.test(tag) || /\bdata-(?:design-system|theme)\b/i.test(tag)) continue;
92
+ const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag);
93
+ const url = (href?.[1] ?? href?.[2] ?? href?.[3] ?? '').replace(/[?#].*$/, '');
94
+ if (!url || /^([a-z][a-z0-9+.-]*:|\/)/i.test(url) || url.includes('decklight-design-system/')) continue;
95
+ const path = resolve(dir, decodeURI(url));
96
+ if (out.some((s) => s.path === path)) continue;
97
+ try { if (existsSync(path) && statSync(path).isFile()) out.push({ href: url, path, text: readFileSync(path, 'utf8') }); } catch { /* unreadable: not ours to migrate */ }
98
+ }
99
+ return out;
100
+ }
101
+
102
+ /**
103
+ * Is a deck behind the design system this machine serves (SPEC
104
+ * DESIGN_SYSTEM_MIGRATIONS)? From the version the deck records and the
105
+ * names it, and the stylesheets it links, still use:
106
+ * `{ behind, recorded, current, major, found, skills, renames }`
107
+ * `behind` when the deck records an older major, or uses a name a migration
108
+ * since its version renamed; `found` is those names (`findRenamed`), `skills`
109
+ * the skills the pending migrations name. A deck that records no version is
110
+ * held to every migration the package declares.
111
+ */
112
+ export function migrationStatus(manifest, recorded, texts) {
113
+ const current = manifest?.version ?? null;
114
+ const pending = pendingMigrations(manifest, recorded);
115
+ const renames = composeRenames(pending);
116
+ const found = findRenamed(texts, renames, tokenPrefixOf(manifest));
117
+ const rm = majorOf(recorded), cm = majorOf(current);
118
+ const major = rm !== null && cm !== null && rm < cm;
119
+ return {
120
+ behind: major || found.length > 0, recorded: recorded ?? null, current, major, found,
121
+ skills: [...new Set(pending.map((m) => m.skill).filter(Boolean))], renames,
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Every design system a deck is behind, from what `check` reads: the deck
127
+ * and the stylesheets it links from `dir` (SPEC DESIGN_SYSTEM_MIGRATIONS).
128
+ * `[{ ref, name, title, recorded, current, skills, message }]`, `message`
129
+ * the one sentence (`behindMessage`) with `deck` as the command's argument.
130
+ * A reference this machine cannot serve is not behind: it is missing, and
131
+ * said as that.
132
+ */
133
+ export function deckBehind(html, dir, home = configHome(), { deck = '<deck.html>' } = {}) {
134
+ const refs = designSystemRefs(html);
135
+ if (!refs.length) return [];
136
+ const sources = markedSources(html);
137
+ const versions = deckDesignSystemVersions(html);
138
+ let texts = null;
139
+ const out = [];
140
+ for (const ref of refs) {
141
+ const r = resolveDesignSystemRef(ref, home, { source: sources[ref.marketplace] ?? null });
142
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
143
+ if (!verdict?.ok) continue;
144
+ texts ??= [html, ...(dir ? linkedStylesheets(html, dir).map((x) => x.text) : [])];
145
+ const status = migrationStatus(verdict.manifest, versions[ref.ref] ?? null, texts);
146
+ if (!status.behind) continue;
147
+ out.push({
148
+ ref: ref.ref, name: ref.name, title: verdict.manifest.title || ref.name,
149
+ recorded: status.recorded, current: status.current, skills: status.skills,
150
+ message: behindMessage(ref.name, status, { ref: ref.ref, deck }),
151
+ });
152
+ }
153
+ return out;
154
+ }
155
+
156
+ /**
157
+ * A newer design system the catalog offers, said as what it means for the
158
+ * decks on it (SPEC DESIGN_SYSTEM_MIGRATIONS): one `newerThanInstalled` row
159
+ * with `note` (*major: decks that use it need migrating, with the acme-migrate
160
+ * skill*) and `how` (where to find them and what moves one) when the package
161
+ * this machine now has declares migrations since the version installed. Any
162
+ * other row comes back as it was.
163
+ */
164
+ export function withMigrationHint(n, home = configHome()) {
165
+ if (n?.type !== 'design-system') return n;
166
+ const r = resolveDesignSystemRef(n.qualified, home);
167
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
168
+ if (!verdict?.ok) return n;
169
+ const pending = pendingMigrations(verdict.manifest, n.from);
170
+ if (!pending.length) return n;
171
+ const skills = [...new Set(pending.map((m) => m.skill).filter(Boolean))];
172
+ const major = n.from === null || (majorOf(n.from) ?? 0) < (majorOf(n.to) ?? 0);
173
+ return {
174
+ ...n, migrations: pending.map((m) => m.version), skills,
175
+ note: `${major ? 'major: ' : ''}decks that use it need migrating${skills.length ? `, with the ${skills.join(' or ')} skill` : ''}`,
176
+ how: `decklight check finds them; decklight design-system migrate ${n.qualified} <deck.html> moves one`,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * What `design-system migrate` does to a deck, worked out in memory and
182
+ * written by nobody (SPEC DESIGN_SYSTEM_MIGRATIONS): the command and the
183
+ * edit server's Migrate both apply it. `{ error }` when the deck does not
184
+ * use `ref` or this machine cannot serve it, else
185
+ * `{ ref, name, title, recorded, version, status, html, sheets, renamed, byKind, changed }`
186
+ * — `html` the deck renamed and its version recorded, `sheets` the linked
187
+ * stylesheets a rename touched (`{ href, path, text, count }`), `byKind`
188
+ * `[[kind, found]]` for the report.
189
+ */
190
+ export function planMigration(html, dir, ref, home = configHome()) {
191
+ const hit = designSystemRefs(html).find((r) => r.ref === ref || r.name === ref);
192
+ if (!hit) return { error: `the deck does not use ${ref}` };
193
+ const r = resolveDesignSystemRef(hit, home, { source: markedSources(html)[hit.marketplace] ?? null });
194
+ if (!r.dir) return { error: `${hit.ref} — ${r.missing}` };
195
+ const verdict = checkDir(r.dir);
196
+ if (!verdict.ok) return { error: `${hit.ref} no longer passes its check — decklight design-system gate ${r.dir}` };
197
+ const m = verdict.manifest;
198
+ const recorded = deckDesignSystemVersions(html)[hit.ref] ?? null;
199
+ const sheets = linkedStylesheets(html, dir);
200
+ const status = migrationStatus(m, recorded, [html, ...sheets.map((x) => x.text)]);
201
+ const prefix = tokenPrefixOf(m);
202
+ const deckOut = applyRenames(html, status.renames, prefix, { config: true });
203
+ const next = setDesignSystemVersion(deckOut.text, hit.ref, m.version);
204
+ const touched = sheets.map((x) => ({ ...x, ...applyRenames(x.text, status.renames, prefix) })).filter((x) => x.count);
205
+ const renamed = deckOut.count + touched.reduce((n, x) => n + x.count, 0);
206
+ return {
207
+ ref: hit.ref, name: hit.name, marketplace: hit.marketplace, title: m.title || hit.name, recorded, version: m.version, status,
208
+ html: next, sheets: touched, renamed,
209
+ byKind: RENAME_KINDS.map((k) => [k, status.found.filter((f) => f.kind === k)]).filter(([, l]) => l.length),
210
+ changed: next !== html || renamed > 0,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * A migration said in lines — what `design-system migrate` prints and what
216
+ * the agent panel records when the edit server runs one: the versions, the
217
+ * renames by kind, the count and where, and the skill named for what a
218
+ * rename cannot decide. `placed(name)` says whether an agent already loads
219
+ * that skill (cli/skills.mjs `placedSkill`): the line then says so instead
220
+ * of how to install it.
221
+ */
222
+ export function migrationLines(plan, deck, { placed = () => null } = {}) {
223
+ const out = [`${deck}: ${plan.ref} ${plan.recorded ?? '(no version recorded)'} → ${plan.version}`];
224
+ if (plan.renamed) {
225
+ for (const [kind, list] of plan.byKind) out.push(` ${kind.padEnd(8)} ${list.map((f) => `${f.from} → ${f.to}`).join(', ')}`);
226
+ out.push(` ${plan.renamed} rename${plan.renamed === 1 ? '' : 's'} — in ${deck}${plan.sheets.map((x) => `, ${x.href}`).join('')}`);
227
+ } else out.push(' nothing it uses was renamed — recorded the new version');
228
+ const skills = plan.status.skills;
229
+ if (skills.length) {
230
+ // where the agent finds it, or how to put it there: every project first
231
+ const missing = skills.filter((s) => !placed(s));
232
+ out.push(` what a rename cannot decide (a name removed with no successor) is the ${skills.join(' and ')} skill's:`
233
+ + (missing.length
234
+ ? ` decklight library add skill ${missing[0]} --global (every project; --dir . for this one only), then ask your agent to finish the migration`
235
+ : ' your agent has it, ask it to finish the migration'));
236
+ }
237
+ return out;
238
+ }
239
+
240
+ /**
241
+ * Where a skill's SKILL.md already is on this machine, or null: the library's
242
+ * copy (`~/.decklight/skills/<name>/`) when one is installed, else the
243
+ * catalog entry's source in its marketplace's checkout, `marketplace` first.
244
+ * What a migration's prompt points the agent at, so running one never
245
+ * installs anything into the project (#893).
246
+ */
247
+ export function skillFile(name, marketplace = null, home = configHome()) {
248
+ const installed = join(home, 'skills', name, 'SKILL.md');
249
+ if (existsSync(installed)) return installed;
250
+ const markets = Object.keys(loadRegistry(home).marketplaces ?? {});
251
+ for (const market of [...(markets.includes(marketplace) ? [marketplace] : []), ...markets.filter((m) => m !== marketplace)]) {
252
+ let cat;
253
+ try { cat = loadCatalog(market, home); } catch { continue; }
254
+ const entry = cat?.ok ? cat.manifest.entries.find((e) => e.type === 'skill' && e.name === name) : null;
255
+ if (!entry?.source || /^https?:\/\//i.test(entry.source)) continue;
256
+ let base;
257
+ try { base = resolveSource(entry.source, { name: market, source: loadRegistry(home).marketplaces[market]?.source }, home); } catch { continue; }
258
+ const file = join(base, 'SKILL.md');
259
+ if (existsSync(file)) return file;
260
+ }
261
+ return null;
262
+ }
263
+
264
+ /**
265
+ * A deck that uses a design system but records no version takes `manifest`'s
266
+ * — unless it, or a stylesheet it links from `dir`, still uses a name a
267
+ * migration renamed: recording the new version then would hide that it is
268
+ * behind, and `migrate` moves it first. The html, recorded or as it was.
269
+ */
270
+ export function recordVersionIfCurrent(html, ref, manifest, dir) {
271
+ if (deckDesignSystemVersions(html)[ref] || !manifest?.version) return html;
272
+ const status = migrationStatus(manifest, null, [html, ...linkedStylesheets(html, dir).map((x) => x.text)]);
273
+ return status.found.length ? html : setDesignSystemVersion(html, ref, manifest.version);
274
+ }
275
+
276
+ /**
277
+ * The one sentence that says a deck is behind, with what to do — the same in
278
+ * `check`, the write-mode toast and `design-system migrate`'s refusal.
279
+ */
280
+ export function behindMessage(name, status, { ref = name, deck = '<deck.html>' } = {}) {
281
+ const was = status.recorded ? `${name} ${status.recorded}` : `an earlier ${name}`;
282
+ const n = status.found.length;
283
+ const shown = status.found.slice(0, 3).map((f) => `${f.from} → ${f.to}`).join(', ');
284
+ const what = n ? `: ${n} renamed name${n === 1 ? '' : 's'} (${shown}${n > 3 ? ', …' : ''})` : ', a new major version';
285
+ const how = status.skills.length
286
+ ? `Migrate with the ${status.skills.join(' or ')} skill, or decklight design-system migrate ${ref} ${deck}`
287
+ : `Migrate with decklight design-system migrate ${ref} ${deck}`;
288
+ return `written for ${was}, this machine serves ${status.current}${what}. ${how}`;
289
+ }
290
+
49
291
  /** The design systems a deck references, parsed; anything else dropped, not guessed at. */
50
292
  export function designSystemRefs(html) {
51
293
  const list = configBlock(html)?.config?.[DESIGN_SYSTEMS_KEY];
@@ -187,14 +429,19 @@ export function brandTags(name, verdict) {
187
429
  * Nothing when the page already carries `<style data-design-system="<name>">`
188
430
  * (a bundle's own copy). An unresolvable reference, or a package that no
189
431
  * longer passes the check, becomes `<meta name="decklight-design-system-missing">`
190
- * naming it and why — never a silently short page.
432
+ * naming it and why — never a silently short page. A deck behind a
433
+ * package's major gets `<meta name="decklight-design-system-behind"
434
+ * data-ref data-version>`, its sentence the content; `dir` is the deck's
435
+ * folder, so the stylesheets it links are read as `check` reads them, and
436
+ * `deck` its file name, for the command the sentence ends on.
191
437
  */
192
- export function linkDesignSystems(html, home = configHome(), { log = null } = {}) {
438
+ export function linkDesignSystems(html, home = configHome(), { log = null, dir = null, deck = '<deck.html>' } = {}) {
193
439
  if (!isDeck(html)) return html;
194
440
  const refs = designSystemRefs(html);
195
441
  if (!refs.length) return html;
196
442
  const sources = markedSources(html);
197
443
  const tags = [];
444
+ let texts = null;
198
445
  for (const ref of refs) {
199
446
  // a bundle's own copy (<style>), or a link this page already got
200
447
  const carried = new RegExp(`<(?:style|link)\\b[^>]*\\bdata-design-system\\s*=\\s*["']${ref.name}["']`, 'i');
@@ -208,6 +455,14 @@ export function linkDesignSystems(html, home = configHome(), { log = null } = {}
208
455
  tags.push(`<script type="application/json" data-design-system-meta="${name}">${scriptJson(designSystemMeta(verdict))}</script>`);
209
456
  tags.push(`<template data-design-system-templates="${name}">\n${verdict.templatesHtml.trim()}\n</template>`);
210
457
  tags.push(...brandTags(ref.name, verdict));
458
+ // a deck behind the major this machine serves: said once, while authoring (SPEC DESIGN_SYSTEM_MIGRATIONS)
459
+ // — read as `check` reads it: the deck and the stylesheets it links from `dir`
460
+ texts ??= [html, ...(dir ? linkedStylesheets(html, dir).map((x) => x.text) : [])];
461
+ const status = migrationStatus(verdict.manifest, deckDesignSystemVersions(html)[ref.ref] ?? null, texts);
462
+ if (status.behind) {
463
+ tags.push(`<meta name="decklight-design-system-behind" data-ref="${escapeHtml(ref.ref)}" data-version="${escapeHtml(status.current)}"`
464
+ + ` content="${escapeHtml(`${verdict.manifest.title || ref.name}: ${behindMessage(ref.name, status, { ref: ref.ref, deck })}`)}">`);
465
+ }
211
466
  } else {
212
467
  tags.push(`<meta name="decklight-design-system-missing" content="${escapeHtml(`${ref.ref} — ${r.missing}`)}">`);
213
468
  log?.(`design system ${ref.ref}: ${r.missing}`);
@@ -347,7 +602,7 @@ export function designSystemAsset(rel, home = configHome()) {
347
602
  * and goes only with the last reference of EITHER kind. Returns `{ html,
348
603
  * changed }`, or throws a MarketplaceError a command prints as-is.
349
604
  */
350
- export function setDesignSystem(html, ref, on, { source = null } = {}) {
605
+ export function setDesignSystem(html, ref, on, { source = null, version = null } = {}) {
351
606
  const parsed = parseRef(ref);
352
607
  if (!parsed) throw new MarketplaceError(`"${ref}" is not a design-system reference — name@marketplace`);
353
608
  const block = configBlock(html);
@@ -374,7 +629,9 @@ export function setDesignSystem(html, ref, on, { source = null } = {}) {
374
629
  }
375
630
  let inner = withKey(block.inner, DESIGN_SYSTEMS_KEY, next.length ? next : null);
376
631
  inner = withKey(inner, SOURCES_KEY, Object.keys(sources).length ? sources : null);
377
- return { html: html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd), changed: true };
632
+ const out = html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
633
+ // the version it took goes in with the reference, and out with it (SPEC DESIGN_SYSTEM_MIGRATIONS)
634
+ return { html: on ? (version ? setDesignSystemVersion(out, parsed.ref, version) : out) : setDesignSystemVersion(out, parsed.ref, null), changed: true };
378
635
  }
379
636
 
380
637
  /**