@vertekum/ext-export-figma 0.3.15

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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # @vertekum/ext-export-figma
2
+
3
+ ## 0.3.15
4
+
5
+ ### Patch Changes
6
+
7
+ - [`b1819c0`](https://github.com/moros-oxus/vertekum/commit/b1819c0f31411bf73a4fe9854b90ee73f8e3e36d) Thanks [@tschemmer](https://github.com/tschemmer)! - New extension: the `figma` exporter resolves a composition into a Figma-shaped model — each resolver set a single-mode collection, each modifier a collection whose contexts are its modes; references as alias edges; typography and shadows as styles with member-variable bindings; every variable carrying both the Figma-typed value and the verbatim DTCG source. Emitted as a versioned `figma.model.json` (JSON Schema shipped), with pluggable dialect writers in target options (`FigmaDialect` — pure model-to-files functions contributed as packages, the terrazzo-plugin pattern). Custom types plug in via `options.types` contributors.
8
+ - Updated dependencies []:
9
+ - @vertekum/core@0.3.15
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 Thomas Schemmer
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/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # @vertekum/ext-export-figma
2
+
3
+ Exports a resolved token composition as a **Figma-shaped model** — collections,
4
+ modes, variables, aliases, and styles — plus pluggable **dialect writers** that
5
+ reshape the model for specific Figma importers.
6
+
7
+ ## The model is the artifact
8
+
9
+ The exporter's canonical output, `figma.model.json`, is a versioned document
10
+ (schema shipped as `model.schema.json`) describing one composition in Figma's own
11
+ vocabulary:
12
+
13
+ - Each resolver **set** becomes a single-mode collection.
14
+ - Each **modifier** becomes a collection whose contexts are its modes, with values
15
+ resolved per context. The composition *is* the topology — nothing to configure.
16
+ - **References survive as alias edges** (per mode); a reference whose target has no
17
+ variable is materialized instead — never dropped.
18
+ - **Figma is variables and styles**: typography tokens become text styles, shadows
19
+ become effect styles, each with resolved per-property values and bindings to
20
+ member variables where the member was authored as a reference.
21
+ - Every variable carries the **Figma-typed value** (`COLOR` as `{r,g,b,a}` floats,
22
+ dimensions as unitless px `FLOAT`, `STRING`, `BOOLEAN`) *and* the verbatim DTCG
23
+ `source` — a consumer of the model loses nothing to any importer's dialect.
24
+ - `scopes` and `codeSyntax` are reserved fields; nothing populates them yet.
25
+
26
+ ## Configuration
27
+
28
+ ```ts
29
+ import { figmaExportExtension } from '@vertekum/ext-export-figma';
30
+ import { microsoftManifest } from '@vertekum/figma-dialect-microsoft';
31
+
32
+ export default defineConfig({
33
+ extensions: [figmaExportExtension],
34
+ targets: [
35
+ {
36
+ id: 'figma',
37
+ exporter: 'figma',
38
+ composition: 'default',
39
+ out: 'build/figma',
40
+ options: {
41
+ dialects: [microsoftManifest({ modes: 'native' })],
42
+ types: { /* custom-$type contributors, see below */ },
43
+ },
44
+ },
45
+ ],
46
+ });
47
+ ```
48
+
49
+ | Option | Value space | Meaning |
50
+ | --- | --- | --- |
51
+ | `dialects` | `FigmaDialect[]` | writers run over the model; their files land under `<out>/<dialect-id>/`. The model itself is always emitted. |
52
+ | `types` | `Record<$type, TypeContributor>` | how a custom type becomes variables (below). A `$type` with no mapping is skipped with a notice in `figma.model.json`. |
53
+
54
+ ## Dialects
55
+
56
+ A dialect is `{ id, write(model): OutputFile[] }` — a pure function from the model
57
+ to one importer's file shape. Ship your own as a package; pass an instance in
58
+ `options.dialects`.
59
+
60
+ The first dialect ships as its own contribution package —
61
+ `@vertekum/figma-dialect-microsoft` — targeting the `figma-variables-import`
62
+ plugin lineage (sidecar manifest, one DTCG string-dialect file per
63
+ collection-mode, with `native`/`split-collections`/`split-files` mode strategies
64
+ for seats without multi-mode collections). The model never downgrades; a
65
+ dialect's output does.
66
+
67
+ ## Custom types
68
+
69
+ A contributor maps one mode-value of a token to variable atoms:
70
+
71
+ ```ts
72
+ const spacial: TypeContributor = (value, token) =>
73
+ (value as Entry[]).map((entry, i) => ({
74
+ suffix: ['top', 'right', 'bottom', 'left'][i], // extends the token's path
75
+ type: 'FLOAT',
76
+ ...(typeof entry === 'string'
77
+ ? { alias: entry.slice(1, -1) } // dotted token path
78
+ : { value: entry.value }),
79
+ }));
80
+ ```
81
+
82
+ `suffix` unfolds a compound into sibling variables; `alias` becomes a real alias
83
+ edge when the target exists in the model.
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@vertekum/ext-export-figma",
3
+ "version": "0.3.15",
4
+ "description": "Vertekum extension: export a resolved, Figma-shaped model (collections, modes, variables, styles) with pluggable dialect writers for Figma importers",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "design-tokens",
8
+ "dtcg",
9
+ "figma",
10
+ "variables",
11
+ "export"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/moros-oxus/vertekum.git",
16
+ "directory": "packages/extensions/export-figma"
17
+ },
18
+ "homepage": "https://github.com/moros-oxus/vertekum",
19
+ "bugs": "https://github.com/moros-oxus/vertekum/issues",
20
+ "files": [
21
+ "CHANGELOG.md",
22
+ "src",
23
+ "tsconfig.json",
24
+ "!src/**/*.test.ts",
25
+ "!src/**/*.test.tsx"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "type": "module",
31
+ "main": "./src/index.ts",
32
+ "types": "./src/index.ts",
33
+ "exports": {
34
+ ".": "./src/index.ts",
35
+ "./api": "./src/api.ts"
36
+ },
37
+ "peerDependencies": {
38
+ "@vertekum/core": "0.3.15"
39
+ },
40
+ "dependencies": {
41
+ "zod": "^3.25.76"
42
+ },
43
+ "devDependencies": {
44
+ "ajv": "^8.20.0",
45
+ "@vertekum/core": "0.3.15"
46
+ }
47
+ }
package/src/api.ts ADDED
@@ -0,0 +1,15 @@
1
+ import {
2
+ type ActivateContext,
3
+ EXPORTER_SERVICE,
4
+ type ExporterService,
5
+ } from '@vertekum/core';
6
+ import { figmaExporter } from './figma';
7
+ import type { figmaManifest } from './index';
8
+
9
+ /**
10
+ * Headless activation: contributes one exporter. The kernel seeds the registry before any
11
+ * extension activates, so activation order never matters — get and register, nothing more.
12
+ */
13
+ export function activate(ctx: ActivateContext<typeof figmaManifest>): void {
14
+ ctx.services.get<ExporterService>(EXPORTER_SERVICE)?.register(figmaExporter);
15
+ }
package/src/dialect.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { FigmaModel } from './model';
2
+
3
+ /**
4
+ * The dialect seam: a writer is a pure function from the model to one importer's file shape,
5
+ * passed in a target's `options.dialects` (the terrazzo pattern — config is the vessel, no
6
+ * registry). Dialect packages peer on this package for the model types and export a factory
7
+ * (`somethingDialect(options)`), so third parties contribute importer support as plain npm
8
+ * packages the same way terrazzo plugins do.
9
+ */
10
+
11
+ export interface OutputFile {
12
+ path: string;
13
+ content: string;
14
+ }
15
+
16
+ export interface FigmaDialect {
17
+ /** Namespaces the writer's files under `<out>/<id>/`. */
18
+ id: string;
19
+ write(model: FigmaModel): OutputFile[];
20
+ }
package/src/figma.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { Exporter } from '@vertekum/core';
2
+ import { z } from 'zod';
3
+ import type { FigmaDialect, OutputFile } from './dialect';
4
+ import { buildModel, type TypeContributor } from './model';
5
+
6
+ /**
7
+ * The `figma` exporter: builds the Figma-shaped model from the resolved composition and emits it
8
+ * as the canonical artifact (`figma.model.json` — the `vertekum` dialect, always on), then runs
9
+ * each configured dialect writer over the model. Writers and type contributors are config-passed
10
+ * plugs (the terrazzo pattern): no registry, third parties ship them as packages.
11
+ */
12
+
13
+ export interface FigmaOptions {
14
+ /** Per-$type model contributors for custom types (e.g. a per-side unfolder). */
15
+ types?: Record<string, TypeContributor>;
16
+ /** Dialect writers; the canonical model is emitted regardless. */
17
+ dialects?: FigmaDialect[];
18
+ }
19
+
20
+ const OPTIONS = z
21
+ .object({
22
+ types: z
23
+ .record(z.custom<TypeContributor>((v) => typeof v === 'function'))
24
+ .optional(),
25
+ dialects: z
26
+ .array(
27
+ z.object({
28
+ id: z.string(),
29
+ write: z.custom<FigmaDialect['write']>(
30
+ (v) => typeof v === 'function',
31
+ ),
32
+ }),
33
+ )
34
+ .optional(),
35
+ })
36
+ .optional();
37
+
38
+ export const figmaExporter: Exporter = {
39
+ id: 'figma',
40
+ name: 'Figma model',
41
+ optionsSchema: OPTIONS,
42
+ async transform(input) {
43
+ const options = (input.options ?? {}) as FigmaOptions;
44
+ const model = await buildModel(input, {
45
+ composition: input.resolver.name,
46
+ types: options.types,
47
+ });
48
+ const files: OutputFile[] = [
49
+ {
50
+ path: 'figma.model.json',
51
+ content: `${JSON.stringify(model, null, 2)}\n`,
52
+ },
53
+ ];
54
+ for (const dialect of options.dialects ?? []) {
55
+ for (const file of dialect.write(model)) {
56
+ files.push({
57
+ path: `${dialect.id}/${file.path}`,
58
+ content: file.content,
59
+ });
60
+ }
61
+ }
62
+ return files;
63
+ },
64
+ };
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { defineExtension, type ExtensionManifest } from '@vertekum/core';
2
+ import { activate } from './api';
3
+
4
+ export type { FigmaDialect, OutputFile } from './dialect';
5
+ export { type FigmaOptions, figmaExporter } from './figma';
6
+ export {
7
+ type BuildModelOptions,
8
+ buildModel,
9
+ type FigmaCollection,
10
+ type FigmaModel,
11
+ type FigmaStyle,
12
+ type FigmaType,
13
+ type FigmaVariable,
14
+ MODEL_VERSION,
15
+ type TypeContributor,
16
+ } from './model';
17
+
18
+ export const figmaManifest = {
19
+ id: 'vtk.export.figma',
20
+ name: 'Figma Export',
21
+ description:
22
+ "Adds the 'figma' exporter, which resolves a composition into a Figma-shaped model — collections, modes, variables, aliases, styles — emitted as a versioned artifact, plus any configured dialect writers targeting specific Figma importers. A non-view extension: no route, no ribbon entry.",
23
+ activation: ['onStartup'],
24
+ } satisfies ExtensionManifest;
25
+
26
+ /**
27
+ * First-party NON-VIEW HostExtension: contributes an exporter and nothing else. The model artifact
28
+ * is the contract consumed by dialect writers here and by external tools (a Figma plugin, agents).
29
+ */
30
+ export const figmaExportExtension = defineExtension<typeof figmaManifest>({
31
+ manifest: figmaManifest,
32
+ activate,
33
+ });
@@ -0,0 +1,119 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "vertekum:figma-model",
4
+ "title": "Figma-shaped model",
5
+ "description": "A resolved view of one composition in Figma's vocabulary: collections with modes, variables with per-mode values and alias edges, and styles. Version 1.",
6
+ "type": "object",
7
+ "required": ["version", "source", "collections", "styles"],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "version": { "const": 1 },
11
+ "source": {
12
+ "type": "object",
13
+ "required": ["generator", "notices"],
14
+ "additionalProperties": false,
15
+ "properties": {
16
+ "composition": { "type": "string" },
17
+ "generator": { "type": "string" },
18
+ "notices": { "type": "array", "items": { "type": "string" } }
19
+ }
20
+ },
21
+ "collections": {
22
+ "type": "array",
23
+ "items": {
24
+ "type": "object",
25
+ "required": ["name", "modes", "variables"],
26
+ "additionalProperties": false,
27
+ "properties": {
28
+ "name": { "type": "string", "minLength": 1 },
29
+ "modes": {
30
+ "type": "array",
31
+ "items": { "type": "string", "minLength": 1 },
32
+ "minItems": 1
33
+ },
34
+ "variables": {
35
+ "type": "array",
36
+ "items": { "$ref": "#/$defs/variable" }
37
+ }
38
+ }
39
+ }
40
+ },
41
+ "styles": {
42
+ "type": "array",
43
+ "items": {
44
+ "type": "object",
45
+ "required": ["kind", "name", "properties", "source"],
46
+ "additionalProperties": false,
47
+ "properties": {
48
+ "kind": { "enum": ["text", "effect"] },
49
+ "name": { "type": "string", "minLength": 1 },
50
+ "properties": {
51
+ "type": "array",
52
+ "items": {
53
+ "type": "object",
54
+ "required": ["property", "value"],
55
+ "additionalProperties": false,
56
+ "properties": {
57
+ "property": { "type": "string" },
58
+ "value": {},
59
+ "variable": { "type": "string" }
60
+ }
61
+ }
62
+ },
63
+ "source": { "$ref": "#/$defs/source" }
64
+ }
65
+ }
66
+ }
67
+ },
68
+ "$defs": {
69
+ "variable": {
70
+ "type": "object",
71
+ "required": ["name", "type", "valuesByMode", "scopes", "codeSyntax"],
72
+ "additionalProperties": false,
73
+ "properties": {
74
+ "name": { "type": "string", "minLength": 1 },
75
+ "type": { "enum": ["COLOR", "FLOAT", "STRING", "BOOLEAN"] },
76
+ "valuesByMode": {
77
+ "type": "object",
78
+ "additionalProperties": {
79
+ "anyOf": [
80
+ { "type": "number" },
81
+ { "type": "string" },
82
+ { "type": "boolean" },
83
+ {
84
+ "type": "object",
85
+ "required": ["r", "g", "b", "a"],
86
+ "additionalProperties": false,
87
+ "properties": {
88
+ "r": { "type": "number" },
89
+ "g": { "type": "number" },
90
+ "b": { "type": "number" },
91
+ "a": { "type": "number" }
92
+ }
93
+ }
94
+ ]
95
+ }
96
+ },
97
+ "alias": {
98
+ "type": "object",
99
+ "additionalProperties": { "type": "string" }
100
+ },
101
+ "source": { "$ref": "#/$defs/source" },
102
+ "scopes": { "type": "array", "items": { "type": "string" } },
103
+ "codeSyntax": {
104
+ "type": "object",
105
+ "additionalProperties": { "type": "string" }
106
+ }
107
+ }
108
+ },
109
+ "source": {
110
+ "type": "object",
111
+ "required": ["$type", "$value"],
112
+ "additionalProperties": false,
113
+ "properties": {
114
+ "$type": { "type": "string" },
115
+ "$value": {}
116
+ }
117
+ }
118
+ }
119
+ }
package/src/model.ts ADDED
@@ -0,0 +1,435 @@
1
+ import { dtcg, type ExporterInput, type Token } from '@vertekum/core';
2
+
3
+ /**
4
+ * The Figma-shaped model — the artifact, and the contract.
5
+ *
6
+ * A resolved view of one composition in Figma's own vocabulary: collections with modes,
7
+ * variables with per-mode values and alias edges, and styles (Figma is variables AND styles).
8
+ * The topology mirrors the resolver: each SET becomes a single-mode collection; each MODIFIER
9
+ * becomes a collection whose contexts are its modes. The composition IS the topology.
10
+ *
11
+ * Every variable carries both the Figma-typed value (`valuesByMode`) and the verbatim DTCG
12
+ * `source` — dialect writers consume the lossy half; a consumer that understands the model
13
+ * (a Figma plugin, an agent) gets the lossless half.
14
+ */
15
+
16
+ export const MODEL_VERSION = 1;
17
+
18
+ export type FigmaType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN';
19
+
20
+ export interface FigmaVariable {
21
+ /** Slash-joined token path — Figma's grouping separator. */
22
+ name: string;
23
+ type: FigmaType;
24
+ /** Figma-typed value per mode: COLOR `{r,g,b,a}` floats, FLOAT unitless px, string, boolean. */
25
+ valuesByMode: Record<string, unknown>;
26
+ /** Per-mode alias target (slash name). An alias wins over the value for that mode. */
27
+ alias?: Record<string, string>;
28
+ /** The authored DTCG notation, verbatim — the lossless half. */
29
+ source?: { $type: string; $value: unknown };
30
+ /** Reserved: nothing populates these yet; the schema keeps their seat. */
31
+ scopes: string[];
32
+ codeSyntax: Record<string, string>;
33
+ }
34
+
35
+ export interface FigmaCollection {
36
+ name: string;
37
+ /** Mode names, default first. Single-mode collections have `['default']`. */
38
+ modes: string[];
39
+ variables: FigmaVariable[];
40
+ }
41
+
42
+ export interface FigmaStyleProperty {
43
+ property: string;
44
+ /** Resolved value (CSS-ish primitive). */
45
+ value: unknown;
46
+ /** Bound member variable (slash name), when the member was authored as a reference. */
47
+ variable?: string;
48
+ }
49
+
50
+ export interface FigmaStyle {
51
+ kind: 'text' | 'effect';
52
+ name: string;
53
+ properties: FigmaStyleProperty[];
54
+ source: { $type: string; $value: unknown };
55
+ }
56
+
57
+ export interface FigmaModel {
58
+ version: typeof MODEL_VERSION;
59
+ source: { composition?: string; generator: string; notices: string[] };
60
+ collections: FigmaCollection[];
61
+ styles: FigmaStyle[];
62
+ }
63
+
64
+ /**
65
+ * A custom-type model contributor (config-passed via the exporter's `options.types`): maps ONE
66
+ * mode-value of a token to variable atoms. `suffix` extends the token's path (per-side unfolds);
67
+ * an atom may carry a concrete `value` or an `alias` (dotted token path).
68
+ */
69
+ export type TypeContributor = (
70
+ value: unknown,
71
+ token: Token,
72
+ ) => Array<{
73
+ suffix?: string;
74
+ type: FigmaType;
75
+ value?: unknown;
76
+ alias?: string;
77
+ }>;
78
+
79
+ export interface BuildModelOptions {
80
+ composition?: string;
81
+ types?: Record<string, TypeContributor>;
82
+ }
83
+
84
+ const GENERATOR = '@vertekum/ext-export-figma';
85
+
86
+ /** Types whose per-token handling is built in (beyond these, `options.types` or a notice). */
87
+ const TEXT_TYPES = new Set([
88
+ 'string',
89
+ 'fontFamily',
90
+ 'textCase',
91
+ 'textDecoration',
92
+ 'strokeStyle',
93
+ ]);
94
+
95
+ const slash = (path: string[]): string => path.join('/');
96
+ const dotToSlash = (dotted: string): string => dotted.replaceAll('.', '/');
97
+
98
+ function isDimension(value: unknown): value is { value: number; unit: string } {
99
+ return (
100
+ typeof value === 'object' &&
101
+ value !== null &&
102
+ typeof (value as { value?: unknown }).value === 'number' &&
103
+ typeof (value as { unit?: unknown }).unit === 'string'
104
+ );
105
+ }
106
+
107
+ function px(value: { value: number; unit: string }): number {
108
+ return value.unit === 'rem' || value.unit === 'em'
109
+ ? value.value * 16
110
+ : value.value;
111
+ }
112
+
113
+ async function figmaColor(value: unknown): Promise<unknown> {
114
+ const srgb = (await dtcg.values.convertColor(value, 'srgb')) as {
115
+ components?: number[];
116
+ alpha?: number;
117
+ };
118
+ if (!Array.isArray(srgb.components)) return undefined;
119
+ const [r, g, b] = srgb.components;
120
+ return { r, g, b, a: srgb.alpha ?? 1 };
121
+ }
122
+
123
+ /** One token's Figma type + converted value, or undefined when the type is not variable-shaped. */
124
+ async function convert(
125
+ type: string,
126
+ value: unknown,
127
+ ): Promise<{ type: FigmaType; value: unknown } | undefined> {
128
+ if (type === 'color') {
129
+ return { type: 'COLOR', value: await figmaColor(value) };
130
+ }
131
+ if (type === 'dimension' && isDimension(value)) {
132
+ return { type: 'FLOAT', value: px(value) };
133
+ }
134
+ if (type === 'duration' && isDimension(value)) {
135
+ return { type: 'FLOAT', value: value.value };
136
+ }
137
+ if (
138
+ type === 'number' ||
139
+ (type === 'fontWeight' && typeof value === 'number')
140
+ ) {
141
+ return typeof value === 'number'
142
+ ? { type: 'FLOAT', value }
143
+ : { type: 'STRING', value: String(value) };
144
+ }
145
+ if (type === 'fontWeight') return { type: 'STRING', value: String(value) };
146
+ if (type === 'fontFamily') {
147
+ return {
148
+ type: 'STRING',
149
+ value: Array.isArray(value) ? String(value[0]) : String(value),
150
+ };
151
+ }
152
+ if (TEXT_TYPES.has(type) && typeof value === 'string') {
153
+ return { type: 'STRING', value };
154
+ }
155
+ if (typeof value === 'boolean') return { type: 'BOOLEAN', value };
156
+ return undefined;
157
+ }
158
+
159
+ /** Typography members → text-style properties; shadow layers → effect-style properties. */
160
+ const TYPOGRAPHY_MEMBERS: Record<string, string> = {
161
+ fontFamily: 'font-family',
162
+ fontSize: 'font-size',
163
+ fontWeight: 'font-weight',
164
+ letterSpacing: 'letter-spacing',
165
+ lineHeight: 'line-height',
166
+ textCase: 'text-case',
167
+ textDecoration: 'text-decoration',
168
+ };
169
+
170
+ function styleValue(member: unknown): unknown {
171
+ if (isDimension(member)) return `${member.value}${member.unit}`;
172
+ if (Array.isArray(member)) return member.map(styleValue).join(', ');
173
+ return member;
174
+ }
175
+
176
+ /**
177
+ * Build the Figma-shaped model from a resolved composition.
178
+ *
179
+ * `input.base` is the default selection; `input.variants` are the fully-resolved non-default
180
+ * contexts. A token belongs to a MODIFIER's collection when its value differs from base in any of
181
+ * that modifier's contexts (or it exists only there); everything else lands in the collection of
182
+ * its resolver SET. Values are read per mode from the corresponding resolved bundle.
183
+ */
184
+ export async function buildModel(
185
+ input: ExporterInput,
186
+ options: BuildModelOptions = {},
187
+ ): Promise<FigmaModel> {
188
+ const notices: string[] = [];
189
+ const model: FigmaModel = {
190
+ version: MODEL_VERSION,
191
+ source: { composition: options.composition, generator: GENERATOR, notices },
192
+ collections: [],
193
+ styles: [],
194
+ };
195
+
196
+ const basePaths = new Map(input.base.map((t) => [t.path.join('.'), t]));
197
+
198
+ // Modifier axes: context order as declared, default first; per-context resolved bundles.
199
+ const axes = Object.entries(input.resolver.modifiers).map(
200
+ ([modifier, mod]) => {
201
+ const contexts = Object.keys(mod.contexts);
202
+ const defaultContext = mod.default ?? contexts[0] ?? 'default';
203
+ const ordered = [
204
+ defaultContext,
205
+ ...contexts.filter((c) => c !== defaultContext),
206
+ ];
207
+ const bundles = new Map<string, Map<string, Token>>();
208
+ bundles.set(defaultContext, basePaths);
209
+ for (const variant of input.variants) {
210
+ if (variant.modifier !== modifier) continue;
211
+ bundles.set(
212
+ variant.context,
213
+ new Map(variant.tokens.map((t) => [t.path.join('.'), t])),
214
+ );
215
+ }
216
+ return { modifier, contexts: ordered, bundles };
217
+ },
218
+ );
219
+
220
+ // A token is claimed by the FIRST modifier (declaration order) under which it varies.
221
+ const claimed = new Map<string, string>();
222
+ for (const axis of axes) {
223
+ for (const [context, bundle] of axis.bundles) {
224
+ if (context === axis.contexts[0]) continue;
225
+ for (const [path, token] of bundle) {
226
+ const base = basePaths.get(path);
227
+ const varies =
228
+ !base || JSON.stringify(base.value) !== JSON.stringify(token.value);
229
+ if (!varies) continue;
230
+ const holder = claimed.get(path);
231
+ if (holder === undefined) claimed.set(path, axis.modifier);
232
+ else if (holder !== axis.modifier) {
233
+ notices.push(
234
+ `'${path}' varies under both '${holder}' and '${axis.modifier}' — modelled under '${holder}'`,
235
+ );
236
+ }
237
+ }
238
+ }
239
+ }
240
+
241
+ // First pass — every variable NAME that will exist, so alias edges can check their targets.
242
+ const variableNames = new Set<string>();
243
+ const atomsOf = async (
244
+ token: Token,
245
+ value: unknown,
246
+ ): Promise<
247
+ | Array<{
248
+ suffix?: string;
249
+ type: FigmaType;
250
+ value?: unknown;
251
+ alias?: string;
252
+ }>
253
+ | undefined
254
+ > => {
255
+ const contributor = options.types?.[token.type];
256
+ if (contributor) return contributor(value, token);
257
+ const converted = await convert(token.type, value);
258
+ return converted
259
+ ? [{ type: converted.type, value: converted.value }]
260
+ : undefined;
261
+ };
262
+ const nameOf = (token: Token, suffix?: string): string =>
263
+ suffix ? `${slash(token.path)}/${suffix}` : slash(token.path);
264
+
265
+ const allTokens = new Map<string, Token>(basePaths);
266
+ for (const variant of input.variants) {
267
+ for (const token of variant.tokens) {
268
+ const path = token.path.join('.');
269
+ if (!allTokens.has(path)) allTokens.set(path, token);
270
+ }
271
+ }
272
+ for (const token of allTokens.values()) {
273
+ if (token.type === 'typography' || token.type === 'shadow') continue;
274
+ const atoms = await atomsOf(token, token.value);
275
+ if (!atoms) continue;
276
+ for (const atom of atoms) variableNames.add(nameOf(token, atom.suffix));
277
+ }
278
+
279
+ // Variable construction for one token across a mode set.
280
+ const buildVariables = async (
281
+ token: Token,
282
+ modes: Array<{ mode: string; bundle: Map<string, Token> }>,
283
+ ): Promise<FigmaVariable[] | 'style' | undefined> => {
284
+ if (token.type === 'typography' || token.type === 'shadow') {
285
+ buildStyle(token);
286
+ return 'style';
287
+ }
288
+ const byName = new Map<string, FigmaVariable>();
289
+ for (const { mode, bundle } of modes) {
290
+ const held = bundle.get(token.path.join('.')) ?? token;
291
+ const raw = held.value;
292
+ // A whole-value curly reference: alias when the target is a variable, else materialize.
293
+ let aliasTarget: string | undefined;
294
+ let value = raw;
295
+ if (dtcg.tokens.isReference(raw)) {
296
+ const target = dotToSlash(dtcg.tokens.referenceToPath(raw));
297
+ if (variableNames.has(target)) aliasTarget = target;
298
+ value = dtcg.tokens.resolveValue(
299
+ held,
300
+ dtcg.tokens.indexByPath([...bundle.values()]),
301
+ );
302
+ }
303
+ const atoms = await atomsOf(held, value);
304
+ if (!atoms) {
305
+ if (mode === modes[0]?.mode) return undefined;
306
+ continue;
307
+ }
308
+ for (const atom of atoms) {
309
+ const name = nameOf(token, atom.suffix);
310
+ let variable = byName.get(name);
311
+ if (!variable) {
312
+ variable = {
313
+ name,
314
+ type: atom.type,
315
+ valuesByMode: {},
316
+ source: { $type: token.type, $value: token.value },
317
+ scopes: [],
318
+ codeSyntax: {},
319
+ };
320
+ byName.set(name, variable);
321
+ }
322
+ if (atom.value !== undefined) variable.valuesByMode[mode] = atom.value;
323
+ const atomAlias =
324
+ atom.alias !== undefined ? dotToSlash(atom.alias) : aliasTarget;
325
+ if (atomAlias !== undefined && variableNames.has(atomAlias)) {
326
+ variable.alias = { ...variable.alias, [mode]: atomAlias };
327
+ }
328
+ }
329
+ }
330
+ return [...byName.values()];
331
+ };
332
+
333
+ const buildStyle = (token: Token): void => {
334
+ const value = token.value;
335
+ if (token.type === 'typography' && value && typeof value === 'object') {
336
+ const raw = (token.sourceValue ?? value) as Record<string, unknown>;
337
+ const resolved = value as Record<string, unknown>;
338
+ const properties: FigmaStyleProperty[] = [];
339
+ for (const [member, property] of Object.entries(TYPOGRAPHY_MEMBERS)) {
340
+ if (!(member in resolved)) continue;
341
+ const authored = raw[member];
342
+ properties.push({
343
+ property,
344
+ value: styleValue(resolved[member]),
345
+ ...(dtcg.tokens.isReference(authored)
346
+ ? { variable: dotToSlash(dtcg.tokens.referenceToPath(authored)) }
347
+ : {}),
348
+ });
349
+ }
350
+ model.styles.push({
351
+ kind: 'text',
352
+ name: slash(token.path),
353
+ properties,
354
+ source: { $type: token.type, $value: token.value },
355
+ });
356
+ return;
357
+ }
358
+ if (token.type === 'shadow') {
359
+ const layers = Array.isArray(value) ? value : [value];
360
+ const properties: FigmaStyleProperty[] = layers.flatMap((layer, index) =>
361
+ layer && typeof layer === 'object'
362
+ ? Object.entries(layer as Record<string, unknown>).map(
363
+ ([member, held]) => ({
364
+ property: layers.length > 1 ? `${index}/${member}` : member,
365
+ value: styleValue(held),
366
+ }),
367
+ )
368
+ : [],
369
+ );
370
+ model.styles.push({
371
+ kind: 'effect',
372
+ name: slash(token.path),
373
+ properties,
374
+ source: { $type: token.type, $value: token.value },
375
+ });
376
+ }
377
+ };
378
+
379
+ // Set collections: resolver sets in order; tokens by source file, minus modifier-claimed ones.
380
+ const skipped = new Set<string>();
381
+ for (const [setName, set] of Object.entries(input.resolver.sets)) {
382
+ const files = new Set(
383
+ (set.sources ?? []).map((source) =>
384
+ String((source as { $ref?: string }).$ref ?? '').replace(/\.json$/, ''),
385
+ ),
386
+ );
387
+ const variables: FigmaVariable[] = [];
388
+ for (const token of input.base) {
389
+ const path = token.path.join('.');
390
+ if (claimed.has(path)) continue;
391
+ if (!files.has(token.set ?? '')) continue;
392
+ const built = await buildVariables(token, [
393
+ { mode: 'default', bundle: basePaths },
394
+ ]);
395
+ if (built === undefined) {
396
+ skipped.add(token.type);
397
+ continue;
398
+ }
399
+ if (built !== 'style') variables.push(...built);
400
+ }
401
+ model.collections.push({ name: setName, modes: ['default'], variables });
402
+ }
403
+
404
+ // Modifier collections: contexts as modes, values per resolved bundle.
405
+ for (const axis of axes) {
406
+ const modes = axis.contexts.map((context) => ({
407
+ mode: context,
408
+ bundle: axis.bundles.get(context) ?? basePaths,
409
+ }));
410
+ const variables: FigmaVariable[] = [];
411
+ for (const [path, modifier] of claimed) {
412
+ if (modifier !== axis.modifier) continue;
413
+ const token = allTokens.get(path);
414
+ if (!token) continue;
415
+ const built = await buildVariables(token, modes);
416
+ if (built === undefined) {
417
+ skipped.add(token.type);
418
+ continue;
419
+ }
420
+ if (built !== 'style') variables.push(...built);
421
+ }
422
+ model.collections.push({
423
+ name: axis.modifier,
424
+ modes: axis.contexts,
425
+ variables,
426
+ });
427
+ }
428
+
429
+ for (const type of skipped) {
430
+ notices.push(
431
+ `tokens of type '${type}' have no Figma mapping — provide one via options.types`,
432
+ );
433
+ }
434
+ return model;
435
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist"
6
+ },
7
+ "include": ["src"]
8
+ }