@adobe/design-data 0.0.0-size-token-taxonomy-20260929225107

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Adobe
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@adobe/design-data",
3
+ "version": "0.0.0-size-token-taxonomy-20260929225107",
4
+ "description": "Node.js helpers for @adobe/design-data-wasm: filesystem dataset loading, token write operations, and authoring-session management",
5
+ "type": "module",
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",
13
+ "./guideline": "./src/guideline.js"
14
+ },
15
+ "files": [
16
+ "src/",
17
+ "README.md"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20.12.0"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/adobe/spectrum-design-data.git",
25
+ "directory": "tools/design-data"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/adobe/spectrum-design-data/issues"
29
+ },
30
+ "homepage": "https://github.com/adobe/spectrum-design-data/tree/main/tools/design-data#readme",
31
+ "keywords": [
32
+ "spectrum",
33
+ "design-system",
34
+ "design-tokens",
35
+ "wasm"
36
+ ],
37
+ "author": "Adobe",
38
+ "license": "Apache-2.0",
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "registry": "https://registry.npmjs.org/",
42
+ "provenance": true
43
+ },
44
+ "dependencies": {
45
+ "ajv": "^8.17.1",
46
+ "ajv-formats": "^3.0.1",
47
+ "@adobe/design-data-wasm": "0.0.0-size-token-taxonomy-20260929225107"
48
+ },
49
+ "devDependencies": {
50
+ "ava": "^6.1.2"
51
+ }
52
+ }
@@ -0,0 +1,67 @@
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
+ * Shared guideline-document loader, used by both @adobe/design-data-mcp's
13
+ * `design-data-guideline` tool and @adobe/design-data-agent-mcp's
14
+ * `describe_guideline` tool, so the read-back logic (and its path-traversal
15
+ * guard) lives in exactly one place instead of being duplicated per server.
16
+ */
17
+
18
+ import { readFileSync, existsSync, readdirSync } from "node:fs";
19
+ import { resolve, sep } from "node:path";
20
+
21
+ /**
22
+ * Load a single guideline document (`<guidelinesDir>/<id>.json`) by slug id.
23
+ *
24
+ * Path safety: the resolved absolute path is asserted to stay within
25
+ * `guidelinesDir` so a crafted `id` (e.g. `../../etc/passwd`) cannot read
26
+ * files outside the intended data directory.
27
+ *
28
+ * @param {string} guidelinesDir - absolute path to the guidelines directory,
29
+ * e.g. `<spectrum-design-data package root>/guidelines`.
30
+ * @param {string} id - kebab-case slug, e.g. "colors" or "motion".
31
+ * @returns {object} the parsed guideline JSON document.
32
+ */
33
+ export function loadGuideline(guidelinesDir, id) {
34
+ if (id === "manifest") {
35
+ throw new Error(`Not found: "${id}" in guidelines/.`);
36
+ }
37
+ const baseDir = resolve(guidelinesDir);
38
+ const filePath = resolve(baseDir, `${id}.json`);
39
+ if (!filePath.startsWith(baseDir + sep)) {
40
+ throw new Error(`Invalid guideline id: "${id}"`);
41
+ }
42
+ if (!existsSync(filePath)) {
43
+ throw new Error(`Not found: "${id}" in guidelines/.`);
44
+ }
45
+ return JSON.parse(readFileSync(filePath, "utf-8"));
46
+ }
47
+
48
+ /**
49
+ * List guideline catalog entries from the manifest, falling back to the files
50
+ * present in the directory when the manifest is unavailable.
51
+ *
52
+ * @param {string} guidelinesDir - absolute path to the guidelines directory.
53
+ * @returns {Array<object>} guideline catalog entries.
54
+ */
55
+ export function listGuidelines(guidelinesDir) {
56
+ const baseDir = resolve(guidelinesDir);
57
+ const manifestPath = resolve(baseDir, "manifest.json");
58
+ if (existsSync(manifestPath)) {
59
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
60
+ return manifest.guidelines ?? [];
61
+ }
62
+
63
+ return readdirSync(baseDir)
64
+ .filter((file) => file.endsWith(".json") && file !== "manifest.json")
65
+ .map((file) => ({ slug: file.replace(/\.json$/, "") }))
66
+ .sort((a, b) => a.slug.localeCompare(b.slug));
67
+ }
package/src/index.js ADDED
@@ -0,0 +1,26 @@
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
+ */
19
+
20
+ export { loadDataset, loadDatasetSync } from "./load.js";
21
+ export {
22
+ validateDataset,
23
+ validateTokenAgainstSchema,
24
+ resolveSchemaDir,
25
+ loadSchemaValidator,
26
+ } from "./validate.js";
package/src/load.js ADDED
@@ -0,0 +1,128 @@
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
+ * Build a Dataset directly from an already-parsed token array.
91
+ * Use this when the caller has already read and parsed the token files to avoid
92
+ * a second filesystem pass.
93
+ *
94
+ * @param {object[]} tokens - Flat array of cascade-format token objects.
95
+ * @returns {Promise<import('@adobe/design-data-wasm').Dataset>}
96
+ */
97
+ export async function buildDataset(tokens) {
98
+ const { Dataset } = await getWasm();
99
+ return Dataset.fromTokens(tokens);
100
+ }
101
+
102
+ /**
103
+ * Synchronous variant using the already-loaded wasm module.
104
+ * The caller is responsible for ensuring the module is initialised first.
105
+ *
106
+ * @param {string} dirPath
107
+ * @param {{ Dataset: typeof import('@adobe/design-data-wasm').Dataset }} wasm
108
+ * @returns {import('@adobe/design-data-wasm').Dataset}
109
+ */
110
+ export function loadDatasetSync(dirPath, wasm) {
111
+ const files = walkTokenFiles(dirPath);
112
+ const tokens = [];
113
+ for (const file of files) {
114
+ let content;
115
+ try {
116
+ content = JSON.parse(readFileSync(file, "utf-8"));
117
+ } catch (e) {
118
+ console.warn(
119
+ `[design-data-js] Skipping unparseable file: ${file} — ${e.message}`,
120
+ );
121
+ continue;
122
+ }
123
+ if (Array.isArray(content)) {
124
+ tokens.push(...content);
125
+ }
126
+ }
127
+ return wasm.Dataset.fromTokens(tokens);
128
+ }
@@ -0,0 +1,272 @@
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 { buildDataset, 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, validate each token's $schema, and accumulate parsed tokens
224
+ // so Layer-2 can reuse the same data without a second filesystem pass.
225
+ const tokenFiles = walkTokenFiles(datasetPath);
226
+ const allTokens = [];
227
+ for (const file of tokenFiles) {
228
+ let parsed;
229
+ try {
230
+ parsed = JSON.parse(readFileSync(file, "utf-8"));
231
+ } catch {
232
+ layer1Errors.push({
233
+ severity: "error",
234
+ message: `Failed to parse ${file}`,
235
+ });
236
+ continue;
237
+ }
238
+ if (!Array.isArray(parsed)) continue; // Legacy object-map format — loadDataset (Layer-2) warns and skips these.
239
+ allTokens.push(...parsed);
240
+ for (const token of parsed) {
241
+ const diags = validateTokenSchema(token, ajv, file);
242
+ layer1Errors.push(...diags);
243
+ }
244
+ }
245
+
246
+ // Layer-2: relational rules via wasm — built from already-parsed tokens.
247
+ const ds = await buildDataset(allTokens);
248
+ const layer2Result = ds.validate();
249
+
250
+ const allErrors = [
251
+ ...layer1Errors.filter((d) => d.severity === "error"),
252
+ ...layer2Result.errors,
253
+ ];
254
+ const allWarnings = [
255
+ ...layer1Errors.filter((d) => d.severity !== "error"),
256
+ ...layer2Result.warnings,
257
+ ];
258
+
259
+ if (strict && allWarnings.length > 0) {
260
+ return {
261
+ valid: false,
262
+ errors: [...allErrors, ...allWarnings],
263
+ warnings: [],
264
+ };
265
+ }
266
+
267
+ return {
268
+ valid: allErrors.length === 0,
269
+ errors: allErrors,
270
+ warnings: allWarnings,
271
+ };
272
+ }