diff --git a/.changeset/paper-token-sync.md b/.changeset/paper-token-sync.md new file mode 100644 index 0000000..8065290 --- /dev/null +++ b/.changeset/paper-token-sync.md @@ -0,0 +1,13 @@ +--- +"@hebilicious/cssforge": minor +--- + +Sync the tokens of a design tool with the configuration, starting with Paper. + +- `cssforge sync remote add --file ` binds a Paper file. `cssforge sync fetch`, `cssforge sync plan` and `cssforge sync push` read the file, show the plan and send it: create, update and delete the tokens that the configuration generates. +- What designers change in the file waits in an inbox: `cssforge sync inbox list`. Settle a new token with `cssforge sync inbox adopt` (after you add it to the configuration) or `cssforge sync inbox reject`, and a changed or deleted token with `cssforge sync inbox overwrite`. +- The state is in `.cssforge/sync/.json`. Commit it. +- Each design tool is an adapter. Tokens have a value per mode (`default`, `light` and `dark` from `light-dark()`, or a selector such as `.dark`), a remote token has its own key, and `sync remote add --options` passes options to the adapter, so a tool with modes and ids, such as Figma, fits the same commands. Paper holds only the `default` mode. +- Each result lists the tokens that Paper has no place for, with the reason, and the number of requests made to Paper. +- The commands are also MCP tools of `cssforge mcp` and typed calls of `@hebilicious/cssforge/capabilities`. `sync.push` and `tokens.build` are marked destructive for MCP clients, and the read-only tools are marked read-only. +- `@acid-cat/core-ts` is updated to 0.15.0. diff --git a/README.md b/README.md index 033f696..59a17fb 100644 --- a/README.md +++ b/README.md @@ -2218,13 +2218,111 @@ Musea reads `value`, `type`, and `$reference` from this file. Keep the default ` mode: previews and token swatches render from `value`, and `attributes.tailwindVariable` is what lets Musea attribute a `var(--token)` written in an art file back to its token. +## Sync tokens with a design tool + +`cssforge` keeps the tokens of a design file in sync with the configuration. The +configuration is the source of truth: the tokens it generates are pushed to the file, and +what designers change in the file waits in an inbox until you decide what to do with it. +[Paper](https://paper.design) is the first supported design tool; its desktop app serves the +MCP server that `cssforge` talks to (`paper-design mcp`). Each design tool is an adapter +behind the same commands, so others (Figma) can follow. + +```bash +# Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. +cssforge sync remote add --file https://app.paper.design/file/ + +# Read the file and show the plan, without changing it (one request) +cssforge sync fetch + +# Show the plan again after a change of the config or a decision (no request) +cssforge sync plan + +# Send the plan: create, update and delete tokens, and carry out the decisions +cssforge sync push +cssforge sync push --dry-run + +# The changes designers made in the file +cssforge sync inbox list + +# A token a designer created: add it to the config first, then adopt it under that path. +# The path is the token path, as each pushed token shows it in its description +# (`cssforge: palette.brand.accent`). The next push renames the token in the file to the +# name the config generates. +cssforge sync inbox adopt --item brand-accent --path palette.brand.accent +# Or delete it from the file at the next push +cssforge sync inbox reject --item brand-accent + +# A token of the config that a designer changed or deleted: the next push writes the +# config's value again. To keep the designer's value, change the config instead. +cssforge sync inbox overwrite --item spacing-size-1 +``` + +Commit `.cssforge/sync/.json`: it holds the target (the file, its modes and the +options), the tokens as they were after the last push with the key the design tool gave each +one, and the decisions, so everyone who syncs shares the same base. `--remote ` selects +another remote (the default is `paper`), and `sync remote add --name ` binds one. +`sync remote add --options '{"collection":"Tokens"}'` passes options to the kind of remote; +Paper takes none. + +### Modes + +A design tool can hold a value for each mode of a token, as a Figma collection does. Sync +gives each token one value per mode: + +| Token in the config | Mode | +| --- | --- | +| At `:root` | `default` | +| A `light-dark(light, dark)` value at `:root`, or a value built from one (a mix of a paired color) | `light` and `dark`, each with its own branch of every `light-dark()` | +| Under a selector or an at-rule, e.g. a theme with `selector: ".dark"` | The selector or at-rule: `.dark` | + +Tokens with the same custom property in several scopes (themes with `variantNameOnly`) are one +token with a value for each of its modes. The target says which modes it holds; a mode it does +not hold is listed in `skipped` with the mode. Paper holds only `default`. + +A token is identified by its custom property in the config and by its key in the design tool: +the name on Paper, an id on a tool that has ids. A designer who renames a token on such a tool +keeps its link to the config. + +| Inbox item | What happened in the file | Decisions | +| --- | --- | --- | +| `new` | A designer created a token that the config does not have | `adopt`, `reject` | +| `edited` | A designer changed the value of a config token | `overwrite` | +| `deleted` | A designer deleted a config token | `overwrite` | +| `collision` | The file has a token with the name of a new config token | `overwrite` | + +When `sync push` renames a token (after `sync inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `sync inbox reject`, or because the token left the +config), Paper replaces each use with the token's last value, so designs keep their look but +lose the link to the token. + +An item without a decision blocks only its own token: `sync push` sends every other change. A +change that the file refuses stays in the plan, and the next push sends it again. Each result +has `callsUsed`, the number of requests made to the design tool, because Paper's free plan +limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored +values back once; with nothing to send, it makes one request. + +Not every token has a place in Paper. Each result lists the tokens it leaves out in `skipped`, +with the reason: + +| Token | In Paper | +| --- | --- | +| Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | +| A token whose value is `var(--other)` | An alias of the other token, when both have the same type | +| Mixed colors (`color-mix()`) | Left out: Paper does not take these values | +| Paired themes (`light-dark()`) and tokens under a selector or an at-rule | Left out: Paper holds only the `default` mode | +| The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | +| Motion, gradients and primitives without a Paper type | Left out | + ## Agentic usage Agents can run the `cssforge` CLI like any other command: an agent gets JSON (`--agent` forces it), and `cssforge list` describes every command and its flags. `cssforge mcp` serves the same commands as MCP tools, through standard input and output: -`tokens.build`, `tokens.generate` and `config.check`, and the event `tokens.built`. Paths +`tokens.build`, `tokens.generate`, `config.check`, the [sync](#sync-tokens-with-a-design-tool) +tools (`sync.fetch`, `sync.push`, `sync.inbox.adopt`, …), and the event `tokens.built`. Each +tool tells the agent whether it changes anything: `sync.push` is marked destructive, so a client +can ask before it runs. Paths resolve against the directory where the agent starts the server, or against the `root` of a call. To add it to Claude Code: diff --git a/packages/cssforge/README.md b/packages/cssforge/README.md index 033f696..59a17fb 100644 --- a/packages/cssforge/README.md +++ b/packages/cssforge/README.md @@ -2218,13 +2218,111 @@ Musea reads `value`, `type`, and `$reference` from this file. Keep the default ` mode: previews and token swatches render from `value`, and `attributes.tailwindVariable` is what lets Musea attribute a `var(--token)` written in an art file back to its token. +## Sync tokens with a design tool + +`cssforge` keeps the tokens of a design file in sync with the configuration. The +configuration is the source of truth: the tokens it generates are pushed to the file, and +what designers change in the file waits in an inbox until you decide what to do with it. +[Paper](https://paper.design) is the first supported design tool; its desktop app serves the +MCP server that `cssforge` talks to (`paper-design mcp`). Each design tool is an adapter +behind the same commands, so others (Figma) can follow. + +```bash +# Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. +cssforge sync remote add --file https://app.paper.design/file/ + +# Read the file and show the plan, without changing it (one request) +cssforge sync fetch + +# Show the plan again after a change of the config or a decision (no request) +cssforge sync plan + +# Send the plan: create, update and delete tokens, and carry out the decisions +cssforge sync push +cssforge sync push --dry-run + +# The changes designers made in the file +cssforge sync inbox list + +# A token a designer created: add it to the config first, then adopt it under that path. +# The path is the token path, as each pushed token shows it in its description +# (`cssforge: palette.brand.accent`). The next push renames the token in the file to the +# name the config generates. +cssforge sync inbox adopt --item brand-accent --path palette.brand.accent +# Or delete it from the file at the next push +cssforge sync inbox reject --item brand-accent + +# A token of the config that a designer changed or deleted: the next push writes the +# config's value again. To keep the designer's value, change the config instead. +cssforge sync inbox overwrite --item spacing-size-1 +``` + +Commit `.cssforge/sync/.json`: it holds the target (the file, its modes and the +options), the tokens as they were after the last push with the key the design tool gave each +one, and the decisions, so everyone who syncs shares the same base. `--remote ` selects +another remote (the default is `paper`), and `sync remote add --name ` binds one. +`sync remote add --options '{"collection":"Tokens"}'` passes options to the kind of remote; +Paper takes none. + +### Modes + +A design tool can hold a value for each mode of a token, as a Figma collection does. Sync +gives each token one value per mode: + +| Token in the config | Mode | +| --- | --- | +| At `:root` | `default` | +| A `light-dark(light, dark)` value at `:root`, or a value built from one (a mix of a paired color) | `light` and `dark`, each with its own branch of every `light-dark()` | +| Under a selector or an at-rule, e.g. a theme with `selector: ".dark"` | The selector or at-rule: `.dark` | + +Tokens with the same custom property in several scopes (themes with `variantNameOnly`) are one +token with a value for each of its modes. The target says which modes it holds; a mode it does +not hold is listed in `skipped` with the mode. Paper holds only `default`. + +A token is identified by its custom property in the config and by its key in the design tool: +the name on Paper, an id on a tool that has ids. A designer who renames a token on such a tool +keeps its link to the config. + +| Inbox item | What happened in the file | Decisions | +| --- | --- | --- | +| `new` | A designer created a token that the config does not have | `adopt`, `reject` | +| `edited` | A designer changed the value of a config token | `overwrite` | +| `deleted` | A designer deleted a config token | `overwrite` | +| `collision` | The file has a token with the name of a new config token | `overwrite` | + +When `sync push` renames a token (after `sync inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `sync inbox reject`, or because the token left the +config), Paper replaces each use with the token's last value, so designs keep their look but +lose the link to the token. + +An item without a decision blocks only its own token: `sync push` sends every other change. A +change that the file refuses stays in the plan, and the next push sends it again. Each result +has `callsUsed`, the number of requests made to the design tool, because Paper's free plan +limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored +values back once; with nothing to send, it makes one request. + +Not every token has a place in Paper. Each result lists the tokens it leaves out in `skipped`, +with the reason: + +| Token | In Paper | +| --- | --- | +| Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | +| A token whose value is `var(--other)` | An alias of the other token, when both have the same type | +| Mixed colors (`color-mix()`) | Left out: Paper does not take these values | +| Paired themes (`light-dark()`) and tokens under a selector or an at-rule | Left out: Paper holds only the `default` mode | +| The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | +| Motion, gradients and primitives without a Paper type | Left out | + ## Agentic usage Agents can run the `cssforge` CLI like any other command: an agent gets JSON (`--agent` forces it), and `cssforge list` describes every command and its flags. `cssforge mcp` serves the same commands as MCP tools, through standard input and output: -`tokens.build`, `tokens.generate` and `config.check`, and the event `tokens.built`. Paths +`tokens.build`, `tokens.generate`, `config.check`, the [sync](#sync-tokens-with-a-design-tool) +tools (`sync.fetch`, `sync.push`, `sync.inbox.adopt`, …), and the event `tokens.built`. Each +tool tells the agent whether it changes anything: `sync.push` is marked destructive, so a client +can ask before it runs. Paths resolve against the directory where the agent starts the server, or against the `root` of a call. To add it to Claude Code: diff --git a/packages/cssforge/cssforge.acidcat.json b/packages/cssforge/cssforge.acidcat.json index 536957a..6193c8d 100644 --- a/packages/cssforge/cssforge.acidcat.json +++ b/packages/cssforge/cssforge.acidcat.json @@ -1,7 +1,7 @@ { "acidcat": "0.1", "title": "CSS Forge", - "description": "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration.", + "description": "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration, and keep the tokens of a design tool in sync with it.", "targets": { "cli": { "bindings": [ @@ -181,6 +181,3364 @@ }, "readOnly": true }, + "sync.fetch": { + "description": "Read the tokens of the remote (one request), record them in the state file, and report the plan: the changes the next push sends, the inbox of changes the remote made, and the configuration tokens that have no place on the remote. Sends nothing to the remote.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote, which addresses a remote token by its key.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "key", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "key", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "key", + "label" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" + } + }, + "required": [ + "remote", + "target", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteUnavailable": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.adopt": { + "description": "Adopt a token that the remote created: first add it to the configuration at a path of your choice, then record that path here. The next push renames the remote token to the name the configuration generates, and sets the value of the configuration, so designs that use the token keep it. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", + "minLength": 1, + "type": "string" + }, + "path": { + "description": "The token path of the configuration token that the item becomes, added to the configuration before this call, e.g. palette.brand.accent. It is the path in the description of each pushed token (cssforge: ).", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item", + "path" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.list": { + "description": "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `sync inbox adopt` (after adding it to the configuration) or `sync inbox reject`, and the others with `sync inbox overwrite`.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote, which addresses a remote token by its key.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "key", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "key", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "key", + "label" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" + } + }, + "required": [ + "remote", + "target", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "readOnly": true + }, + "sync.inbox.overwrite": { + "description": "Settle a token that the remote changed, deleted, or created with the name of a configuration token: the next push writes the value of the configuration. To keep the value of the remote instead, change the configuration to that value; the item then goes away at the next fetch. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.reject": { + "description": "Reject a token that the remote created: the next push deletes it from the remote. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + }, + "key": { + "type": "string" + } + }, + "required": [ + "item", + "key", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.plan": { + "description": "Report the plan against the tokens of the last fetch, with no request to the remote: the changes the next push sends, the inbox, and the configuration tokens that have no place on the remote. Use it after a change of the configuration or a decision.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote, which addresses a remote token by its key.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "key", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "key", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "key", + "label" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" + } + }, + "required": [ + "remote", + "target", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "readOnly": true + }, + "sync.push": { + "description": "Read the remote, then send the changes of the plan: create and update the tokens of the configuration, delete the ones removed from it, and carry out the decisions on inbox items. Items without a decision stay in the inbox, and their tokens are not changed. One request to read, up to two to write and one to read the stored values back; only the first when the plan is empty.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "dry-run": { + "default": false, + "description": "Read the remote and report the plan, but send nothing.", + "type": "boolean" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "applied": { + "description": "What the remote did with each operation. Empty for a dry run.", + "items": { + "additionalProperties": false, + "properties": { + "key": { + "description": "The key of the token after the operation.", + "type": "string" + }, + "message": { + "type": "string" + }, + "ok": { + "type": "boolean" + }, + "operation": { + "description": "A change to send to the remote, which addresses a remote token by its key.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "key", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "key", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "key", + "label" + ], + "type": "object" + } + ] + } + }, + "required": [ + "operation", + "ok" + ], + "type": "object" + }, + "type": "array" + }, + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "label": { + "description": "The name of the token on the remote.", + "type": "string" + }, + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "note": { + "type": "string" + }, + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "key", + "label", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote, which addresses a remote token by its key.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "op", + "key", + "name", + "type", + "values", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "key", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "key", + "label" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + "items": { + "additionalProperties": false, + "properties": { + "mode": { + "type": "string" + }, + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" + } + }, + "required": [ + "remote", + "target", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed", + "applied" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteUnavailable": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": true, + "idempotent": true + }, + "sync.remote.add": { + "description": "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file with the options (one request), and writes .cssforge/sync/.json. Binding the same file with the same options again keeps the sync state; binding another target starts the sync again.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "file": { + "description": "The file of the remote that the tokens sync with: its id or its URL.", + "minLength": 1, + "type": "string" + }, + "kind": { + "default": "paper", + "description": "The kind of remote, e.g. paper.", + "minLength": 1, + "type": "string" + }, + "name": { + "default": "paper", + "description": "The name of the remote, as `sync remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "default": {}, + "description": "The options of the kind of remote, as JSON, e.g. {\"collection\":\"Tokens\"}. Paper takes none.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "file" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "kind": { + "type": "string" + }, + "remote": { + "type": "string" + }, + "state": { + "description": "The absolute path of the state file.", + "type": "string" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" + } + }, + "required": [ + "remote", + "kind", + "target", + "state", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "InvalidOptions": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidOptions", + "description": "The kind of remote does not take the options.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteUnavailable": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownKind": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownKind", + "description": "The kind of remote is not known.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": true, + "idempotent": true + }, "tokens.build": { "description": "Generate the outputs of a CSS Forge configuration and write them to files: CSS custom properties, JSON, TypeScript and Style Dictionary tokens. Every output is generated before the first file is written, so an invalid configuration leaves the previous files in place. The result lists the files written and the warnings of the configuration.", "audience": [ @@ -412,7 +3770,9 @@ ], "type": "object" } - } + }, + "destructive": true, + "idempotent": true }, "tokens.generate": { "description": "Generate one output of a CSS Forge configuration and give it as text, with the warnings of the configuration. Writes no file.", diff --git a/packages/cssforge/jsr.json b/packages/cssforge/jsr.json index 96c4113..8814822 100644 --- a/packages/cssforge/jsr.json +++ b/packages/cssforge/jsr.json @@ -9,7 +9,7 @@ "./capabilities": "./src/capabilities.ts" }, "imports": { - "@acid-cat/core-ts": "npm:@acid-cat/core-ts@0.13.0", + "@acid-cat/core-ts": "npm:@acid-cat/core-ts@0.15.0", "chokidar": "npm:chokidar@4.0.3", "colorjs.io": "npm:colorjs.io@0.5.2", "utopia-core": "npm:utopia-core@1.6.0", diff --git a/packages/cssforge/package.json b/packages/cssforge/package.json index e42bdd3..e6ef295 100644 --- a/packages/cssforge/package.json +++ b/packages/cssforge/package.json @@ -46,14 +46,14 @@ "cssforge.acidcat.json" ], "dependencies": { - "@acid-cat/core-ts": "0.13.0", + "@acid-cat/core-ts": "0.15.0", "chokidar": "4.0.3", "colorjs.io": "0.5.2", "utopia-core": "1.6.0", "zod": "4.6.7" }, "devDependencies": { - "@acid-cat/cli": "0.13.0", + "@acid-cat/cli": "0.15.0", "@biomejs/biome": "2.4.2", "@types/node": "24.3.0", "mdbox": "0.1.1", diff --git a/packages/cssforge/src/capabilities.ts b/packages/cssforge/src/capabilities.ts index ffcfd79..add4fc2 100644 --- a/packages/cssforge/src/capabilities.ts +++ b/packages/cssforge/src/capabilities.ts @@ -65,6 +65,8 @@ import { } from "./forge.ts"; import { type ColorFormat, diagnosticCodes } from "./lib.ts"; import { supportedColorFormats } from "./modules/colors.ts"; +import { syncCapabilities } from "./sync/capabilities.ts"; +import type { RemoteAdapter } from "./sync/remote.ts"; /** * `createSession` opens a session on {@link cssforge}, for typed calls from @@ -73,6 +75,27 @@ import { supportedColorFormats } from "./modules/colors.ts"; * cancellation or a defect. */ export { CallFailureError, createSession } from "@acid-cat/core-ts"; +export type { ListedToken, TokenKind } from "./generator.ts"; +export * from "./sync/capabilities.ts"; +export { type PaperOptions, paperAdapter } from "./sync/paper.ts"; +export type { + BaseEntry, + Decision, + InboxItem, + ModeValues, + Operation, + RemoteToken, +} from "./sync/plan.ts"; +export { DEFAULT_MODE } from "./sync/plan.ts"; +export type { + ApplyResult, + RemoteAdapter, + RemoteOptions, + RemoteSession, + RemoteTarget, + TokenMapping, +} from "./sync/remote.ts"; +export { RemoteError } from "./sync/remote.ts"; /** The JSON Schema of a schema of {@link cssforge}, for the catalog and the bindings. */ export const toJsonSchema: ToJsonSchema = (schema) => { @@ -86,6 +109,8 @@ export const toJsonSchema: ToJsonSchema = (schema) => { export interface ForgeContext { /** The directory that relative paths resolve against, when an input gives no `root`. */ cwd: string; + /** The remotes that token sync knows. The default is the Paper remote. */ + remotes?: readonly RemoteAdapter[]; } // --- Schemas ------------------------------------------------------------------------------- @@ -354,6 +379,8 @@ export const tokensBuild: Capability< description: "Generate the outputs of a CSS Forge configuration and write them to files: CSS custom properties, JSON, TypeScript and Style Dictionary tokens. Every output is generated before the first file is written, so an invalid configuration leaves the previous files in place. The result lists the files written and the warnings of the configuration.", audience: everyone, + destructive: true, + idempotent: true, input: buildInput, output: buildReport, failures: buildFailures, @@ -450,7 +477,7 @@ export const tokensBuilt: EventDefinition< export const cssforge: App = defineApp({ title: "CSS Forge", description: - "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration.", + "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration, and keep the tokens of a design tool in sync with it.", targets: { cli: { bindings: ["cli"], @@ -474,6 +501,6 @@ export const cssforge: App = defineApp({ description: "Typed calls from code, through @hebilicious/cssforge/capabilities.", }, }, - capabilities: [tokensBuild, tokensGenerate, configCheck], + capabilities: [tokensBuild, tokensGenerate, configCheck, ...syncCapabilities], events: [tokensBuilt], }); diff --git a/packages/cssforge/src/forge.ts b/packages/cssforge/src/forge.ts index 23f626b..fb01fbe 100644 --- a/packages/cssforge/src/forge.ts +++ b/packages/cssforge/src/forge.ts @@ -19,6 +19,8 @@ import { generateStyleDictionaryJSON, generateTS, getDiagnostics, + type ListedToken, + listTokens, } from "./generator.ts"; import type { ColorFormat, Diagnostic, GenerateOptions } from "./lib.ts"; import { type LoadedConfig, loadConfig } from "./loader.ts"; @@ -182,6 +184,12 @@ export async function generateOutput( })); } +/** Lists the tokens of the configuration at `configPath`, for token sync. Writes nothing. */ +export async function listConfigTokens(configPath: string): Promise { + const { config, dependencies } = await loadForgeConfig(configPath); + return generating(configPath, dependencies, () => listTokens(config)); +} + /** * Writes a file, creating its parent directory first. The parent comes from the * platform-aware `dirname` of `node:path`, so `C:\project\.cssforge\output.css` diff --git a/packages/cssforge/src/generator.ts b/packages/cssforge/src/generator.ts index 94a0677..5989a95 100644 --- a/packages/cssforge/src/generator.ts +++ b/packages/cssforge/src/generator.ts @@ -508,6 +508,55 @@ export function generateStyleDictionaryJSON( return JSON.stringify(styleDictionaryValues, null, 2); } +/** The kind of a token, as the Style Dictionary output and token sync infer it. */ +export type TokenKind = StyleDictionaryTokenType; + +/** One generated custom property, as token sync reads it. */ +export interface ListedToken { + /** The custom property name, e.g. `--color-red-100`. */ + name: string; + /** The CSS value as generated. It may contain `var(...)` references. */ + value: string; + /** The value with every reference to another token of the configuration substituted. */ + resolvedValue: string; + /** The kind inferred from the path and the resolved value. */ + kind: TokenKind; + /** The configuration path of the token. */ + sourcePath: string; + /** The CSS scope it is emitted into: `:root`, or the wrapper chain of a selector or an at-rule. */ + scope: string; +} + +/** + * Lists every custom property of a configuration in output order, with its + * resolved value and inferred kind, for tools that copy tokens elsewhere. + * @example + * ```ts + * const [token] = listTokens({ spacing: { size: { value: { 1: "4px" } } } }); + * // token.name: "--spacing-size-1", token.kind: "spacing" + * ``` + */ +export function listTokens( + config: Partial, + options: GenerateOptions = {}, +): ListedToken[] { + const resolveMap = collectResolveMap(config, options); + const tokensByCssVariable = new Map( + [...resolveMap.values()].map((token) => [token.key, token]), + ); + return [...resolveMap.values()].map((token) => { + const resolvedValue = resolveTokenValue(token, tokensByCssVariable); + return { + name: token.key, + value: token.value, + resolvedValue, + kind: inferValueKind(token.sourcePath, resolvedValue, token.type), + sourcePath: token.sourcePath, + scope: getTokenScope(token), + }; + }); +} + /** * Generates a JSON string from the CSSForge configuration. * This can be used to create a JSON file with all the design tokens. diff --git a/packages/cssforge/src/lib.ts b/packages/cssforge/src/lib.ts index d553ea8..b1d2395 100644 --- a/packages/cssforge/src/lib.ts +++ b/packages/cssforge/src/lib.ts @@ -66,6 +66,27 @@ export interface TokenMetadata { */ export const ROOT_SCOPE = ":root"; +/** The wrappers of a scope: an at-rule, a selector, or both. An empty string is no wrapper. */ +export interface ScopeParts { + atRule: string; + selector: string; +} + +/** + * The scope of a declaration under `atRule` and `selector`. Both are kept whole, in a form + * that never confuses them: a selector may contain any character, `|` included + * (`[lang|=en]`). No wrapper gives `ROOT_SCOPE`. + */ +export const scopeOf = ({ atRule, selector }: ScopeParts): string => + !atRule && !selector ? ROOT_SCOPE : JSON.stringify([atRule, selector]); + +/** The wrappers of a scope that {@link scopeOf} made. `ROOT_SCOPE` has none. */ +export const scopeParts = (scope: string): ScopeParts => { + if (scope === ROOT_SCOPE) return { atRule: "", selector: "" }; + const [atRule, selector] = JSON.parse(scope) as [string, string]; + return { atRule, selector }; +}; + export interface ResolvedToken extends TokenMetadata { /** CSS custom property name, e.g. `--theme-light-content-primary`. */ key: string; diff --git a/packages/cssforge/src/modules/colors.ts b/packages/cssforge/src/modules/colors.ts index 7536898..9a1edb8 100644 --- a/packages/cssforge/src/modules/colors.ts +++ b/packages/cssforge/src/modules/colors.ts @@ -24,6 +24,7 @@ import { ROOT_SCOPE, resolveValue, resolveVariable, + scopeOf, withTokenScope, } from "../lib.ts"; @@ -48,8 +49,7 @@ const describeScope = (settings: WithCondition | undefined): string => { const { atRule, selector } = readCondition(settings); const scopedSelector = selector === ROOT_SCOPE ? "" : selector; - if (!atRule && !scopedSelector) return ROOT_SCOPE; - return `${atRule}|${scopedSelector}`; + return scopeOf({ atRule, selector: scopedSelector }); }; type ExactlyOne = { diff --git a/packages/cssforge/src/sync/capabilities.ts b/packages/cssforge/src/sync/capabilities.ts new file mode 100644 index 0000000..e2e14e7 --- /dev/null +++ b/packages/cssforge/src/sync/capabilities.ts @@ -0,0 +1,1027 @@ +/** + * The token sync capabilities: they keep the tokens of a design tool (a remote) in sync + * with a CSS Forge configuration. The configuration is the source of truth. What the + * remote changes waits in an inbox until a decision settles it. + * + * @module + */ + +import { resolve } from "node:path"; +import type { Capability, Result } from "@acid-cat/core-ts"; +import { capabilitiesFor, fail, ok } from "@acid-cat/core-ts"; +import { z } from "zod"; +import type { ForgeContext } from "../capabilities.ts"; +import { defaultConfigPath, ForgeError, listConfigTokens } from "../forge.ts"; +import { desiredTokens, type SkippedToken } from "./modes.ts"; +import { paperAdapter } from "./paper.ts"; +import { + type BaseEntry, + type Decision, + type DesiredToken, + type InboxItem, + type Operation, + planSync, + type RemoteToken, + type SyncPlan, +} from "./plan.ts"; +import { + type ApplyResult, + type RemoteAdapter, + RemoteError, + type RemoteOptions, + type RemoteSession, + type RemoteTarget, +} from "./remote.ts"; +import { + REMOTE_NAME, + readState, + StateError, + type SyncState, + statePath, + writeState, +} from "./state.ts"; + +// --- Types --------------------------------------------------------------------------------- + +/** The members of every sync input, with the defaults filled in. */ +export interface SyncInput { + config: string; + root?: string; + remote: string; +} + +/** The input of `sync.remote.add`. */ +export interface RemoteAddInput { + root?: string; + name: string; + kind: string; + file: string; + options: RemoteOptions; +} + +/** The input of `sync.push`. */ +export interface PushInput extends SyncInput { + "dry-run": boolean; +} + +/** The input of `sync.inbox.adopt`. */ +export interface AdoptInput extends SyncInput { + item: string; + path: string; +} + +/** The input of `sync.inbox.reject` and `sync.inbox.overwrite`. */ +export interface ItemInput extends SyncInput { + item: string; +} + +export type { SkippedToken }; + +/** The plan of a sync, as the capabilities report it. */ +export interface SyncReport { + remote: string; + target: RemoteTarget; + /** When the remote tokens were read. */ + fetchedAt: string; + /** The changes the next push sends. */ + operations: Operation[]; + inbox: InboxItem[]; + skipped: SkippedToken[]; + /** The requests made to the remote by this call. */ + callsUsed: number; +} + +/** The report of `sync.push`. */ +export interface PushReport extends SyncReport { + /** What the remote did with each operation. Empty for a dry run. */ + applied: ApplyResult[]; +} + +/** The report of `sync.remote.add`. */ +export interface RemoteAddReport { + remote: string; + kind: string; + target: RemoteTarget; + /** The absolute path of the state file. */ + state: string; + callsUsed: number; +} + +/** The report of a decision. */ +export interface DecisionReport { + remote: string; + decision: Decision; + /** The items that still wait for a decision. */ + inbox: InboxItem[]; + skipped: SkippedToken[]; + /** The requests made to the remote by this call: always 0. */ + callsUsed: number; +} + +/** A failure of a sync capability. */ +export interface SyncFailure { + _tag: Tag; + message: string; + /** The file that the failure concerns. */ + path?: string; +} + +type ReadTags = + | "ConfigLoadFailed" + | "InvalidConfig" + | "RemoteNotConfigured" + | "InvalidState"; +type RemoteTags = "RemoteUnavailable" | "RemoteFailed"; + +/** The failures of the capabilities that read the configuration and the state. */ +export type SyncReadFailures = { [Tag in ReadTags]: SyncFailure }; +/** The failures of the capabilities that also call the remote. */ +export type SyncRemoteFailures = SyncReadFailures & { + [Tag in RemoteTags]: SyncFailure; +}; +/** The failures of `sync.plan` and `sync.inbox.list`. */ +export type SyncPlanFailures = SyncReadFailures & { + NotFetched: SyncFailure<"NotFetched">; +}; +/** The failures of `sync.remote.add`. */ +export type RemoteAddFailures = { + [Tag in RemoteTags | "UnknownKind" | "InvalidOptions"]: SyncFailure; +}; +/** The failures of a decision. */ +export type DecisionFailures = SyncPlanFailures & { + UnknownItem: SyncFailure<"UnknownItem">; + InvalidDecision: SyncFailure<"InvalidDecision">; +}; + +// --- Schemas ------------------------------------------------------------------------------- + +const rootSchema = z + .string() + .min(1) + .optional() + .describe( + "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + ); + +const remoteSchema = z + .string() + .regex(REMOTE_NAME, "A remote name is lowercase words joined by hyphens, e.g. paper.") + .default("paper") + .describe("The name of the remote, as `sync remote add --name` gave it."); + +const syncShape = { + config: z + .string() + .min(1) + .default(defaultConfigPath) + .describe("The path of the configuration file."), + root: rootSchema, + remote: remoteSchema, +}; + +const itemSchema = z + .string() + .min(1) + .describe( + "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", + ); + +const syncInput = z.strictObject(syncShape); +const pushInput = z.strictObject({ + ...syncShape, + "dry-run": z + .boolean() + .default(false) + .describe("Read the remote and report the plan, but send nothing."), +}); +const adoptInput = z.strictObject({ + ...syncShape, + item: itemSchema, + path: z + .string() + .min(1) + .describe( + "The token path of the configuration token that the item becomes, added to the configuration before this call, e.g. palette.brand.accent. It is the path in the description of each pushed token (cssforge: ).", + ), +}); +const itemInput = z.strictObject({ ...syncShape, item: itemSchema }); +const remoteAddInput = z.strictObject({ + root: rootSchema, + name: remoteSchema, + kind: z.string().min(1).default("paper").describe("The kind of remote, e.g. paper."), + file: z + .string() + .min(1) + .describe("The file of the remote that the tokens sync with: its id or its URL."), + options: z + .record(z.string(), z.string()) + .default({}) + .describe( + 'The options of the kind of remote, as JSON, e.g. {"collection":"Tokens"}. Paper takes none.', + ), +}); + +const modeValuesSchema = z + .record(z.string(), z.string()) + .describe("A value for each mode: default for :root, light and dark, or a selector."); + +const targetSchema = z + .strictObject({ + file: z.string().describe("The id of the file on the remote."), + fileName: z.string(), + modes: z.array(z.string()).describe("The modes the target holds."), + options: z.record(z.string(), z.string()), + }) + .describe("The part of the remote the tokens sync with."); + +const operationSchema = z + .discriminatedUnion("op", [ + z.strictObject({ + op: z.literal("create"), + name: z.string(), + type: z.string(), + values: modeValuesSchema, + description: z.string(), + }), + z.strictObject({ + op: z.literal("update"), + key: z.string(), + name: z.string(), + type: z.string(), + values: modeValuesSchema, + description: z.string(), + }), + z.strictObject({ + op: z.literal("rename"), + key: z.string(), + from: z.string(), + to: z.string(), + }), + z.strictObject({ op: z.literal("delete"), key: z.string(), label: z.string() }), + ]) + .describe("A change to send to the remote, which addresses a remote token by its key."); + +const decisionSchema = z.discriminatedUnion("action", [ + z.strictObject({ + item: z.string(), + key: z.string(), + action: z.literal("adopt"), + path: z.string(), + }), + z.strictObject({ item: z.string(), key: z.string(), action: z.literal("reject") }), + z.strictObject({ item: z.string(), key: z.string(), action: z.literal("overwrite") }), +]); + +const inboxItemSchema = z + .strictObject({ + id: z.string(), + kind: z.enum(["new", "edited", "deleted", "collision"]), + key: z + .string() + .describe("The key of the token on the remote, or the key a deleted token had."), + label: z.string().describe("The name of the token on the remote."), + type: z.string(), + remoteValues: modeValuesSchema.optional(), + localValues: modeValuesSchema.optional(), + actions: z.array(z.enum(["adopt", "reject", "overwrite"])), + note: z.string().optional(), + }) + .describe( + "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + ); + +const reportShape = { + remote: z.string(), + target: targetSchema, + fetchedAt: z + .string() + .describe("When the remote tokens were read, as an ISO 8601 time."), + operations: z + .array(operationSchema) + .describe("The changes the next push sends, in order."), + inbox: z.array(inboxItemSchema), + skipped: z + .array( + z.strictObject({ + name: z.string(), + sourcePath: z.string(), + mode: z.string().optional(), + reason: z.string(), + }), + ) + .describe( + "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + ), + callsUsed: z.number().int().describe("The requests made to the remote by this call."), +}; + +const syncReport = z.strictObject(reportShape); +const pushReport = z.strictObject({ + ...reportShape, + applied: z + .array( + z.strictObject({ + operation: operationSchema, + ok: z.boolean(), + message: z.string().optional(), + key: z.string().optional().describe("The key of the token after the operation."), + }), + ) + .describe("What the remote did with each operation. Empty for a dry run."), +}); +const remoteAddReport = z.strictObject({ + remote: z.string(), + kind: z.string(), + target: targetSchema, + state: z.string().describe("The absolute path of the state file."), + callsUsed: z.number().int(), +}); +const decisionReport = z.strictObject({ + remote: z.string(), + decision: decisionSchema, + inbox: z.array(inboxItemSchema).describe("The items that still wait for a decision."), + skipped: reportShape.skipped, + callsUsed: z + .number() + .int() + .describe("The requests made to the remote by this call: always 0."), +}); + +const failureSchema = (tag: Tag, description: string) => + z.strictObject({ + _tag: z.literal(tag).describe(description), + message: z.string(), + path: z.string().optional().describe("The file that the failure concerns."), + }); + +const readFailures = { + ConfigLoadFailed: failureSchema( + "ConfigLoadFailed", + "The configuration file could not be found or evaluated.", + ), + InvalidConfig: failureSchema( + "InvalidConfig", + "CSS Forge rejects a value of the configuration.", + ), + RemoteNotConfigured: failureSchema( + "RemoteNotConfigured", + "The remote has no state file: add it with `cssforge sync remote add`.", + ), + InvalidState: failureSchema( + "InvalidState", + "The state file of the remote is not valid.", + ), +}; +const remoteFailures = { + RemoteUnavailable: failureSchema( + "RemoteUnavailable", + "The remote cannot be reached: its program is not installed or not running.", + ), + RemoteFailed: failureSchema( + "RemoteFailed", + "The remote refused a request or answered in an unknown form.", + ), +}; +const notFetched = { + NotFetched: failureSchema( + "NotFetched", + "The remote has not been read yet: run `cssforge sync fetch` first.", + ), +}; +const decisionFailures = { + ...readFailures, + ...notFetched, + UnknownItem: failureSchema("UnknownItem", "The inbox has no item with this id."), + InvalidDecision: failureSchema( + "InvalidDecision", + "The decision does not settle the item, or the adopted path does not fit.", + ), +}; + +// --- Operations ---------------------------------------------------------------------------- + +/** The adapters a context gives, or the Paper adapter. */ +const adaptersOf = (context: ForgeContext): readonly RemoteAdapter[] => + context.remotes ?? [paperAdapter()]; + +const rootOf = (context: ForgeContext, input: { root?: string }) => + resolve(context.cwd, input.root ?? "."); + +/** A failure of a sync operation, before it becomes a typed failure. */ +class SyncError extends Error { + readonly tag: string; + + constructor(tag: string, message: string) { + super(message); + this.name = "SyncError"; + this.tag = tag; + } +} + +/** Runs an operation, and gives every known error as a failure. Other errors are defects. */ +async function attempt( + operation: () => Promise, +): Promise> { + try { + return ok(await operation()); + } catch (error) { + if ( + error instanceof ForgeError || + error instanceof StateError || + error instanceof RemoteError || + error instanceof SyncError + ) { + const path = + "path" in error && typeof error.path === "string" ? error.path : undefined; + const failure = { + _tag: error.tag, + message: error.message, + ...(path === undefined ? {} : { path }), + }; + // The tag is only known at run time. Each capability declares every tag its + // operation can throw in its failures schema, and the session validates the + // failure against that schema. + return fail(failure as unknown as Failure); + } + throw error; + } +} + +const adapterOf = (context: ForgeContext, kind: string): RemoteAdapter => { + const adapter = adaptersOf(context).find((candidate) => candidate.kind === kind); + if (!adapter) { + const kinds = adaptersOf(context).map((candidate) => candidate.kind); + throw new SyncError( + "UnknownKind", + `There is no remote kind "${kind}". Known kinds: ${kinds.join(", ")}.`, + ); + } + return adapter; +}; + +interface Loaded { + root: string; + state: SyncState; + adapter: RemoteAdapter; + desired: DesiredToken[]; + skipped: SkippedToken[]; +} + +async function load(context: ForgeContext, input: SyncInput): Promise { + const root = rootOf(context, input); + const state = await readState(root, input.remote); + const adapter = adaptersOf(context).find((candidate) => candidate.kind === state.kind); + if (!adapter) { + throw new StateError( + "InvalidState", + `The state file names the remote kind "${state.kind}", which this version of cssforge does not know.`, + statePath(root, input.remote), + ); + } + const tokens = await listConfigTokens(resolve(root, input.config)); + return { root, state, adapter, ...desiredTokens(tokens, adapter, state.target.modes) }; +} + +const fetchedOf = (state: SyncState, remote: string) => { + if (state.fetched === null) { + throw new SyncError( + "NotFetched", + `The remote "${remote}" has not been read yet. Run \`cssforge sync fetch --remote ${remote}\`.`, + ); + } + return state.fetched; +}; + +const planOf = (loaded: Loaded, remote: readonly RemoteToken[]): SyncPlan => + planSync({ + desired: loaded.desired, + skipped: skippedNames(loaded), + remote, + base: loaded.state.base, + decisions: loaded.state.decisions, + }); + +/** The configuration tokens that have no mode on the remote at all. */ +const skippedNames = (loaded: Loaded): Set => { + const desired = new Set(loaded.desired.map((token) => token.name)); + return new Set( + loaded.skipped.flatMap((token) => (desired.has(token.name) ? [] : [token.name])), + ); +}; + +const reportOf = ( + input: SyncInput, + loaded: Loaded, + plan: SyncPlan, + fetchedAt: string, + callsUsed: number, +): SyncReport => ({ + remote: input.remote, + target: loaded.state.target, + fetchedAt, + operations: plan.operations.map((planned) => planned.operation), + inbox: plan.inbox, + skipped: loaded.skipped, + callsUsed, +}); + +/** Opens a session on the remote, runs `use`, and closes the session. */ +async function withSession( + adapter: RemoteAdapter, + signal: AbortSignal, + use: (session: RemoteSession) => Promise, +): Promise { + const session = await adapter.open(signal); + try { + return await use(session); + } finally { + session.close(); + } +} + +/** Reads the remote and records the fetch in the state. */ +async function fetchRemote(loaded: Loaded, session: RemoteSession, remote: string) { + const tokens = await session.read(loaded.state.target); + const fetched = { at: new Date().toISOString(), tokens }; + loaded.state = { ...loaded.state, fetched }; + await writeState(loaded.root, remote, loaded.state); + return fetched; +} + +/** The plan against the last fetch, with no request to the remote. */ +const planFromFetch = (input: SyncInput, context: ForgeContext) => + attempt(async () => { + const loaded = await load(context, input); + const fetched = fetchedOf(loaded.state, input.remote); + return reportOf(input, loaded, planOf(loaded, fetched.tokens), fetched.at, 0); + }); + +// --- Capabilities ---------------------------------------------------------------------------- + +const capability = capabilitiesFor(); +const everyone = ["cli", "mcp", "library"]; + +/** `cssforge sync remote add`: bind a remote file to the configuration. */ +export const syncRemoteAdd: Capability< + ForgeContext, + RemoteAddInput, + RemoteAddReport, + RemoteAddFailures, + never, + "sync.remote.add", + Partial +> = capability({ + id: "sync.remote.add", + description: + "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file with the options (one request), and writes .cssforge/sync/.json. Binding the same file with the same options again keeps the sync state; binding another target starts the sync again.", + audience: everyone, + destructive: true, + idempotent: true, + input: remoteAddInput, + output: remoteAddReport, + failures: { + ...remoteFailures, + UnknownKind: failureSchema("UnknownKind", "The kind of remote is not known."), + InvalidOptions: failureSchema( + "InvalidOptions", + "The kind of remote does not take the options.", + ), + }, + run: (input, { context, signal }) => + attempt(async () => { + const root = rootOf(context, input); + const adapter = adapterOf(context, input.kind); + adapter.checkOptions(input.options); + return withSession(adapter, signal, async (session) => { + const target = await session.resolve(input.file, input.options); + const previous = await readState(root, input.name).catch(() => undefined); + const kept = + previous?.kind === input.kind && sameTarget(previous.target, target) + ? previous + : undefined; + const state: SyncState = kept + ? { ...kept, target } + : { + version: 1, + kind: input.kind, + target, + base: [], + fetched: null, + decisions: [], + }; + const path = await writeState(root, input.name, state); + return { + remote: input.name, + kind: input.kind, + target, + state: path, + callsUsed: session.calls, + }; + }); + }), +}); + +/** `cssforge sync fetch`: read the remote and report the plan. */ +export const syncFetch: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncRemoteFailures, + never, + "sync.fetch", + Partial +> = capability({ + id: "sync.fetch", + description: + "Read the tokens of the remote (one request), record them in the state file, and report the plan: the changes the next push sends, the inbox of changes the remote made, and the configuration tokens that have no place on the remote. Sends nothing to the remote.", + audience: everyone, + destructive: false, + idempotent: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...remoteFailures }, + run: (input, { context, signal }) => + attempt(async () => { + const loaded = await load(context, input); + return withSession(loaded.adapter, signal, async (session) => { + const fetched = await fetchRemote(loaded, session, input.remote); + return reportOf( + input, + loaded, + planOf(loaded, fetched.tokens), + fetched.at, + session.calls, + ); + }); + }), +}); + +/** `cssforge sync plan`: the plan against the last fetch, with no request. */ +export const syncPlan: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncPlanFailures, + never, + "sync.plan", + Partial +> = capability({ + id: "sync.plan", + description: + "Report the plan against the tokens of the last fetch, with no request to the remote: the changes the next push sends, the inbox, and the configuration tokens that have no place on the remote. Use it after a change of the configuration or a decision.", + audience: everyone, + readOnly: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...notFetched }, + run: (input, { context }) => planFromFetch(input, context), +}); + +/** `cssforge sync push`: read the remote, then send the plan. */ +export const syncPush: Capability< + ForgeContext, + PushInput, + PushReport, + SyncRemoteFailures, + never, + "sync.push", + Partial +> = capability({ + id: "sync.push", + description: + "Read the remote, then send the changes of the plan: create and update the tokens of the configuration, delete the ones removed from it, and carry out the decisions on inbox items. Items without a decision stay in the inbox, and their tokens are not changed. One request to read, up to two to write and one to read the stored values back; only the first when the plan is empty.", + audience: everyone, + destructive: true, + idempotent: true, + input: pushInput, + output: pushReport, + failures: { ...readFailures, ...remoteFailures }, + run: (input, { context, signal }) => + attempt(async () => { + const loaded = await load(context, input); + return withSession(loaded.adapter, signal, async (session) => { + const fetched = await fetchRemote(loaded, session, input.remote); + const plan = planOf(loaded, fetched.tokens); + const operations = plan.operations.map((planned) => planned.operation); + const applied = + input["dry-run"] || operations.length === 0 + ? [] + : withKeys( + await session.apply( + loaded.state.target, + operations, + keysOf(loaded.state), + ), + ); + if (!input["dry-run"] && applied.length === 0) { + const next = settle(loaded.state, plan, applied, fetched.tokens); + await writeState(loaded.root, input.remote, next); + } + if (!input["dry-run"] && applied.length > 0) { + // Record what the remote accepted before anything else can fail. + const accepted = settle(loaded.state, plan, applied, null); + await writeState(loaded.root, input.remote, accepted); + // Then read the tokens back, so that the base records each value as the remote + // stored it. Without this, a change made on the remote before the next fetch + // would read as the remote's own form of the value. + const stored = await session.read(loaded.state.target); + const next = settle(loaded.state, plan, applied, stored); + await writeState(loaded.root, input.remote, next); + } + const report = reportOf(input, loaded, plan, fetched.at, session.calls); + return { + ...report, + operations: input["dry-run"] ? report.operations : refused(operations, applied), + applied, + }; + }); + }), +}); + +/** The operations that the remote refused, which the next push sends again. */ +const refused = (operations: readonly Operation[], applied: readonly ApplyResult[]) => + operations.filter((_, index) => applied[index]?.ok !== true); + +/** The key of each custom property the remote has: from the fetch, then from the base. */ +const keysOf = (state: SyncState): Map => { + const keys = new Map(); + for (const token of state.fetched?.tokens ?? []) { + if (token.name !== undefined) keys.set(token.name, token.key); + } + for (const entry of state.base) keys.set(entry.name, entry.key); + return keys; +}; + +/** + * The results of a push, with each create or rename that the remote accepted without a key + * counted as refused: without the key, the configuration cannot own the token. The next fetch + * shows such a token as a collision. + */ +const withKeys = (applied: readonly ApplyResult[]): ApplyResult[] => + applied.map((result) => + result.ok && + (result.operation.op === "create" || result.operation.op === "rename") && + !result.key + ? { + operation: result.operation, + ok: false, + message: "The remote accepted the change but gave no key for the token.", + } + : result, + ); + +/** Whether two targets are the same file with the same options. */ +const sameTarget = (left: RemoteTarget, right: RemoteTarget): boolean => + left.file === right.file && + JSON.stringify(Object.entries(left.options).sort()) === + JSON.stringify(Object.entries(right.options).sort()); + +/** The key of the remote token that an operation addresses, before it runs. */ +const keyOf = (operation: Operation): string | undefined => + operation.op === "create" ? undefined : operation.key; + +/** + * The state after a push. `stored` is the remote read back after the push, or `null` when it + * is not read yet: the stored values stay unknown, and the fetch is cleared because it is + * older than the push. + */ +function settle( + state: SyncState, + plan: SyncPlan, + applied: readonly ApplyResult[], + stored: readonly RemoteToken[] | null, +): SyncState { + const previousByName = new Map(state.base.map((entry) => [entry.name, entry])); + const previousByKey = new Map(state.base.map((entry) => [entry.key, entry])); + const base = new Map(plan.carried.map((entry) => [entry.name, entry])); + const decisions = [...plan.pending]; + const decisionByKey = new Map( + state.decisions.map((decision) => [decision.key, decision]), + ); + /** The key each token has after the operations so far, for a result that gives none. */ + const keyByName = new Map(); + + plan.operations.forEach((planned, index) => { + const result = applied[index]; + if (result?.ok === true) { + if (planned.replaces !== undefined) base.delete(planned.replaces); + if (planned.base) { + const key = result.key ?? keyByName.get(planned.base.name) ?? planned.base.key; + keyByName.set(planned.base.name, key); + base.set(planned.base.name, { ...planned.base, key }); + } + return; + } + const key = keyOf(planned.operation); + const kept = + (planned.replaces === undefined + ? undefined + : previousByName.get(planned.replaces)) ?? + (key === undefined ? undefined : previousByKey.get(key)); + if (kept) base.set(kept.name, kept); + const decision = + planned.settles === undefined ? undefined : decisionByKey.get(planned.settles); + if (decision && !decisions.includes(decision)) decisions.push(decision); + }); + + if (stored === null) { + return { ...state, base: [...base.values()], fetched: null, decisions }; + } + const storedByKey = new Map(stored.map((token) => [token.key, token.values])); + const recorded = [...base.values()].map((entry) => + entry.stored === null + ? { ...entry, stored: storedByKey.get(entry.key) ?? null } + : entry, + ); + return { + ...state, + base: recorded, + fetched: { at: new Date().toISOString(), tokens: [...stored] }, + decisions, + }; +} + +/** `cssforge sync inbox list`: the items that wait for a decision. */ +export const syncInboxList: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncPlanFailures, + never, + "sync.inbox.list", + Partial +> = capability({ + id: "sync.inbox.list", + description: + "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `sync inbox adopt` (after adding it to the configuration) or `sync inbox reject`, and the others with `sync inbox overwrite`.", + audience: everyone, + readOnly: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...notFetched }, + run: (input, { context }) => planFromFetch(input, context), +}); + +/** An answer to an inbox item, before it is recorded with the item's id and key. */ +type Answer = + | { action: "adopt"; path: string } + | { action: "reject" } + | { action: "overwrite" }; + +/** Records a decision on an item of the inbox of the last fetch. */ +async function decide( + context: ForgeContext, + input: SyncInput & { item: string }, + answer: Answer, + check: (item: InboxItem, loaded: Loaded) => void, +): Promise { + const loaded = await load(context, input); + const fetched = fetchedOf(loaded.state, input.remote); + const plan = planOf(loaded, fetched.tokens); + const item = plan.inbox.find((candidate) => candidate.id === input.item); + if (!item) { + const ids = plan.inbox.map((candidate) => candidate.id); + throw new SyncError( + "UnknownItem", + `The inbox has no item "${input.item}".${ids.length > 0 ? ` Items: ${ids.join(", ")}.` : " The inbox is empty."}`, + ); + } + if (!item.actions.includes(answer.action)) { + throw new SyncError( + "InvalidDecision", + `The ${item.kind} item "${item.id}" is settled with ${item.actions.join(" or ")}, not ${answer.action}.`, + ); + } + check(item, loaded); + const decision: Decision = { item: item.id, key: item.key, ...answer }; + const decisions = [ + ...loaded.state.decisions.filter((entry) => entry.key !== item.key), + decision, + ]; + loaded.state = { ...loaded.state, decisions }; + await writeState(loaded.root, input.remote, loaded.state); + const next = planOf(loaded, fetched.tokens); + return { + remote: input.remote, + decision, + inbox: next.inbox, + skipped: loaded.skipped, + callsUsed: 0, + }; +} + +/** `cssforge sync inbox adopt`: make a new remote token a token of the configuration. */ +export const syncInboxAdopt: Capability< + ForgeContext, + AdoptInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.adopt", + Partial +> = capability({ + id: "sync.inbox.adopt", + description: + "Adopt a token that the remote created: first add it to the configuration at a path of your choice, then record that path here. The next push renames the remote token to the name the configuration generates, and sets the value of the configuration, so designs that use the token keep it. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: adoptInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => + decide(context, input, { action: "adopt", path: input.path }, (item, loaded) => { + const target = loaded.desired.find((token) => token.sourcePath === input.path); + if (!target) { + const skipped = loaded.skipped.find((token) => token.sourcePath === input.path); + throw new SyncError( + "InvalidDecision", + skipped + ? `The path "${input.path}" generates ${skipped.name}, which has no place on the remote: ${skipped.reason}` + : `The configuration has no token at "${input.path}". Add the token to the configuration first, then adopt it.`, + ); + } + if ( + loaded.state.fetched?.tokens.some( + (token) => token.name === target.name && token.key !== item.key, + ) + ) { + throw new SyncError( + "InvalidDecision", + `The path "${input.path}" generates ${target.name}, which the remote already has.`, + ); + } + const taken = loaded.state.decisions.find( + (entry) => + entry.action === "adopt" && + entry.path === input.path && + entry.key !== item.key, + ); + if (taken) { + throw new SyncError( + "InvalidDecision", + `The item "${taken.item}" is already adopted as "${input.path}". Two remote tokens cannot become one configuration token.`, + ); + } + }), + ), +}); + +/** `cssforge sync inbox reject`: delete a new remote token at the next push. */ +export const syncInboxReject: Capability< + ForgeContext, + ItemInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.reject", + Partial +> = capability({ + id: "sync.inbox.reject", + description: + "Reject a token that the remote created: the next push deletes it from the remote. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: itemInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => decide(context, input, { action: "reject" }, () => {})), +}); + +/** `cssforge sync inbox overwrite`: give the value of the configuration back to the remote. */ +export const syncInboxOverwrite: Capability< + ForgeContext, + ItemInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.overwrite", + Partial +> = capability({ + id: "sync.inbox.overwrite", + description: + "Settle a token that the remote changed, deleted, or created with the name of a configuration token: the next push writes the value of the configuration. To keep the value of the remote instead, change the configuration to that value; the item then goes away at the next fetch. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: itemInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => decide(context, input, { action: "overwrite" }, () => {})), +}); + +/** Every sync capability, in the order the help lists them. */ +export const syncCapabilities = [ + syncRemoteAdd, + syncFetch, + syncPlan, + syncPush, + syncInboxList, + syncInboxAdopt, + syncInboxReject, + syncInboxOverwrite, +] as const; diff --git a/packages/cssforge/src/sync/mcp-client.ts b/packages/cssforge/src/sync/mcp-client.ts new file mode 100644 index 0000000..97a982e --- /dev/null +++ b/packages/cssforge/src/sync/mcp-client.ts @@ -0,0 +1,159 @@ +/** + * A minimal MCP client over standard input and output: it starts a server process, makes + * the handshake, and calls tools. Token sync uses it to talk to the MCP server of a + * design tool. It has no dependency beyond Node.js. + * + * @module + */ + +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { createInterface } from "node:readline"; + +/** The MCP revision that the client asks for. */ +const PROTOCOL_VERSION = "2025-06-18"; + +/** A failure to start the server or to get an answer from it. */ +export class McpClientError extends Error { + /** `spawn`: the server did not start. `protocol`: it did not answer as MCP. `tool`: a tool failed. */ + readonly reason: "spawn" | "protocol" | "tool"; + + constructor(message: string, reason: "spawn" | "protocol" | "tool") { + super(message); + this.name = "McpClientError"; + this.reason = reason; + } +} + +/** The text items of a tool result, in order. */ +export type ToolText = string[]; + +interface Pending { + resolve: (message: Record) => void; + reject: (error: Error) => void; +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +export interface McpClient { + /** Calls a tool, and gives the text items of its result. A tool error rejects. */ + callTool(name: string, args: Record): Promise; + /** Stops the server process. */ + close(): void; +} + +/** + * Starts `command` with `args` as an MCP server and makes the handshake. Rejects with a + * {@link McpClientError} when the process does not start or does not answer. + */ +export async function connectMcp( + command: string, + args: readonly string[], + signal?: AbortSignal, +): Promise { + const child: ChildProcessWithoutNullStreams = spawn(command, args, { + stdio: ["pipe", "pipe", "pipe"], + }); + const pending = new Map(); + let nextId = 1; + let ended: McpClientError | undefined; + let stderr = ""; + + const fail = (error: McpClientError) => { + ended ??= error; + for (const waiter of pending.values()) waiter.reject(ended); + pending.clear(); + }; + + child.stderr.on("data", (chunk: Buffer) => { + stderr = `${stderr}${chunk.toString()}`.slice(-2000); + }); + child.on("error", (error: NodeJS.ErrnoException) => { + fail( + new McpClientError( + error.code === "ENOENT" + ? `The command "${command}" was not found. Install it, or put it on the PATH.` + : `The command "${command}" did not start: ${error.message}`, + "spawn", + ), + ); + }); + child.on("exit", (code) => { + const detail = stderr.trim() ? `: ${stderr.trim()}` : "."; + fail( + new McpClientError( + `The MCP server "${command}" stopped with code ${code}${detail}`, + "protocol", + ), + ); + }); + + createInterface({ input: child.stdout }).on("line", (line) => { + if (!line.trim()) return; + let message: unknown; + try { + message = JSON.parse(line); + } catch { + return; + } + if (!isRecord(message) || typeof message.id !== "number") return; + const waiter = pending.get(message.id); + if (!waiter) return; + pending.delete(message.id); + waiter.resolve(message); + }); + + const send = (message: Record) => + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`); + + const request = (method: string, params: Record) => + new Promise>((resolve, reject) => { + if (ended) return reject(ended); + const id = nextId++; + pending.set(id, { resolve, reject }); + send({ id, method, params }); + }).then((message) => { + if (isRecord(message.error)) { + throw new McpClientError( + `The MCP server answered ${method} with an error: ${String(message.error.message)}`, + "protocol", + ); + } + return isRecord(message.result) ? message.result : {}; + }); + + const close = () => { + child.stdin.end(); + child.kill(); + }; + signal?.addEventListener("abort", close, { once: true }); + + try { + await request("initialize", { + protocolVersion: PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: "cssforge", version: "0" }, + }); + } catch (error) { + close(); + throw error; + } + send({ method: "notifications/initialized" }); + + return { + close, + async callTool(name, args) { + const result = await request("tools/call", { name, arguments: args }); + const content = Array.isArray(result.content) ? result.content : []; + const text = content.flatMap((item) => + isRecord(item) && item.type === "text" && typeof item.text === "string" + ? [item.text] + : [], + ); + if (result.isError === true) { + throw new McpClientError(`The tool ${name} failed: ${text.join(" ")}`, "tool"); + } + return text; + }, + }; +} diff --git a/packages/cssforge/src/sync/modes.ts b/packages/cssforge/src/sync/modes.ts new file mode 100644 index 0000000..aed84ab --- /dev/null +++ b/packages/cssforge/src/sync/modes.ts @@ -0,0 +1,179 @@ +/** + * The modes of the configuration tokens. The generator emits a token once for each scope + * it lives in; a remote with modes (a Figma collection) holds one token with a value for + * each mode. This module makes the one from the other, and asks the adapter where each + * mode of each token goes. + * + * - A token at `:root` has the mode `default`. + * - A `light-dark(light, dark)` value at `:root` has the modes `light` and `dark`. + * - A token under a selector or an at-rule has the mode named after it, e.g. `.dark`. + * + * Tokens with the same custom property in several scopes are one token with several modes. + * + * @module + */ + +import type { ListedToken } from "../generator.ts"; +import { ROOT_SCOPE, scopeParts } from "../lib.ts"; +import { DEFAULT_MODE, type DesiredToken, type ModeValues } from "./plan.ts"; +import type { RemoteAdapter } from "./remote.ts"; + +/** A configuration token, or one mode of it, that has no place on the remote. */ +export interface SkippedToken { + name: string; + sourcePath: string; + /** The mode that has no place, when the token has others that do. */ + mode?: string; + reason: string; +} + +/** The mode of a scope: `default` for `:root`, else the at-rule and the selector it is under. */ +export const modeOfScope = (scope: string): string => { + if (scope === ROOT_SCOPE) return DEFAULT_MODE; + const { atRule, selector } = scopeParts(scope); + return [atRule, selector].filter(Boolean).join(" "); +}; + +/** The two arguments of a `light-dark()` value, split at its top-level comma. */ +export const lightDarkArguments = (value: string): [string, string] | undefined => { + const trimmed = value.trim(); + if (!/^light-dark\(/i.test(trimmed) || !trimmed.endsWith(")")) return undefined; + const inner = trimmed.slice("light-dark(".length, -1); + let depth = 0; + for (let index = 0; index < inner.length; index++) { + const character = inner[index]; + if (character === "(") depth++; + else if (character === ")") depth--; + else if (character === "," && depth === 0) { + return [inner.slice(0, index).trim(), inner.slice(index + 1).trim()]; + } + } + return undefined; +}; + +const ALIAS = /^var\((--[a-zA-Z0-9_-]+)\)$/; + +const withoutMode = ({ mode: _mode, ...entry }: SkippedToken): SkippedToken => entry; + +/** One mode of a listed token: its generated value and its resolved value. */ +interface ModeValue { + mode: string; + value: string; + resolvedValue: string; +} + +/** + * A value as one color scheme computes it: each `light-dark(light, dark)` in it, at any depth, + * becomes its light or its dark argument. + */ +export const inScheme = (value: string, scheme: "light" | "dark"): string => { + const start = value.search(/light-dark\(/i); + if (start === -1) return value; + const open = start + "light-dark(".length; + let depth = 1; + let end = open; + while (end < value.length && depth > 0) { + if (value[end] === "(") depth++; + else if (value[end] === ")") depth--; + end++; + } + const pair = lightDarkArguments(value.slice(start, end)); + if (pair === undefined) return value; + const chosen = scheme === "light" ? pair[0] : pair[1]; + return inScheme(`${value.slice(0, start)}${chosen}${value.slice(end)}`, scheme); +}; + +/** + * The modes of a listed token. A token at `:root` whose value depends on the color scheme + * (a `light-dark()` value, or a value built from one) has the modes `light` and `dark`, each + * with its own branch of every `light-dark()`. + */ +const modeValuesOf = (token: ListedToken): ModeValue[] => { + const mode = modeOfScope(token.scope); + if (mode === DEFAULT_MODE && /light-dark\(/i.test(token.resolvedValue)) { + return (["light", "dark"] as const).map((scheme) => ({ + mode: scheme, + value: inScheme(token.value, scheme), + resolvedValue: inScheme(token.resolvedValue, scheme), + })); + } + return [{ mode, value: token.value, resolvedValue: token.resolvedValue }]; +}; + +/** + * The configuration tokens that go to the remote, with a value for each mode the target + * holds, and the tokens and modes that have no place there. + */ +export function desiredTokens( + tokens: readonly ListedToken[], + adapter: RemoteAdapter, + modes: readonly string[], +): { desired: DesiredToken[]; skipped: SkippedToken[] } { + const held = new Set(modes); + const groups = new Map(); + for (const token of tokens) + groups.set(token.name, [...(groups.get(token.name) ?? []), token]); + + const desired: DesiredToken[] = []; + const skipped: SkippedToken[] = []; + + for (const [name, scoped] of groups) { + const values: ModeValues = {}; + const aliases: ModeValues = {}; + const types = new Set(); + const modeSkips: (SkippedToken & { unheld: boolean })[] = []; + const main = scoped.find((token) => token.scope === ROOT_SCOPE) ?? scoped[0]; + if (main === undefined) continue; + + for (const token of scoped) { + for (const { mode, value, resolvedValue } of modeValuesOf(token)) { + const skip = (reason: string, unheld = false) => + modeSkips.push({ name, sourcePath: token.sourcePath, mode, reason, unheld }); + if (!held.has(mode)) { + skip(`The remote has no mode "${mode}". It holds: ${modes.join(", ")}.`, true); + continue; + } + const mapping = adapter.map({ ...token, value, resolvedValue }); + if ("skip" in mapping) { + skip(mapping.skip); + continue; + } + types.add(mapping.type); + values[mode] = mapping.value; + const alias = ALIAS.exec(value.trim())?.[1]; + if (alias !== undefined) aliases[mode] = alias; + } + } + + if (types.size > 1) { + skipped.push({ + name, + sourcePath: main.sourcePath, + reason: `Its modes map to different types on the remote: ${[...types].join(", ")}.`, + }); + continue; + } + const [type] = types; + if (type === undefined) { + // No mode has a place: the token is skipped, with the reason of each mode. The mode + // is named when it is the reason, or when the token has several. + skipped.push( + ...modeSkips.map(({ unheld, ...entry }) => + unheld || modeSkips.length > 1 ? entry : withoutMode(entry), + ), + ); + continue; + } + skipped.push(...modeSkips.map(({ unheld: _unheld, ...entry }) => entry)); + desired.push({ + name, + type, + values, + ...(Object.keys(aliases).length > 0 ? { aliases } : {}), + sourcePath: main.sourcePath, + description: `cssforge: ${main.sourcePath}`, + }); + } + + return { desired, skipped }; +} diff --git a/packages/cssforge/src/sync/paper.ts b/packages/cssforge/src/sync/paper.ts new file mode 100644 index 0000000..5bcdd0b --- /dev/null +++ b/packages/cssforge/src/sync/paper.ts @@ -0,0 +1,323 @@ +/** + * The Paper remote (https://paper.design). It talks to the MCP server of Paper Desktop, + * which `paper-design mcp` starts, and uses its token tools: `get_basic_info`, + * `get_tokens`, `create_tokens` and `set_tokens`. + * + * @module + */ + +import { z } from "zod"; +import type { ListedToken, TokenKind } from "../generator.ts"; +import { connectMcp, McpClientError } from "./mcp-client.ts"; +import { + CUSTOM_PROPERTY, + DEFAULT_MODE, + type ModeValues, + type Operation, +} from "./plan.ts"; +import { + type ApplyResult, + type RemoteAdapter, + RemoteError, + type RemoteOptions, + type RemoteSession, + type TokenMapping, +} from "./remote.ts"; + +/** The token types of Paper. */ +type PaperType = + | "breakpoint" + | "color" + | "container" + | "fontFamily" + | "fontSize" + | "fontWeight" + | "letterSpacing" + | "lineHeight" + | "opacity" + | "radius" + | "spacing"; + +/** The Paper type of each token kind that Paper stores. */ +const paperTypes: Partial> = { + color: "color", + spacing: "spacing", + fontSize: "fontSize", + fontWeight: "fontWeight", + fontFamily: "fontFamily", + lineHeight: "lineHeight", + letterSpacing: "letterSpacing", + borderRadius: "radius", + opacity: "opacity", +}; + +/** + * The typography module emits two kinds under one token kind: the font weights of + * `typography.weight` and the fluid sizes of `typography_fluid`. + */ +const typographyType = (sourcePath: string): PaperType | undefined => { + if (sourcePath.startsWith("typography.weight.")) return "fontWeight"; + if (sourcePath.startsWith("typography_fluid.")) return "fontSize"; + return undefined; +}; + +/** Paper types whose numbers Paper takes as JSON numbers. */ +const numericTypes = new Set(["fontWeight", "lineHeight", "opacity"]); + +const LENGTH = /^-?\d*\.?\d+(?:px|rem|em|%|vw|vh|vmin|vmax|ch|ex)?$/i; +const SIZE_FUNCTION = /^(?:clamp|calc|min|max)\(/i; +/** The helper tokens of a `pow()` type scale: unitless inputs and partial terms. */ +const POW_SCALE_PATH = /\.pow(?:[.@]|$)/; + +/** + * Maps a configuration token to Paper. Paper has no modes: token sync only asks for the + * `default` mode. Paper rejects `color-mix()` and references inside a value. + */ +export function mapToPaper(token: ListedToken): TokenMapping { + const type = + token.kind === "typography" + ? typographyType(token.sourcePath) + : paperTypes[token.kind]; + if (type === undefined) return { skip: `Paper has no ${token.kind} tokens.` }; + + const value = token.resolvedValue.trim(); + if (value.includes("var(")) { + return { + skip: "Its value references a custom property that the configuration does not declare.", + }; + } + if (type === "color" && /(?:color-mix|light-dark)\(/i.test(value)) { + return { skip: "Paper does not take color-mix() values." }; + } + if (type === "fontSize") { + if (POW_SCALE_PATH.test(token.sourcePath)) { + return { + skip: "It is part of a pow() type scale; the clamp() scale is synced instead.", + }; + } + if (!LENGTH.test(value) && !SIZE_FUNCTION.test(value)) { + return { skip: "Its value is not a size." }; + } + } + return { type, value }; +} + +// --- MCP results ---------------------------------------------------------------------------- + +/** Each file-scoped Paper tool answers with the file first, then the result. */ +const resultOf = (schema: z.ZodType, text: readonly string[], tool: string): T => { + const body = text.at(-1); + try { + return schema.parse(JSON.parse(body ?? "")); + } catch { + throw new RemoteError( + "RemoteFailed", + `Paper answered ${tool} in a form that cssforge does not read: ${body ?? "(nothing)"}`, + ); + } +}; + +const basicInfo = z.object({ fileName: z.string() }); +const fileHeader = z.object({ file: z.object({ id: z.string(), name: z.string() }) }); +const tokenList = z.object({ + tokens: z.array( + z.object({ + // The rule of the state file, so that a fetch never records a name it cannot read back. + name: z.string().regex(CUSTOM_PROPERTY), + type: z.string(), + value: z.union([z.string(), z.number()]), + description: z.string().optional(), + }), + ), +}); +const entryResults = z.object({ + tokens: z.array(z.object({ result: z.string(), message: z.string().optional() })), +}); + +const paperValue = (type: string, value: string): string | number => + numericTypes.has(type) && /^-?\d*\.?\d+$/.test(value) ? Number(value) : value; + +/** An operation that `set_tokens` carries out: everything but a create. */ +type Change = Exclude; + +const isChange = (operation: Operation): operation is Change => operation.op !== "create"; + +/** The value of the one mode Paper holds. */ +const defaultValue = (values: ModeValues): string => values[DEFAULT_MODE] ?? ""; + +/** + * The `set_tokens` entry of a change. A Paper key is the token name, so a rename changes + * it: `renamed` maps the keys renamed earlier in the batch to their new names. + */ +const setTokensEntry = (operation: Change, renamed: Map) => { + const name = renamed.get(operation.key) ?? operation.key; + switch (operation.op) { + case "update": + return { + name, + value: paperValue(operation.type, defaultValue(operation.values)), + description: operation.description, + }; + case "rename": + renamed.set(operation.key, operation.to); + return { name, newName: operation.to }; + case "delete": + return { name, delete: true }; + } +}; + +/** Paper takes no options. */ +const checkPaperOptions = (options: RemoteOptions): void => { + const names = Object.keys(options); + if (names.length > 0) { + throw new RemoteError( + "InvalidOptions", + `Paper takes no options. Received: ${names.join(", ")}.`, + ); + } +}; + +// --- Adapter -------------------------------------------------------------------------------- + +export interface PaperOptions { + /** The command that serves the MCP server of Paper Desktop. */ + command?: string; + args?: readonly string[]; +} + +/** The Paper remote. */ +export function paperAdapter({ + command = "paper-design", + args = ["mcp"], +}: PaperOptions = {}): RemoteAdapter { + return { + kind: "paper", + map: mapToPaper, + checkOptions: checkPaperOptions, + async open(signal) { + const client = await connectMcp(command, args, signal).catch((error: unknown) => { + throw new RemoteError( + "RemoteUnavailable", + error instanceof Error + ? `Paper is not reachable: ${error.message} Start Paper Desktop and open the file.` + : String(error), + ); + }); + let calls = 0; + const call = async (tool: string, input: Record) => { + calls += 1; + try { + return await client.callTool(tool, input); + } catch (error) { + if (error instanceof McpClientError && error.reason === "tool") { + throw new RemoteError("RemoteFailed", error.message); + } + throw new RemoteError( + "RemoteUnavailable", + error instanceof Error ? error.message : String(error), + ); + } + }; + + const session: RemoteSession = { + get calls() { + return calls; + }, + close: () => client.close(), + async resolve(file, options) { + checkPaperOptions(options); + const text = await call("get_basic_info", { fileId: file }); + const header = fileHeader.safeParse(JSON.parse(text[0] ?? "null")); + const info = resultOf(basicInfo, text, "get_basic_info"); + if (!header.success) { + throw new RemoteError( + "RemoteFailed", + "Paper did not say which file it read.", + ); + } + return { + file: header.data.file.id, + fileName: info.fileName, + modes: [DEFAULT_MODE], + options: {}, + }; + }, + async read(target) { + const text = await call("get_tokens", { fileId: target.file, format: "json" }); + return resultOf(tokenList, text, "get_tokens").tokens.map((token) => ({ + key: token.name, + label: token.name, + name: token.name, + type: token.type, + values: { [DEFAULT_MODE]: String(token.value) }, + ...(token.description === undefined + ? {} + : { description: token.description }), + })); + }, + async apply(target, operations) { + const creates = operations.filter((operation) => operation.op === "create"); + const changes = operations.filter(isChange); + const results: ApplyResult[] = []; + const renamed = new Map(); + + /** The key each operation leaves its token with, in the order sent. */ + const keys = new Map(); + const report = ( + batch: readonly Operation[], + text: readonly string[], + tool: string, + ) => { + const entries = resultOf(entryResults, text, tool).tokens; + batch.forEach((operation, index) => { + const entry = entries[index]; + const ok = entry !== undefined && entry.result !== "error"; + results.push({ + operation, + ok, + ...(ok + ? { key: keys.get(operation) ?? "" } + : { message: entry?.message ?? "Paper gave no result." }), + }); + }); + }; + + if (creates.length > 0) { + // A Paper key is the name. + for (const operation of creates) keys.set(operation, operation.name); + const text = await call("create_tokens", { + fileId: target.file, + tokens: creates.map((operation) => ({ + type: operation.type, + name: operation.name, + value: paperValue(operation.type, defaultValue(operation.values)), + description: operation.description, + })), + }); + report(creates, text, "create_tokens"); + } + if (changes.length > 0) { + const entries = changes.map((operation) => { + const entry = setTokensEntry(operation, renamed); + // A Paper key is the name: the name after this entry, renamed or not. + keys.set( + operation, + operation.op === "rename" + ? operation.to + : (renamed.get(operation.key) ?? operation.key), + ); + return entry; + }); + const text = await call("set_tokens", { + fileId: target.file, + tokens: entries, + }); + report(changes, text, "set_tokens"); + } + return results; + }, + }; + return session; + }, + }; +} diff --git a/packages/cssforge/src/sync/plan.ts b/packages/cssforge/src/sync/plan.ts new file mode 100644 index 0000000..55ab76f --- /dev/null +++ b/packages/cssforge/src/sync/plan.ts @@ -0,0 +1,464 @@ +/** + * The three-way plan of token sync. It compares the tokens that the configuration + * wants on a remote (a design tool), the tokens the remote has now, and the base: the + * tokens as they were after the last push. Writes nothing and calls no remote. + * + * The configuration is the source of truth. A token that only the configuration changed + * is pushed. A token that the remote created, changed or deleted becomes an inbox item, + * and stays one until a decision settles it: `adopt` or `reject` for a new token, + * `overwrite` for the others. + * + * Two identities meet here. The configuration names a token by its custom property + * (`--palette-brand-500`). A remote has its own key for it: the same name on Paper, a + * variable id on Figma. The base records both, so a remote that renames or re-keys a + * token keeps the link. + * + * @module + */ + +/** The pattern of a custom property name, e.g. `--color-primary`. */ +export const CUSTOM_PROPERTY = /^--[a-zA-Z0-9_-]+$/; + +/** The mode of a token emitted at `:root`. */ +export const DEFAULT_MODE = "default"; + +/** The values of a token, one for each mode, e.g. `{ default: "8px" }` or `{ light, dark }`. */ +export type ModeValues = Record; + +/** A token as a remote stores it. */ +export interface RemoteToken { + /** The identity of the token on the remote: a name or an id that only the remote assigns. */ + key: string; + /** The name people see on the remote, e.g. `--brand-accent` or `color/brand/accent`. */ + label: string; + /** The custom property the token stands for, when the remote records one. */ + name?: string; + /** The token type of the remote, e.g. `color` or `spacing`. */ + type: string; + values: ModeValues; + description?: string; +} + +/** A token that the configuration wants on the remote. */ +export interface DesiredToken { + /** The custom property name, e.g. `--palette-brand-500`. */ + name: string; + type: string; + /** The literal value of each mode, with every reference resolved. */ + values: ModeValues; + /** For each mode whose generated value is exactly `var()`, the aliased token. */ + aliases?: ModeValues; + /** The configuration path of the token. */ + sourcePath: string; + /** A description the remote shows beside the token. */ + description: string; +} + +/** A token the configuration owns on the remote, as it was after the last push. */ +export interface BaseEntry { + /** The custom property name. */ + name: string; + /** The key of the token on the remote. */ + key: string; + type: string; + /** The values the last push sent. */ + sent: ModeValues; + /** The values as the remote stored them, read back after the push. `null` until read. */ + stored: ModeValues | null; + sourcePath: string; +} + +/** + * A recorded answer to an inbox item. `key` is the remote key of the token it settles, which + * stays the same when labels repeat or change; `item` is the id the answer was given for. + */ +export type Decision = + | { item: string; key: string; action: "adopt"; path: string } + | { item: string; key: string; action: "reject" } + | { item: string; key: string; action: "overwrite" }; + +/** A change to send to the remote. A remote token is addressed by its key. */ +export type Operation = + | { op: "create"; name: string; type: string; values: ModeValues; description: string } + | { + op: "update"; + key: string; + name: string; + type: string; + values: ModeValues; + description: string; + } + | { op: "rename"; key: string; from: string; to: string } + | { op: "delete"; key: string; label: string }; + +/** A change that the remote made, which waits for a decision. */ +export interface InboxItem { + /** + * The id of the item, made from the label: `brand-accent` for `--brand-accent`. When two + * items share a label, each id ends with `#` and the key. + */ + id: string; + /** + * `new`: the remote created a token that the configuration does not have. + * `edited`: the remote changed the value of a token that the configuration owns. + * `deleted`: the remote deleted a token that the configuration owns. + * `collision`: the remote has a token with the name of a new configuration token. + */ + kind: "new" | "edited" | "deleted" | "collision"; + /** The key of the token on the remote, or the key it had before the remote deleted it. */ + key: string; + /** The name of the token on the remote, or the custom property of a deleted token. */ + label: string; + type: string; + /** The values on the remote, unless the remote deleted the token. */ + remoteValues?: ModeValues; + /** The values the configuration wants, unless the configuration does not have the token. */ + localValues?: ModeValues; + /** The decisions that settle the item. */ + actions: Decision["action"][]; + /** Why a recorded decision does not apply yet, for example an adopted path that is missing. */ + note?: string; +} + +/** A planned operation with the base entry it gives when the remote accepts it. */ +export interface PlannedOperation { + operation: Operation; + /** + * The base entry after the operation, or `null` when the operation removes the entry. + * The remote may give the token a new key; the push records it. + */ + base: BaseEntry | null; + /** The name of the base entry the operation removes when it succeeds. */ + replaces?: string; + /** The key of the decision that the operation carries out, removed when it succeeds. */ + settles?: string; +} + +export interface SyncPlan { + operations: PlannedOperation[]; + inbox: InboxItem[]; + /** The base entries that no operation changes, with the stored values of this fetch. */ + carried: BaseEntry[]; + /** The decisions that still wait: their items are in the inbox. */ + pending: Decision[]; +} + +export interface PlanInput { + desired: readonly DesiredToken[]; + /** + * The names of configuration tokens that have no place on the remote. A pushed token + * that becomes one keeps its remote copy: it is skipped, not removed from the configuration. + */ + skipped?: ReadonlySet; + remote: readonly RemoteToken[]; + base: readonly BaseEntry[]; + decisions: readonly Decision[]; +} + +/** The inbox id of a label: `brand-accent` for `--brand-accent`, `color/brand` as it is. */ +export const itemIdOf = (label: string): string => label.replace(/^--/, ""); + +/** Whether two sets of mode values are the same. */ +export const sameValues = (left: ModeValues, right: ModeValues): boolean => { + const modes = Object.keys(left); + return ( + modes.length === Object.keys(right).length && + modes.every((mode) => Object.hasOwn(right, mode) && right[mode] === left[mode]) + ); +}; + +/** + * Plans a sync. Operations come in the order the remote must apply them: creates first, + * each after the tokens it aliases, then renames, updates and deletes. + */ +export function planSync(input: PlanInput): SyncPlan { + const { remote, base, decisions } = input; + const skipped = input.skipped ?? new Set(); + const desired = withAliases(input.desired); + const desiredByName = new Map(desired.map((token) => [token.name, token])); + const remoteByKey = new Map(remote.map((token) => [token.key, token])); + const baseKeys = new Set(base.map((entry) => entry.key)); + const baseNames = new Set(base.map((entry) => entry.name)); + /** The custom properties the remote already has a token for. */ + const remoteNames = new Set( + remote.flatMap((token) => (token.name === undefined ? [] : [token.name])), + ); + const decisionByKey = new Map(decisions.map((decision) => [decision.key, decision])); + + const creates: PlannedOperation[] = []; + const changes: PlannedOperation[] = []; + const inbox: InboxItem[] = []; + const carried: BaseEntry[] = []; + const pending: Decision[] = []; + /** Configuration tokens that a remote token becomes or collides with, so they are not created. */ + const claimedNames = new Set(); + + const entryOf = (token: DesiredToken, key: string): BaseEntry => ({ + name: token.name, + key, + type: token.type, + sent: token.values, + stored: null, + sourcePath: token.sourcePath, + }); + const hold = (decision: Decision | undefined) => { + if (decision) pending.push(decision); + }; + + // A token that the remote has and the base does not: new, or adopted under a decision. + for (const remoteToken of remote) { + if (baseKeys.has(remoteToken.key)) continue; + const id = itemIdOf(remoteToken.label); + const decision = decisionByKey.get(remoteToken.key); + const settles = remoteToken.key; + const wanted = + remoteToken.name === undefined ? undefined : desiredByName.get(remoteToken.name); + + if (wanted && !baseNames.has(wanted.name)) { + // The configuration wants a token with this name, which it never pushed. + claimedNames.add(wanted.name); + if (decision?.action === "overwrite") { + changes.push({ + operation: update(wanted, remoteToken.key), + base: entryOf(wanted, remoteToken.key), + settles, + }); + continue; + } + hold(decision); + inbox.push({ + id, + kind: "collision", + key: remoteToken.key, + label: remoteToken.label, + type: remoteToken.type, + remoteValues: remoteToken.values, + localValues: wanted.values, + actions: ["overwrite"], + }); + continue; + } + + if (decision?.action === "reject") { + changes.push({ + operation: { op: "delete", key: remoteToken.key, label: remoteToken.label }, + base: null, + settles, + }); + continue; + } + + if (decision?.action === "adopt") { + const target = desired.find((token) => token.sourcePath === decision.path); + const blocked = + target === undefined + ? `The adopted path "${decision.path}" is not in the configuration.` + : remoteNames.has(target.name) || baseNames.has(target.name) + ? `The adopted path "${decision.path}" generates ${target.name}, which the remote already has.` + : claimedNames.has(target.name) + ? `Another item is already adopted as "${decision.path}".` + : undefined; + if (target && blocked === undefined) { + claimedNames.add(target.name); + changes.push({ + operation: { + op: "rename", + key: remoteToken.key, + from: remoteToken.label, + to: target.name, + }, + base: { ...entryOf(target, remoteToken.key), sent: remoteToken.values }, + settles, + }); + if (!sameValues(target.values, remoteToken.values)) { + // The key after the rename is not known yet: the push sends the update with it. + changes.push({ + operation: update(target, remoteToken.key), + base: entryOf(target, remoteToken.key), + }); + } + continue; + } + pending.push(decision); + inbox.push({ ...newItem(remoteToken), ...(blocked ? { note: blocked } : {}) }); + continue; + } + + hold(decision); + inbox.push(newItem(remoteToken)); + } + + // A token that the base has: the configuration owns it. + for (const entry of base) { + const wanted = desiredByName.get(entry.name); + const remoteToken = remoteByKey.get(entry.key); + const id = itemIdOf(remoteToken?.label ?? entry.name); + const decision = decisionByKey.get(entry.key); + const settles = entry.key; + + if (!wanted && skipped.has(entry.name)) { + carried.push({ ...entry, stored: entry.stored ?? remoteToken?.values ?? null }); + continue; + } + if (!wanted) { + // Removed from the configuration: delete it from the remote, if it is still there. + if (remoteToken) { + changes.push({ + operation: { op: "delete", key: entry.key, label: remoteToken.label }, + base: null, + replaces: entry.name, + }); + } + continue; + } + + if (!remoteToken) { + if (decision?.action === "overwrite") { + creates.push({ + operation: create(wanted), + base: entryOf(wanted, entry.key), + replaces: entry.name, + settles, + }); + continue; + } + hold(decision); + carried.push(entry); + inbox.push({ + id, + kind: "deleted", + key: entry.key, + label: entry.name, + type: entry.type, + localValues: wanted.values, + actions: ["overwrite"], + }); + continue; + } + + const stored = entry.stored ?? remoteToken.values; + const remoteChanged = !sameValues(remoteToken.values, stored); + const localChanged = !sameValues(wanted.values, entry.sent); + + if (remoteChanged) { + if (decision?.action === "overwrite") { + changes.push({ + operation: update(wanted, entry.key), + base: entryOf(wanted, entry.key), + settles, + }); + continue; + } + hold(decision); + carried.push({ ...entry, stored }); + inbox.push({ + id, + kind: "edited", + key: entry.key, + label: remoteToken.label, + type: entry.type, + remoteValues: remoteToken.values, + localValues: wanted.values, + actions: ["overwrite"], + }); + continue; + } + + if (localChanged) { + changes.push({ + operation: update(wanted, entry.key), + base: entryOf(wanted, entry.key), + }); + continue; + } + carried.push({ ...entry, stored }); + } + + // A token that only the configuration has: create it. The remote gives it its key. + for (const token of desired) { + if (baseNames.has(token.name) || claimedNames.has(token.name)) continue; + creates.push({ operation: create(token), base: entryOf(token, "") }); + } + + return { + operations: [...orderCreates(creates, desiredByName), ...changes], + inbox: withUniqueIds(inbox), + carried, + pending, + }; +} + +/** Gives the items that share an id a suffix with their key, so that each id names one item. */ +function withUniqueIds(inbox: readonly InboxItem[]): InboxItem[] { + const counts = new Map(); + for (const item of inbox) counts.set(item.id, (counts.get(item.id) ?? 0) + 1); + return inbox.map((item) => + (counts.get(item.id) ?? 0) > 1 ? { ...item, id: `${item.id}#${item.key}` } : item, + ); +} + +const create = (token: DesiredToken): Operation => ({ + op: "create", + name: token.name, + type: token.type, + values: token.values, + description: token.description, +}); + +const update = (token: DesiredToken, key: string): Operation => ({ + op: "update", + key, + name: token.name, + type: token.type, + values: token.values, + description: token.description, +}); + +const newItem = (token: RemoteToken): InboxItem => ({ + id: itemIdOf(token.label), + kind: "new", + key: token.key, + label: token.label, + type: token.type, + remoteValues: token.values, + actions: ["adopt", "reject"], +}); + +/** + * Writes each mode that aliases another pushed token of the same type as `var(--target)`, + * so that the remote keeps the link. Any other mode sends its literal value. + */ +function withAliases(desired: readonly DesiredToken[]): DesiredToken[] { + const types = new Map(desired.map((token) => [token.name, token.type])); + return desired.map((token) => { + if (token.aliases === undefined) return token; + const values = { ...token.values }; + for (const [mode, target] of Object.entries(token.aliases)) { + if (types.get(target) === token.type && Object.hasOwn(values, mode)) { + values[mode] = `var(${target})`; + } + } + return { ...token, values }; + }); +} + +/** Orders creates so that each comes after the tokens it aliases. */ +function orderCreates( + creates: readonly PlannedOperation[], + desiredByName: ReadonlyMap, +): PlannedOperation[] { + const pending = new Map(creates.map((planned) => [planned.base?.name ?? "", planned])); + const ordered: PlannedOperation[] = []; + + const visit = (name: string) => { + const planned = pending.get(name); + if (!planned) return; + pending.delete(name); + for (const alias of Object.values(desiredByName.get(name)?.aliases ?? {})) + visit(alias); + ordered.push(planned); + }; + + for (const name of [...pending.keys()]) visit(name); + return ordered; +} diff --git a/packages/cssforge/src/sync/remote.ts b/packages/cssforge/src/sync/remote.ts new file mode 100644 index 0000000..212adef --- /dev/null +++ b/packages/cssforge/src/sync/remote.ts @@ -0,0 +1,96 @@ +/** + * The interface between token sync and a remote: a design tool that stores tokens. Each + * kind of remote (Paper, and later others such as Figma) has one adapter. Token sync knows + * nothing else about a remote. + * + * @module + */ + +import type { ListedToken } from "../generator.ts"; +import type { Operation, RemoteToken } from "./plan.ts"; + +/** The options of a remote, as `sync remote add --options` gives them, e.g. a Figma collection. */ +export type RemoteOptions = Record; + +/** The part of a remote that the tokens sync with, as the adapter resolved it. */ +export interface RemoteTarget { + /** The id of the file on the remote. */ + file: string; + /** The name of the file, for people. */ + fileName: string; + /** + * The modes the target holds, by the names token sync uses: `default` for tokens at + * `:root`, `light` and `dark` for `light-dark()` values, and the selector or at-rule of + * any other scope, e.g. `.dark`. A remote with no modes holds only `default`. + */ + modes: string[]; + /** The options, as the adapter normalized them, e.g. a collection name resolved to an id. */ + options: RemoteOptions; +} + +/** What the remote did with one operation. */ +export interface ApplyResult { + operation: Operation; + ok: boolean; + /** Why the remote refused the operation. */ + message?: string; + /** The key of the token after the operation: the key a create gives, or a rename changes. */ + key?: string; +} + +/** + * A connection to the remote for one capability call. `calls` counts the requests made, + * because some remotes limit them. + */ +export interface RemoteSession { + /** Finds the target from a file id or URL and the options. */ + resolve(file: string, options: RemoteOptions): Promise; + /** Reads every token of the target. */ + read(target: RemoteTarget): Promise; + /** + * Sends the operations in order, and reports each one. A `var(--name)` value aliases the + * token with that custom property; `keys` gives the key of each one the remote has. + */ + apply( + target: RemoteTarget, + operations: readonly Operation[], + keys: ReadonlyMap, + ): Promise; + readonly calls: number; + close(): void; +} + +/** Where a configuration token goes on the remote in one mode, or why it has no place there. */ +export type TokenMapping = { type: string; value: string } | { skip: string }; + +/** One kind of remote. */ +export interface RemoteAdapter { + /** The kind, as `sync remote add --kind` names it, e.g. `paper`. */ + kind: string; + /** + * Maps a configuration token in one mode to the remote. `token.resolvedValue` is the + * value of that mode. + */ + map(token: ListedToken): TokenMapping; + /** + * Checks the options of `sync remote add` before any request, and throws a + * {@link RemoteError} `InvalidOptions` for options this kind does not take. + */ + checkOptions(options: RemoteOptions): void; + /** Opens a session. Rejects with a {@link RemoteError} when the remote cannot be reached. */ + open(signal: AbortSignal): Promise; +} + +/** A failure of the remote, as a capability failure. */ +export class RemoteError extends Error { + readonly tag: "RemoteUnavailable" | "RemoteFailed" | "InvalidOptions"; + + constructor( + tag: "RemoteUnavailable" | "RemoteFailed" | "InvalidOptions", + message: string, + ) { + super(message); + this.name = "RemoteError"; + this.tag = tag; + } +} diff --git a/packages/cssforge/src/sync/state.ts b/packages/cssforge/src/sync/state.ts new file mode 100644 index 0000000..b92cb22 --- /dev/null +++ b/packages/cssforge/src/sync/state.ts @@ -0,0 +1,163 @@ +/** + * The state of the sync with one remote, in `.cssforge/sync/.json`: the target it + * syncs with (the file, its modes and the options), the base (the tokens as they were after the last push), the last fetch, and + * the decisions that wait for the next push. Commit it, so that everyone who syncs shares + * the base. + * + * @module + */ + +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { z } from "zod"; +import { + type BaseEntry, + CUSTOM_PROPERTY, + type Decision, + type RemoteToken, +} from "./plan.ts"; +import type { RemoteTarget } from "./remote.ts"; + +/** The pattern of a remote name: a word in lowercase, e.g. `paper` or `paper-marketing`. */ +export const REMOTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; + +export interface SyncState { + version: 1; + /** The kind of remote, e.g. `paper`. */ + kind: string; + /** The part of the remote the tokens sync with: the file, its modes and the options. */ + target: RemoteTarget; + base: BaseEntry[]; + /** The remote tokens of the last fetch, or `null` before the first fetch. */ + fetched: { at: string; tokens: RemoteToken[] } | null; + decisions: Decision[]; +} + +const customProperty = z.string().regex(CUSTOM_PROPERTY); +const modeValues = z.record(z.string(), z.string()); + +const stateSchema = z.strictObject({ + version: z.literal(1), + kind: z.string().min(1), + target: z.strictObject({ + file: z.string().min(1), + fileName: z.string(), + modes: z.array(z.string()).min(1), + options: z.record(z.string(), z.string()), + }), + base: z.array( + z.strictObject({ + name: customProperty, + key: z.string().min(1), + type: z.string(), + sent: modeValues, + stored: modeValues.nullable(), + sourcePath: z.string(), + }), + ), + fetched: z + .strictObject({ + at: z.string(), + tokens: z.array( + z.strictObject({ + key: z.string().min(1), + label: z.string().min(1), + name: customProperty.optional(), + type: z.string(), + values: modeValues, + description: z.string().optional(), + }), + ), + }) + .nullable(), + decisions: z.array( + z.discriminatedUnion("action", [ + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("adopt"), + path: z.string(), + }), + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("reject"), + }), + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("overwrite"), + }), + ]), + ), +}); + +/** The path of the state file of `remote`, under `root`. */ +export const statePath = (root: string, remote: string): string => + join(root, ".cssforge", "sync", `${remote}.json`); + +/** A state file that is missing, or that is not a valid state. */ +export class StateError extends Error { + readonly tag: "RemoteNotConfigured" | "InvalidState"; + /** The state file. */ + readonly path: string; + + constructor( + tag: "RemoteNotConfigured" | "InvalidState", + message: string, + path: string, + ) { + super(message); + this.name = "StateError"; + this.tag = tag; + this.path = path; + } +} + +/** Reads and validates the state of `remote`. */ +export async function readState(root: string, remote: string): Promise { + const path = statePath(root, remote); + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + throw new StateError( + "RemoteNotConfigured", + `There is no remote "${remote}". Add it with \`cssforge sync remote add --name ${remote} --kind paper --file \`.`, + path, + ); + } + let data: unknown; + try { + data = JSON.parse(text); + } catch (error) { + throw new StateError( + "InvalidState", + `The state file is not JSON: ${String(error)}`, + path, + ); + } + const parsed = stateSchema.safeParse(data); + if (!parsed.success) { + throw new StateError( + "InvalidState", + `The state file is not valid: ${z.prettifyError(parsed.error)}`, + path, + ); + } + return parsed.data; +} + +/** Writes the state of `remote` in one step: a reader never sees half a file. */ +export async function writeState( + root: string, + remote: string, + state: SyncState, +): Promise { + const path = statePath(root, remote); + await mkdir(dirname(path), { recursive: true }); + const temporary = `${path}.${process.pid}.tmp`; + await writeFile(temporary, `${JSON.stringify(state, null, "\t")}\n`, "utf8"); + await rename(temporary, path); + return path; +} diff --git a/packages/cssforge/tests/acidcat.test.ts b/packages/cssforge/tests/acidcat.test.ts index 175f9db..cfb15b2 100644 --- a/packages/cssforge/tests/acidcat.test.ts +++ b/packages/cssforge/tests/acidcat.test.ts @@ -141,12 +141,31 @@ test("mcp - cssforge mcp serves the capabilities as tools", async () => { send({ jsonrpc: "2.0", method: "notifications/initialized" }); send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); - const listed = (await nextLine()).result as { tools: { name: string }[] }; + const listed = (await nextLine()).result as { + tools: { name: string; annotations?: Record }[]; + }; expect(listed.tools.map((tool) => tool.name).sort()).toEqual([ "config.check", + "sync.fetch", + "sync.inbox.adopt", + "sync.inbox.list", + "sync.inbox.overwrite", + "sync.inbox.reject", + "sync.plan", + "sync.push", + "sync.remote.add", "tokens.build", "tokens.generate", ]); + // An agent client asks before a destructive tool, and not before a read-only one. + const annotations = (name: string) => + listed.tools.find((tool) => tool.name === name)?.annotations; + expect(annotations("sync.push")).toMatchObject({ + destructiveHint: true, + idempotentHint: true, + }); + expect(annotations("sync.inbox.reject")).toMatchObject({ destructiveHint: false }); + expect(annotations("sync.plan")).toMatchObject({ readOnlyHint: true }); send({ jsonrpc: "2.0", diff --git a/packages/cssforge/tests/fixtures/fake-paper-mcp.ts b/packages/cssforge/tests/fixtures/fake-paper-mcp.ts new file mode 100644 index 0000000..fc46d6e --- /dev/null +++ b/packages/cssforge/tests/fixtures/fake-paper-mcp.ts @@ -0,0 +1,99 @@ +/** + * A stand-in for the MCP server of Paper Desktop (`paper-design mcp`), in the wire form + * of Paper 0.5.19: each file tool answers with a text item that names the file, then a + * text item with the result as JSON. It serves the token tools that sync uses. + * + * FAKE_PAPER_STATE is a JSON file with the tokens of the file, kept between processes. + * FAKE_PAPER_LOG gets one JSON line for each tool call: `{ name, arguments }`. + */ +import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +interface Token { + name: string; + type: string; + value: string | number; + description?: string; +} + +const statePath = process.env.FAKE_PAPER_STATE ?? ""; +const logPath = process.env.FAKE_PAPER_LOG ?? ""; +const file = { id: "01FAKE", name: "Fake file" }; + +const readTokens = (): Token[] => + existsSync(statePath) ? (JSON.parse(readFileSync(statePath, "utf8")) as Token[]) : []; +const writeTokens = (tokens: Token[]) => writeFileSync(statePath, JSON.stringify(tokens)); + +const answer = (id: unknown, result: unknown) => + process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`); +const toolResult = (body: unknown) => ({ + content: [ + { type: "text", text: JSON.stringify({ file, contentHash: { tokens: "0" } }) }, + { type: "text", text: JSON.stringify(body) }, + ], +}); + +const tools: Record) => unknown> = { + get_basic_info: () => ({ fileName: file.name, tokens: { items: [] } }), + get_tokens: () => ({ + tokens: readTokens().map((token) => ({ ...token, value: String(token.value) })), + }), + create_tokens: (args) => { + const tokens = readTokens(); + const results = (args.tokens as Token[]).map((token) => { + tokens.push(token); + return { name: token.name, result: "created" }; + }); + writeTokens(tokens); + return { tokens: results, count: results.length }; + }, + set_tokens: (args) => { + let tokens = readTokens(); + const edits = args.tokens as { + name: string; + newName?: string; + value?: string; + delete?: boolean; + }[]; + const results = edits.map((edit) => { + const token = tokens.find((candidate) => candidate.name === edit.name); + if (!token) return { result: "error", message: `Token not found: "${edit.name}".` }; + if (edit.delete) { + tokens = tokens.filter((candidate) => candidate !== token); + return { name: edit.name, result: "deleted" }; + } + if (edit.newName) token.name = edit.newName; + if (edit.value !== undefined) token.value = edit.value; + return { name: edit.name, result: "updated" }; + }); + writeTokens(tokens); + return { tokens: results, count: results.length }; + }, +}; + +createInterface({ input: process.stdin }).on("line", (line) => { + const message = JSON.parse(line) as { + id?: unknown; + method: string; + params?: Record; + }; + if (message.method === "initialize") { + answer(message.id, { + protocolVersion: "2025-06-18", + capabilities: { tools: {} }, + serverInfo: { name: "paper-desktop", version: "0.0.1" }, + }); + return; + } + if (message.method !== "tools/call") return; + const name = String(message.params?.name); + const args = (message.params?.arguments ?? {}) as Record; + appendFileSync(logPath, `${JSON.stringify({ name, arguments: args })}\n`); + const tool = tools[name]; + answer( + message.id, + tool + ? toolResult(tool(args)) + : { isError: true, content: [{ type: "text", text: `Unknown tool ${name}.` }] }, + ); +}); diff --git a/packages/cssforge/tests/sync-paper.test.ts b/packages/cssforge/tests/sync-paper.test.ts new file mode 100644 index 0000000..a89761d --- /dev/null +++ b/packages/cssforge/tests/sync-paper.test.ts @@ -0,0 +1,239 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSession } from "@acid-cat/core-ts"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { + cssforge, + paperAdapter, + syncFetch, + syncInboxAdopt, + syncPlan, + syncPush, + syncRemoteAdd, + toJsonSchema, +} from "../src/capabilities.ts"; + +const fakePaper = fileURLToPath(new URL("./fixtures/fake-paper-mcp.ts", import.meta.url)); + +let projectDir = ""; +let logPath = ""; + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), "cssforge-sync-paper-")); + logPath = join(projectDir, "paper.log"); + await writeFile(logPath, "", "utf8"); + process.env.FAKE_PAPER_STATE = join(projectDir, "paper.json"); + process.env.FAKE_PAPER_LOG = logPath; + await writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify({ + colors: { palette: { value: { brand: { 500: "oklch(60% 0.2 250)" } } } }, + typography: { weight: { body: { value: { bold: "700" } } } }, + })};\n`, + "utf8", + ); +}); + +afterEach(async () => { + delete process.env.FAKE_PAPER_STATE; + delete process.env.FAKE_PAPER_LOG; + await rm(projectDir, { recursive: true, force: true }); +}); + +const openSession = (command: string, args: string[]) => + createSession(cssforge, { + target: "library", + context: { cwd: projectDir, remotes: [paperAdapter({ command, args })] }, + toJsonSchema, + }); + +const toolCalls = async () => + (await readFile(logPath, "utf8")) + .split("\n") + .filter(Boolean) + .map( + (line) => JSON.parse(line) as { name: string; arguments: Record }, + ); + +test("paper - remote add binds the file id that Paper reports for a file URL", async () => { + await using session = openSession(process.execPath, [fakePaper]); + + const result = await session.call(syncRemoteAdd, { + file: "https://app.paper.design/file/01FAKE/p-1-0", + }); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + if (!result.ok) return; + expect(result.value.target).toEqual({ + file: "01FAKE", + fileName: "Fake file", + modes: ["default"], + options: {}, + }); + expect(await toolCalls()).toEqual([ + { + name: "get_basic_info", + arguments: { fileId: "https://app.paper.design/file/01FAKE/p-1-0" }, + }, + ]); +}); + +test("paper - push sends Paper's token types, a font weight as a number, and reads the values back", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + + const result = await session.call(syncPush, {}); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + expect((await toolCalls()).slice(1)).toEqual([ + { name: "get_tokens", arguments: { fileId: "01FAKE", format: "json" } }, + { + name: "create_tokens", + arguments: { + fileId: "01FAKE", + tokens: [ + { + type: "color", + name: "--palette-brand-500", + value: "oklch(60% 0.2 250)", + description: "cssforge: palette.brand.500", + }, + { + type: "fontWeight", + name: "--typography-weight-body-bold", + value: 700, + description: "cssforge: typography.weight.body.bold", + }, + ], + }, + }, + { name: "get_tokens", arguments: { fileId: "01FAKE", format: "json" } }, + ]); + if (result.ok) expect(result.value.callsUsed).toEqual(3); +}); + +test("paper - a missing paper-design command fails as RemoteUnavailable", async () => { + await using session = openSession(join(projectDir, "no-such-paper-design"), ["mcp"]); + + const result = await session.call(syncRemoteAdd, { file: "01FAKE" }); + + expect(result.ok ? undefined : result.error._tag).toEqual("RemoteUnavailable"); + if (!result.ok) expect(result.error.message).toContain("was not found"); +}); + +test("paper - a token name the state cannot hold fails the fetch and leaves the state readable", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([{ name: "brand", type: "color", value: "#ff0000" }]), + "utf8", + ); + + const fetched = await session.call(syncFetch, {}); + const planned = await session.call(syncPlan, {}); + + expect(fetched.ok ? undefined : fetched.error._tag).toEqual("RemoteFailed"); + expect(planned.ok ? undefined : planned.error._tag).toEqual("NotFetched"); +}); + +test("paper - remote add refuses options before it starts Paper", async () => { + await using session = openSession(join(projectDir, "no-such-paper-design"), ["mcp"]); + + const result = await session.call(syncRemoteAdd, { + file: "01FAKE", + options: { collection: "Tokens" }, + }); + + expect(result.ok ? undefined : result.error._tag).toEqual("InvalidOptions"); +}); + +test("paper - adopting a token with a new value renames it, then updates it under the new name", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + await session.call(syncPush, {}); + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([ + ...JSON.parse(await readFile(process.env.FAKE_PAPER_STATE ?? "", "utf8")), + { name: "--brand-accent", type: "color", value: "oklch(70% 0.2 30)" }, + ]), + "utf8", + ); + await session.call(syncFetch, {}); + await writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify({ + colors: { + palette: { + value: { brand: { 500: "oklch(60% 0.2 250)", accent: "oklch(72% 0.2 30)" } }, + }, + }, + typography: { weight: { body: { value: { bold: "700" } } } }, + })};\n`, + "utf8", + ); + await session.call(syncInboxAdopt, { + item: "brand-accent", + path: "palette.brand.accent", + }); + await writeFile(logPath, "", "utf8"); + + const result = await session.call(syncPush, {}); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + const setTokens = (await toolCalls()).find((call) => call.name === "set_tokens"); + expect(setTokens?.arguments.tokens).toEqual([ + { name: "--brand-accent", newName: "--palette-brand-accent" }, + { + name: "--palette-brand-accent", + value: "oklch(72% 0.2 30)", + description: "cssforge: palette.brand.accent", + }, + ]); +}); + +test("paper - each result gives the key its token has after that operation", async () => { + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([{ name: "--old", type: "spacing", value: "4px" }]), + "utf8", + ); + const session = await paperAdapter({ + command: process.execPath, + args: [fakePaper], + }).open(new AbortController().signal); + try { + const target = { + file: "01FAKE", + fileName: "Fake file", + modes: ["default"], + options: {}, + }; + + const results = await session.apply( + target, + [ + { + op: "update", + key: "--old", + name: "--old", + type: "spacing", + values: { default: "8px" }, + description: "", + }, + { op: "rename", key: "--old", from: "--old", to: "--new" }, + ], + new Map(), + ); + + expect(results.map(({ ok, key }) => [ok, key])).toEqual([ + [true, "--old"], + [true, "--new"], + ]); + } finally { + session.close(); + } +}); diff --git a/packages/cssforge/tests/sync.test.ts b/packages/cssforge/tests/sync.test.ts new file mode 100644 index 0000000..1a62a37 --- /dev/null +++ b/packages/cssforge/tests/sync.test.ts @@ -0,0 +1,913 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSession } from "@acid-cat/core-ts"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { + type ApplyResult, + cssforge, + type ModeValues, + type Operation, + paperAdapter, + type RemoteAdapter, + RemoteError, + type RemoteOptions, + type RemoteToken, + syncFetch, + syncInboxAdopt, + syncInboxOverwrite, + syncInboxReject, + syncPlan, + syncPush, + syncRemoteAdd, + toJsonSchema, +} from "../src/capabilities.ts"; +import { childEnv } from "./helpers.ts"; + +interface FakeRemoteSettings { + kind: string; + /** The modes the target holds. */ + modes: string[]; + /** `name`: the key is the custom property, as on Paper. `id`: the remote assigns an id. */ + keys: "name" | "id"; + /** The mapping of the remote. The default is Paper's. */ + map?: RemoteAdapter["map"]; +} + +/** + * An in-memory design file. It keeps the rules that sync depends on: an alias must name an + * existing token of the same type, a change addresses an existing key, and duplicate names + * are allowed. With `keys: "name"` it behaves as Paper, whose key is the token name; with + * `keys: "id"` it assigns ids and keeps them across renames. `store` changes a value as the + * remote normalizes it. + */ +class FakeRemote { + tokens: RemoteToken[] = []; + requests = 0; + /** Names whose create or update the remote refuses. */ + refuse = new Set(); + store = (value: string) => value; + /** The number of reads that succeed before every later read fails. */ + readsBeforeFailure = Number.POSITIVE_INFINITY; + /** The options of the last `resolve`. */ + options: RemoteOptions | undefined; + /** Accept creates without giving their key, as a faulty adapter would. */ + omitKeys = false; + private nextId = 1; + private readonly settings: FakeRemoteSettings; + readonly adapter: RemoteAdapter; + + constructor(settings: FakeRemoteSettings) { + this.settings = settings; + this.adapter = { + kind: settings.kind, + // The mapping of the real Paper remote: only the transport is fake. + map: settings.map ?? paperAdapter().map, + // A fake of a kind with options takes any. + checkOptions: () => {}, + open: async () => { + let calls = 0; + const request = () => { + calls += 1; + this.requests += 1; + }; + return { + get calls() { + return calls; + }, + close: () => {}, + resolve: async (file, options) => { + request(); + this.options = options; + return { + file: file.replace(/^.*\/file\//, ""), + fileName: "Tokens", + modes: settings.modes, + options, + }; + }, + read: async () => { + request(); + if (this.readsBeforeFailure <= 0) { + throw new RemoteError("RemoteUnavailable", "The remote stopped."); + } + this.readsBeforeFailure -= 1; + return this.tokens.map((token) => ({ + ...token, + values: { ...token.values }, + })); + }, + apply: async (_target, operations) => { + request(); + const renamed = new Map(); + return operations.map((operation) => this.apply(operation, renamed)); + }, + }; + }, + }; + } + + /** Adds a token as a designer would. A tool with ids may record no custom property. */ + add(name: string, type: string, values: ModeValues, label = name) { + const key = this.settings.keys === "name" ? name : `V${this.nextId++}`; + this.tokens.push({ key, label, ...(name ? { name } : {}), type, values }); + } + + byKey = (key: string) => this.tokens.find((token) => token.key === key); + + private find = (key: string) => this.tokens.find((token) => token.key === key); + + private stored = (values: ModeValues): ModeValues => + Object.fromEntries( + Object.entries(values).map(([mode, value]) => [mode, this.store(value)]), + ); + + private apply(operation: Operation, renamed: Map): ApplyResult { + const refused = (message: string): ApplyResult => ({ operation, ok: false, message }); + if (operation.op === "create") { + if (this.refuse.has(operation.name)) return refused("Refused."); + for (const value of Object.values(operation.values)) { + const alias = /^var\((--[\w-]+)\)$/.exec(value)?.[1]; + const target = this.tokens.find((token) => token.name === alias); + if (alias && target?.type !== operation.type) { + return refused(`Invalid value "${value}".`); + } + } + const key = this.settings.keys === "name" ? operation.name : `V${this.nextId++}`; + this.tokens.push({ + key, + label: operation.name, + name: operation.name, + type: operation.type, + values: this.stored(operation.values), + description: operation.description, + }); + return this.omitKeys ? { operation, ok: true } : { operation, ok: true, key }; + } + const token = this.find(renamed.get(operation.key) ?? operation.key); + if (!token) return refused("Token not found."); + switch (operation.op) { + case "update": + if (this.refuse.has(operation.name)) return refused("Refused."); + token.values = this.stored(operation.values); + return { operation, ok: true, key: token.key }; + case "rename": { + token.label = operation.to; + token.name = operation.to; + if (this.settings.keys === "name") { + renamed.set(token.key, operation.to); + token.key = operation.to; + } + return { operation, ok: true, key: token.key }; + } + case "delete": + this.tokens = this.tokens.filter((candidate) => candidate !== token); + return { operation, ok: true }; + } + } + + byName = (name: string) => this.tokens.find((token) => token.name === name); + value = (name: string) => this.byName(name)?.values.default; +} + +/** A palette color, an alias to it, two sizes, and three tokens Paper has no place for. */ +const baseConfig = { + colors: { + palette: { + value: { + brand: { + 500: "oklch(60% 0.2 250)", + 600: { mix: { from: "palette.brand.500", with: "black", amount: 20 } }, + }, + }, + }, + theme: { + value: { + light: { + value: { + surface: { + value: { accent: "var(--brand)" }, + variables: { brand: "palette.brand.500" }, + }, + }, + }, + dark: { + value: { surface: { value: { accent: "oklch(30% 0.1 250)" } } }, + settings: { selector: ".dark" }, + }, + }, + }, + }, + spacing: { custom: { size: { value: { 1: "4px", 2: "8px" } } } }, + motion: { duration: { ui: { value: { press: "120ms" } } } }, +}; + +/** One color with a `.dark` override, and one `light-dark()` pair. */ +const themedConfig = { + colors: { + palette: { value: { brand: { 500: "oklch(60% 0.2 250)" } } }, + theme: { + value: { + base: { + value: { + surface: { + value: { accent: "var(--brand)" }, + variables: { brand: "palette.brand.500" }, + settings: { variantNameOnly: true }, + }, + }, + }, + night: { + value: { + surface: { + value: { accent: "oklch(30% 0.1 250)" }, + settings: { variantNameOnly: true }, + }, + }, + settings: { selector: ".dark" }, + }, + light: { value: { text: { value: { body: "oklch(20% 0 0)" } } } }, + dark: { value: { text: { value: { body: "oklch(95% 0 0)" } } } }, + }, + settings: { lightDark: { light: "light", dark: "dark" } }, + }, + }, +}; + +let projectDir = ""; +let paper: FakeRemote; + +const writeConfig = (config: unknown) => + writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify(config)};\n`, + "utf8", + ); + +const withSpacing = (sizes: Record) => ({ + ...baseConfig, + spacing: { custom: { size: { value: sizes } } }, +}); + +/** One spacing token, for remotes whose keys the test counts. */ +const spacingOnly = (size: string) => ({ + spacing: { custom: { size: { value: { 1: size } } } }, +}); + +const withAccent = (accent: string) => ({ + ...baseConfig, + colors: { + ...baseConfig.colors, + palette: { + value: { brand: { ...baseConfig.colors.palette.value.brand, accent } }, + }, + }, +}); + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), "cssforge-sync-")); + paper = new FakeRemote({ kind: "paper", modes: ["default"], keys: "name" }); + await writeConfig(baseConfig); +}); + +afterEach(async () => { + await rm(projectDir, { recursive: true, force: true }); +}); + +const openSession = (remotes: RemoteAdapter[] = [paper.adapter]) => + createSession(cssforge, { + target: "library", + context: { cwd: projectDir, remotes }, + toJsonSchema, + }); + +/** Calls a capability, and gives its value, or fails the test with its failure. */ +const expectValue = async ( + result: Promise<{ ok: true; value: T } | { ok: false; error: unknown }>, +) => { + const settled = await result; + if (!settled.ok) + throw new Error(`Expected a value. Received ${JSON.stringify(settled.error)}`); + return settled.value; +}; + +/** A session with the remote added and the configuration pushed once. */ +const pushedSession = async () => { + const session = openSession(); + await expectValue( + session.call(syncRemoteAdd, { file: "https://app.paper.design/file/F1" }), + ); + await expectValue(session.call(syncPush, {})); + return session; +}; + +const created = (name: string, type: string, value: string, sourcePath: string) => ({ + op: "create", + name, + type, + values: { default: value }, + description: `cssforge: ${sourcePath}`, +}); + +test("push - creates the configuration tokens on an empty remote, each alias after its target", async () => { + await using session = openSession(); + await expectValue( + session.call(syncRemoteAdd, { file: "https://app.paper.design/file/F1" }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied).toEqual([ + { + operation: created( + "--palette-brand-500", + "color", + "oklch(60% 0.2 250)", + "palette.brand.500", + ), + ok: true, + key: "--palette-brand-500", + }, + { + operation: created( + "--theme-light-surface-accent", + "color", + "var(--palette-brand-500)", + "theme.light.surface.accent", + ), + ok: true, + key: "--theme-light-surface-accent", + }, + { + operation: created( + "--spacing-size-1", + "spacing", + "0.25rem", + "spacing.custom.size.1", + ), + ok: true, + key: "--spacing-size-1", + }, + { + operation: created( + "--spacing-size-2", + "spacing", + "0.5rem", + "spacing.custom.size.2", + ), + ok: true, + key: "--spacing-size-2", + }, + ]); + expect(report.operations).toEqual([]); + expect(report.target).toEqual({ + file: "F1", + fileName: "Tokens", + modes: ["default"], + options: {}, + }); +}); + +test("push - reports each configuration token that has no place on Paper, with the reason", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + + const report = await expectValue(session.call(syncPush, { "dry-run": true })); + + expect(report.skipped).toEqual([ + { + name: "--palette-brand-600", + sourcePath: "palette.brand.600", + reason: "Paper does not take color-mix() values.", + }, + { + name: "--theme-dark-surface-accent", + sourcePath: "theme.dark.surface.accent", + mode: ".dark", + reason: 'The remote has no mode ".dark". It holds: default.', + }, + { + name: "--motion-duration-ui-press", + sourcePath: "motion.duration.ui.press", + reason: "Paper has no duration tokens.", + }, + ]); + expect(report.applied).toEqual([]); + expect(paper.tokens).toEqual([]); +}); + +test("push - a push with no change reads the remote once and sends nothing", async () => { + await using session = await pushedSession(); + paper.requests = 0; + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied).toEqual([]); + expect(report.callsUsed).toEqual(paper.requests); + expect(paper.requests).toEqual(1); +}); + +test("push - updates a changed token and deletes a token removed from the configuration", async () => { + await using session = await pushedSession(); + await writeConfig(withSpacing({ 1: "6px" })); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { + op: "update", + key: "--spacing-size-1", + name: "--spacing-size-1", + type: "spacing", + values: { default: "0.375rem" }, + description: "cssforge: spacing.custom.size.1", + }, + { op: "delete", key: "--spacing-size-2", label: "--spacing-size-2" }, + ]); + expect(paper.value("--spacing-size-1")).toEqual("0.375rem"); + expect(paper.byName("--spacing-size-2")).toBeUndefined(); +}); + +test("fetch - a value the remote stores in another form is not a change", async () => { + paper.store = (value) => value.replace("oklch(60% 0.2 250)", "oklch(60.0% 0.200 250)"); + await using session = await pushedSession(); + + const report = await expectValue(session.call(syncFetch, {})); + + expect(report.operations).toEqual([]); + expect(report.inbox).toEqual([]); +}); + +test("inbox - a value edited on the remote waits until overwrite gives the configuration value back", async () => { + await using session = await pushedSession(); + const edited = paper.byName("--spacing-size-1"); + if (edited) edited.values = { default: "12px" }; + + const held = await expectValue(session.call(syncPush, {})); + + expect(held.applied).toEqual([]); + expect(held.inbox).toEqual([ + { + id: "spacing-size-1", + kind: "edited", + key: "--spacing-size-1", + label: "--spacing-size-1", + type: "spacing", + remoteValues: { default: "12px" }, + localValues: { default: "0.25rem" }, + actions: ["overwrite"], + }, + ]); + expect(paper.value("--spacing-size-1")).toEqual("12px"); + + await expectValue(session.call(syncInboxOverwrite, { item: "spacing-size-1" })); + const restored = await expectValue(session.call(syncPush, {})); + + expect(paper.value("--spacing-size-1")).toEqual("0.25rem"); + expect(restored.inbox).toEqual([]); +}); + +test("inbox - a token the remote created is deleted by the push after a reject", async () => { + await using session = await pushedSession(); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + + const fetched = await expectValue(session.call(syncFetch, {})); + expect(fetched.inbox).toEqual([ + { + id: "brand-accent", + kind: "new", + key: "--brand-accent", + label: "--brand-accent", + type: "color", + remoteValues: { default: "oklch(70% 0.2 30)" }, + actions: ["adopt", "reject"], + }, + ]); + + const decided = await expectValue( + session.call(syncInboxReject, { item: "brand-accent" }), + ); + expect(decided.callsUsed).toEqual(0); + expect(decided.skipped.map((token) => token.name)).toEqual([ + "--palette-brand-600", + "--theme-dark-surface-accent", + "--motion-duration-ui-press", + ]); + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { op: "delete", key: "--brand-accent", label: "--brand-accent" }, + ]); + expect(paper.byName("--brand-accent")).toBeUndefined(); + expect(report.inbox).toEqual([]); +}); + +test("inbox - adopt renames a token the remote created to the name the configuration gives it", async () => { + await using session = await pushedSession(); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + await expectValue(session.call(syncFetch, {})); + + const early = await session.call(syncInboxAdopt, { + item: "brand-accent", + path: "palette.brand.accent", + }); + expect(early.ok).toEqual(false); + if (!early.ok) expect(early.error._tag).toEqual("InvalidDecision"); + + await writeConfig(withAccent("oklch(70% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { + op: "rename", + key: "--brand-accent", + from: "--brand-accent", + to: "--palette-brand-accent", + }, + ]); + expect(paper.value("--palette-brand-accent")).toEqual("oklch(70% 0.2 30)"); + expect(paper.byName("--brand-accent")).toBeUndefined(); + + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); + expect(after.inbox).toEqual([]); +}); + +test("inbox - adopt with a new value renames the token, then updates it under its new key", async () => { + await using session = await pushedSession(); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + await expectValue(session.call(syncFetch, {})); + await writeConfig(withAccent("oklch(72% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation, ok }) => [operation.op, ok])).toEqual([ + ["rename", true], + ["update", true], + ]); + expect(paper.value("--palette-brand-accent")).toEqual("oklch(72% 0.2 30)"); + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); +}); + +test("push - an operation the remote refuses is reported and sent again at the next push", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.refuse.add("--spacing-size-2"); + + const first = await expectValue(session.call(syncPush, {})); + + expect(first.applied.find(({ ok }) => !ok)).toEqual({ + operation: created("--spacing-size-2", "spacing", "0.5rem", "spacing.custom.size.2"), + ok: false, + message: "Refused.", + }); + expect(first.operations.map((operation) => operation.op)).toEqual(["create"]); + + paper.refuse.clear(); + const second = await expectValue(session.call(syncPush, {})); + + expect(second.applied.map(({ operation, ok }) => [operation.op, ok])).toEqual([ + ["create", true], + ]); + expect(paper.value("--spacing-size-2")).toEqual("0.5rem"); +}); + +test("plan - fails with RemoteNotConfigured before remote add, and NotFetched before a fetch", async () => { + await using session = openSession(); + + const unbound = await session.call(syncPlan, {}); + expect(unbound.ok ? undefined : unbound.error._tag).toEqual("RemoteNotConfigured"); + + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + const unread = await session.call(syncPlan, {}); + expect(unread.ok ? undefined : unread.error._tag).toEqual("NotFetched"); +}); + +test("remote add - binding the same target again keeps the sync state", async () => { + await using session = await pushedSession(); + + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + + const kept = await expectValue(session.call(syncPlan, {})); + expect(kept.operations).toEqual([]); +}); + +test("remote add - binding another file starts the sync again", async () => { + await using session = await pushedSession(); + + await expectValue(session.call(syncRemoteAdd, { file: "F2" })); + + const restarted = await session.call(syncPlan, {}); + expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); +}); + +test("remote add - binding the same file with other options starts the sync again", async () => { + await using session = await pushedSession(); + + await expectValue( + session.call(syncRemoteAdd, { file: "F1", options: { collection: "Brand" } }), + ); + + expect(paper.options).toEqual({ collection: "Brand" }); + const restarted = await session.call(syncPlan, {}); + expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); +}); + +test("cli - cssforge sync plan runs its capability and gives a failure as JSON", () => { + const cliPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url)); + + const plan = spawnSync(process.execPath, [cliPath, "sync", "plan", "--agent"], { + cwd: projectDir, + encoding: "utf8", + env: childEnv, + }); + + expect(plan.status).toEqual(1); + expect(JSON.parse(plan.stdout)).toMatchObject({ _tag: "RemoteNotConfigured" }); +}); + +test("push - a pushed token whose new value has no place on Paper keeps its Paper copy", async () => { + await using session = await pushedSession(); + await writeConfig({ + ...baseConfig, + colors: { + ...baseConfig.colors, + palette: { + value: { + brand: { + 400: "oklch(50% 0.2 250)", + 500: { mix: { from: "palette.brand.400", with: "black", amount: 10 } }, + }, + }, + }, + }, + }); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation.op)).toEqual(["create"]); + expect(report.skipped.map((token) => token.name)).toContain("--palette-brand-500"); + expect(paper.value("--palette-brand-500")).toEqual("oklch(60% 0.2 250)"); + expect(paper.value("--theme-light-surface-accent")).toEqual("var(--palette-brand-500)"); +}); + +test("inbox - two remote tokens cannot be adopted as the same configuration token", async () => { + await using session = await pushedSession(); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + paper.add("--accent", "color", { default: "oklch(70% 0.2 30)" }); + await expectValue(session.call(syncFetch, {})); + await writeConfig(withAccent("oklch(70% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + + const second = await session.call(syncInboxAdopt, { + item: "accent", + path: "palette.brand.accent", + }); + + expect(second.ok ? undefined : second.error._tag).toEqual("InvalidDecision"); +}); + +test("push - tokens the remote accepted stay owned when the read-back after the push fails", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.readsBeforeFailure = 1; + + const failed = await session.call(syncPush, {}); + expect(failed.ok ? undefined : failed.error._tag).toEqual("RemoteUnavailable"); + expect(paper.tokens).toHaveLength(4); + + paper.readsBeforeFailure = Number.POSITIVE_INFINITY; + const next = await expectValue(session.call(syncPush, {})); + + expect(next.applied).toEqual([]); + expect(next.inbox).toEqual([]); +}); + +test("modes - a remote with modes gets one token per custom property, with a value for each mode", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", ".dark", "light", "dark"], + keys: "id", + }); + await writeConfig(themedConfig); + await using session = openSession([figma.adapter]); + await expectValue( + session.call(syncRemoteAdd, { + kind: "figma", + file: "F1", + options: { collection: "Tokens" }, + }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied).toEqual([ + { + operation: created( + "--palette-brand-500", + "color", + "oklch(60% 0.2 250)", + "palette.brand.500", + ), + ok: true, + key: "V1", + }, + { + operation: { + op: "create", + name: "--accent", + type: "color", + values: { default: "var(--palette-brand-500)", ".dark": "oklch(30% 0.1 250)" }, + description: "cssforge: theme.base.surface.accent", + }, + ok: true, + key: "V2", + }, + { + operation: { + op: "create", + name: "--theme-text-body", + type: "color", + values: { light: "oklch(20% 0 0)", dark: "oklch(95% 0 0)" }, + description: "cssforge: theme.text.body", + }, + ok: true, + key: "V3", + }, + ]); + expect(report.skipped).toEqual([]); + expect(report.target.options).toEqual({ collection: "Tokens" }); + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); +}); + +test("modes - a token a designer renames keeps its link to the configuration through its key", async () => { + const figma = new FakeRemote({ kind: "figma", modes: ["default"], keys: "id" }); + await writeConfig(spacingOnly("4px")); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + await expectValue(session.call(syncPush, {})); + const token = figma.byName("--spacing-size-1"); + if (token) { + token.label = "spacing/size/1"; + delete token.name; + } + await writeConfig(spacingOnly("6px")); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.inbox).toEqual([]); + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { + op: "update", + key: "V1", + name: "--spacing-size-1", + type: "spacing", + values: { default: "0.375rem" }, + description: "cssforge: spacing.custom.size.1", + }, + ]); + expect(figma.byKey("V1")?.values).toEqual({ default: "0.375rem" }); +}); + +test("inbox - items that share a label get distinct ids, and a decision settles only its own", async () => { + const figma = new FakeRemote({ kind: "figma", modes: ["default"], keys: "id" }); + await writeConfig(spacingOnly("4px")); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + await expectValue(session.call(syncPush, {})); + figma.add("", "color", { default: "#ff0000" }, "brand"); + figma.add("", "color", { default: "#00ff00" }, "brand"); + + const fetched = await expectValue(session.call(syncFetch, {})); + expect(fetched.inbox.map((item) => item.id)).toEqual(["brand#V2", "brand#V3"]); + + await expectValue(session.call(syncInboxReject, { item: "brand#V2" })); + await expectValue(session.call(syncPush, {})); + + expect(figma.byKey("V2")).toBeUndefined(); + expect(figma.byKey("V3")?.values).toEqual({ default: "#00ff00" }); +}); + +test("push - a create the remote accepts without a key is refused, and the state stays readable", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.omitKeys = true; + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.every(({ ok }) => !ok)).toEqual(true); + expect(report.applied[0]?.message).toEqual( + "The remote accepted the change but gave no key for the token.", + ); + paper.omitKeys = false; + const next = await expectValue(session.call(syncFetch, {})); + expect(next.inbox.map((item) => item.kind)).toEqual([ + "collision", + "collision", + "collision", + "collision", + ]); +}); + +test("modes - a selector with a | is a mode name kept whole", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", "[lang|=en]"], + keys: "id", + }); + await writeConfig({ + colors: { + palette: { value: {} }, + theme: { + value: { + base: { + value: { + surface: { + value: { accent: "#000000" }, + settings: { variantNameOnly: true }, + }, + }, + }, + english: { + value: { + surface: { + value: { accent: "#ffffff" }, + settings: { variantNameOnly: true }, + }, + }, + settings: { selector: "[lang|=en]" }, + }, + }, + }, + }, + }); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.skipped).toEqual([]); + expect(figma.byName("--accent")?.values).toEqual({ + default: "#000000", + "[lang|=en]": "#ffffff", + }); +}); + +test("modes - each mode of a paired color gets its own branch of every light-dark() it builds on", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", "light", "dark"], + keys: "id", + map: (token) => ({ type: "color", value: token.resolvedValue }), + }); + const hover = { mix: { from: "theme.background.primary", with: "black", amount: 5 } }; + await writeConfig({ + colors: { + palette: { + value: { base: { white: "oklch(100% 0 0)", ink: "oklch(14.5% 0 0)" } }, + }, + theme: { + value: { + light: { + value: { + background: { + value: { primary: "var(--white)", hover }, + variables: { white: "palette.base.white" }, + }, + }, + }, + dark: { + value: { + background: { + value: { primary: "var(--ink)", hover }, + variables: { ink: "palette.base.ink" }, + }, + }, + }, + }, + settings: { lightDark: { light: "light", dark: "dark" } }, + }, + }, + }); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + + await expectValue(session.call(syncPush, {})); + + expect(figma.byName("--theme-background-hover")?.values).toEqual({ + light: "color-mix(in oklch, oklch(100% 0 none), black 5%)", + dark: "color-mix(in oklch, oklch(14.5% 0 none), black 5%)", + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 699d64d..3de83cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -288,8 +288,8 @@ importers: packages/cssforge: dependencies: '@acid-cat/core-ts': - specifier: 0.13.0 - version: 0.13.0 + specifier: 0.15.0 + version: 0.15.0 chokidar: specifier: 4.0.3 version: 4.0.3 @@ -304,8 +304,8 @@ importers: version: 4.6.7 devDependencies: '@acid-cat/cli': - specifier: 0.13.0 - version: 0.13.0(redis@6.3.1) + specifier: 0.15.0 + version: 0.15.0(redis@6.3.1) '@biomejs/biome': specifier: 2.4.2 version: 2.4.2 @@ -377,12 +377,12 @@ packages: resolution: {integrity: sha512-fNdBOb3MgDz/1UCIoeY4wDuGbp+/3s5y6UrsyfMabECbh/CVycj7Er33JXqSxRwxrRKXcGE1Jipuq/1mODInsQ==} engines: {node: '>=11'} - '@acid-cat/catalog@0.13.0': - resolution: {integrity: sha512-KD67iK20urO4DMES5GaMDdd+KPzFQASiiEijfKyKWCM7JxmWm54Q9b5en2j57TgrnxXZ5cQAACRT5BTDM8WZjw==} + '@acid-cat/catalog@0.15.0': + resolution: {integrity: sha512-O3Nt8YaJTaCK2tqMyLloZDEdHz1qJw6tNAJSCvwEcH8cjuN/re7AJ6r5GgBLlu1G9R5+DW8okW2BwCYgWEsxwA==} engines: {node: '>=24'} - '@acid-cat/cli@0.13.0': - resolution: {integrity: sha512-2jAo9UazEbb4vHGX3A0PIFIsLX3NxXuqVtfokOThrvGCAM7toKhXrDz5myfjJp2oHSkN3FPqLiipy/dM3xEu7w==} + '@acid-cat/cli@0.15.0': + resolution: {integrity: sha512-sGEu2ejkuscyefaKQXFjlFYDVctEnx45DcxAF/02ElnWvHkytsfblxJCjjRtE6DnPKHH8ZMwEbgH8DH5ZaV4uQ==} engines: {node: '>=24'} hasBin: true peerDependencies: @@ -391,16 +391,16 @@ packages: playwright: optional: true - '@acid-cat/core-ts@0.13.0': - resolution: {integrity: sha512-Vg7yHQQc9I+0oKSSAvScdgQLXCzYBDeiWZB77xrzN+AeD3w+cwvNFYtC7eON1umgmMCbV0pwCEa9g8QbQvvs+w==} + '@acid-cat/core-ts@0.15.0': + resolution: {integrity: sha512-dZzqijq6TVKDdRa5tgImyhQeKeFmcpuODb2wEzulSaUO30SF4JbF0mUtgrQptyJoTpzlEErrqbDF/KVj8dvFRA==} engines: {node: '>=24'} - '@acid-cat/mcp-handshake@0.13.0': - resolution: {integrity: sha512-F9ddrvktaJPNFK5MmLfilcn0RZYeronzrgw9FEzj99QBGJlT/zGr7T+oDAk1uPvbJso7nklAF07lRalh3xpuQQ==} + '@acid-cat/mcp-handshake@0.15.0': + resolution: {integrity: sha512-O+zuySXjrUF9kuYEV7Sqebzvef9PMa8dXD11D5B7aQPU+D5wvRYVLH15Ehcbl1SnkQLHVbe8NHtR+Cb7op59gw==} engines: {node: '>=24'} - '@acid-cat/spec-ts@0.13.0': - resolution: {integrity: sha512-4N2eDx+3YIR4L3gpjHLeNsmrcvO3uwgLNBTSNteuualoAq+Z/TBFKnbpweUgZZAqqDHEYYrrblIdut+mzQSBJw==} + '@acid-cat/spec-ts@0.15.0': + resolution: {integrity: sha512-cv9U8JuI059xSJuvk4vvZZv41m7VPDWnhTTzK+fmw0Pz5qurDgaHIeUUunlFbCvp08XL+9P0Fm2CLomL1KC9hg==} engines: {node: '>=24'} '@algolia/abtesting@1.15.0': @@ -7685,12 +7685,12 @@ snapshots: js-yaml: 4.3.1 section-matter: 1.0.0 - '@acid-cat/catalog@0.13.0': {} + '@acid-cat/catalog@0.15.0': {} - '@acid-cat/cli@0.13.0(redis@6.3.1)': + '@acid-cat/cli@0.15.0(redis@6.3.1)': dependencies: - '@acid-cat/catalog': 0.13.0 - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/catalog': 0.15.0 + '@acid-cat/spec-ts': 0.15.0 '@effect/platform-node': 4.1.4(effect@4.1.4)(redis@6.3.1) '@effect/platform-node-shared': 4.1.4(effect@4.1.4) '@modelcontextprotocol/client': 2.4.0 @@ -7701,17 +7701,17 @@ snapshots: - redis - utf-8-validate - '@acid-cat/core-ts@0.13.0': + '@acid-cat/core-ts@0.15.0': dependencies: - '@acid-cat/catalog': 0.13.0 - '@acid-cat/mcp-handshake': 0.13.0 - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/catalog': 0.15.0 + '@acid-cat/mcp-handshake': 0.15.0 + '@acid-cat/spec-ts': 0.15.0 - '@acid-cat/mcp-handshake@0.13.0': + '@acid-cat/mcp-handshake@0.15.0': dependencies: - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/spec-ts': 0.15.0 - '@acid-cat/spec-ts@0.13.0': {} + '@acid-cat/spec-ts@0.15.0': {} '@algolia/abtesting@1.15.0': dependencies: diff --git a/skills/cssforge/references/cli-reference.md b/skills/cssforge/references/cli-reference.md index ae265b0..f379737 100644 --- a/skills/cssforge/references/cli-reference.md +++ b/skills/cssforge/references/cli-reference.md @@ -21,9 +21,45 @@ On a terminal, each command writes text for a person. For a script, in CI or for - `cssforge --watch [flags]` (`--watch` first): build now and after each change of the config or a local module it imports. One JSON line per build: `{ data: { ok: true, files, … } }` or `{ data: { ok: false, failure } }`. Exits with `130` when interrupted. -- `cssforge mcp`: serve the same capabilities as MCP tools through stdio. +- `cssforge mcp`: serve the same capabilities as MCP tools through stdio. `sync.push` and + `tokens.build` are marked destructive; `sync.plan`, `sync.inbox.list`, `tokens.generate` + and `config.check` read only. - `cssforge list`: every command with its flags. +## Token sync + +Sync keeps the tokens of a design file (Paper, through `paper-design mcp`) in sync with the +config. The config is the source of truth; what the file changes waits in an inbox. The +capabilities are in `packages/cssforge/src/sync/capabilities.ts`, the three-way plan in +`packages/cssforge/src/sync/plan.ts`, and the Paper mapping in `packages/cssforge/src/sync/paper.ts`. +State: `.cssforge/sync/.json` (commit it). Every command takes `--remote` (default `paper`). + +- `cssforge sync remote add --file [--name] [--kind paper]`: bind the file. 1 request. +- `cssforge sync fetch`: read the file, record it, report the plan. 1 request. +- `cssforge sync plan`: the plan against the last fetch. No request. +- `cssforge sync push [--dry-run]`: read, send the plan, read back. 1 to 4 requests. +- `cssforge sync inbox list`: the items of the last fetch. No request. +- `cssforge sync inbox adopt --item --path `: a `new` item becomes the config token at + the path (add it to the config first). The next push renames it in the file. +- `cssforge sync inbox reject --item `: the next push deletes a `new` item from the file. Paper + replaces each use of a deleted token with its last value; a renamed token keeps its uses. +- `cssforge sync inbox overwrite --item `: the next push writes the config value for an `edited`, + `deleted` or `collision` item. To keep the file's value, change the config instead. + +Results: `{ remote, target, fetchedAt, operations, inbox, skipped, callsUsed }`, and `applied` +for `push`. Values are per mode (`{ default: "8px" }`): `default` at `:root`, `light` and `dark` +for `light-dark()`, the selector or at-rule for other scopes. The target lists the modes it holds +(Paper: `default`); the others are in `skipped` with `mode`. A remote token has a `key` (Paper: its +name; other tools: an id) and a `label`; operations address it by key. +`sync remote add --options ''` passes adapter options (Paper takes none: `InvalidOptions`). An item id is the token name without `--`. A token path is the path in each pushed token's +description (`cssforge: palette.brand.500`). Failure tags: `RemoteNotConfigured`, `InvalidState`, +`RemoteUnavailable`, `RemoteFailed`, `NotFetched`, `UnknownItem`, `InvalidDecision`, +`UnknownKind`, `InvalidOptions`. Paper's free plan limits MCP calls: prefer `sync plan` and `sync inbox list` (no request) +after one `sync fetch`. + +Agent loop: `sync fetch` → read `sync inbox list` → edit the config → +`sync inbox adopt|reject|overwrite` → `sync plan` → `sync push`. + ## Flags - `--config`: config path (default `./cssforge.config.ts`)