@atelier-ui/create-workspace 0.3.15 → 0.4.1

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.
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * check-contracts.mjs — ADR-0121 Decision 4, stage 1 of "the stories are the spec".
3
+ * check-contracts — "the stories are the spec", stage 1.
4
4
  *
5
5
  * Offline, no Storybook build, no browser: joins three DERIVED inputs with the
6
- * hand-written micro-contracts (`libs/spec/src/contracts/*.contract.ts`) and reports
7
- * drift. One process per framework, driven by the recipe proven in
8
- * `tasks/docgen-spike-2026-09-10.md`:
6
+ * hand-written micro-contracts (`<name>.contract.ts`, one per component) and
7
+ * reports drift. One docgen pass per framework:
9
8
  *
10
9
  * 1. Docgen per component — Angular/Vue via the Storybook framework worker
11
10
  * (`@storybook/{angular-vite,vue3}/internal/docgen-worker`, story file as the
12
- * entry point); React via `react-docgen`'s own `parse()` directly (the worker's
13
- * React export is the react-component-meta engine, inactive in this repo).
11
+ * entry point); React via `react-docgen`'s own `parse()` directly (the
12
+ * worker's React export is the react-component-meta engine, which is not
13
+ * the default docgen path).
14
14
  * 2. Story `args` per story via `storybook/internal/csf-tools`
15
15
  * (`loadCsf(...).parse()` + `createStoryArgsResolver`).
16
- * 3. The Figma snapshot, `tools/figma/snapshot.json`.
17
- * 4. The contracts, read statically with `tools/scripts/lib/ts-eval.js`.
16
+ * 3. The Figma snapshot (a JSON file, refreshed by `figma-snapshot-contracts`).
17
+ * 4. The contracts, read statically (no code is executed) with `ts-eval.cjs`.
18
18
  *
19
- * Rules, tags, and the CLI surface are documented in `libs/spec/src/contracts/README.md`
20
- * and this file's own comments above each check. Run via `npm run check:contracts`.
19
+ * Every setting comes from a CLI flag or `contracts.config.json` in the working
20
+ * directory — nothing is derived from where this package is installed. See the
21
+ * package README for every field. Exit codes: 0 = no errors (warnings allowed),
22
+ * 1 = errors found, 2 = the check could not run (bad or missing settings).
21
23
  *
22
- * [CONTRACT-IMPORT] (S5b): a component story file whose component has a contract
23
- * must import it — by the `@atelier-ui/spec/contracts/<name>.contract` alias here,
24
- * or by a relative path to the contracts directory in a scaffold — and set
25
- * `contract` in the meta's `parameters`; error where `docs-block.ts` ships beside
26
- * the contracts, warning otherwise — a textual check, the same heuristic
27
- * `check-story-descriptions.js` uses for `component: metadata.purpose`.
24
+ * [CONTRACT-IMPORT]: a component story file whose component has a contract
25
+ * must import it — by the configured `contractImportAlias`, or by a relative path
26
+ * to the contracts directory — and set `contract` in the meta's `parameters`;
27
+ * severity is `contractImportSeverity` — a textual check, the same convention-
28
+ * following heuristic as the other story-meta scans in this file.
28
29
  */
29
30
  'use strict';
30
31
 
31
32
  import fs from 'node:fs';
32
33
  import path from 'node:path';
33
- import { fileURLToPath } from 'node:url';
34
34
  import { createRequire } from 'node:module';
35
35
  import { loadCsf, createStoryArgsResolver } from 'storybook/internal/csf-tools';
36
36
  import {
@@ -43,53 +43,36 @@ import {
43
43
  normalizeReactDocgen,
44
44
  findExternalPackageDir,
45
45
  errorMessage,
46
- } from './lib/docgen.mjs';
47
-
48
- // ts-eval.js is always required relative to THIS script's own directory
49
- // (`lib/ts-eval.js` beside it, via createRequire(import.meta.url) — not the
50
- // cwd) so a copied pair (canonical script + lib/ts-eval.js) works unmodified
51
- // wherever it is dropped, including inside a scaffolded workspace.
46
+ } from '../src/docgen.mjs';
47
+ import { buildCodeSpec, INTERACTION_STATE_VALUES } from '../src/codespec.mjs';
48
+ import {
49
+ FRAMEWORKS,
50
+ die,
51
+ readConfigFile,
52
+ dirsFor,
53
+ readSharedPropsSetting,
54
+ CONFIG_FILE_NAME,
55
+ } from '../src/config.mjs';
56
+
57
+ // ts-eval.cjs ships in this package (`../src/ts-eval.cjs`) and is loaded by a
58
+ // path relative to THIS file, so it works from node_modules and from a vendored
59
+ // copy alike. It needs `typescript`, which resolves from the consumer's install.
52
60
  const require = createRequire(import.meta.url);
53
- const { parseExportedVars } = require('./lib/ts-eval.js');
54
-
55
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
56
- // ROOT is likewise derived from the script's own location, not the cwd — a
57
- // byte-identical copy at <scaffold>/tools/scripts/check-contracts.mjs
58
- // therefore defaults to the SCAFFOLD's own tree (its own libs/spec,
59
- // tools/figma/snapshot.json) with zero changes below, whenever CLI flags and
60
- // contracts.config.json don't override a given path.
61
- const ROOT = path.resolve(__dirname, '../..');
62
- // Framework docgen packages (react-docgen, the Storybook framework workers),
63
- // by contrast, are resolved from the CWD's node_modules — not this script's
64
- // own directory — so that running `node tools/scripts/check-contracts.mjs`
65
- // from inside a scaffold picks up the scaffold's own installed Storybook
66
- // packages rather than whatever happens to be findable by walking up from
67
- // this file (which, for a copied pair, is usually the same tree anyway, but
68
- // CWD is the explicit, unambiguous contract).
61
+ const { parseExportedVars } = require('../src/ts-eval.cjs');
62
+
63
+ // Every path below is relative to the working directory, never to this file.
64
+ // Framework docgen packages (react-docgen, the Storybook framework workers)
65
+ // resolve from the working directory's node_modules too, so the check always
66
+ // reads the workspace's own installed Storybook.
69
67
  const CWD = process.cwd();
70
68
  const cwdRequire = createRequire(path.join(CWD, 'package.json'));
71
69
  const { reactParseFile } = makeReactDocgenTools(cwdRequire);
72
- const FRAMEWORKS = ['angular', 'react', 'vue'];
73
-
74
- // Interaction values on a `state` axis (ADR-0114): CSS pseudo-classes, not code-modelled
75
- // state. Every OTHER value on a `state` axis (completed, optional, error, filled, open,
76
- // invalid, checked, filtered, selected, ...) is data-flavoured and must be covered by an
77
- // `axisMap` entry or a `figmaOnly` entry named `state=<value>`.
78
- const INTERACTION_STATE_VALUES = new Set([
79
- 'default',
80
- 'hover',
81
- 'focus',
82
- 'focus-visible',
83
- 'active',
84
- 'pressed',
85
- ]);
86
70
 
87
71
  const UNRESOLVABLE = Symbol('unresolvable');
88
72
 
89
73
  // Master-description mirror grammar for contract `codeOnly` entries. A `codeOnly` entry
90
74
  // `x` is mirrored only by a line "- Code-only `x`: <reason>" (non-empty reason) or by the
91
- // existing opt-out line "- Boolean `x`: not modelled — <reason>" that check-figma.js
92
- // parses (same shape). Substring mentions in prose prove nothing.
75
+ // existing opt-out line "- Boolean `x`: not modelled — <reason>" (same shape). Substring mentions in prose prove nothing.
93
76
  function hasCodeOnlyMirror(description, name) {
94
77
  const n = escapeRegExp(name);
95
78
  return new RegExp(
@@ -125,9 +108,7 @@ const TAG_LEVEL = {
125
108
  'STALE-MIRROR': 'warning',
126
109
  'NO-STORY-META': 'warning',
127
110
  ROSTER: 'error',
128
- // 'CONTRACT-IMPORT' is set below, once CONTRACTS_DIR is resolved — its
129
- // severity (error vs. warning) depends on whether this tree ships
130
- // `docs-block.ts` beside its contracts (see the assignment near CONTRACTS_DIR).
111
+ // 'CONTRACT-IMPORT' is set below, from the `contractImportSeverity` setting.
131
112
  };
132
113
 
133
114
  // ─── CLI args ───────────────────────────────────────────────────────────────
@@ -155,44 +136,65 @@ function parseArgs(argv) {
155
136
 
156
137
  const args = parseArgs(process.argv.slice(2));
157
138
 
158
- // ─── Resolution layer (portable across the monorepo and a scaffolded
159
- // single-framework workspace) ────────────────────────────────────────────
160
- // Precedence per field: CLI flag > `contracts.config.json` at the cwd root >
161
- // monorepo default. Nothing below changes what a plain
162
- // `node tools/scripts/check-contracts.mjs` run from the repo root does — no
163
- // flags, no contracts.config.json at the repo root, so every field falls
164
- // through to the same defaults this script always used.
165
- const CONFIG_PATH = path.join(CWD, 'contracts.config.json');
166
- let fileConfig = null;
167
- if (fs.existsSync(CONFIG_PATH)) {
168
- try {
169
- fileConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
170
- } catch (e) {
171
- console.error(`${CONFIG_PATH}: invalid JSON (${e.message})`);
172
- process.exit(2);
139
+ // ─── Settings ───────────────────────────────────────────────────────────────
140
+ // Precedence per field: CLI flag > `contracts.config.json` in the working
141
+ // directory. There are no built-in defaults for locations: a missing required
142
+ // setting is a usage error (exit 2).
143
+ const fileConfig = readConfigFile(CWD);
144
+
145
+ const requestedFw = args.fw
146
+ ? [args.fw]
147
+ : fileConfig?.framework
148
+ ? [fileConfig.framework]
149
+ : Array.isArray(fileConfig?.frameworks)
150
+ ? fileConfig.frameworks
151
+ : null;
152
+ if (!requestedFw || requestedFw.length === 0) {
153
+ die(
154
+ `No framework set — pass --fw <${FRAMEWORKS.join('|')}> or set "framework" ` +
155
+ `(or "frameworks": [...]) in ${CONFIG_FILE_NAME}.`,
156
+ );
157
+ }
158
+ const targetFrameworks = requestedFw;
159
+ for (const fw of targetFrameworks) {
160
+ if (!FRAMEWORKS.includes(fw)) {
161
+ die(`Unknown framework '${fw}' — expected one of ${FRAMEWORKS.join(', ')}`);
173
162
  }
174
163
  }
175
164
 
176
- const requestedFw = args.fw || fileConfig?.framework || null;
177
- const targetFrameworks = requestedFw ? [requestedFw] : FRAMEWORKS;
165
+ // `--stories` (repeatable, applies to every requested framework) or config
166
+ // `stories`: either one list of roots for every framework (`["src"]`) or a map
167
+ // per framework (`{ "angular": ["packages/a/src"] }`). Each root is walked
168
+ // recursively for `**/*.stories.{ts,tsx}` (node_modules excluded).
169
+ const STORIES_SETTING = args.stories.length
170
+ ? args.stories
171
+ : fileConfig?.stories;
172
+ const STORIES_DIRS_BY_FW = new Map();
178
173
  for (const fw of targetFrameworks) {
179
- if (!FRAMEWORKS.includes(fw)) {
180
- console.error(
181
- `Unknown framework '${fw}' — expected one of ${FRAMEWORKS.join(', ')}`,
174
+ const dirs = dirsFor(STORIES_SETTING, fw, CWD);
175
+ if (!dirs) {
176
+ die(
177
+ `No story roots for '${fw}' — pass --stories <dir> or set "stories" ` +
178
+ `(a list, or a map per framework) in ${CONFIG_FILE_NAME}.`,
182
179
  );
183
- process.exit(2);
184
180
  }
181
+ STORIES_DIRS_BY_FW.set(fw, dirs);
185
182
  }
186
183
 
187
- // `--stories` (repeatable) or config `stories: [...]` — one or more roots
188
- // walked recursively for `**/*.stories.{ts,tsx}` (node_modules excluded).
189
- // `null` means "no override": findStoryFiles() falls back to its historic
190
- // per-framework `libs/<fw>/src/lib` walk.
191
- const STORIES_DIRS = args.stories.length
192
- ? args.stories.map((d) => path.resolve(CWD, d))
193
- : Array.isArray(fileConfig?.stories) && fileConfig.stories.length
194
- ? fileConfig.stories.map((d) => path.resolve(CWD, d))
195
- : null;
184
+ // Optional: directories searched (besides a story's own directory) for a CHILD
185
+ // component's source when an `axisMap` names `Child.prop` — a list or a map per
186
+ // framework, like `stories`.
187
+ const COMPONENT_DIRS_SETTING = fileConfig?.componentDirs;
188
+ // Optional: a directory of per-component stylesheets kept apart from the
189
+ // components, looked up as `<styleDirs>/<component directory name>` (--emit only).
190
+ const STYLE_DIR = fileConfig?.styleDir
191
+ ? path.resolve(CWD, fileConfig.styleDir)
192
+ : null;
193
+ // Optional: CSS custom-property prefix scanned for design tokens (--emit only).
194
+ const TOKEN_PREFIX = fileConfig?.tokenPrefix ?? '--';
195
+ // Optional: `{ file, name }` — a base interface whose string props the React
196
+ // destructuring fallback may recover (see normalizeReactDocgen in docgen.mjs).
197
+ const SHARED_PROPS = readSharedPropsSetting(fileConfig, CWD);
196
198
 
197
199
  // ─── Findings ───────────────────────────────────────────────────────────────
198
200
 
@@ -206,7 +208,7 @@ function report(tag, fw, msg) {
206
208
  // ─── codeOnly cross-framework staleness tracking (R1d) ─────────────────────
207
209
  // `codeOnly` staleness can only be judged once every requested framework has run:
208
210
  // a prop absent from one framework's manifest but present in another is
209
- // [FW-ONLY] (ADR-0093 territory), not a stale exemption. Populated per-framework
211
+ // [FW-ONLY] (a cross-framework API divergence), not a stale exemption. Populated per-framework
210
212
  // inside processComponent, evaluated once in runCodeOnlyStalenessChecks() after
211
213
  // the whole `targetFrameworks` loop completes.
212
214
  const reachedByFw = new Map(); // selector -> Set<fw> the component's docgen was reached in
@@ -214,11 +216,18 @@ const codeOnlyPresentByFw = new Map(); // selector -> Map<entryName, Set<fw>> wh
214
216
 
215
217
  // ─── Snapshot ───────────────────────────────────────────────────────────────
216
218
 
217
- const snapshotPath = args.snapshot
218
- ? path.resolve(CWD, args.snapshot)
219
- : fileConfig?.snapshot
220
- ? path.resolve(CWD, fileConfig.snapshot)
221
- : path.join(ROOT, 'tools/figma/snapshot.json');
219
+ const snapshotSetting = args.snapshot ?? fileConfig?.snapshot;
220
+ if (!snapshotSetting) {
221
+ die(
222
+ `No Figma snapshot set — pass --snapshot <file> or set "snapshot" in ${CONFIG_FILE_NAME}.`,
223
+ );
224
+ }
225
+ const snapshotPath = path.resolve(CWD, snapshotSetting);
226
+ if (!fs.existsSync(snapshotPath)) {
227
+ die(
228
+ `Figma snapshot not found: ${snapshotPath} — refresh it with figma-snapshot-contracts.`,
229
+ );
230
+ }
222
231
  const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf-8'));
223
232
  const snapshotBySelector = new Map(
224
233
  snapshot.components.map((c) => [c.selector, c]),
@@ -231,36 +240,35 @@ function stripId(name) {
231
240
 
232
241
  // ─── Contracts ──────────────────────────────────────────────────────────────
233
242
 
234
- const CONTRACTS_DIR = args.contracts
235
- ? path.resolve(CWD, args.contracts)
236
- : fileConfig?.contracts
237
- ? path.resolve(CWD, fileConfig.contracts)
238
- : path.join(ROOT, 'libs/spec/src/contracts');
239
-
240
- // Whether CONTRACTS_DIR is this repo's own monorepo contracts directory — the
241
- // only place the `@atelier-ui/spec/contracts/<base>` path alias actually
242
- // resolves (a scaffold neither ships nor depends on a `@atelier-ui/spec`
243
- // package). Named once here so `hasContractImport` (accepting the alias) and
244
- // `suggestedContractSpecifier` (suggesting it) read the same test rather than
245
- // each re-deriving it and risking drift.
246
- const CONTRACTS_DIR_IS_MONOREPO =
247
- CONTRACTS_DIR === path.join(ROOT, 'libs/spec/src/contracts');
248
-
249
- // [CONTRACT-IMPORT] exists because `libs/spec/src/contracts/docs-block.ts`'s
250
- // `ContractBlock` reads `parameters.contract` off the story meta and renders
251
- // it — an unwired story is a real gap in THIS repo (error) because that block
252
- // ships here. A fresh `create-atelier-ui-workspace` scaffold doesn't ship
253
- // `docs-block.ts` yet (S5b's "block that displays it" is monorepo-only so
254
- // far), so the identical finding has nothing to render into there — downgrade
255
- // to a warning rather than fail a scaffold's `check:contracts` over wiring
256
- // with no visible effect yet. Set once here (CONTRACTS_DIR is resolved by
257
- // this point) rather than in the TAG_LEVEL literal above.
258
- const CONTRACT_IMPORT_HAS_DOCS_BLOCK = fs.existsSync(
259
- path.join(CONTRACTS_DIR, 'docs-block.ts'),
260
- );
261
- TAG_LEVEL['CONTRACT-IMPORT'] = CONTRACT_IMPORT_HAS_DOCS_BLOCK
262
- ? 'error'
263
- : 'warning';
243
+ const contractsSetting = args.contracts ?? fileConfig?.contracts;
244
+ if (!contractsSetting) {
245
+ die(
246
+ `No contracts directory set — pass --contracts <dir> or set "contracts" in ${CONFIG_FILE_NAME}.`,
247
+ );
248
+ }
249
+ const CONTRACTS_DIR = path.resolve(CWD, contractsSetting);
250
+ if (!fs.existsSync(CONTRACTS_DIR)) {
251
+ die(`Contracts directory not found: ${CONTRACTS_DIR}`);
252
+ }
253
+
254
+ // Optional: a module-path prefix (e.g. a tsconfig path alias such as
255
+ // `@scope/spec/contracts`) under which a story may import a contract as
256
+ // `<alias>/<name>.contract`. Accepted by [CONTRACT-IMPORT] and used in its
257
+ // suggestion; without it only a relative import of the contract file is accepted.
258
+ const CONTRACT_IMPORT_ALIAS = fileConfig?.contractImportAlias
259
+ ? String(fileConfig.contractImportAlias).replace(/\/+$/, '')
260
+ : null;
261
+
262
+ // [CONTRACT-IMPORT]: an unwired story is a gap only where something renders the
263
+ // wiring (a docs block that reads `parameters.contract`), so the severity is a
264
+ // setting: "error" or "warning" (the default).
265
+ const importSeverity = fileConfig?.contractImportSeverity ?? 'warning';
266
+ if (importSeverity !== 'error' && importSeverity !== 'warning') {
267
+ die(
268
+ `${CONFIG_FILE_NAME}: "contractImportSeverity" must be "error" or "warning", got ${JSON.stringify(importSeverity)}`,
269
+ );
270
+ }
271
+ TAG_LEVEL['CONTRACT-IMPORT'] = importSeverity;
264
272
 
265
273
  const contractFiles = fs
266
274
  .readdirSync(CONTRACTS_DIR)
@@ -412,18 +420,16 @@ function runGlobalChecks() {
412
420
  }
413
421
 
414
422
  // ─── Per-framework docgen ───────────────────────────────────────────────────
415
- // collectStoryFilesUnder / findStoryFiles / toRepoImportPath now live in
416
- // ./lib/docgen.mjs (ADR-0121 §5 / S6(a)), shared with check-manifest-parity.mjs.
417
- // findStoryFiles(fw) here is always findStoryFiles(fw, { root: ROOT, storiesDirs: STORIES_DIRS }).
418
-
419
- // ─── CONTRACT-IMPORT (S5b) ──────────────────────────────────────────────────
420
- // The Storybook docs page's `ContractBlock` (`libs/spec/src/contracts/docs-
421
- // block.ts`) reads `parameters.contract` off the current story meta — it has
422
- // nothing to render unless the story file imports the component's contract
423
- // and wires it in. Textual, not AST: the same convention-following heuristic
424
- // `check-story-descriptions.js` uses for `component: metadata.purpose`. Every
425
- // story file in this repo follows one shape (`const meta ... export default
426
- // meta;`), so a lexical scan for that shape is enough.
423
+ // collectStoryFilesUnder / findStoryFiles / toRepoImportPath live in
424
+ // ../src/docgen.mjs, shared with any script that reads the same docgen payloads.
425
+
426
+ // ─── CONTRACT-IMPORT ────────────────────────────────────────────────────────
427
+ // A Storybook docs block that displays the contract reads `parameters.contract`
428
+ // off the current story meta — it has nothing to render unless the story file
429
+ // imports the component's contract and wires it in. Textual, not AST: a
430
+ // convention-following heuristic. Story files are expected to follow one shape
431
+ // (`const meta ... export default meta;`), so a lexical scan for that shape is
432
+ // enough.
427
433
 
428
434
  /** The `const meta = {...}; export default meta;` slice, or `null` if the file
429
435
  * doesn't follow that convention (treated as "not wired" below, not a crash). */
@@ -463,26 +469,23 @@ function findImportSpecifiers(source) {
463
469
 
464
470
  /**
465
471
  * Whether `contract` is imported by any specifier in `source`, accepting
466
- * EITHER of two forms: the monorepo's `@atelier-ui/spec/contracts/<base>`
467
- * path alias — only accepted when `CONTRACTS_DIR_IS_MONOREPO`, since that
468
- * alias only ever resolves inside this repo; a scaffold neither ships nor
469
- * depends on a `@atelier-ui/spec` package, so the identical string in a
470
- * scaffold's story would be a specifier that can never resolve there, not a
471
- * valid wiring — or a RELATIVE specifier that, resolved from `storyFile`'s own
472
- * directory (a trailing `.js` stripped first — a NodeNext-style
473
- * `./contracts/button.contract.js` import resolves to the `.ts` source file
474
- * under bundler/NodeNext resolution — then `.ts` appended when the resolved
475
- * path doesn't already end in it), lands on the exact file `CONTRACTS_DIR`
476
- * holds this contract at. The relative form is what a scaffold's own contract
477
- * import looks like — `CONTRACTS_DIR` there is `<app>/src/contracts`, not a
478
- * workspace alias.
472
+ * EITHER of two forms: the configured `contractImportAlias`
473
+ * (`<alias>/<name>.contract`, only when one is set — a path alias is
474
+ * meaningless without it), or a RELATIVE specifier that, resolved from
475
+ * `storyFile`'s own directory (a trailing `.js` stripped first — a
476
+ * NodeNext-style `./contracts/button.contract.js` import resolves to the `.ts`
477
+ * source file under bundler/NodeNext resolution — then `.ts` appended when the
478
+ * resolved path doesn't already end in it), lands on the exact file
479
+ * `CONTRACTS_DIR` holds this contract at.
479
480
  */
480
481
  function hasContractImport(storyFile, source, contract) {
481
482
  const expectedBase = contract.__file.replace(/\.ts$/, '');
482
- const aliasSpecifier = `@atelier-ui/spec/contracts/${expectedBase}`;
483
+ const aliasSpecifier = CONTRACT_IMPORT_ALIAS
484
+ ? `${CONTRACT_IMPORT_ALIAS}/${expectedBase}`
485
+ : null;
483
486
  const targetFile = path.join(CONTRACTS_DIR, contract.__file);
484
487
  return findImportSpecifiers(source).some((spec) => {
485
- if (CONTRACTS_DIR_IS_MONOREPO && spec === aliasSpecifier) return true;
488
+ if (aliasSpecifier && spec === aliasSpecifier) return true;
486
489
  if (!spec.startsWith('.')) return false;
487
490
  let resolved = path.resolve(path.dirname(storyFile), spec);
488
491
  if (resolved.endsWith('.js')) resolved = resolved.slice(0, -3);
@@ -492,17 +495,17 @@ function hasContractImport(storyFile, source, contract) {
492
495
  }
493
496
 
494
497
  /**
495
- * The specifier suggested in the [CONTRACT-IMPORT] message: the monorepo's
496
- * path alias when `CONTRACTS_DIR_IS_MONOREPO` (the only place that alias
497
- * resolves), otherwise a relative path from `storyFile`'s directory to the
498
- * contract file — extensionless, forward slashes, `./`-prefixed unless it
499
- * already climbs upward with `../` — i.e. exactly the form `hasContractImport`
500
- * above accepts, so following the suggestion always clears the finding.
498
+ * The specifier suggested in the [CONTRACT-IMPORT] message: the configured
499
+ * alias when there is one, otherwise a relative path from `storyFile`'s
500
+ * directory to the contract file — extensionless, forward slashes,
501
+ * `./`-prefixed unless it already climbs upward with `../` — i.e. exactly the
502
+ * form `hasContractImport` above accepts, so following the suggestion always
503
+ * clears the finding.
501
504
  */
502
505
  function suggestedContractSpecifier(storyFile, contract) {
503
506
  const expectedBase = contract.__file.replace(/\.ts$/, '');
504
- if (CONTRACTS_DIR_IS_MONOREPO) {
505
- return `@atelier-ui/spec/contracts/${expectedBase}`;
507
+ if (CONTRACT_IMPORT_ALIAS) {
508
+ return `${CONTRACT_IMPORT_ALIAS}/${expectedBase}`;
506
509
  }
507
510
  const rel = path
508
511
  .relative(path.dirname(storyFile), path.join(CONTRACTS_DIR, expectedBase))
@@ -513,10 +516,8 @@ function suggestedContractSpecifier(storyFile, contract) {
513
516
 
514
517
  /** Reports [CONTRACT-IMPORT] when `name`'s contract exists but `storyFile`
515
518
  * neither imports it (see `hasContractImport`) nor sets `contract` in the
516
- * meta's `parameters`. No-op when `name` has no contract. Severity is decided
517
- * once, near `CONTRACTS_DIR` (`TAG_LEVEL['CONTRACT-IMPORT']`): error in this
518
- * repo (docs-block.ts renders the wiring), warning in a scaffold that doesn't
519
- * ship that block yet. */
519
+ * meta's `parameters`. No-op when `name` has no contract. Severity is the
520
+ * `contractImportSeverity` setting (`TAG_LEVEL['CONTRACT-IMPORT']`). */
520
521
  function checkContractImport(fw, storyFile, source, name, contract) {
521
522
  if (!contract) return;
522
523
  const hasImport = hasContractImport(storyFile, source, contract);
@@ -529,13 +530,14 @@ function checkContractImport(fw, storyFile, source, name, contract) {
529
530
 
530
531
  if (!hasImport || !hasContractParam) {
531
532
  const suggestion = suggestedContractSpecifier(storyFile, contract);
532
- const suffix = CONTRACT_IMPORT_HAS_DOCS_BLOCK
533
- ? ''
534
- : ' (warning here: no docs-block.ts beside the contracts, so nothing renders the wiring yet)';
533
+ const suffix =
534
+ importSeverity === 'error'
535
+ ? ''
536
+ : ' (a warning here: set "contractImportSeverity": "error" in contracts.config.json to enforce it)';
535
537
  report(
536
538
  'CONTRACT-IMPORT',
537
539
  fw,
538
- `${path.relative(ROOT, storyFile)}: ${name} has a contract but its story meta ` +
540
+ `${path.relative(CWD, storyFile)}: ${name} has a contract but its story meta ` +
539
541
  `does not wire it in — add "import { contract } from '${suggestion}';" ` +
540
542
  `and set 'contract' in the meta's parameters.${suffix}`,
541
543
  );
@@ -543,11 +545,10 @@ function checkContractImport(fw, storyFile, source, name, contract) {
543
545
  }
544
546
 
545
547
  // --- Angular/Vue worker docgen, React's react-docgen parse(), and both
546
- // frameworks' normalizers now live in ./lib/docgen.mjs (ADR-0121 §5 / S6(a)) —
547
- // makeWorkerDocgen(fw, cwdRequire, ROOT), normalizeAngular, normalizeVue,
548
+ // frameworks' normalizers live in ../src/docgen.mjs —
549
+ // makeWorkerDocgen(fw, cwdRequire, root), normalizeAngular, normalizeVue,
548
550
  // makeReactDocgenTools(cwdRequire).reactParseFile, normalizeReactDocgen —
549
- // shared with check-manifest-parity.mjs so the two scripts read one framework
550
- // payload the same way.
551
+ // shared so every script reads one framework payload the same way.
551
552
 
552
553
  // ─── Dotted child-prop resolution (R2) ──────────────────────────────────────
553
554
  // `axisMap[].codeProp` may be `Child.prop`: the prop lives on a CHILD component's own
@@ -556,7 +557,7 @@ function checkContractImport(fw, storyFile, source, name, contract) {
556
557
  // sibling is registered. Angular/Vue's worker only ever returns the ONE component
557
558
  // `meta.component` names, so the child's props are recovered with a lightweight
558
559
  // source-level scan (the same "read the component source with a regex" idiom
559
- // check-defaults.js already uses for cross-framework default extraction) rather than a
560
+ // other scans in this file use) rather than a
560
561
  // second full docgen pass, which the worker's story-file-only entry point does not
561
562
  // support for an arbitrary export.
562
563
 
@@ -616,7 +617,10 @@ function classifyTypeText(typeText, literalArg) {
616
617
  * mapping, not to run AXIS/COVERAGE against the child itself (deferred to stage 2, see
617
618
  * [NO-STORY-META]). */
618
619
  function regexResolveChildProp(fw, childName, propName, contextDir) {
619
- const searchDirs = [contextDir, path.join(ROOT, 'libs', fw, 'src/lib')];
620
+ const searchDirs = [
621
+ contextDir,
622
+ ...(dirsFor(COMPONENT_DIRS_SETTING, fw, CWD) || []),
623
+ ];
620
624
  for (const dir of searchDirs) {
621
625
  for (const file of walkSourceFiles(dir)) {
622
626
  const src = fs.readFileSync(file, 'utf-8');
@@ -649,7 +653,7 @@ function regexResolveChildProp(fw, childName, propName, contextDir) {
649
653
  } else if (fw === 'react') {
650
654
  // react-docgen's FindExportedDefinitionsResolver only recognises functions whose
651
655
  // body looks like a component (JSX, forwardRef, class); a pass-through function
652
- // (e.g. `function AtlStep({ children }) { return children; }`) is invisible to
656
+ // (e.g. `function Step({ children }) { return children; }`) is invisible to
653
657
  // it, so the sibling registry above can be empty even though the export is real.
654
658
  // Fall back to the same interface-literal regex idiom as Angular/Vue.
655
659
  if (
@@ -845,7 +849,7 @@ function scanLiteralAttrs(text, fw, into) {
845
849
  }
846
850
 
847
851
  /** `(['a', 'b'] as const).map(x => <Foo prop={x} />)` — same "read the source with a
848
- * regex" idiom `check-defaults.js` uses for cross-framework default extraction. Does
852
+ * regex" idiom used for the other source scans in this file. Does
849
853
  * not evaluate the loop; only credits the array's literal members when the loop
850
854
  * variable is then forwarded verbatim into some prop in the same text. */
851
855
  function scanArrayMapCredit(text, fw, into) {
@@ -880,7 +884,7 @@ function scanArrayMapCredit(text, fw, into) {
880
884
  }
881
885
 
882
886
  /** `prop: 'value'` / `prop: "value"` object-literal idiom (R1b): the imperative
883
- * call-site shape (Angular `AtlToast`: `toastService.show(msg, { variant: 'success' })`)
887
+ * call-site shape (Angular `Toast`: `toastService.show(msg, { variant: 'success' })`)
884
888
  * and any general config-object case (`{ variant: 'success', duration: 2000 }`). Same
885
889
  * scope as `scanLiteralAttrs` — the story's own node range, plus the meta's `render`
886
890
  * when the story has none. */
@@ -976,9 +980,11 @@ function collectStoryClaims(csf, fw, componentName, source) {
976
980
 
977
981
  function scanCssTokens(dir, fw) {
978
982
  const tokens = new Set();
979
- // The component's own directory plus the shared, class-rooted `libs/styles`
980
- // sheet — a component whose CSS moved there has none left in its own directory.
981
- const dirs = [dir, path.join(ROOT, 'libs/styles/src', path.basename(dir))];
983
+ // The component's own directory plus, when configured, the shared stylesheet
984
+ // directory (`styleDir/<component directory name>`) — a component whose CSS
985
+ // lives there has none left in its own directory.
986
+ const dirs = [dir];
987
+ if (STYLE_DIR) dirs.push(path.join(STYLE_DIR, path.basename(dir)));
982
988
  for (const d of dirs) {
983
989
  let files = [];
984
990
  try {
@@ -996,7 +1002,10 @@ function scanCssTokens(dir, fw) {
996
1002
  }
997
1003
  for (const f of files) {
998
1004
  const src = fs.readFileSync(path.join(d, f), 'utf-8');
999
- const re = /var\(\s*(--ui-[\w-]+)/g;
1005
+ const re = new RegExp(
1006
+ `var\\(\\s*(${escapeRegExp(TOKEN_PREFIX)}[\\w-]+)`,
1007
+ 'g',
1008
+ );
1000
1009
  let m;
1001
1010
  while ((m = re.exec(src))) tokens.add(m[1]);
1002
1011
  }
@@ -1119,6 +1128,24 @@ function processComponent(
1119
1128
  }
1120
1129
  } else {
1121
1130
  for (const v of valuesToCheck) covered.add(v);
1131
+ // Without `values`, a boolean prop's Figma axis must already be
1132
+ // exactly the strings 'true' and 'false' (any order, case-sensitive):
1133
+ // anything else (ja/nein, an/aus, a single value) leaves open which
1134
+ // Figma value means true, so the author has to say it.
1135
+ if (
1136
+ resolved.kind === 'boolean' &&
1137
+ !(
1138
+ axisValues.length === 2 &&
1139
+ axisValues.includes('true') &&
1140
+ axisValues.includes('false')
1141
+ )
1142
+ ) {
1143
+ report(
1144
+ 'AXIS',
1145
+ fw,
1146
+ `${name}: axisMap ${axisName} -> ${entry.codeProp} is a boolean prop but the Figma axis has values ${axisValues.join(', ')}; add \`values\` mapping each Figma value to true/false`,
1147
+ );
1148
+ }
1122
1149
  if (resolved.kind === 'enum' && resolved.members) {
1123
1150
  const propSet = new Set(resolved.members);
1124
1151
  const axisSet = new Set(axisValues);
@@ -1243,7 +1270,7 @@ function processComponent(
1243
1270
  report(
1244
1271
  'NO-MASTER',
1245
1272
  fw,
1246
- `${name}: docgen payload exists but no snapshot master in tools/figma/snapshot.json — nothing to compare against Figma; ENUM-UNDRAWN and coverage skipped`,
1273
+ `${name}: docgen payload exists but no snapshot master in ${path.relative(CWD, snapshotPath)} — nothing to compare against Figma; ENUM-UNDRAWN and coverage skipped`,
1247
1274
  );
1248
1275
  } else {
1249
1276
  const axisNames = new Set(Object.keys(master.variantAxes || {}));
@@ -1354,12 +1381,9 @@ function processComponent(
1354
1381
 
1355
1382
  async function runFramework(fw) {
1356
1383
  const t0 = performance.now();
1357
- const storyFiles = findStoryFiles(fw, {
1358
- root: ROOT,
1359
- storiesDirs: STORIES_DIRS,
1360
- });
1384
+ const storyFiles = findStoryFiles(STORIES_DIRS_BY_FW.get(fw));
1361
1385
  const workerDocgen =
1362
- fw !== 'react' ? await makeWorkerDocgen(fw, cwdRequire, ROOT) : null;
1386
+ fw !== 'react' ? await makeWorkerDocgen(fw, cwdRequire, CWD) : null;
1363
1387
 
1364
1388
  const byComponent = new Map(); // name -> { docgenResult, contextDir, files: [csf...] }
1365
1389
  const reachedMeta = new Set();
@@ -1388,7 +1412,7 @@ async function runFramework(fw) {
1388
1412
  }).parse();
1389
1413
  } catch (e) {
1390
1414
  console.error(
1391
- ` ! ${path.relative(ROOT, storyFile)}: csf-tools failed to parse (${e.message})`,
1415
+ ` ! ${path.relative(CWD, storyFile)}: csf-tools failed to parse (${e.message})`,
1392
1416
  );
1393
1417
  continue;
1394
1418
  }
@@ -1399,9 +1423,9 @@ async function runFramework(fw) {
1399
1423
  continue;
1400
1424
  }
1401
1425
 
1402
- // A component imported from an installed PACKAGE (a real scaffold's
1403
- // `@atelier-ui/<fw>`, not this monorepo's tsconfig path alias of the same
1404
- // name — that alias has no `node_modules` entry and so never matches
1426
+ // A component imported from an installed PACKAGE (a workspace consuming a
1427
+ // component library from the registry, not a tsconfig path alias of the
1428
+ // same name — that alias has no `node_modules` entry and so never matches
1405
1429
  // here) gets skipped before any docgen call, uniformly across all three
1406
1430
  // frameworks. Left to each engine's own accident, the three frameworks
1407
1431
  // disagree on what "can't read into node_modules" means: React's relative-
@@ -1412,7 +1436,7 @@ async function runFramework(fw) {
1412
1436
  // this script would otherwise mistake for a workspace component with no
1413
1437
  // props and fail on ([DOCGEN-EMPTY], [AXIS], [BOOLEAN], ...). Skipping the
1414
1438
  // call here — rather than filtering its result afterwards — is what makes
1415
- // the scaffold's promise ("local docgen cannot read into node_modules, so
1439
+ // the promise ("local docgen cannot read into node_modules, so
1416
1440
  // the check has nothing to compare and reports only [NO-STORY-META]")
1417
1441
  // actually true for Angular too, by construction, instead of by luck.
1418
1442
  if (findExternalPackageDir(storyFile, csf._rawComponentPath)) {
@@ -1436,14 +1460,18 @@ async function runFramework(fw) {
1436
1460
  try {
1437
1461
  const docgens = reactParseFile(componentFile);
1438
1462
  for (const d of docgens)
1439
- registerSibling(fw, d.displayName, normalizeReactDocgen(d));
1463
+ registerSibling(
1464
+ fw,
1465
+ d.displayName,
1466
+ normalizeReactDocgen(d, SHARED_PROPS),
1467
+ );
1440
1468
  const match =
1441
1469
  docgens.find((d) => d.displayName === localName) ||
1442
1470
  docgens.find((d) => d.displayName === metaComponent);
1443
1471
  if (match) {
1444
1472
  docgenResult = {
1445
1473
  name: match.displayName,
1446
- props: normalizeReactDocgen(match),
1474
+ props: normalizeReactDocgen(match, SHARED_PROPS),
1447
1475
  description: match.description,
1448
1476
  slots: undefined,
1449
1477
  };
@@ -1454,7 +1482,7 @@ async function runFramework(fw) {
1454
1482
  report(
1455
1483
  'DOCGEN-FAILED',
1456
1484
  fw,
1457
- `${path.relative(ROOT, storyFile)}: react-docgen failed — ${errorMessage(e)}`,
1485
+ `${path.relative(CWD, storyFile)}: react-docgen failed — ${errorMessage(e)}`,
1458
1486
  );
1459
1487
  }
1460
1488
  }
@@ -1478,7 +1506,7 @@ async function runFramework(fw) {
1478
1506
  report(
1479
1507
  'DOCGEN-FAILED',
1480
1508
  fw,
1481
- `${path.relative(ROOT, storyFile)}: ${fw} docgen failed — ${result.reason}`,
1509
+ `${path.relative(CWD, storyFile)}: ${fw} docgen failed — ${result.reason}`,
1482
1510
  );
1483
1511
  }
1484
1512
  }
@@ -1489,8 +1517,8 @@ async function runFramework(fw) {
1489
1517
  // OUT of noComponentCount on purpose: this story file DID have a
1490
1518
  // resolvable meta.component, so it is still "measurable" for the
1491
1519
  // [ROSTER] check below. Folding it into noComponentCount is exactly
1492
- // the ADR-0124 bug — it let a broken docgen worker shrink the roster
1493
- // instead of showing up as a hole in it.
1520
+ // the bug where a broken docgen worker shrank the roster instead of
1521
+ // showing up as a hole in it.
1494
1522
  if (!docgenFailed) noComponentCount++;
1495
1523
  continue;
1496
1524
  }
@@ -1515,9 +1543,9 @@ async function runFramework(fw) {
1515
1543
  // component — everything except a story with no meta.component at all
1516
1544
  // (noComponentCount) and a deliberately-skipped external-package import
1517
1545
  // (externalCount, see the comment above the findExternalPackageDir() call).
1518
- // Subtracting externalCount before the floor is what keeps a scaffolded
1519
- // one-framework workspace — whose only story imports from
1520
- // `@atelier-ui/<fw>` — at measurable === 0 and therefore silent here,
1546
+ // Subtracting externalCount before the floor is what keeps a
1547
+ // workspace whose only story imports from an installed component package
1548
+ // — at measurable === 0 and therefore silent here,
1521
1549
  // exactly as that comment promises ("the check has nothing to compare and
1522
1550
  // reports only [NO-STORY-META]"). If there WAS something measurable and
1523
1551
  // byComponent still ended up empty, docgen measured nothing this run.
@@ -1554,28 +1582,13 @@ async function runFramework(fw) {
1554
1582
  }
1555
1583
 
1556
1584
  if (args.emit) {
1557
- const props = entry.docgenResult.props.filter((p) => !p.isOutput);
1558
- const events = entry.docgenResult.props.filter((p) => p.isOutput);
1559
- const codeSpec = {
1560
- componentAPI: {
1561
- props: props.map((p) => ({
1562
- name: p.name,
1563
- type: p.typeText || p.kind,
1564
- values: p.kind === 'enum' ? p.members : undefined,
1565
- defaultValue: p.default,
1566
- description: p.description,
1567
- required: p.required,
1568
- })),
1569
- events: events.map((e) => ({
1570
- name: e.name,
1571
- type: e.typeText,
1572
- description: e.description,
1573
- })),
1574
- slots: entry.docgenResult.slots,
1575
- },
1576
- metadata: { name, description: entry.docgenResult.description },
1577
- tokens: { usedTokens: scanCssTokens(entry.contextDir, fw) },
1578
- };
1585
+ const codeSpec = buildCodeSpec({
1586
+ name,
1587
+ docgenResult: entry.docgenResult,
1588
+ master: snapshotBySelector.get(name) || null,
1589
+ contract: contract || null,
1590
+ usedTokens: scanCssTokens(entry.contextDir, fw),
1591
+ });
1579
1592
  const outDir = path.join(path.resolve(args.emit), fw);
1580
1593
  fs.mkdirSync(outDir, { recursive: true });
1581
1594
  fs.writeFileSync(
@@ -1655,7 +1668,7 @@ function runCodeOnlyStalenessChecks() {
1655
1668
  report(
1656
1669
  'FW-ONLY',
1657
1670
  null,
1658
- `${selector}: codeOnly '${entry.name}' missing from ${absent.join(', ')} — present in the other framework(s) (ADR-0093 territory)`,
1671
+ `${selector}: codeOnly '${entry.name}' missing from ${absent.join(', ')} — present in the other framework(s) (a cross-framework API divergence)`,
1659
1672
  );
1660
1673
  }
1661
1674
  }