@adobe/design-data 0.12.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -186,7 +186,7 @@ file or class name and description of purpose be included on the
186
186
  same "printed page" as the copyright notice for easier
187
187
  identification within third-party archives.
188
188
 
189
- Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
189
+ Copyright 2026 Adobe
190
190
 
191
191
  Licensed under the Apache License, Version 2.0 (the "License");
192
192
  you may not use this file except in compliance with the License.
package/package.json CHANGED
@@ -1,38 +1,37 @@
1
1
  {
2
2
  "name": "@adobe/design-data",
3
- "version": "0.12.0",
4
- "description": "design-data CLI — validate and inspect Spectrum design data",
3
+ "version": "2.0.0",
4
+ "description": "Node.js helpers for @adobe/design-data-wasm: filesystem dataset loading, token write operations, and authoring-session management",
5
5
  "type": "module",
6
- "bin": {
7
- "design-data": "bin/design-data.js"
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./load": "./src/load.js",
10
+ "./write": "./src/write.js",
11
+ "./session": "./src/session.js",
12
+ "./validate": "./src/validate.js"
8
13
  },
9
14
  "files": [
10
- "bin/design-data.js",
15
+ "src/",
11
16
  "README.md"
12
17
  ],
13
- "optionalDependencies": {
14
- "@adobe/design-data-darwin-arm64": "0.12.0",
15
- "@adobe/design-data-darwin-x64": "0.12.0",
16
- "@adobe/design-data-linux-x64": "0.12.0",
17
- "@adobe/design-data-win32-x64": "0.12.0"
18
- },
19
18
  "engines": {
20
19
  "node": ">=20.12.0"
21
20
  },
22
21
  "repository": {
23
22
  "type": "git",
24
23
  "url": "git+https://github.com/adobe/spectrum-design-data.git",
25
- "directory": "sdk/cli"
24
+ "directory": "tools/design-data"
26
25
  },
27
26
  "bugs": {
28
27
  "url": "https://github.com/adobe/spectrum-design-data/issues"
29
28
  },
30
- "homepage": "https://github.com/adobe/spectrum-design-data/tree/main/sdk/cli#readme",
29
+ "homepage": "https://github.com/adobe/spectrum-design-data/tree/main/tools/design-data#readme",
31
30
  "keywords": [
32
31
  "spectrum",
33
32
  "design-system",
34
33
  "design-tokens",
35
- "cli"
34
+ "wasm"
36
35
  ],
37
36
  "author": "Adobe",
38
37
  "license": "Apache-2.0",
@@ -40,5 +39,13 @@
40
39
  "access": "public",
41
40
  "registry": "https://registry.npmjs.org/",
42
41
  "provenance": true
42
+ },
43
+ "dependencies": {
44
+ "ajv": "^8.17.1",
45
+ "ajv-formats": "^3.0.1",
46
+ "@adobe/design-data-wasm": "0.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "ava": "^6.1.2"
43
50
  }
44
51
  }
package/src/index.js ADDED
@@ -0,0 +1,45 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License. You may obtain a copy
4
+ // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
+ //
6
+ // Unless required by applicable law or agreed to in writing, software distributed under
7
+ // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
+ // OF ANY KIND, either express or implied. See the License for the specific language
9
+ // governing permissions and limitations under the License.
10
+
11
+ /**
12
+ * @adobe/design-data
13
+ *
14
+ * Node.js glue layer over @adobe/design-data-wasm:
15
+ *
16
+ * - `loadDataset(dir)` — walk *.tokens.json from a directory → Dataset
17
+ * - `loadDatasetSync(dir, wasm)` — synchronous variant for pre-loaded wasm modules
18
+ * - `writeProductContext(opts)` — write/update product-context.json
19
+ * - `writeToken(key, token, opts)` — write a token into a target JSON file
20
+ * - `buildTokenFromWizard(opts)` — build a token object from authoring-session state
21
+ * - `startSession / stepClassification / stepValues / commitSession / cancelSession / getSession / listSessions`
22
+ * — on-disk authoring-session state machine (JS port of sdk/core/src/authoring/session.rs)
23
+ */
24
+
25
+ export { loadDataset, loadDatasetSync } from "./load.js";
26
+ export {
27
+ writeProductContext,
28
+ writeToken,
29
+ buildTokenFromWizard,
30
+ } from "./write.js";
31
+ export {
32
+ startSession,
33
+ getSession,
34
+ listSessions,
35
+ stepClassification,
36
+ stepValues,
37
+ commitSession,
38
+ cancelSession,
39
+ } from "./session.js";
40
+ export {
41
+ validateDataset,
42
+ validateTokenAgainstSchema,
43
+ resolveSchemaDir,
44
+ loadSchemaValidator,
45
+ } from "./validate.js";
package/src/load.js ADDED
@@ -0,0 +1,115 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License. You may obtain a copy
4
+ // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
+ //
6
+ // Unless required by applicable law or agreed to in writing, software distributed under
7
+ // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
+ // OF ANY KIND, either express or implied. See the License for the specific language
9
+ // governing permissions and limitations under the License.
10
+
11
+ /**
12
+ * Filesystem dataset loader for @adobe/design-data-wasm.
13
+ *
14
+ * Walks a directory for *.tokens.json files (cascade array format), merges them,
15
+ * and returns a Dataset built via Dataset.fromTokens(). This mirrors the token-loading
16
+ * behaviour of `design-data query/resolve/validate/diff <dataPath>` but runs in-process.
17
+ */
18
+
19
+ import { readFileSync, readdirSync, statSync } from "node:fs";
20
+ import { join } from "node:path";
21
+
22
+ let _wasmModule;
23
+
24
+ async function getWasm() {
25
+ if (!_wasmModule) {
26
+ _wasmModule = await import("@adobe/design-data-wasm");
27
+ }
28
+ return _wasmModule;
29
+ }
30
+
31
+ /**
32
+ * Walk `dir` recursively and collect all `*.tokens.json` file paths.
33
+ * Results are sorted for stable, deterministic ordering.
34
+ *
35
+ * @param {string} dir
36
+ * @returns {string[]}
37
+ */
38
+ export function walkTokenFiles(dir) {
39
+ const results = [];
40
+ for (const entry of readdirSync(dir)) {
41
+ const fullPath = join(dir, entry);
42
+ const stat = statSync(fullPath);
43
+ if (stat.isDirectory()) {
44
+ results.push(...walkTokenFiles(fullPath));
45
+ } else if (entry.endsWith(".tokens.json")) {
46
+ results.push(fullPath);
47
+ }
48
+ }
49
+ return results.sort();
50
+ }
51
+
52
+ /**
53
+ * Load all cascade token files from `dirPath` and return a Dataset.
54
+ *
55
+ * Accepts the cascade array format: each `.tokens.json` file must contain a
56
+ * JSON array of token objects (the same format `Dataset.fromTokens()` expects).
57
+ * Files in object-map (legacy) format are skipped with a warning.
58
+ *
59
+ * @param {string} dirPath - Path to the token dataset directory.
60
+ * @returns {Promise<import('@adobe/design-data-wasm').Dataset>}
61
+ */
62
+ export async function loadDataset(dirPath) {
63
+ const { Dataset } = await getWasm();
64
+ const files = walkTokenFiles(dirPath);
65
+ const tokens = [];
66
+ for (const file of files) {
67
+ let content;
68
+ try {
69
+ content = JSON.parse(readFileSync(file, "utf-8"));
70
+ } catch (e) {
71
+ console.warn(
72
+ `[design-data-js] Skipping unparseable file: ${file} — ${e.message}`,
73
+ );
74
+ continue;
75
+ }
76
+ if (Array.isArray(content)) {
77
+ tokens.push(...content);
78
+ } else {
79
+ // Legacy object-map format is not supported by Dataset.fromTokens() —
80
+ // the wasm surface only handles cascade arrays. Warn and skip.
81
+ console.warn(
82
+ `[design-data-js] Skipping legacy object-map file (not cascade format): ${file}`,
83
+ );
84
+ }
85
+ }
86
+ return Dataset.fromTokens(tokens);
87
+ }
88
+
89
+ /**
90
+ * Synchronous variant using the already-loaded wasm module.
91
+ * The caller is responsible for ensuring the module is initialised first.
92
+ *
93
+ * @param {string} dirPath
94
+ * @param {{ Dataset: typeof import('@adobe/design-data-wasm').Dataset }} wasm
95
+ * @returns {import('@adobe/design-data-wasm').Dataset}
96
+ */
97
+ export function loadDatasetSync(dirPath, wasm) {
98
+ const files = walkTokenFiles(dirPath);
99
+ const tokens = [];
100
+ for (const file of files) {
101
+ let content;
102
+ try {
103
+ content = JSON.parse(readFileSync(file, "utf-8"));
104
+ } catch (e) {
105
+ console.warn(
106
+ `[design-data-js] Skipping unparseable file: ${file} — ${e.message}`,
107
+ );
108
+ continue;
109
+ }
110
+ if (Array.isArray(content)) {
111
+ tokens.push(...content);
112
+ }
113
+ }
114
+ return wasm.Dataset.fromTokens(tokens);
115
+ }
package/src/session.js ADDED
@@ -0,0 +1,253 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License. You may obtain a copy
4
+ // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
+ //
6
+ // Unless required by applicable law or agreed to in writing, software distributed under
7
+ // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
+ // OF ANY KIND, either express or implied. See the License for the specific language
9
+ // governing permissions and limitations under the License.
10
+
11
+ /**
12
+ * On-disk authoring-session store — JS port of sdk/core/src/authoring/session.rs.
13
+ *
14
+ * Session state is one JSON file per session in the sessions directory, matching
15
+ * the file format produced by the Rust CLI so that in-progress sessions started by
16
+ * the CLI can be continued here and vice versa.
17
+ *
18
+ * NOTE: `stepIntent` (the NLP suggestion-ranking step) still delegates to the CLI
19
+ * because the `suggest` API is not yet exposed on the wasm surface. All other
20
+ * session operations (start, classification, values, commit, cancel, get, list)
21
+ * run fully in-process.
22
+ */
23
+
24
+ import {
25
+ readFileSync,
26
+ writeFileSync,
27
+ mkdirSync,
28
+ unlinkSync,
29
+ readdirSync,
30
+ renameSync,
31
+ } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { randomUUID } from "node:crypto";
34
+ import { homedir } from "node:os";
35
+ import {
36
+ buildTokenFromWizard,
37
+ writeToken,
38
+ writeProductContext,
39
+ } from "./write.js";
40
+ import { validateTokenAgainstSchema, resolveSchemaDir } from "./validate.js";
41
+
42
+ /**
43
+ * Return the directory where session JSON files are stored.
44
+ * Mirrors `sessions_dir()` from sdk/core/src/authoring/session.rs.
45
+ *
46
+ * @returns {string}
47
+ */
48
+ function sessionsDir() {
49
+ if (process.env.DESIGN_DATA_AUTHORING_SESSIONS_DIR) {
50
+ return process.env.DESIGN_DATA_AUTHORING_SESSIONS_DIR;
51
+ }
52
+ let base;
53
+ if (process.platform === "win32") {
54
+ base = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
55
+ } else if (process.platform === "darwin") {
56
+ base = join(homedir(), "Library", "Application Support");
57
+ } else {
58
+ base = process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share");
59
+ }
60
+ return join(base, "design-data", "authoring-sessions");
61
+ }
62
+
63
+ function sessionPath(sessionId) {
64
+ return join(sessionsDir(), `${sessionId}.json`);
65
+ }
66
+
67
+ function atomicWriteSession(draft) {
68
+ const dir = sessionsDir();
69
+ mkdirSync(dir, { recursive: true });
70
+ const tmp =
71
+ sessionPath(draft.session_id) + ".tmp." + randomUUID().slice(0, 8);
72
+ writeFileSync(tmp, JSON.stringify(draft, null, 2) + "\n", "utf-8");
73
+ renameSync(tmp, sessionPath(draft.session_id));
74
+ }
75
+
76
+ function readSessionOrThrow(sessionId) {
77
+ try {
78
+ return JSON.parse(readFileSync(sessionPath(sessionId), "utf-8"));
79
+ } catch {
80
+ throw new Error(`Session not found: ${sessionId}`);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Start a new authoring session.
86
+ *
87
+ * @param {string} datasetPath - Absolute path to the token dataset directory.
88
+ * @returns {{ session_id: string, dataset_path: string, wizard: object }}
89
+ */
90
+ export function startSession(datasetPath) {
91
+ const sessionId = randomUUID();
92
+ const draft = {
93
+ session_id: sessionId,
94
+ dataset_path: datasetPath,
95
+ wizard: {
96
+ intent: null,
97
+ classification: null,
98
+ values: null,
99
+ },
100
+ };
101
+ atomicWriteSession(draft);
102
+ return draft;
103
+ }
104
+
105
+ /**
106
+ * Get the current state of a session.
107
+ *
108
+ * @param {string} sessionId
109
+ */
110
+ export function getSession(sessionId) {
111
+ return readSessionOrThrow(sessionId);
112
+ }
113
+
114
+ /**
115
+ * List all active sessions.
116
+ *
117
+ * @returns {object[]}
118
+ */
119
+ export function listSessions() {
120
+ const dir = sessionsDir();
121
+ try {
122
+ return readdirSync(dir)
123
+ .filter((f) => f.endsWith(".json") && !f.endsWith(".tmp"))
124
+ .map((f) => JSON.parse(readFileSync(join(dir, f), "utf-8")));
125
+ } catch {
126
+ return [];
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Update the classification step (layer, property, nameFields).
132
+ *
133
+ * @param {string} sessionId
134
+ * @param {{ layer: string, property: string, nameFields?: Array<{key:string,value:string}> }} opts
135
+ * @returns {object} Updated session draft.
136
+ */
137
+ export function stepClassification(
138
+ sessionId,
139
+ { layer, property, nameFields = [] },
140
+ ) {
141
+ const draft = readSessionOrThrow(sessionId);
142
+ draft.wizard.classification = { layer, property, nameFields };
143
+ atomicWriteSession(draft);
144
+ return draft;
145
+ }
146
+
147
+ /**
148
+ * Update the values step (mode-specific literal or alias rows).
149
+ *
150
+ * @param {string} sessionId
151
+ * @param {Array<{mode_combo: string[][], kind: 'Literal'|'Alias', alias_target: string, literal: string}>} rows
152
+ * @returns {object} Updated session draft.
153
+ */
154
+ export function stepValues(sessionId, rows) {
155
+ const draft = readSessionOrThrow(sessionId);
156
+ draft.wizard.values = rows;
157
+ atomicWriteSession(draft);
158
+ return draft;
159
+ }
160
+
161
+ /**
162
+ * Commit the session: build the token from wizard state, validate it against its
163
+ * JSON Schema (Layer-1), write it to disk, and delete the session file.
164
+ *
165
+ * @param {object} opts
166
+ * @param {string} opts.sessionId
167
+ * @param {string} opts.schemaUrl - The `$schema` URL for the token type.
168
+ * @param {string} opts.target - Target file path.
169
+ * @param {string} [opts.rationale]
170
+ * @param {string} [opts.productContext]
171
+ * @param {string} [opts.schemaPath] - Path to the schemas/ directory (contains
172
+ * token-types/ and token-file.json). Defaults to @adobe/spectrum-tokens schemas.
173
+ * Pass an explicit path when working with a custom schema set.
174
+ * @param {boolean} [opts.isOverride]
175
+ * @returns {{ writtenTo: string, productContextUpdated: boolean, tokenKey: string }}
176
+ * @throws {Error} When the built token fails Layer-1 JSON-Schema validation.
177
+ */
178
+ export function commitSession({
179
+ sessionId,
180
+ schemaUrl,
181
+ target,
182
+ rationale,
183
+ productContext,
184
+ schemaPath,
185
+ isOverride = false,
186
+ }) {
187
+ const draft = readSessionOrThrow(sessionId);
188
+
189
+ if (!draft.wizard.classification) {
190
+ throw new Error(
191
+ `Session ${sessionId} has no classification step — call stepClassification first.`,
192
+ );
193
+ }
194
+ if (!draft.wizard.values || draft.wizard.values.length === 0) {
195
+ throw new Error(
196
+ `Session ${sessionId} has no values step — call stepValues first.`,
197
+ );
198
+ }
199
+
200
+ const [tokenKey, token] = buildTokenFromWizard({
201
+ schemaUrl,
202
+ classification: draft.wizard.classification,
203
+ rows: draft.wizard.values,
204
+ uuid: randomUUID(),
205
+ });
206
+
207
+ // Layer-1: validate the built token against its JSON Schema before writing.
208
+ // Validation runs when a schema directory is available. If schemaPath is
209
+ // explicitly provided it must resolve (throws on bad path). If it is omitted
210
+ // and auto-discovery finds nothing (e.g. @adobe/spectrum-tokens not installed),
211
+ // validation is skipped rather than blocking the commit.
212
+ const schemaDir = resolveSchemaDir(schemaPath ?? null, {
213
+ required: !!schemaPath,
214
+ });
215
+ if (schemaDir) {
216
+ const validation = validateTokenAgainstSchema(token, schemaDir);
217
+ if (!validation.valid) {
218
+ const summary = validation.errors.map((e) => e.message).join("; ");
219
+ throw new Error(`Token failed JSON-Schema validation: ${summary}`);
220
+ }
221
+ }
222
+
223
+ const result = writeToken(tokenKey, token, {
224
+ target,
225
+ productContext,
226
+ rationale,
227
+ isOverride,
228
+ });
229
+
230
+ // Delete session file after successful commit.
231
+ try {
232
+ unlinkSync(sessionPath(sessionId));
233
+ } catch {
234
+ /* already gone */
235
+ }
236
+
237
+ return { ...result, tokenKey };
238
+ }
239
+
240
+ /**
241
+ * Cancel and delete a session.
242
+ *
243
+ * @param {string} sessionId
244
+ * @returns {{ cancelled: string }}
245
+ */
246
+ export function cancelSession(sessionId) {
247
+ try {
248
+ unlinkSync(sessionPath(sessionId));
249
+ } catch {
250
+ /* already gone — idempotent */
251
+ }
252
+ return { cancelled: sessionId };
253
+ }
@@ -0,0 +1,270 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License. You may obtain a copy
4
+ // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
+ //
6
+ // Unless required by applicable law or agreed to in writing, software distributed under
7
+ // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
+ // OF ANY KIND, either express or implied. See the License for the specific language
9
+ // governing permissions and limitations under the License.
10
+
11
+ /**
12
+ * Layer-1 (JSON-Schema structural) validation for design token datasets.
13
+ *
14
+ * The wasm Dataset.validate() runs Layer-2 relational rules only — it explicitly
15
+ * omits Layer-1 because JSON-Schema validation requires filesystem access not
16
+ * available in wasm. This module fills that gap for Node.js callers.
17
+ *
18
+ * Mirrors the Rust implementation in sdk/core/src/validate/structural.rs using
19
+ * Ajv 2020-12 (same draft as the Rust jsonschema crate).
20
+ *
21
+ * Schema source: packages/tokens/schemas/ (also published in @adobe/spectrum-tokens)
22
+ */
23
+
24
+ import { createRequire } from "node:module";
25
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
26
+ import { join, dirname } from "node:path";
27
+ import Ajv from "ajv/dist/2020.js";
28
+ import addFormats from "ajv-formats";
29
+ import { loadDataset, walkTokenFiles } from "./load.js";
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Schema directory resolution
33
+ // ---------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Attempt to locate the Spectrum token schemas directory by resolving
37
+ * @adobe/spectrum-tokens (the npm package that ships them).
38
+ *
39
+ * @returns {string|null} Absolute path to the schemas/ directory, or null.
40
+ */
41
+ function resolveSpectrumTokensSchemaDir() {
42
+ try {
43
+ const req = createRequire(import.meta.url);
44
+ const pkgJson = req.resolve("@adobe/spectrum-tokens/package.json");
45
+ return join(dirname(pkgJson), "schemas");
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Return the schemas directory to use.
53
+ *
54
+ * @param {string|null|undefined} schemaPath - Caller-supplied override (the
55
+ * directory that contains token-types/ and token-file.json). If omitted the
56
+ * function falls back to @adobe/spectrum-tokens.
57
+ * @param {{ required?: boolean }} [opts]
58
+ * @returns {string|null} Absolute path to the schemas directory, or null when
59
+ * no path was supplied AND auto-discovery failed (only when required is false).
60
+ * @throws {Error} When schemaPath is provided but does not exist or lacks
61
+ * token-types/; or when required is true and no path can be auto-resolved.
62
+ */
63
+ export function resolveSchemaDir(schemaPath, { required = true } = {}) {
64
+ if (schemaPath) {
65
+ if (!existsSync(schemaPath)) {
66
+ throw new Error(
67
+ `schema_path does not exist: "${schemaPath}". ` +
68
+ `Point it at the directory that contains token-types/ and token-file.json.`,
69
+ );
70
+ }
71
+ const typesDir = join(schemaPath, "token-types");
72
+ if (!existsSync(typesDir)) {
73
+ throw new Error(
74
+ `schema_path "${schemaPath}" does not contain a token-types/ subdirectory. ` +
75
+ `Expected a schemas/ root that contains token-types/*.json and token-file.json.`,
76
+ );
77
+ }
78
+ return schemaPath;
79
+ }
80
+
81
+ const fallback = resolveSpectrumTokensSchemaDir();
82
+ if (fallback && existsSync(join(fallback, "token-types"))) {
83
+ return fallback;
84
+ }
85
+
86
+ if (required) {
87
+ throw new Error(
88
+ `Cannot locate the Spectrum token schemas directory. ` +
89
+ `Either install @adobe/spectrum-tokens or pass an explicit schema_path ` +
90
+ `pointing at a directory containing token-types/ and token-file.json.`,
91
+ );
92
+ }
93
+
94
+ return null;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Ajv setup
99
+ // ---------------------------------------------------------------------------
100
+
101
+ /**
102
+ * Build an Ajv 2020-12 instance with all token-type schemas and token-file.json
103
+ * pre-registered so relative $ref resolution works offline.
104
+ *
105
+ * @param {string} schemaDir - Absolute path to schemas/ directory.
106
+ * @returns {import('ajv').default} Configured Ajv instance.
107
+ */
108
+ export function loadSchemaValidator(schemaDir) {
109
+ const ajv = new Ajv({ strict: false, allErrors: true });
110
+ addFormats(ajv);
111
+
112
+ // Register all token-type schemas by $id.
113
+ const typesDir = join(schemaDir, "token-types");
114
+ for (const file of readdirSync(typesDir).filter((f) => f.endsWith(".json"))) {
115
+ const schema = JSON.parse(readFileSync(join(typesDir, file), "utf-8"));
116
+ const id = schema["$id"];
117
+ if (!id)
118
+ throw new Error(
119
+ `Token-type schema "${file}" is missing a required $id field`,
120
+ );
121
+ if (!ajv.getSchema(id)) ajv.addSchema(schema, id);
122
+ }
123
+
124
+ // Register token-file.json.
125
+ const tokenFileSchema = JSON.parse(
126
+ readFileSync(join(schemaDir, "token-file.json"), "utf-8"),
127
+ );
128
+ const tokenFileId = tokenFileSchema["$id"];
129
+ if (!tokenFileId)
130
+ throw new Error(`token-file.json is missing a required $id field`);
131
+ if (!ajv.getSchema(tokenFileId)) ajv.addSchema(tokenFileSchema, tokenFileId);
132
+
133
+ return ajv;
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Per-token validation
138
+ // ---------------------------------------------------------------------------
139
+
140
+ /**
141
+ * Validate a single token object against its declared $schema, returning any
142
+ * Ajv errors as Layer-1 diagnostics.
143
+ *
144
+ * @param {object} token - Token object (must have $schema and value fields).
145
+ * @param {import('ajv').default} ajv - Pre-configured Ajv instance.
146
+ * @param {string} [context] - Optional label for error messages (e.g. filename/key).
147
+ * @returns {{ severity: string, message: string, path?: string, ruleId?: undefined }[]}
148
+ */
149
+ function validateTokenSchema(token, ajv, context = "") {
150
+ const schemaId = token["$schema"];
151
+ if (!schemaId) return []; // Missing $schema is allowed for cascade tokens.
152
+
153
+ const validate = ajv.getSchema(schemaId);
154
+ if (!validate) {
155
+ return [
156
+ {
157
+ severity: "error",
158
+ message: `Unknown $schema URL "${schemaId}"${context ? ` in ${context}` : ""}.`,
159
+ },
160
+ ];
161
+ }
162
+
163
+ const valid = validate(token);
164
+ if (valid) return [];
165
+
166
+ return (validate.errors ?? []).map((err) => ({
167
+ severity: "error",
168
+ message: `${err.instancePath || "(root)"} ${err.message}${context ? ` [${context}]` : ""}`,
169
+ path: err.instancePath || undefined,
170
+ }));
171
+ }
172
+
173
+ /**
174
+ * Validate a single token against its $schema. Convenience wrapper that
175
+ * handles schema directory resolution and Ajv setup.
176
+ *
177
+ * @param {object} token
178
+ * @param {string} schemaDir - Resolved schemas/ directory (from resolveSchemaDir).
179
+ * @returns {{ valid: boolean, errors: object[], warnings: object[] }}
180
+ */
181
+ export function validateTokenAgainstSchema(token, schemaDir) {
182
+ const ajv = loadSchemaValidator(schemaDir);
183
+ const errors = validateTokenSchema(token, ajv);
184
+ return { valid: errors.length === 0, errors, warnings: [] };
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Dataset-level validation (Layer-1 + Layer-2 merged)
189
+ // ---------------------------------------------------------------------------
190
+
191
+ /**
192
+ * Run full validation (Layer-1 JSON-Schema + Layer-2 relational) over a dataset
193
+ * directory, returning a merged ValidationResult.
194
+ *
195
+ * @param {string} datasetPath - Path to the token dataset directory.
196
+ * @param {object} [opts]
197
+ * @param {string|null} [opts.schemaPath] - Override schemas/ directory.
198
+ * @param {string|null} [opts.exceptionsPath] - NOT supported in the in-process path
199
+ * (exceptions apply to SPEC-007 naming in the relational layer which requires the
200
+ * CLI). Pass null or omit; throws if a non-null value is provided.
201
+ * @param {boolean} [opts.strict] - Promote warnings to errors.
202
+ * @returns {Promise<{ valid: boolean, errors: object[], warnings: object[] }>}
203
+ */
204
+ export async function validateDataset(
205
+ datasetPath,
206
+ { schemaPath, exceptionsPath, strict = false } = {},
207
+ ) {
208
+ if (exceptionsPath) {
209
+ throw new Error(
210
+ `exceptionsPath is not supported by the in-process validator (it applies to SPEC-007 ` +
211
+ `naming checks in the relational layer which requires the CLI). ` +
212
+ `Omit exceptionsPath or use the design-data CLI directly: design-data validate --exceptions-path.`,
213
+ );
214
+ }
215
+
216
+ // Layer-1: JSON-Schema structural validation.
217
+ const resolvedSchemaDir = resolveSchemaDir(schemaPath ?? null, {
218
+ required: true,
219
+ });
220
+ const ajv = loadSchemaValidator(resolvedSchemaDir);
221
+ const layer1Errors = [];
222
+
223
+ // Walk token files and validate each token's $schema.
224
+ const tokenFiles = walkTokenFiles(datasetPath);
225
+ for (const file of tokenFiles) {
226
+ let parsed;
227
+ try {
228
+ parsed = JSON.parse(readFileSync(file, "utf-8"));
229
+ } catch {
230
+ layer1Errors.push({
231
+ severity: "error",
232
+ message: `Failed to parse ${file}`,
233
+ });
234
+ continue;
235
+ }
236
+ if (!Array.isArray(parsed)) continue; // Legacy object-map format — loadDataset (Layer-2) warns and skips these.
237
+ const tokens = parsed;
238
+ for (const token of tokens) {
239
+ const diags = validateTokenSchema(token, ajv, file);
240
+ layer1Errors.push(...diags);
241
+ }
242
+ }
243
+
244
+ // Layer-2: relational rules via wasm.
245
+ const ds = await loadDataset(datasetPath);
246
+ const layer2Result = ds.validate();
247
+
248
+ const allErrors = [
249
+ ...layer1Errors.filter((d) => d.severity === "error"),
250
+ ...layer2Result.errors,
251
+ ];
252
+ const allWarnings = [
253
+ ...layer1Errors.filter((d) => d.severity !== "error"),
254
+ ...layer2Result.warnings,
255
+ ];
256
+
257
+ if (strict && allWarnings.length > 0) {
258
+ return {
259
+ valid: false,
260
+ errors: [...allErrors, ...allWarnings],
261
+ warnings: [],
262
+ };
263
+ }
264
+
265
+ return {
266
+ valid: allErrors.length === 0,
267
+ errors: allErrors,
268
+ warnings: allWarnings,
269
+ };
270
+ }
package/src/write.js ADDED
@@ -0,0 +1,179 @@
1
+ // Copyright 2026 Adobe. All rights reserved.
2
+ // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License. You may obtain a copy
4
+ // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
+ //
6
+ // Unless required by applicable law or agreed to in writing, software distributed under
7
+ // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
+ // OF ANY KIND, either express or implied. See the License for the specific language
9
+ // governing permissions and limitations under the License.
10
+
11
+ /**
12
+ * Token write helpers — pure Node.js implementations of the CLI's write and
13
+ * write-token operations. No native binary required.
14
+ *
15
+ * These mirror `design-data write` and `design-data write-token` but run
16
+ * in-process, with atomic file writes (tmp-then-rename) for safety.
17
+ */
18
+
19
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
20
+ import { dirname, resolve } from "node:path";
21
+ import { randomUUID } from "node:crypto";
22
+
23
+ /**
24
+ * Atomically write `content` to `dest` (via a `.tmp` sibling).
25
+ *
26
+ * @param {string} dest
27
+ * @param {string} content
28
+ */
29
+ function atomicWrite(dest, content) {
30
+ const tmp = dest + ".tmp." + randomUUID().slice(0, 8);
31
+ mkdirSync(dirname(dest), { recursive: true });
32
+ writeFileSync(tmp, content, "utf-8");
33
+ renameSync(tmp, dest);
34
+ }
35
+
36
+ /**
37
+ * Write or update a `product-context.json` document.
38
+ *
39
+ * Mirrors `design-data write --output <path> [--rationale <text>]`.
40
+ * Creates the file if absent with the standard `specVersion`/`layer`/`createdBy`
41
+ * scaffold; overwrites in place if it already exists.
42
+ *
43
+ * @param {object} opts
44
+ * @param {string} opts.output - Destination file path.
45
+ * @param {string} [opts.rationale] - Optional rationale string to embed.
46
+ * @returns {string} Confirmation message (matches CLI stdout).
47
+ */
48
+ export function writeProductContext({ output, rationale } = {}) {
49
+ const dest = resolve(output);
50
+ let doc;
51
+ try {
52
+ doc = JSON.parse(readFileSync(dest, "utf-8"));
53
+ } catch {
54
+ doc = {
55
+ specVersion: "1.0.0-draft",
56
+ layer: "product",
57
+ };
58
+ }
59
+ if (rationale != null) doc.rationale = rationale;
60
+ doc.createdBy = { type: "agent", tool: "design-data" };
61
+ doc.createdAt = new Date().toISOString();
62
+
63
+ atomicWrite(dest, JSON.stringify(doc, null, 2) + "\n");
64
+ return `Wrote ${dest}`;
65
+ }
66
+
67
+ /**
68
+ * Write a single token into a target JSON file.
69
+ *
70
+ * Mirrors `design-data write-token <key>` (without JSON-Schema validation —
71
+ * structural validation requires the schema files, which callers should handle
72
+ * at a higher level or via the CLI if strict validation is needed).
73
+ *
74
+ * The target file is treated as an object-keyed token map (legacy format):
75
+ * `{ "<key>": { ...token fields... } }`
76
+ * If the file is absent it is created; if it exists the key is merged in.
77
+ *
78
+ * @param {string} key - Token key, e.g. `"accent-background-color-default"`.
79
+ * @param {object} token - The token object to write (must include `$schema`, `uuid`, etc.).
80
+ * @param {object} [opts]
81
+ * @param {string} opts.target - Target file path.
82
+ * @param {string} [opts.productContext] - Optional path to product-context.json to update.
83
+ * @param {string} [opts.rationale] - Rationale to embed in the product-context update.
84
+ * @param {boolean} [opts.isOverride] - Whether this is a product-layer override.
85
+ * @returns {{ writtenTo: string, productContextUpdated: boolean }}
86
+ */
87
+ export function writeToken(
88
+ key,
89
+ token,
90
+ { target, productContext, rationale, isOverride = false } = {},
91
+ ) {
92
+ const dest = resolve(target);
93
+ let existing;
94
+ try {
95
+ existing = JSON.parse(readFileSync(dest, "utf-8"));
96
+ } catch {
97
+ existing = {};
98
+ }
99
+ existing[key] = token;
100
+ atomicWrite(dest, JSON.stringify(existing, null, 2) + "\n");
101
+
102
+ let productContextUpdated = false;
103
+ if (productContext) {
104
+ writeProductContext({ output: productContext, rationale });
105
+ productContextUpdated = true;
106
+ }
107
+
108
+ return { writtenTo: dest, productContextUpdated };
109
+ }
110
+
111
+ /**
112
+ * Build a cascade-format token object from authoring-session wizard state.
113
+ *
114
+ * Converts the wizard's `rows` (ValueRowInput[]) into either a simple
115
+ * `{ value }` token or a `{ sets: { ... } }` multi-mode token.
116
+ *
117
+ * @param {object} opts
118
+ * @param {string} opts.schemaUrl - The `$schema` URL.
119
+ * @param {object} opts.classification - `{ layer, property, nameFields }`.
120
+ * @param {Array<{mode_combo: string[][], kind: 'Literal'|'Alias', alias_target: string, literal: string}>} opts.rows
121
+ * @param {string} opts.uuid - Token UUID.
122
+ * @returns {[string, object]} Tuple of [tokenKey, tokenObject].
123
+ */
124
+ export function buildTokenFromWizard({
125
+ schemaUrl,
126
+ classification,
127
+ rows,
128
+ uuid,
129
+ }) {
130
+ const { layer, property, nameFields = [] } = classification;
131
+ const name = { property };
132
+ for (const { key, value } of nameFields) name[key] = value;
133
+
134
+ const tokenKey = [property, ...nameFields.map(({ value }) => value)].join(
135
+ "/",
136
+ );
137
+
138
+ // Build the value portion from rows.
139
+ let tokenValue;
140
+ if (rows.length === 1 && rows[0].mode_combo.length === 0) {
141
+ // Single base value — simple format.
142
+ const row = rows[0];
143
+ tokenValue =
144
+ row.kind === "Alias"
145
+ ? { value: { ref: row.alias_target } }
146
+ : { value: row.literal };
147
+ } else {
148
+ // Multi-mode format: group rows by the first dimension key.
149
+ const sets = {};
150
+ for (const row of rows) {
151
+ let target = sets;
152
+ const pairs = row.mode_combo;
153
+ for (let i = 0; i < pairs.length; i++) {
154
+ const [k, v] = pairs[i];
155
+ if (i < pairs.length - 1) {
156
+ target[k] = target[k] ?? {};
157
+ target = target[k][v] = target[k][v] ?? {};
158
+ } else {
159
+ target[k] = target[k] ?? {};
160
+ target[k][v] =
161
+ row.kind === "Alias"
162
+ ? { value: { ref: row.alias_target } }
163
+ : { value: row.literal };
164
+ }
165
+ }
166
+ }
167
+ tokenValue = { sets };
168
+ }
169
+
170
+ const token = {
171
+ $schema: schemaUrl,
172
+ uuid: uuid ?? randomUUID(),
173
+ name,
174
+ layer,
175
+ ...tokenValue,
176
+ };
177
+
178
+ return [tokenKey, token];
179
+ }
package/README.md DELETED
@@ -1,52 +0,0 @@
1
- # [**@adobe/design-data**](https://github.com/adobe/design-data)
2
-
3
- CLI tool for working with [Adobe Spectrum](https://spectrum.adobe.com) design tokens and component schemas.
4
-
5
- ## Install
6
-
7
- ```sh
8
- npm install -g @adobe/design-data
9
- # or use without installing:
10
- npx @adobe/design-data <command>
11
- ```
12
-
13
- Requires Node.js ≥ 20.12. No Rust toolchain needed — the CLI binary is included via platform-specific optional dependencies.
14
-
15
- ## Usage
16
-
17
- ```sh
18
- # Get a structural overview of the Spectrum dataset (great for AI agent sessions)
19
- design-data primer --format json
20
-
21
- # Query tokens by name or property
22
- design-data query "property=color*"
23
-
24
- # Get AI-powered token suggestions for a given intent
25
- design-data suggest "primary background color"
26
-
27
- # Resolve a token's value for a given mode-set context
28
- design-data resolve color-background-layer-1 --color-scheme light
29
-
30
- # Print a component schema
31
- design-data component button
32
-
33
- # Validate a design-data directory
34
- design-data validate ./my-tokens
35
- ```
36
-
37
- ## Configuration
38
-
39
- Drop a `.design-data.toml` in your project root to point at a specific dataset version:
40
-
41
- ```toml
42
- [source]
43
- type = "github"
44
- repo = "adobe/spectrum-design-data"
45
- tag = "@adobe/spectrum-tokens@14.11.0"
46
- ```
47
-
48
- Without configuration, the embedded Spectrum snapshot is used automatically (offline, zero-setup).
49
-
50
- ## License
51
-
52
- Apache-2.0 — see the [project repository](https://github.com/adobe/spectrum-design-data) for details.
@@ -1,68 +0,0 @@
1
- #!/usr/bin/env node
2
- // Copyright 2026 Adobe. All rights reserved.
3
- // This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License. You may obtain a copy
5
- // of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- //
7
- // Unless required by applicable law or agreed to in writing, software distributed under
8
- // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- // OF ANY KIND, either express or implied. See the License for the specific language
10
- // governing permissions and limitations under the License.
11
-
12
- /**
13
- * design-data launcher (esbuild/biome pattern).
14
- *
15
- * npm installs only the matching @adobe/design-data-{os}-{cpu} package via
16
- * optionalDependencies + os/cpu fields. This script resolves the right binary
17
- * path and execs it, forwarding all arguments and stdio transparently.
18
- */
19
-
20
- import { execFileSync } from "child_process";
21
- import { createRequire } from "module";
22
-
23
- const require = createRequire(import.meta.url);
24
-
25
- /** Map of `${process.platform}-${process.arch}` → platform package name. */
26
- const PLATFORM_PACKAGES = {
27
- "darwin-arm64": "@adobe/design-data-darwin-arm64",
28
- "darwin-x64": "@adobe/design-data-darwin-x64",
29
- "linux-x64": "@adobe/design-data-linux-x64",
30
- "win32-x64": "@adobe/design-data-win32-x64",
31
- };
32
-
33
- const platformKey = `${process.platform}-${process.arch}`;
34
- const platformPkg = PLATFORM_PACKAGES[platformKey];
35
-
36
- if (!platformPkg) {
37
- process.stderr.write(
38
- `design-data: unsupported platform "${platformKey}".\n` +
39
- `Supported platforms: ${Object.keys(PLATFORM_PACKAGES).join(", ")}\n`,
40
- );
41
- process.exit(1);
42
- }
43
-
44
- const binaryName = `design-data${process.platform === "win32" ? ".exe" : ""}`;
45
-
46
- let binaryPath;
47
- try {
48
- binaryPath = require.resolve(`${platformPkg}/bin/${binaryName}`);
49
- } catch {
50
- process.stderr.write(
51
- `design-data: platform package "${platformPkg}" is not installed.\n` +
52
- `Try: npm install ${platformPkg}\n` +
53
- `Or reinstall @adobe/design-data to let npm pick the right package automatically.\n`,
54
- );
55
- process.exit(1);
56
- }
57
-
58
- try {
59
- execFileSync(binaryPath, process.argv.slice(2), { stdio: "inherit" });
60
- } catch (/** @type {any} */ err) {
61
- if (err?.code === "EACCES") {
62
- process.stderr.write(
63
- `design-data: permission denied executing "${binaryPath}".\n` +
64
- `Try: chmod +x "${binaryPath}"\n`,
65
- );
66
- }
67
- process.exit(err?.status ?? 1);
68
- }