@rien7/seji 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/design-surface.mjs +6 -0
- package/bin/postinstall.mjs +19 -0
- package/bin/seji.mjs +573 -0
- package/dist/agent/host.d.mts +34 -0
- package/dist/agent/host.mjs +387 -0
- package/dist/agent/messages.d.mts +9 -0
- package/dist/agent/messages.mjs +70 -0
- package/dist/agent/runtimes.mjs +157 -0
- package/dist/cli/app.mjs +321 -0
- package/dist/cli/appScan.mjs +284 -0
- package/dist/cli/catalog.mjs +78 -0
- package/dist/cli/component.mjs +165 -0
- package/dist/cli/consolidate.mjs +159 -0
- package/dist/cli/cssImport.mjs +68 -0
- package/dist/cli/dev.mjs +335 -0
- package/dist/cli/doctor.mjs +306 -0
- package/dist/cli/init.mjs +338 -0
- package/dist/cli/legacyNames.mjs +266 -0
- package/dist/cli/migrate.mjs +163 -0
- package/dist/cli/prompt.mjs +34 -0
- package/dist/cli/propose.mjs +208 -0
- package/dist/cli/providers.mjs +344 -0
- package/dist/cli/reviewOps.mjs +110 -0
- package/dist/cli/semver.mjs +45 -0
- package/dist/cli/setup.mjs +357 -0
- package/dist/cli/sketches.mjs +47 -0
- package/dist/cli/skills.mjs +150 -0
- package/dist/cli/snapshot.mjs +107 -0
- package/dist/cli/tokenOps.mjs +120 -0
- package/dist/cli/types.mjs +191 -0
- package/dist/cli/updater.mjs +274 -0
- package/dist/components/astIndex.mjs +992 -0
- package/dist/components/ops.mjs +1069 -0
- package/dist/editor/AgentProposalCard.d.ts +10 -0
- package/dist/editor/AgentProposalCard.d.ts.map +1 -0
- package/dist/editor/AgentProposalCard.js +31 -0
- package/dist/editor/AgentProposalCard.js.map +1 -0
- package/dist/editor/App.d.ts +2 -0
- package/dist/editor/App.d.ts.map +1 -0
- package/dist/editor/App.js +2832 -0
- package/dist/editor/App.js.map +1 -0
- package/dist/editor/CanvasHud.d.ts +12 -0
- package/dist/editor/CanvasHud.d.ts.map +1 -0
- package/dist/editor/CanvasHud.js +13 -0
- package/dist/editor/CanvasHud.js.map +1 -0
- package/dist/editor/CanvasSurface.d.ts +31 -0
- package/dist/editor/CanvasSurface.d.ts.map +1 -0
- package/dist/editor/CanvasSurface.js +270 -0
- package/dist/editor/CanvasSurface.js.map +1 -0
- package/dist/editor/CommentPopover.d.ts +17 -0
- package/dist/editor/CommentPopover.d.ts.map +1 -0
- package/dist/editor/CommentPopover.js +62 -0
- package/dist/editor/CommentPopover.js.map +1 -0
- package/dist/editor/Comments.d.ts +13 -0
- package/dist/editor/Comments.d.ts.map +1 -0
- package/dist/editor/Comments.js +41 -0
- package/dist/editor/Comments.js.map +1 -0
- package/dist/editor/ComponentPage.d.ts +28 -0
- package/dist/editor/ComponentPage.d.ts.map +1 -0
- package/dist/editor/ComponentPage.js +55 -0
- package/dist/editor/ComponentPage.js.map +1 -0
- package/dist/editor/ComponentPanel.d.ts +38 -0
- package/dist/editor/ComponentPanel.d.ts.map +1 -0
- package/dist/editor/ComponentPanel.js +275 -0
- package/dist/editor/ComponentPanel.js.map +1 -0
- package/dist/editor/Glyph.d.ts +51 -0
- package/dist/editor/Glyph.d.ts.map +1 -0
- package/dist/editor/Glyph.js +50 -0
- package/dist/editor/Glyph.js.map +1 -0
- package/dist/editor/History.d.ts +7 -0
- package/dist/editor/History.d.ts.map +1 -0
- package/dist/editor/History.js +51 -0
- package/dist/editor/History.js.map +1 -0
- package/dist/editor/Inspector.d.ts +56 -0
- package/dist/editor/Inspector.d.ts.map +1 -0
- package/dist/editor/Inspector.js +510 -0
- package/dist/editor/Inspector.js.map +1 -0
- package/dist/editor/LazyMount.d.ts +10 -0
- package/dist/editor/LazyMount.d.ts.map +1 -0
- package/dist/editor/LazyMount.js +29 -0
- package/dist/editor/LazyMount.js.map +1 -0
- package/dist/editor/LocaleSwitch.d.ts +3 -0
- package/dist/editor/LocaleSwitch.d.ts.map +1 -0
- package/dist/editor/LocaleSwitch.js +9 -0
- package/dist/editor/LocaleSwitch.js.map +1 -0
- package/dist/editor/PreviewFrame.d.ts +10 -0
- package/dist/editor/PreviewFrame.d.ts.map +1 -0
- package/dist/editor/PreviewFrame.js +22 -0
- package/dist/editor/PreviewFrame.js.map +1 -0
- package/dist/editor/ProjectIndex.d.ts +12 -0
- package/dist/editor/ProjectIndex.d.ts.map +1 -0
- package/dist/editor/ProjectIndex.js +43 -0
- package/dist/editor/ProjectIndex.js.map +1 -0
- package/dist/editor/PromoteComponent.d.ts +28 -0
- package/dist/editor/PromoteComponent.d.ts.map +1 -0
- package/dist/editor/PromoteComponent.js +33 -0
- package/dist/editor/PromoteComponent.js.map +1 -0
- package/dist/editor/PromoteForm.d.ts +18 -0
- package/dist/editor/PromoteForm.d.ts.map +1 -0
- package/dist/editor/PromoteForm.js +35 -0
- package/dist/editor/PromoteForm.js.map +1 -0
- package/dist/editor/PromoteToken.d.ts +31 -0
- package/dist/editor/PromoteToken.d.ts.map +1 -0
- package/dist/editor/PromoteToken.js +94 -0
- package/dist/editor/PromoteToken.js.map +1 -0
- package/dist/editor/StatePreviews.d.ts +28 -0
- package/dist/editor/StatePreviews.d.ts.map +1 -0
- package/dist/editor/StatePreviews.js +113 -0
- package/dist/editor/StatePreviews.js.map +1 -0
- package/dist/editor/ValueCombo.d.ts +51 -0
- package/dist/editor/ValueCombo.d.ts.map +1 -0
- package/dist/editor/ValueCombo.js +260 -0
- package/dist/editor/ValueCombo.js.map +1 -0
- package/dist/editor/agent/AgentPanel.d.ts +19 -0
- package/dist/editor/agent/AgentPanel.d.ts.map +1 -0
- package/dist/editor/agent/AgentPanel.js +271 -0
- package/dist/editor/agent/AgentPanel.js.map +1 -0
- package/dist/editor/agent/Markdown.d.ts +5 -0
- package/dist/editor/agent/Markdown.d.ts.map +1 -0
- package/dist/editor/agent/Markdown.js +28 -0
- package/dist/editor/agent/Markdown.js.map +1 -0
- package/dist/editor/agent/agentApi.d.ts +106 -0
- package/dist/editor/agent/agentApi.d.ts.map +1 -0
- package/dist/editor/agent/agentApi.js +66 -0
- package/dist/editor/agent/agentApi.js.map +1 -0
- package/dist/editor/agent/toolLines.d.ts +38 -0
- package/dist/editor/agent/toolLines.d.ts.map +1 -0
- package/dist/editor/agent/toolLines.js +159 -0
- package/dist/editor/agent/toolLines.js.map +1 -0
- package/dist/editor/agent/useAgent.d.ts +15 -0
- package/dist/editor/agent/useAgent.d.ts.map +1 -0
- package/dist/editor/agent/useAgent.js +65 -0
- package/dist/editor/agent/useAgent.js.map +1 -0
- package/dist/editor/api.d.ts +378 -0
- package/dist/editor/api.d.ts.map +1 -0
- package/dist/editor/api.js +247 -0
- package/dist/editor/api.js.map +1 -0
- package/dist/editor/camera.d.ts +18 -0
- package/dist/editor/camera.d.ts.map +1 -0
- package/dist/editor/camera.js +40 -0
- package/dist/editor/camera.js.map +1 -0
- package/dist/editor/canvas.d.ts +25 -0
- package/dist/editor/canvas.d.ts.map +1 -0
- package/dist/editor/canvas.js +35 -0
- package/dist/editor/canvas.js.map +1 -0
- package/dist/editor/changes/ChangesPage.d.ts +25 -0
- package/dist/editor/changes/ChangesPage.d.ts.map +1 -0
- package/dist/editor/changes/ChangesPage.js +132 -0
- package/dist/editor/changes/ChangesPage.js.map +1 -0
- package/dist/editor/changes/changeModel.d.ts +25 -0
- package/dist/editor/changes/changeModel.d.ts.map +1 -0
- package/dist/editor/changes/changeModel.js +81 -0
- package/dist/editor/changes/changeModel.js.map +1 -0
- package/dist/editor/changes/changeState.d.mts +29 -0
- package/dist/editor/changes/changeState.mjs +187 -0
- package/dist/editor/chrome/EditorChrome.d.ts +49 -0
- package/dist/editor/chrome/EditorChrome.d.ts.map +1 -0
- package/dist/editor/chrome/EditorChrome.js +21 -0
- package/dist/editor/chrome/EditorChrome.js.map +1 -0
- package/dist/editor/drafts.d.ts +46 -0
- package/dist/editor/drafts.d.ts.map +1 -0
- package/dist/editor/drafts.js +38 -0
- package/dist/editor/drafts.js.map +1 -0
- package/dist/editor/i18n.d.ts +29 -0
- package/dist/editor/i18n.d.ts.map +1 -0
- package/dist/editor/i18n.js +2320 -0
- package/dist/editor/i18n.js.map +1 -0
- package/dist/editor/iconStroke.d.ts +6 -0
- package/dist/editor/iconStroke.d.ts.map +1 -0
- package/dist/editor/iconStroke.js +6 -0
- package/dist/editor/iconStroke.js.map +1 -0
- package/dist/editor/main.d.ts +2 -0
- package/dist/editor/main.d.ts.map +1 -0
- package/dist/editor/main.js +14 -0
- package/dist/editor/main.js.map +1 -0
- package/dist/editor/model.d.ts +16 -0
- package/dist/editor/model.d.ts.map +1 -0
- package/dist/editor/model.js +11 -0
- package/dist/editor/model.js.map +1 -0
- package/dist/editor/reasons.d.ts +44 -0
- package/dist/editor/reasons.d.ts.map +1 -0
- package/dist/editor/reasons.js +131 -0
- package/dist/editor/reasons.js.map +1 -0
- package/dist/editor/reviewLifecycle.d.ts +8 -0
- package/dist/editor/reviewLifecycle.d.ts.map +1 -0
- package/dist/editor/reviewLifecycle.js +21 -0
- package/dist/editor/reviewLifecycle.js.map +1 -0
- package/dist/editor/styles.css +8737 -0
- package/dist/editor/tokenMatch.d.ts +59 -0
- package/dist/editor/tokenMatch.d.ts.map +1 -0
- package/dist/editor/tokenMatch.js +198 -0
- package/dist/editor/tokenMatch.js.map +1 -0
- package/dist/editor/tokens/ConsolidatePage.d.ts +16 -0
- package/dist/editor/tokens/ConsolidatePage.d.ts.map +1 -0
- package/dist/editor/tokens/ConsolidatePage.js +244 -0
- package/dist/editor/tokens/ConsolidatePage.js.map +1 -0
- package/dist/editor/tokens/TokenActivity.d.ts +18 -0
- package/dist/editor/tokens/TokenActivity.d.ts.map +1 -0
- package/dist/editor/tokens/TokenActivity.js +18 -0
- package/dist/editor/tokens/TokenActivity.js.map +1 -0
- package/dist/editor/tokens/TokenDialogs.d.ts +26 -0
- package/dist/editor/tokens/TokenDialogs.d.ts.map +1 -0
- package/dist/editor/tokens/TokenDialogs.js +119 -0
- package/dist/editor/tokens/TokenDialogs.js.map +1 -0
- package/dist/editor/tokens/TokenList.d.ts +21 -0
- package/dist/editor/tokens/TokenList.d.ts.map +1 -0
- package/dist/editor/tokens/TokenList.js +98 -0
- package/dist/editor/tokens/TokenList.js.map +1 -0
- package/dist/editor/tokens/TokenPage.d.ts +25 -0
- package/dist/editor/tokens/TokenPage.d.ts.map +1 -0
- package/dist/editor/tokens/TokenPage.js +108 -0
- package/dist/editor/tokens/TokenPage.js.map +1 -0
- package/dist/editor/tokens/tokenModel.d.ts +35 -0
- package/dist/editor/tokens/tokenModel.d.ts.map +1 -0
- package/dist/editor/tokens/tokenModel.js +72 -0
- package/dist/editor/tokens/tokenModel.js.map +1 -0
- package/dist/editor/ui/Button.d.ts +3 -0
- package/dist/editor/ui/Button.d.ts.map +1 -0
- package/dist/editor/ui/Button.js +6 -0
- package/dist/editor/ui/Button.js.map +1 -0
- package/dist/editor/ui/CommentBox.d.ts +23 -0
- package/dist/editor/ui/CommentBox.d.ts.map +1 -0
- package/dist/editor/ui/CommentBox.js +41 -0
- package/dist/editor/ui/CommentBox.js.map +1 -0
- package/dist/editor/ui/Icon.d.ts +8 -0
- package/dist/editor/ui/Icon.d.ts.map +1 -0
- package/dist/editor/ui/Icon.js +6 -0
- package/dist/editor/ui/Icon.js.map +1 -0
- package/dist/editor/ui/IconButton.d.ts +11 -0
- package/dist/editor/ui/IconButton.d.ts.map +1 -0
- package/dist/editor/ui/IconButton.js +6 -0
- package/dist/editor/ui/IconButton.js.map +1 -0
- package/dist/editor/ui/NumberInput.d.ts +14 -0
- package/dist/editor/ui/NumberInput.d.ts.map +1 -0
- package/dist/editor/ui/NumberInput.js +6 -0
- package/dist/editor/ui/NumberInput.js.map +1 -0
- package/dist/editor/ui/PageLine.d.ts +14 -0
- package/dist/editor/ui/PageLine.d.ts.map +1 -0
- package/dist/editor/ui/PageLine.js +7 -0
- package/dist/editor/ui/PageLine.js.map +1 -0
- package/dist/editor/ui/SearchPicker.d.ts +41 -0
- package/dist/editor/ui/SearchPicker.d.ts.map +1 -0
- package/dist/editor/ui/SearchPicker.js +82 -0
- package/dist/editor/ui/SearchPicker.js.map +1 -0
- package/dist/editor/ui/Select.d.ts +19 -0
- package/dist/editor/ui/Select.d.ts.map +1 -0
- package/dist/editor/ui/Select.js +12 -0
- package/dist/editor/ui/Select.js.map +1 -0
- package/dist/editor/ui/TokenField.d.ts +14 -0
- package/dist/editor/ui/TokenField.d.ts.map +1 -0
- package/dist/editor/ui/TokenField.js +41 -0
- package/dist/editor/ui/TokenField.js.map +1 -0
- package/dist/editor/ui/TokenPicker.d.ts +31 -0
- package/dist/editor/ui/TokenPicker.d.ts.map +1 -0
- package/dist/editor/ui/TokenPicker.js +26 -0
- package/dist/editor/ui/TokenPicker.js.map +1 -0
- package/dist/editor/useBuildError.d.ts +7 -0
- package/dist/editor/useBuildError.d.ts.map +1 -0
- package/dist/editor/useBuildError.js +30 -0
- package/dist/editor/useBuildError.js.map +1 -0
- package/dist/editor/useLatestRequest.d.ts +22 -0
- package/dist/editor/useLatestRequest.d.ts.map +1 -0
- package/dist/editor/useLatestRequest.js +49 -0
- package/dist/editor/useLatestRequest.js.map +1 -0
- package/dist/editor-bundle/editor.css +2 -0
- package/dist/editor-bundle/editor.js +83 -0
- package/dist/editor-ui.d.ts +15 -0
- package/dist/editor-ui.d.ts.map +1 -0
- package/dist/editor-ui.js +14 -0
- package/dist/editor-ui.js.map +1 -0
- package/dist/inspector/runtime.d.ts +18 -0
- package/dist/inspector/runtime.d.ts.map +1 -0
- package/dist/inspector/runtime.js +1280 -0
- package/dist/inspector/runtime.js.map +1 -0
- package/dist/preview/main.d.ts +3 -0
- package/dist/preview/main.d.ts.map +1 -0
- package/dist/preview/main.js +320 -0
- package/dist/preview/main.js.map +1 -0
- package/dist/preview/preview.css +40 -0
- package/dist/runtime/index.d.ts +3 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/shared/buildError.d.mts +27 -0
- package/dist/shared/buildError.mjs +141 -0
- package/dist/shared/cameraFit.d.mts +16 -0
- package/dist/shared/cameraFit.mjs +47 -0
- package/dist/shared/canvasLayout.d.mts +13 -0
- package/dist/shared/canvasLayout.mjs +171 -0
- package/dist/shared/commentShots.d.mts +12 -0
- package/dist/shared/commentShots.mjs +53 -0
- package/dist/shared/componentExtract.d.mts +43 -0
- package/dist/shared/componentExtract.mjs +136 -0
- package/dist/shared/componentMeta.d.mts +26 -0
- package/dist/shared/componentMeta.mjs +87 -0
- package/dist/shared/componentOps.d.mts +70 -0
- package/dist/shared/componentOps.mjs +407 -0
- package/dist/shared/componentTarget.d.mts +15 -0
- package/dist/shared/componentTarget.mjs +58 -0
- package/dist/shared/components.d.mts +30 -0
- package/dist/shared/components.mjs +106 -0
- package/dist/shared/consolidateCategories.d.mts +2 -0
- package/dist/shared/consolidateCategories.mjs +6 -0
- package/dist/shared/env.d.mts +4 -0
- package/dist/shared/env.mjs +18 -0
- package/dist/shared/gitChanges.d.mts +2 -0
- package/dist/shared/gitChanges.mjs +30 -0
- package/dist/shared/oklab.d.mts +6 -0
- package/dist/shared/oklab.mjs +56 -0
- package/dist/shared/optimizeEntries.d.mts +5 -0
- package/dist/shared/optimizeEntries.mjs +24 -0
- package/dist/shared/packages.d.mts +11 -0
- package/dist/shared/packages.mjs +96 -0
- package/dist/shared/projectFiles.d.mts +23 -0
- package/dist/shared/projectFiles.mjs +72 -0
- package/dist/shared/prompt.d.mts +20 -0
- package/dist/shared/prompt.mjs +201 -0
- package/dist/shared/proposals.d.mts +11 -0
- package/dist/shared/proposals.mjs +42 -0
- package/dist/shared/protocol.d.ts +122 -0
- package/dist/shared/protocol.d.ts.map +1 -0
- package/dist/shared/protocol.js +7 -0
- package/dist/shared/protocol.js.map +1 -0
- package/dist/shared/reviewArchive.d.mts +4 -0
- package/dist/shared/reviewArchive.mjs +19 -0
- package/dist/shared/reviewStore.d.mts +30 -0
- package/dist/shared/reviewStore.mjs +218 -0
- package/dist/shared/reviewVerify.d.mts +21 -0
- package/dist/shared/reviewVerify.mjs +158 -0
- package/dist/shared/sizeModes.d.mts +15 -0
- package/dist/shared/sizeModes.mjs +53 -0
- package/dist/shared/sketches.d.mts +10 -0
- package/dist/shared/sketches.mjs +64 -0
- package/dist/shared/snapshotCheck.d.mts +13 -0
- package/dist/shared/snapshotCheck.mjs +81 -0
- package/dist/shared/timeout.d.mts +1 -0
- package/dist/shared/timeout.mjs +15 -0
- package/dist/shared/tokens.d.ts +2 -0
- package/dist/shared/tokens.d.ts.map +1 -0
- package/dist/shared/tokens.js +2 -0
- package/dist/shared/tokens.js.map +1 -0
- package/dist/shared/types.d.ts +689 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +13 -0
- package/dist/shared/types.js.map +1 -0
- package/dist/shared/wheelRouting.d.mts +9 -0
- package/dist/shared/wheelRouting.mjs +31 -0
- package/dist/shared/writeScope.mjs +96 -0
- package/dist/snapshots/diff.d.mts +28 -0
- package/dist/snapshots/diff.mjs +263 -0
- package/dist/snapshots/index.d.mts +110 -0
- package/dist/snapshots/index.mjs +638 -0
- package/dist/snapshots/render.d.mts +24 -0
- package/dist/snapshots/render.mjs +250 -0
- package/dist/snapshots/toolOps.d.mts +25 -0
- package/dist/snapshots/toolOps.mjs +69 -0
- package/dist/tokens/adapters/css.mjs +51 -0
- package/dist/tokens/adapters/cssInCode.mjs +314 -0
- package/dist/tokens/adapters/oxcShared.mjs +80 -0
- package/dist/tokens/adapters/preprocessor.mjs +63 -0
- package/dist/tokens/adapters/registry.mjs +53 -0
- package/dist/tokens/adapters/tailwindcss.mjs +424 -0
- package/dist/tokens/adapters/types.mjs +117 -0
- package/dist/tokens/consolidate/index.d.mts +42 -0
- package/dist/tokens/consolidate/index.mjs +111 -0
- package/dist/tokens/consolidate/normalize.mjs +479 -0
- package/dist/tokens/consolidate/plan.mjs +726 -0
- package/dist/tokens/consolidate/scan.mjs +928 -0
- package/dist/tokens/extract.mjs +441 -0
- package/dist/tokens/moduleData.d.mts +14 -0
- package/dist/tokens/moduleData.mjs +32 -0
- package/dist/tokens/opLock.d.mts +4 -0
- package/dist/tokens/opLock.mjs +108 -0
- package/dist/tokens/ops.d.mts +71 -0
- package/dist/tokens/ops.mjs +1511 -0
- package/dist/tokens/pipeline.mjs +813 -0
- package/dist/tokens/report.d.mts +47 -0
- package/dist/tokens/report.mjs +257 -0
- package/dist/tokens/rewrite/code.mjs +172 -0
- package/dist/tokens/rewrite/css.mjs +154 -0
- package/dist/tokens/rewrite/index.mjs +244 -0
- package/dist/tokens/rewrite/tailwind.mjs +288 -0
- package/dist/tokens/rewrite/text.mjs +116 -0
- package/dist/tokens/rewrite/value.mjs +115 -0
- package/dist/tokens/usage.d.mts +97 -0
- package/dist/tokens/usage.mjs +680 -0
- package/dist/vite/agent.d.ts +21 -0
- package/dist/vite/agent.d.ts.map +1 -0
- package/dist/vite/agent.js +165 -0
- package/dist/vite/agent.js.map +1 -0
- package/dist/vite/events.d.ts +27 -0
- package/dist/vite/events.d.ts.map +1 -0
- package/dist/vite/events.js +156 -0
- package/dist/vite/events.js.map +1 -0
- package/dist/vite/layout.d.ts +2 -0
- package/dist/vite/layout.d.ts.map +1 -0
- package/dist/vite/layout.js +4 -0
- package/dist/vite/layout.js.map +1 -0
- package/dist/vite/plugin.d.ts +40 -0
- package/dist/vite/plugin.d.ts.map +1 -0
- package/dist/vite/plugin.js +1255 -0
- package/dist/vite/plugin.js.map +1 -0
- package/dist/vite/requestGuard.d.mts +3 -0
- package/dist/vite/requestGuard.mjs +43 -0
- package/dist/vite/review.d.ts +11 -0
- package/dist/vite/review.d.ts.map +1 -0
- package/dist/vite/review.js +283 -0
- package/dist/vite/review.js.map +1 -0
- package/package.json +104 -4
- package/skills/seji/SKILL.md +395 -0
- package/skills/seji-authoring/SKILL.md +397 -0
- package/skills/seji-tokens/SKILL.md +432 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1511 @@
|
|
|
1
|
+
// Token operations the tool executes itself (no agent): rename, merge, deprecate, delete,
|
|
2
|
+
// describe, set value, literal → token, and revert. Each one:
|
|
3
|
+
// 1. edits the DTCG source (JSON), and rewrites static references in code with the AST
|
|
4
|
+
// rewriters (src/tokens/rewrite) — `dryRun` stops here and lists every place;
|
|
5
|
+
// 2. checks every file still has the content that was parsed (token sources: retry the
|
|
6
|
+
// whole operation; code files: re-parse and re-plan that file) before writing;
|
|
7
|
+
// 3. rebuilds the generated CSS / TS / manifest (restoring every file if the build fails);
|
|
8
|
+
// 4. records ONE review item + batch in design/<design>/review.json: "tool changed N
|
|
9
|
+
// places, left M for agent" with each leftover's file:line and reason. The batch keeps
|
|
10
|
+
// undo edits so `tokens revert <batch>` restores the files.
|
|
11
|
+
import { randomUUID } from 'node:crypto'
|
|
12
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
|
13
|
+
import { basename, isAbsolute, join, relative, sep } from 'node:path'
|
|
14
|
+
|
|
15
|
+
import { SAFE_DESIGN_ID, mutateReview, readReviewFile, reviewFilePath } from '../shared/reviewStore.mjs'
|
|
16
|
+
import { writeScope } from '../shared/writeScope.mjs'
|
|
17
|
+
import { TokenLockTimeoutError, withTokenOpLock } from './opLock.mjs'
|
|
18
|
+
import {
|
|
19
|
+
analyzeTokens,
|
|
20
|
+
cssNameOf,
|
|
21
|
+
loadTokenConfig,
|
|
22
|
+
readTokenRecords,
|
|
23
|
+
resolveRecords,
|
|
24
|
+
runTokenPipeline,
|
|
25
|
+
scanFiles,
|
|
26
|
+
walkTokens,
|
|
27
|
+
} from './pipeline.mjs'
|
|
28
|
+
import { verifyReviews } from './report.mjs'
|
|
29
|
+
import {
|
|
30
|
+
StaleFileError,
|
|
31
|
+
planRewrites,
|
|
32
|
+
prepareRewrites,
|
|
33
|
+
restoreWrites,
|
|
34
|
+
undoEdits,
|
|
35
|
+
writeAll,
|
|
36
|
+
writesFor,
|
|
37
|
+
} from './rewrite/index.mjs'
|
|
38
|
+
import { buildThemeUtilityIndex } from './rewrite/tailwind.mjs'
|
|
39
|
+
import { applyEdits, sha256 } from './rewrite/text.mjs'
|
|
40
|
+
import { renameVarsInString, rewriteValueVars, valueReferences } from './rewrite/value.mjs'
|
|
41
|
+
import { buildUsageIndex, deleteBlockers } from './usage.mjs'
|
|
42
|
+
|
|
43
|
+
export const TOKEN_OPS = ['rename', 'merge', 'deprecate', 'delete', 'describe', 'set', 'create', 'replace-literal', 'revert']
|
|
44
|
+
export const TOKEN_TIERS = ['primitive', 'semantic', 'component']
|
|
45
|
+
|
|
46
|
+
const MAX_ATTEMPTS = 3
|
|
47
|
+
const MAX_ITEM_CHANGES = 200
|
|
48
|
+
const UNO_CONFIGS = ['uno.config.ts', 'uno.config.js', 'uno.config.mjs', 'unocss.config.ts', 'unocss.config.js']
|
|
49
|
+
|
|
50
|
+
const toPosix = (file) => file.split(sep).join('/')
|
|
51
|
+
const lower = (value) => String(value ?? '').trim().toLowerCase()
|
|
52
|
+
|
|
53
|
+
export class TokenOpError extends Error {
|
|
54
|
+
constructor(message, details) {
|
|
55
|
+
super(message)
|
|
56
|
+
this.name = 'TokenOpError'
|
|
57
|
+
if (details) this.details = details
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const fail = (message, details) => {
|
|
62
|
+
throw new TokenOpError(message, details)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Fail with a message the editor can translate: `why: { code, params }` travels with the error
|
|
67
|
+
* (HTTP body, CLI JSON) next to the English message, which stays what the CLI prints.
|
|
68
|
+
*/
|
|
69
|
+
const failWhy = (code, params, message, details) => fail(message, { ...details, why: { code, params } })
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Notes of a plan: the English text (`notes`, what the CLI prints) and the same notes as
|
|
73
|
+
* `{ code, params }` (`noteCodes`, what the editor translates), in the same order.
|
|
74
|
+
*/
|
|
75
|
+
function noteList() {
|
|
76
|
+
const notes = []
|
|
77
|
+
notes.codes = []
|
|
78
|
+
notes.add = (code, params, text) => {
|
|
79
|
+
notes.push(text)
|
|
80
|
+
notes.codes.push({ code, params })
|
|
81
|
+
}
|
|
82
|
+
return notes
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A plan's note list (plain string notes become `{ code: 'text' }` entries). */
|
|
86
|
+
function notesOf(plan) {
|
|
87
|
+
if (!plan.notes?.add) {
|
|
88
|
+
const list = noteList()
|
|
89
|
+
for (const text of plan.notes ?? []) list.add('text', { text }, text)
|
|
90
|
+
plan.notes = list
|
|
91
|
+
}
|
|
92
|
+
return plan.notes
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const required = (value, flag) => {
|
|
96
|
+
if (typeof value !== 'string' || !value.trim()) fail(`${flag} is required`)
|
|
97
|
+
return value.trim()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Hold the project's token-operation lock for `fn`; a timeout becomes a TokenOpError. */
|
|
101
|
+
async function locked(root, fn) {
|
|
102
|
+
try {
|
|
103
|
+
return await withTokenOpLock(root, fn)
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error instanceof TokenLockTimeoutError) fail(error.message, { code: 'busy', ...(error.owner ? { owner: error.owner } : {}) })
|
|
106
|
+
throw error
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------------------
|
|
111
|
+
// Context and DTCG JSON helpers
|
|
112
|
+
|
|
113
|
+
async function loadContext(root) {
|
|
114
|
+
const config = loadTokenConfig(root)
|
|
115
|
+
const scope = writeScope(root, { writableDirs: config.writableDirs })
|
|
116
|
+
const { files, records } = readTokenRecords(root, config.tokenDir)
|
|
117
|
+
resolveRecords(records)
|
|
118
|
+
const sources = files.map((abs) => {
|
|
119
|
+
const text = readFileSync(abs, 'utf8')
|
|
120
|
+
return { abs, rel: toPosix(relative(root, abs)), text, hash: sha256(text), json: JSON.parse(text) }
|
|
121
|
+
})
|
|
122
|
+
return {
|
|
123
|
+
root,
|
|
124
|
+
config,
|
|
125
|
+
records,
|
|
126
|
+
sources,
|
|
127
|
+
byCss: new Map(records.map((record) => [record.cssName, record])),
|
|
128
|
+
byPath: new Map(records.map((record) => [record.path.join('.'), record])),
|
|
129
|
+
theme: config.cssFormat === 'theme',
|
|
130
|
+
uno: UNO_CONFIGS.some((file) => existsSync(join(root, file))),
|
|
131
|
+
scope,
|
|
132
|
+
// `scan`: files the tool may rewrite; `outside`: only reported (shared/writeScope.mjs).
|
|
133
|
+
...scope.split(scanFiles(root, config)),
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Plans for files outside the project: every would-be change becomes a leftover. */
|
|
138
|
+
async function planOutside(root, files, code) {
|
|
139
|
+
if (!files.length) return []
|
|
140
|
+
const plans = await planRewrites({ root, files, ...code })
|
|
141
|
+
return plans.map((plan) => ({
|
|
142
|
+
...plan,
|
|
143
|
+
after: plan.before,
|
|
144
|
+
edits: [],
|
|
145
|
+
changes: [],
|
|
146
|
+
leftovers: [
|
|
147
|
+
...plan.changes.map((entry) => ({ ...entry, reason: 'outside-project-root', text: entry.from })),
|
|
148
|
+
...plan.leftovers,
|
|
149
|
+
],
|
|
150
|
+
}))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function findRecord(ctx, ref, flag = 'token') {
|
|
154
|
+
const name = required(ref, flag)
|
|
155
|
+
const record =
|
|
156
|
+
ctx.byCss.get(name) ?? ctx.byPath.get(name) ?? (name.startsWith('--') ? undefined : ctx.byCss.get(`--${name}`))
|
|
157
|
+
if (!record) failWhy('unknown-token', { token: name }, `unknown token: ${name}`)
|
|
158
|
+
return record
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const keyOf = (record) => record.path.join('.')
|
|
162
|
+
|
|
163
|
+
function parsePath(input) {
|
|
164
|
+
const value = required(input, '--to / --into')
|
|
165
|
+
if (value.startsWith('--')) {
|
|
166
|
+
failWhy('path-not-css', { value }, `give the new token as a DTCG dot path (e.g. color.text), not a CSS name (${value})`)
|
|
167
|
+
}
|
|
168
|
+
const path = value.split('.')
|
|
169
|
+
for (const segment of path) {
|
|
170
|
+
if (!segment || segment.startsWith('$') || segment.includes('{') || segment.includes('}')) {
|
|
171
|
+
failWhy('invalid-path', { value }, `invalid token path: ${value}`)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const cssName = cssNameOf(path)
|
|
175
|
+
if (!/^--[a-zA-Z0-9_-]+$/.test(cssName)) {
|
|
176
|
+
failWhy('invalid-css-name', { value, cssName }, `${value} does not give a valid CSS variable name (${cssName})`)
|
|
177
|
+
}
|
|
178
|
+
return path
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function nodeAt(json, path) {
|
|
182
|
+
let node = json
|
|
183
|
+
for (const segment of path) {
|
|
184
|
+
if (!node || typeof node !== 'object' || !Object.hasOwn(node, segment)) return null
|
|
185
|
+
node = node[segment]
|
|
186
|
+
}
|
|
187
|
+
return node
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function replaceEntries(obj, entries) {
|
|
191
|
+
for (const key of Object.keys(obj)) delete obj[key]
|
|
192
|
+
for (const [key, value] of entries) obj[key] = value
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function insertAfter(obj, afterKey, key, value) {
|
|
196
|
+
const entries = []
|
|
197
|
+
for (const entry of Object.entries(obj)) {
|
|
198
|
+
entries.push(entry)
|
|
199
|
+
if (entry[0] === afterKey) entries.push([key, value])
|
|
200
|
+
}
|
|
201
|
+
if (!Object.hasOwn(obj, afterKey)) entries.push([key, value])
|
|
202
|
+
replaceEntries(obj, entries)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function renameKey(obj, oldKey, newKey, value) {
|
|
206
|
+
replaceEntries(
|
|
207
|
+
obj,
|
|
208
|
+
Object.entries(obj).map(([key, current]) => (key === oldKey ? [newKey, value] : [key, current])),
|
|
209
|
+
)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Remove a token and any groups left without children. */
|
|
213
|
+
function removeAt(json, path) {
|
|
214
|
+
const parent = nodeAt(json, path.slice(0, -1))
|
|
215
|
+
if (parent) delete parent[path[path.length - 1]]
|
|
216
|
+
for (let depth = path.length - 1; depth > 0; depth -= 1) {
|
|
217
|
+
const group = nodeAt(json, path.slice(0, depth))
|
|
218
|
+
if (!group || Object.keys(group).some((key) => !key.startsWith('$'))) break
|
|
219
|
+
delete nodeAt(json, path.slice(0, depth - 1))[path[depth - 1]]
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function ensureGroups(json, groupPath) {
|
|
224
|
+
let node = json
|
|
225
|
+
for (const segment of groupPath) {
|
|
226
|
+
if (!Object.hasOwn(node, segment)) node[segment] = {}
|
|
227
|
+
node = node[segment]
|
|
228
|
+
if (!node || typeof node !== 'object' || '$value' in node) {
|
|
229
|
+
fail(`cannot place a token under ${groupPath.join('.')}: ${segment} is a token, not a group`)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return node
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Tier / $type a token at `groupPath` in this file would inherit. */
|
|
236
|
+
function inheritedAt(json, groupPath, rel) {
|
|
237
|
+
let meta = { ...(json.$extensions?.['design-surface'] ?? {}) }
|
|
238
|
+
let type = json.$type
|
|
239
|
+
let node = json
|
|
240
|
+
for (const segment of groupPath) {
|
|
241
|
+
node = node && typeof node === 'object' ? node[segment] : undefined
|
|
242
|
+
if (!node || typeof node !== 'object') break
|
|
243
|
+
meta = { ...meta, ...(node.$extensions?.['design-surface'] ?? {}) }
|
|
244
|
+
type = node.$type ?? type
|
|
245
|
+
}
|
|
246
|
+
const fileTier = /^(primitive|semantic|component)\.tokens\.json$/.exec(basename(rel))?.[1]
|
|
247
|
+
return { tier: meta.tier ?? fileTier, type }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The source file whose groups already hold the longest prefix of `path` (else `fallback`). */
|
|
251
|
+
function targetSourceFor(ctx, path, fallback) {
|
|
252
|
+
let best = { rel: fallback, depth: 0 }
|
|
253
|
+
for (const source of ctx.sources) {
|
|
254
|
+
let node = source.json
|
|
255
|
+
let depth = 0
|
|
256
|
+
for (const segment of path.slice(0, -1)) {
|
|
257
|
+
const next = node?.[segment]
|
|
258
|
+
if (!next || typeof next !== 'object' || '$value' in next) break
|
|
259
|
+
node = next
|
|
260
|
+
depth += 1
|
|
261
|
+
}
|
|
262
|
+
if (depth > best.depth || (depth === best.depth && depth > 0 && source.rel === fallback)) {
|
|
263
|
+
best = { rel: source.rel, depth }
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return best.rel
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function createDraft(ctx) {
|
|
270
|
+
const drafts = new Map()
|
|
271
|
+
const changes = []
|
|
272
|
+
return {
|
|
273
|
+
drafts,
|
|
274
|
+
changes,
|
|
275
|
+
json(rel) {
|
|
276
|
+
if (!drafts.has(rel)) {
|
|
277
|
+
const source = ctx.sources.find((entry) => entry.rel === rel)
|
|
278
|
+
if (!source) fail(`token source not found: ${rel}`)
|
|
279
|
+
drafts.set(rel, structuredClone(source.json))
|
|
280
|
+
}
|
|
281
|
+
return drafts.get(rel)
|
|
282
|
+
},
|
|
283
|
+
node(record) {
|
|
284
|
+
return nodeAt(this.json(record.source), record.path)
|
|
285
|
+
},
|
|
286
|
+
note(change) {
|
|
287
|
+
changes.push(change)
|
|
288
|
+
},
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Point token aliases `{from}` and `var(--from)` inside token values at `to`. */
|
|
293
|
+
function retargetTokenRefs(ctx, draft, from, to, skip = new Set()) {
|
|
294
|
+
const renames = new Map([[from.cssName, to.cssName]])
|
|
295
|
+
const fromKey = keyOf(from)
|
|
296
|
+
for (const record of ctx.records) {
|
|
297
|
+
const key = keyOf(record)
|
|
298
|
+
if (skip.has(key)) continue
|
|
299
|
+
const node = draft.node(record)
|
|
300
|
+
if (!node) continue
|
|
301
|
+
if (record.alias === fromKey) {
|
|
302
|
+
draft.note({ file: record.source, token: key, change: 'retarget-alias', from: node.$value, to: `{${to.path}}` })
|
|
303
|
+
node.$value = `{${to.path}}`
|
|
304
|
+
} else if (!record.alias && typeof node.$value === 'string') {
|
|
305
|
+
const next = renameVarsInString(node.$value, renames)
|
|
306
|
+
if (next !== node.$value) {
|
|
307
|
+
draft.note({ file: record.source, token: key, change: 'retarget-var', from: node.$value, to: next })
|
|
308
|
+
node.$value = next
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function renameSpec(ctx, renames) {
|
|
315
|
+
const names = new Set([...ctx.byCss.keys(), ...renames.values()])
|
|
316
|
+
return {
|
|
317
|
+
mode: 'rename',
|
|
318
|
+
renames,
|
|
319
|
+
theme: ctx.theme,
|
|
320
|
+
themeIndex: ctx.theme || ctx.uno ? buildThemeUtilityIndex(names) : null,
|
|
321
|
+
...(ctx.uno ? { themeUnsupported: 'unsupported-scheme: UnoCSS' } : {}),
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const aliasNodeFor = (record, oldNode, targetPath, targetCss, reason, description) => ({
|
|
326
|
+
$type: record.dtcgType,
|
|
327
|
+
$value: `{${targetPath}}`,
|
|
328
|
+
$description: description ?? `Deprecated alias of ${targetPath}; use var(${targetCss}).`,
|
|
329
|
+
$deprecated: reason,
|
|
330
|
+
...(oldNode.$extensions ? { $extensions: structuredClone(oldNode.$extensions) } : {}),
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
const noAliasRefusal = (record) => ({ leftovers }) =>
|
|
334
|
+
leftovers.length
|
|
335
|
+
? {
|
|
336
|
+
message: `--no-alias would leave ${leftovers.length} reference(s) to ${record.cssName} that the tool cannot rewrite pointing at nothing. Keep the deprecated alias (the default) and let the agent fix the leftovers, then delete it once usage is 0.`,
|
|
337
|
+
why: { code: 'no-alias-leftovers', params: { count: leftovers.length, cssName: record.cssName } },
|
|
338
|
+
}
|
|
339
|
+
: null
|
|
340
|
+
|
|
341
|
+
// ---------------------------------------------------------------------------------------
|
|
342
|
+
// Operation builders: (ctx) => plan. A plan never writes; `execute` does.
|
|
343
|
+
|
|
344
|
+
function planRename(args) {
|
|
345
|
+
return async (ctx) => {
|
|
346
|
+
const record = findRecord(ctx, args.token)
|
|
347
|
+
const oldKey = keyOf(record)
|
|
348
|
+
const newPath = parsePath(args.to)
|
|
349
|
+
const newKey = newPath.join('.')
|
|
350
|
+
const newCss = cssNameOf(newPath)
|
|
351
|
+
if (newKey === oldKey) failWhy('same-name', {}, 'the new name is the current name')
|
|
352
|
+
if (ctx.byPath.has(newKey) || ctx.byCss.has(newCss)) {
|
|
353
|
+
failWhy('exists', { name: newKey, token: oldKey }, `${newKey} already exists; use \`tokens merge ${oldKey} --into ${newKey}\` instead`)
|
|
354
|
+
}
|
|
355
|
+
// Any node at the new path — a group as well as a token — would be overwritten.
|
|
356
|
+
for (const source of ctx.sources) {
|
|
357
|
+
const existing = nodeAt(source.json, newPath)
|
|
358
|
+
if (existing !== null && existing !== undefined) {
|
|
359
|
+
const what = existing && typeof existing === 'object' && !('$value' in existing) ? 'a token group' : 'a token'
|
|
360
|
+
failWhy('path-taken', { name: newKey, file: source.rel }, `${newKey} is already ${what} in ${source.rel}; choose a path that does not exist yet`)
|
|
361
|
+
}
|
|
362
|
+
for (let depth = 1; depth < newPath.length; depth += 1) {
|
|
363
|
+
const prefix = nodeAt(source.json, newPath.slice(0, depth))
|
|
364
|
+
if (prefix && typeof prefix === 'object' && '$value' in prefix && newPath.slice(0, depth).join('.') !== oldKey) {
|
|
365
|
+
const parent = newPath.slice(0, depth).join('.')
|
|
366
|
+
failWhy('under-token', { name: newKey, parent }, `cannot place ${newKey} under ${parent}: it is a token, not a group (${source.rel})`)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const keepAlias = args.alias !== false
|
|
371
|
+
const draft = createDraft(ctx)
|
|
372
|
+
const notes = noteList()
|
|
373
|
+
const oldJson = draft.json(record.source)
|
|
374
|
+
const oldNode = nodeAt(oldJson, record.path)
|
|
375
|
+
const oldParent = nodeAt(oldJson, record.path.slice(0, -1))
|
|
376
|
+
const nextNode = structuredClone(oldNode)
|
|
377
|
+
delete nextNode.$deprecated
|
|
378
|
+
const ownMeta = nextNode.$extensions?.['design-surface']
|
|
379
|
+
if (ownMeta?.cssName) {
|
|
380
|
+
delete ownMeta.cssName
|
|
381
|
+
notes.add('dropped-css-override', { old: record.cssName, cssName: newCss }, `dropped the cssName override ${record.cssName}; the new token is ${newCss}`)
|
|
382
|
+
}
|
|
383
|
+
const targetRel = targetSourceFor(ctx, newPath, record.source)
|
|
384
|
+
const targetJson = draft.json(targetRel)
|
|
385
|
+
const inherited = inheritedAt(targetJson, newPath.slice(0, -1), targetRel)
|
|
386
|
+
if (inherited.tier !== record.tier) {
|
|
387
|
+
nextNode.$extensions = {
|
|
388
|
+
...(nextNode.$extensions ?? {}),
|
|
389
|
+
'design-surface': { ...(nextNode.$extensions?.['design-surface'] ?? {}), tier: record.tier },
|
|
390
|
+
}
|
|
391
|
+
notes.add('kept-tier', { tier: record.tier, inherited: inherited.tier ?? '' }, `kept tier ${record.tier} explicitly (the new location would give ${inherited.tier ?? 'none'})`)
|
|
392
|
+
}
|
|
393
|
+
if ((nextNode.$type ?? inherited.type) !== record.dtcgType) nextNode.$type = record.dtcgType
|
|
394
|
+
const sameParent =
|
|
395
|
+
targetRel === record.source &&
|
|
396
|
+
newPath.length === record.path.length &&
|
|
397
|
+
newPath.slice(0, -1).every((segment, index) => segment === record.path[index])
|
|
398
|
+
const oldLeaf = record.path[record.path.length - 1]
|
|
399
|
+
const newLeaf = newPath[newPath.length - 1]
|
|
400
|
+
const reason = args.reason?.trim() || `Renamed to ${newKey}.`
|
|
401
|
+
|
|
402
|
+
if (keepAlias) {
|
|
403
|
+
oldParent[oldLeaf] = aliasNodeFor(record, oldNode, newKey, newCss, reason, undefined)
|
|
404
|
+
if (sameParent) insertAfter(oldParent, oldLeaf, newLeaf, nextNode)
|
|
405
|
+
else ensureGroups(targetJson, newPath.slice(0, -1))[newLeaf] = nextNode
|
|
406
|
+
draft.note({ file: record.source, token: oldKey, change: 'deprecated-alias', to: `{${newKey}}`, reason })
|
|
407
|
+
} else if (sameParent) {
|
|
408
|
+
renameKey(oldParent, oldLeaf, newLeaf, nextNode)
|
|
409
|
+
} else {
|
|
410
|
+
removeAt(oldJson, record.path)
|
|
411
|
+
ensureGroups(targetJson, newPath.slice(0, -1))[newLeaf] = nextNode
|
|
412
|
+
draft.note({ file: record.source, token: oldKey, change: 'remove' })
|
|
413
|
+
}
|
|
414
|
+
draft.note({ file: targetRel, token: newKey, change: 'add', from: oldKey, value: nextNode.$value })
|
|
415
|
+
retargetTokenRefs(ctx, draft, record, { path: newKey, cssName: newCss }, new Set([oldKey]))
|
|
416
|
+
|
|
417
|
+
return {
|
|
418
|
+
op: 'rename',
|
|
419
|
+
record,
|
|
420
|
+
draft,
|
|
421
|
+
notes,
|
|
422
|
+
target: { path: newKey, cssName: newCss },
|
|
423
|
+
codeSpec: renameSpec(ctx, new Map([[record.cssName, newCss]])),
|
|
424
|
+
refuse: keepAlias ? null : noAliasRefusal(record),
|
|
425
|
+
expect: keepAlias
|
|
426
|
+
? { present: [newCss], aliases: { [record.cssName]: newKey } }
|
|
427
|
+
: { present: [newCss], absent: [record.cssName] },
|
|
428
|
+
item: { tokenAction: 'rename', from: oldKey, to: newKey, tokenAlias: newKey },
|
|
429
|
+
args: { from: oldKey, to: newKey, fromCss: record.cssName, toCss: newCss, alias: keepAlias },
|
|
430
|
+
summary: `Renamed ${oldKey} (${record.cssName}) to ${newKey} (${newCss})${keepAlias ? '; the old name stays as a deprecated alias' : ''}`,
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function planMerge(args) {
|
|
436
|
+
return async (ctx, shared) => {
|
|
437
|
+
const source = findRecord(ctx, args.token)
|
|
438
|
+
const target = findRecord(ctx, args.into, '--into')
|
|
439
|
+
const sourceKey = keyOf(source)
|
|
440
|
+
const targetKey = keyOf(target)
|
|
441
|
+
if (source === target) failWhy('merge-self', {}, 'cannot merge a token into itself')
|
|
442
|
+
if (source.dtcgType !== target.dtcgType) {
|
|
443
|
+
failWhy(
|
|
444
|
+
'type-mismatch',
|
|
445
|
+
{ token: sourceKey, type: source.dtcgType, other: targetKey, otherType: target.dtcgType },
|
|
446
|
+
`cannot merge ${source.dtcgType} ${sourceKey} into ${target.dtcgType} ${targetKey}`,
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
const keep = args.keep ?? 'target'
|
|
450
|
+
if (keep !== 'target' && keep !== 'source') fail('--keep must be "target" or "source"')
|
|
451
|
+
const keepAlias = args.alias !== false
|
|
452
|
+
const draft = shared?.draft ?? createDraft(ctx)
|
|
453
|
+
const notes = noteList()
|
|
454
|
+
const sourceNode = draft.node(source)
|
|
455
|
+
const targetNode = draft.node(target)
|
|
456
|
+
const targetIsSource =
|
|
457
|
+
target.alias === sourceKey || (typeof target.raw === 'string' && target.raw.trim() === `var(${source.cssName})`)
|
|
458
|
+
if (!targetIsSource && typeof target.raw === 'string' && valueReferences(target.raw, [source.cssName])) {
|
|
459
|
+
failWhy(
|
|
460
|
+
'merge-cycle',
|
|
461
|
+
{ token: sourceKey, other: targetKey, value: target.raw },
|
|
462
|
+
`${targetKey} uses ${sourceKey} inside a larger value (${target.raw}); merging would make it reference itself. ` +
|
|
463
|
+
`Give ${targetKey} its own value first (\`tokens set ${targetKey} --value …\`) or merge the other way.`,
|
|
464
|
+
)
|
|
465
|
+
}
|
|
466
|
+
const targetAliasesSource = targetIsSource
|
|
467
|
+
let resultValue = target.value
|
|
468
|
+
if ((keep === 'source' || targetAliasesSource) && source.alias !== targetKey) {
|
|
469
|
+
if (keep !== 'source') {
|
|
470
|
+
notes.add('takes-value', { token: targetKey, other: sourceKey }, `${targetKey} referenced ${sourceKey}, so it takes ${sourceKey}'s value`)
|
|
471
|
+
}
|
|
472
|
+
draft.note({ file: target.source, token: targetKey, change: 'set-value', from: targetNode.$value, to: sourceNode.$value })
|
|
473
|
+
targetNode.$value = structuredClone(sourceNode.$value)
|
|
474
|
+
resultValue = source.value
|
|
475
|
+
}
|
|
476
|
+
const reason = args.reason?.trim() || `Merged into ${targetKey}.`
|
|
477
|
+
if (keepAlias) {
|
|
478
|
+
nodeAt(draft.json(source.source), source.path.slice(0, -1))[source.path[source.path.length - 1]] = aliasNodeFor(
|
|
479
|
+
source,
|
|
480
|
+
sourceNode,
|
|
481
|
+
targetKey,
|
|
482
|
+
target.cssName,
|
|
483
|
+
reason,
|
|
484
|
+
undefined,
|
|
485
|
+
)
|
|
486
|
+
draft.note({ file: source.source, token: sourceKey, change: 'deprecated-alias', to: `{${targetKey}}`, reason })
|
|
487
|
+
} else {
|
|
488
|
+
removeAt(draft.json(source.source), source.path)
|
|
489
|
+
draft.note({ file: source.source, token: sourceKey, change: 'remove' })
|
|
490
|
+
}
|
|
491
|
+
retargetTokenRefs(ctx, draft, source, { path: targetKey, cssName: target.cssName }, new Set([sourceKey, targetKey]))
|
|
492
|
+
return {
|
|
493
|
+
op: 'merge',
|
|
494
|
+
record: source,
|
|
495
|
+
draft,
|
|
496
|
+
notes,
|
|
497
|
+
values: { source: source.value, target: target.value, kept: keep, result: resultValue },
|
|
498
|
+
codeSpec: renameSpec(ctx, new Map([[source.cssName, target.cssName]])),
|
|
499
|
+
refuse: keepAlias ? null : noAliasRefusal(source),
|
|
500
|
+
expect: keepAlias
|
|
501
|
+
? { present: [target.cssName], aliases: { [source.cssName]: targetKey } }
|
|
502
|
+
: { present: [target.cssName], absent: [source.cssName] },
|
|
503
|
+
item: { tokenAction: 'merge', from: sourceKey, to: targetKey, tokenAlias: targetKey },
|
|
504
|
+
args: { from: sourceKey, to: targetKey, kept: keep, value: resultValue, alias: keepAlias },
|
|
505
|
+
summary: `Merged ${sourceKey} into ${targetKey} (${keep} value ${resultValue} wins)${keepAlias ? '; the old name stays as a deprecated alias' : ''}`,
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function planDeprecate(args) {
|
|
511
|
+
return async (ctx) => {
|
|
512
|
+
const record = findRecord(ctx, args.token)
|
|
513
|
+
const key = keyOf(record)
|
|
514
|
+
const reason = args.reason?.trim()
|
|
515
|
+
if (args.replacement && args.noReplacement) fail('pass either --replacement or --no-replacement, not both')
|
|
516
|
+
if (!args.replacement && !args.noReplacement) {
|
|
517
|
+
fail('deprecate needs a replacement: --replacement <token>, or --no-replacement --reason "<why>"')
|
|
518
|
+
}
|
|
519
|
+
if (args.noReplacement && !reason) fail('--no-replacement requires --reason "<why there is no replacement>"')
|
|
520
|
+
const mode = args.mode ?? 'mark-only'
|
|
521
|
+
if (mode !== 'mark-only' && mode !== 'replace-all') fail('--mode must be "mark-only" or "replace-all"')
|
|
522
|
+
if (mode === 'replace-all' && !args.replacement) fail('--mode replace-all needs a --replacement')
|
|
523
|
+
const replacement = args.replacement ? findRecord(ctx, args.replacement, '--replacement') : null
|
|
524
|
+
const draft = createDraft(ctx)
|
|
525
|
+
const notes = noteList()
|
|
526
|
+
const node = draft.node(record)
|
|
527
|
+
let replacementKey
|
|
528
|
+
if (replacement) {
|
|
529
|
+
replacementKey = keyOf(replacement)
|
|
530
|
+
if (replacement === record) failWhy('replacement-self', {}, 'a token cannot replace itself')
|
|
531
|
+
if (replacement.dtcgType !== record.dtcgType) {
|
|
532
|
+
failWhy(
|
|
533
|
+
'type-mismatch',
|
|
534
|
+
{ token: key, type: record.dtcgType, other: replacementKey, otherType: replacement.dtcgType },
|
|
535
|
+
`cannot replace ${record.dtcgType} ${key} with ${replacement.dtcgType} ${replacementKey}`,
|
|
536
|
+
)
|
|
537
|
+
}
|
|
538
|
+
if (replacement.deprecated !== undefined) {
|
|
539
|
+
notes.add('replacement-deprecated', { token: replacementKey }, `${replacementKey} is itself deprecated`)
|
|
540
|
+
}
|
|
541
|
+
const replacementNode = draft.node(replacement)
|
|
542
|
+
const replacementIsRecord =
|
|
543
|
+
replacement.alias === key ||
|
|
544
|
+
(typeof replacement.raw === 'string' && replacement.raw.trim() === `var(${record.cssName})`)
|
|
545
|
+
if (!replacementIsRecord && typeof replacement.raw === 'string' && valueReferences(replacement.raw, [record.cssName])) {
|
|
546
|
+
failWhy(
|
|
547
|
+
'deprecate-cycle',
|
|
548
|
+
{ token: key, other: replacementKey, value: replacement.raw },
|
|
549
|
+
`${replacementKey} uses ${key} inside a larger value (${replacement.raw}); aliasing ${key} to it would make a cycle. ` +
|
|
550
|
+
`Choose another replacement or give ${replacementKey} its own value first.`,
|
|
551
|
+
)
|
|
552
|
+
}
|
|
553
|
+
if (replacementIsRecord) {
|
|
554
|
+
notes.add('takes-value', { token: replacementKey, other: key }, `${replacementKey} referenced ${key}, so it takes ${key}'s value`)
|
|
555
|
+
draft.note({ file: replacement.source, token: replacementKey, change: 'set-value', from: replacementNode.$value, to: node.$value })
|
|
556
|
+
replacementNode.$value = structuredClone(node.$value)
|
|
557
|
+
} else if (lower(replacement.value) !== lower(record.value)) {
|
|
558
|
+
notes.add(
|
|
559
|
+
'value-changes',
|
|
560
|
+
{ token: key, from: record.value, to: replacement.value, other: replacementKey },
|
|
561
|
+
`${key} changes value ${record.value} → ${replacement.value} (it now aliases ${replacementKey})`,
|
|
562
|
+
)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const finalReason = reason || `Use ${replacementKey} instead.`
|
|
566
|
+
const deprecatedNote = `Deprecated: ${finalReason}`
|
|
567
|
+
draft.note({
|
|
568
|
+
file: record.source,
|
|
569
|
+
token: key,
|
|
570
|
+
change: 'deprecate',
|
|
571
|
+
reason: finalReason,
|
|
572
|
+
...(replacement ? { from: node.$value, to: `{${replacementKey}}` } : {}),
|
|
573
|
+
})
|
|
574
|
+
node.$deprecated = finalReason
|
|
575
|
+
if (replacement) node.$value = `{${replacementKey}}`
|
|
576
|
+
if (!String(node.$description ?? '').includes(deprecatedNote)) {
|
|
577
|
+
node.$description = node.$description ? `${node.$description} ${deprecatedNote}` : deprecatedNote
|
|
578
|
+
}
|
|
579
|
+
let codeSpec = null
|
|
580
|
+
if (mode === 'replace-all') {
|
|
581
|
+
retargetTokenRefs(ctx, draft, record, { path: replacementKey, cssName: replacement.cssName }, new Set([key, replacementKey]))
|
|
582
|
+
codeSpec = renameSpec(ctx, new Map([[record.cssName, replacement.cssName]]))
|
|
583
|
+
}
|
|
584
|
+
return {
|
|
585
|
+
op: 'deprecate',
|
|
586
|
+
record,
|
|
587
|
+
draft,
|
|
588
|
+
notes,
|
|
589
|
+
mode,
|
|
590
|
+
codeSpec,
|
|
591
|
+
expect: replacement
|
|
592
|
+
? { present: [record.cssName, replacement.cssName], aliases: { [record.cssName]: replacementKey } }
|
|
593
|
+
: { present: [record.cssName] },
|
|
594
|
+
item: {
|
|
595
|
+
tokenAction: 'deprecate',
|
|
596
|
+
from: key,
|
|
597
|
+
to: replacementKey ?? '',
|
|
598
|
+
...(replacementKey ? { tokenAlias: replacementKey } : {}),
|
|
599
|
+
rationale: finalReason,
|
|
600
|
+
},
|
|
601
|
+
args: { token: key, replacement: replacementKey ?? null, mode, reason: finalReason },
|
|
602
|
+
summary: `Deprecated ${key}${replacement ? ` → ${replacementKey}` : ' (no replacement)'} (${mode}): ${finalReason}`,
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** Every reason `record` cannot be deleted yet (empty when usage is 0). */
|
|
608
|
+
async function usageBlockers(ctx, record) {
|
|
609
|
+
const key = keyOf(record)
|
|
610
|
+
const index = await buildUsageIndex({ root: ctx.root })
|
|
611
|
+
const usage = index.tokenUsage(record.cssName)
|
|
612
|
+
const tokens = ctx.records
|
|
613
|
+
.filter(
|
|
614
|
+
(entry) =>
|
|
615
|
+
entry !== record &&
|
|
616
|
+
(entry.alias === key || (!entry.alias && typeof entry.raw === 'string' && valueReferences(entry.raw, [record.cssName]))),
|
|
617
|
+
)
|
|
618
|
+
.map(keyOf)
|
|
619
|
+
const probe = await planRewrites({
|
|
620
|
+
root: ctx.root,
|
|
621
|
+
files: [...ctx.scan, ...ctx.outside],
|
|
622
|
+
spec: renameSpec(ctx, new Map([[record.cssName, '--seji-delete-probe']])),
|
|
623
|
+
})
|
|
624
|
+
const places = probe.flatMap((plan) => [
|
|
625
|
+
...plan.changes.map((entry) => ({ file: entry.file, line: entry.line, column: entry.column, text: entry.from })),
|
|
626
|
+
...plan.leftovers.map((entry) => ({ file: entry.file, line: entry.line, column: entry.column, text: entry.text, reason: entry.reason })),
|
|
627
|
+
])
|
|
628
|
+
// The same rule as the usage report's `deletable` (usage.mjs), with this context's token
|
|
629
|
+
// references and every place a rename probe finds.
|
|
630
|
+
const { blockedBy } = deleteBlockers({
|
|
631
|
+
tokens,
|
|
632
|
+
localAliases: usage?.referencedBy.localAliases ?? [],
|
|
633
|
+
codeRefs: Math.max(usage?.code.count ?? 0, places.length),
|
|
634
|
+
components: usage?.summary.components ?? 0,
|
|
635
|
+
})
|
|
636
|
+
const blockers = []
|
|
637
|
+
if (blockedBy.tokens.length) blockers.push(`${blockedBy.tokens.length} token(s) reference it: ${blockedBy.tokens.join(', ')}`)
|
|
638
|
+
if (blockedBy.localAliases.length) blockers.push(`local CSS alias(es) point at it: ${blockedBy.localAliases.join(', ')}`)
|
|
639
|
+
if (blockedBy.codeRefs) blockers.push(`${blockedBy.codeRefs} code reference(s)`)
|
|
640
|
+
if (blockedBy.components && !blockedBy.codeRefs) blockers.push(`${blockedBy.components} component(s)`)
|
|
641
|
+
return { blockers, blockedBy, tokens, places, usage: usage?.summary }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function planDelete(args) {
|
|
645
|
+
return async (ctx) => {
|
|
646
|
+
const record = findRecord(ctx, args.token)
|
|
647
|
+
const key = keyOf(record)
|
|
648
|
+
const { blockers, blockedBy, tokens, places, usage } = await usageBlockers(ctx, record)
|
|
649
|
+
const draft = createDraft(ctx)
|
|
650
|
+
if (!blockers.length) {
|
|
651
|
+
removeAt(draft.json(record.source), record.path)
|
|
652
|
+
draft.note({ file: record.source, token: key, change: 'remove' })
|
|
653
|
+
}
|
|
654
|
+
return {
|
|
655
|
+
op: 'delete',
|
|
656
|
+
record,
|
|
657
|
+
draft,
|
|
658
|
+
notes: [],
|
|
659
|
+
codeSpec: null,
|
|
660
|
+
refusal: blockers.length
|
|
661
|
+
? {
|
|
662
|
+
message: `cannot delete ${key}: it is still used — ${blockers.join('; ')}. Deprecate it with a replacement (\`tokens deprecate ${key} --replacement <token> --mode replace-all\`), let the agent fix the leftovers, and delete once usage is 0.`,
|
|
663
|
+
why: {
|
|
664
|
+
code: 'delete-in-use',
|
|
665
|
+
params: {
|
|
666
|
+
token: key,
|
|
667
|
+
tokens: blockedBy.tokens.length,
|
|
668
|
+
localAliases: blockedBy.localAliases.length,
|
|
669
|
+
codeRefs: blockedBy.codeRefs,
|
|
670
|
+
components: blockedBy.components,
|
|
671
|
+
},
|
|
672
|
+
},
|
|
673
|
+
details: { usage, blockedBy, tokens, places: places.slice(0, 50) },
|
|
674
|
+
}
|
|
675
|
+
: null,
|
|
676
|
+
expect: { absent: [record.cssName] },
|
|
677
|
+
item: { tokenAction: 'delete', from: key, to: '' },
|
|
678
|
+
args: { token: key, cssName: record.cssName, refused: blockers.length > 0 },
|
|
679
|
+
summary: blockers.length
|
|
680
|
+
? `Refused to delete ${key} (${record.cssName}); it is still used`
|
|
681
|
+
: `Deleted ${key} (${record.cssName}); usage was 0`,
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function planDescribe(args) {
|
|
687
|
+
return async (ctx) => {
|
|
688
|
+
const record = findRecord(ctx, args.token)
|
|
689
|
+
const description = required(args.description, '--description')
|
|
690
|
+
const draft = createDraft(ctx)
|
|
691
|
+
const node = draft.node(record)
|
|
692
|
+
draft.note({ file: record.source, token: keyOf(record), change: 'describe', from: node.$description ?? '', to: description })
|
|
693
|
+
node.$description = description
|
|
694
|
+
return {
|
|
695
|
+
op: 'describe',
|
|
696
|
+
record,
|
|
697
|
+
draft,
|
|
698
|
+
notes: [],
|
|
699
|
+
codeSpec: null,
|
|
700
|
+
expect: { present: [record.cssName] },
|
|
701
|
+
item: { tokenAction: 'describe', from: record.description ?? '', to: description, tokenDescription: description },
|
|
702
|
+
args: { token: keyOf(record) },
|
|
703
|
+
summary: `Set the $description of ${keyOf(record)}`,
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function planSet(args) {
|
|
709
|
+
return async (ctx) => {
|
|
710
|
+
const record = findRecord(ctx, args.token)
|
|
711
|
+
const key = keyOf(record)
|
|
712
|
+
const raw = required(args.value, '--value')
|
|
713
|
+
const draft = createDraft(ctx)
|
|
714
|
+
const node = draft.node(record)
|
|
715
|
+
let next = raw
|
|
716
|
+
const alias = /^\{([^}]+)\}$/.exec(raw)?.[1]
|
|
717
|
+
if (alias) {
|
|
718
|
+
if (!ctx.byPath.has(alias)) failWhy('unknown-alias', { token: alias }, `--value aliases unknown token ${alias}`)
|
|
719
|
+
if (alias === key) failWhy('self-alias', {}, 'a token cannot alias itself')
|
|
720
|
+
} else if (node.$value && typeof node.$value === 'object' && 'unit' in node.$value) {
|
|
721
|
+
const match = /^(-?\d*\.?\d+)([a-z%]+)$/i.exec(raw)
|
|
722
|
+
if (match) next = { value: Number(match[1]), unit: match[2] }
|
|
723
|
+
}
|
|
724
|
+
draft.note({ file: record.source, token: key, change: 'set-value', from: node.$value, to: next })
|
|
725
|
+
node.$value = next
|
|
726
|
+
return {
|
|
727
|
+
op: 'set',
|
|
728
|
+
record,
|
|
729
|
+
draft,
|
|
730
|
+
notes: [],
|
|
731
|
+
codeSpec: null,
|
|
732
|
+
expect: alias ? { aliases: { [record.cssName]: alias } } : { values: { [record.cssName]: raw } },
|
|
733
|
+
item: { tokenAction: alias ? 'alias' : 'update', from: record.value, to: raw, ...(alias ? { tokenAlias: alias } : {}) },
|
|
734
|
+
args: { token: key, value: raw },
|
|
735
|
+
summary: `Set ${key} to ${raw}`,
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
const DIMENSION = /^(-?\d*\.?\d+)([a-z%]+)$/i
|
|
741
|
+
|
|
742
|
+
/** The source file a new token at `path` with `tier` goes into, and whether it needs an explicit tier. */
|
|
743
|
+
function sourceForNewToken(ctx, path, tier) {
|
|
744
|
+
const groupPath = path.slice(0, -1)
|
|
745
|
+
const depthIn = (json) => {
|
|
746
|
+
let node = json
|
|
747
|
+
let depth = 0
|
|
748
|
+
for (const segment of groupPath) {
|
|
749
|
+
const next = node?.[segment]
|
|
750
|
+
if (!next || typeof next !== 'object' || '$value' in next) break
|
|
751
|
+
node = next
|
|
752
|
+
depth += 1
|
|
753
|
+
}
|
|
754
|
+
return depth
|
|
755
|
+
}
|
|
756
|
+
const ranked = ctx.sources
|
|
757
|
+
.map((source) => ({
|
|
758
|
+
source,
|
|
759
|
+
depth: depthIn(source.json),
|
|
760
|
+
tier: inheritedAt(source.json, groupPath, source.rel).tier,
|
|
761
|
+
named: basename(source.rel) === `${tier}.tokens.json`,
|
|
762
|
+
}))
|
|
763
|
+
.sort(
|
|
764
|
+
(a, b) =>
|
|
765
|
+
Number(b.tier === tier) - Number(a.tier === tier) ||
|
|
766
|
+
b.depth - a.depth ||
|
|
767
|
+
Number(b.named) - Number(a.named) ||
|
|
768
|
+
a.source.rel.localeCompare(b.source.rel),
|
|
769
|
+
)
|
|
770
|
+
const best = ranked[0]
|
|
771
|
+
return { rel: best.source.rel, inheritedTier: best.tier }
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** Add a token to `draft`. Name (dot path), value, an explicit tier and a $description are required. */
|
|
775
|
+
function addTokenToDraft(ctx, draft, args) {
|
|
776
|
+
const path = parsePath(args.token)
|
|
777
|
+
const key = path.join('.')
|
|
778
|
+
const cssName = cssNameOf(path)
|
|
779
|
+
const tier = required(args.tier, '--tier')
|
|
780
|
+
if (!TOKEN_TIERS.includes(tier)) fail(`--tier must be one of ${TOKEN_TIERS.join(', ')} (there is no default tier)`)
|
|
781
|
+
const description = required(args.description, '--description')
|
|
782
|
+
const raw = required(args.value, '--value')
|
|
783
|
+
if (ctx.byPath.has(key) || ctx.byCss.has(cssName)) fail(`${key} already exists; choose a new name or reuse it`)
|
|
784
|
+
for (const source of ctx.sources) {
|
|
785
|
+
const existing = nodeAt(draft.drafts.get(source.rel) ?? source.json, path)
|
|
786
|
+
if (existing !== null && existing !== undefined) fail(`${key} already exists in ${source.rel}; choose a path that does not exist yet`)
|
|
787
|
+
}
|
|
788
|
+
const alias = /^\{([^}]+)\}$/.exec(raw)?.[1]
|
|
789
|
+
let type = args.type?.trim()
|
|
790
|
+
let value = raw
|
|
791
|
+
if (alias) {
|
|
792
|
+
const target = ctx.byPath.get(alias)
|
|
793
|
+
if (!target) fail(`--value aliases unknown token ${alias}`)
|
|
794
|
+
type = type || target.dtcgType
|
|
795
|
+
if (type !== target.dtcgType) fail(`${key} is ${type} but ${alias} is ${target.dtcgType}`)
|
|
796
|
+
} else {
|
|
797
|
+
const match = DIMENSION.exec(raw)
|
|
798
|
+
if (!type) type = match ? 'dimension' : 'color'
|
|
799
|
+
if (type === 'dimension') {
|
|
800
|
+
if (!match) fail(`a dimension value needs a number and unit (e.g. 12px), not ${raw}`)
|
|
801
|
+
value = { value: Number(match[1]), unit: match[2].toLowerCase() }
|
|
802
|
+
} else if ((type === 'number' || type === 'fontWeight') && /^-?\d*\.?\d+$/.test(raw)) {
|
|
803
|
+
value = Number(raw)
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const { rel, inheritedTier } = sourceForNewToken(ctx, path, tier)
|
|
807
|
+
const node = { $type: type, $value: value, $description: description }
|
|
808
|
+
if (inheritedTier !== tier) node.$extensions = { 'design-surface': { tier } }
|
|
809
|
+
const json = draft.json(rel)
|
|
810
|
+
ensureGroups(json, path.slice(0, -1))[path[path.length - 1]] = node
|
|
811
|
+
draft.note({ file: rel, token: key, change: 'add', value, tier })
|
|
812
|
+
const record = { path, cssName, source: rel, tier, dtcgType: type, type: type === 'color' ? 'color' : type === 'dimension' ? 'length' : 'text', value: raw }
|
|
813
|
+
return {
|
|
814
|
+
record,
|
|
815
|
+
expect: alias ? { present: [cssName], aliases: { [cssName]: alias } } : { present: [cssName], values: { [cssName]: raw } },
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function planCreate(args) {
|
|
820
|
+
return async (ctx) => {
|
|
821
|
+
const draft = createDraft(ctx)
|
|
822
|
+
const { record, expect } = addTokenToDraft(ctx, draft, args)
|
|
823
|
+
const key = keyOf(record)
|
|
824
|
+
return {
|
|
825
|
+
op: 'create',
|
|
826
|
+
record,
|
|
827
|
+
draft,
|
|
828
|
+
notes: [],
|
|
829
|
+
codeSpec: null,
|
|
830
|
+
expect,
|
|
831
|
+
item: {
|
|
832
|
+
tokenAction: 'create',
|
|
833
|
+
from: '',
|
|
834
|
+
to: args.value.trim(),
|
|
835
|
+
tokenTier: record.tier,
|
|
836
|
+
tokenDescription: args.description.trim(),
|
|
837
|
+
...(expect.aliases ? { tokenAlias: expect.aliases[record.cssName] } : {}),
|
|
838
|
+
},
|
|
839
|
+
args: { token: key, cssName: record.cssName, tier: record.tier, value: args.value.trim() },
|
|
840
|
+
summary: `Created ${key} (${record.cssName}, ${record.tier}) = ${args.value.trim()}`,
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function planReplaceLiteral(args) {
|
|
846
|
+
return async (ctx) => {
|
|
847
|
+
const literal = required(args.literal, '<literal>')
|
|
848
|
+
const record = findRecord(ctx, args.token, '--token')
|
|
849
|
+
if (lower(record.value) !== lower(literal)) {
|
|
850
|
+
fail(`${keyOf(record)} is ${record.value}, not ${literal}; the tool only replaces exactly equal values`)
|
|
851
|
+
}
|
|
852
|
+
const scope = args.scope ? toPosix(args.scope).replace(/^\.\//, '').replace(/\/$/, '') : ''
|
|
853
|
+
const inScope = (abs) => {
|
|
854
|
+
const rel = toPosix(relative(ctx.root, abs))
|
|
855
|
+
return rel === scope || rel.startsWith(`${scope}/`)
|
|
856
|
+
}
|
|
857
|
+
const files = scope ? ctx.scan.filter(inScope) : ctx.scan
|
|
858
|
+
const outsideFiles = scope ? ctx.outside.filter(inScope) : ctx.outside
|
|
859
|
+
return {
|
|
860
|
+
op: 'replace-literal',
|
|
861
|
+
record,
|
|
862
|
+
draft: createDraft(ctx),
|
|
863
|
+
notes: [],
|
|
864
|
+
files,
|
|
865
|
+
outsideFiles,
|
|
866
|
+
codeSpec: {
|
|
867
|
+
mode: 'literal',
|
|
868
|
+
literal,
|
|
869
|
+
token: record.cssName,
|
|
870
|
+
replacement: `var(${record.cssName})`,
|
|
871
|
+
...(args.property ? { property: args.property } : {}),
|
|
872
|
+
theme: ctx.theme && !ctx.uno,
|
|
873
|
+
},
|
|
874
|
+
expect: { present: [record.cssName] },
|
|
875
|
+
item: { tokenAction: 'replace-literal', from: literal, to: keyOf(record) },
|
|
876
|
+
args: { literal, token: keyOf(record), cssName: record.cssName, scope },
|
|
877
|
+
summary: `Replaced hard-coded ${literal} with ${keyOf(record)} (${record.cssName})${scope ? ` in ${scope}` : ''}`,
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// ---------------------------------------------------------------------------------------
|
|
883
|
+
// Execution
|
|
884
|
+
|
|
885
|
+
function listDesignIds(root) {
|
|
886
|
+
const base = join(root, 'design')
|
|
887
|
+
if (!existsSync(base)) return []
|
|
888
|
+
return readdirSync(base, { withFileTypes: true })
|
|
889
|
+
.filter(
|
|
890
|
+
(entry) =>
|
|
891
|
+
entry.isDirectory() &&
|
|
892
|
+
SAFE_DESIGN_ID.test(entry.name) &&
|
|
893
|
+
(existsSync(join(base, entry.name, 'design.tsx')) || existsSync(join(base, entry.name, 'review.json'))),
|
|
894
|
+
)
|
|
895
|
+
.map((entry) => entry.name)
|
|
896
|
+
.sort()
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** The ledger a batch goes into: `design`, or the project's only design. */
|
|
900
|
+
export function resolveDesign(root, design) {
|
|
901
|
+
if (design !== undefined && design !== null && design !== '') {
|
|
902
|
+
if (!SAFE_DESIGN_ID.test(String(design))) fail(`invalid design id: ${design}`)
|
|
903
|
+
return String(design)
|
|
904
|
+
}
|
|
905
|
+
const ids = listDesignIds(root)
|
|
906
|
+
if (ids.length === 1) return ids[0]
|
|
907
|
+
failWhy('needs-design', { designs: ids.join(', ') }, `pass --design <id> to choose the review ledger${ids.length ? ` (${ids.join(', ')})` : ''}`)
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const placeOf = (entry) => ({
|
|
911
|
+
file: entry.file,
|
|
912
|
+
line: entry.line,
|
|
913
|
+
column: entry.column,
|
|
914
|
+
...(entry.property ? { property: entry.property } : {}),
|
|
915
|
+
...(entry.scheme ? { scheme: entry.scheme } : {}),
|
|
916
|
+
...(entry.from !== undefined ? { from: entry.from, to: entry.to } : {}),
|
|
917
|
+
...(entry.reason ? { reason: entry.reason } : {}),
|
|
918
|
+
...(entry.text ? { text: entry.text } : {}),
|
|
919
|
+
})
|
|
920
|
+
|
|
921
|
+
function buildReport(plan, { codePlans, tokenFiles, dryRun, design }) {
|
|
922
|
+
const changes = codePlans.flatMap((entry) => entry.changes).map(placeOf)
|
|
923
|
+
const codeLeftovers = codePlans.flatMap((entry) => entry.leftovers)
|
|
924
|
+
// Places a composite operation already knows it cannot change (`extraLeftovers`), unless a
|
|
925
|
+
// rewriter reported the same place and reason.
|
|
926
|
+
const extra = (plan.extraLeftovers ?? []).filter(
|
|
927
|
+
(entry) => !codeLeftovers.some((code) => code.file === entry.file && code.line === entry.line && code.reason === entry.reason),
|
|
928
|
+
)
|
|
929
|
+
const leftovers = [...codeLeftovers, ...extra].map(placeOf)
|
|
930
|
+
return {
|
|
931
|
+
op: plan.op,
|
|
932
|
+
dryRun,
|
|
933
|
+
...(design ? { design } : {}),
|
|
934
|
+
token: { path: keyOf(plan.record), cssName: plan.record.cssName, source: plan.record.source },
|
|
935
|
+
summary: plan.summary,
|
|
936
|
+
...(plan.args ? { args: plan.args } : {}),
|
|
937
|
+
...(plan.mode ? { mode: plan.mode } : {}),
|
|
938
|
+
...(plan.values ? { values: plan.values } : {}),
|
|
939
|
+
counts: {
|
|
940
|
+
tokenFileChanges: plan.draft.changes.length,
|
|
941
|
+
changed: changes.length,
|
|
942
|
+
leftovers: leftovers.length,
|
|
943
|
+
files: [...new Set([...tokenFiles.map((entry) => entry.rel), ...codePlans.filter((entry) => entry.after !== entry.before).map((entry) => entry.file)])].length,
|
|
944
|
+
},
|
|
945
|
+
tokenChanges: plan.draft.changes,
|
|
946
|
+
changes,
|
|
947
|
+
leftovers,
|
|
948
|
+
...(notesOf(plan).length ? { notes: [...plan.notes], noteCodes: [...plan.notes.codes] } : {}),
|
|
949
|
+
...(plan.target ? { target: plan.target } : {}),
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/** The review item a plan will record (ids fixed before the write, so a baseline can be taken). */
|
|
954
|
+
function prepareRecord(design, plan, report) {
|
|
955
|
+
const now = new Date().toISOString()
|
|
956
|
+
const batchId = `tokens-${plan.op}-${now.replace(/[-:.TZ]/g, '').slice(0, 14)}-${randomUUID().slice(0, 6)}`
|
|
957
|
+
const itemId = `token-op-${batchId}`
|
|
958
|
+
const changed = report.counts.changed + report.counts.tokenFileChanges
|
|
959
|
+
const left = report.counts.leftovers
|
|
960
|
+
const body = `Tool changed ${changed} place(s) (${report.counts.tokenFileChanges} in token sources, ${report.counts.changed} in code), left ${left} for agent.`
|
|
961
|
+
const item = {
|
|
962
|
+
id: itemId,
|
|
963
|
+
design,
|
|
964
|
+
kind: 'token',
|
|
965
|
+
scope: 'design',
|
|
966
|
+
target: { type: 'token', token: plan.record.cssName },
|
|
967
|
+
...(plan.itemExtra ?? {}),
|
|
968
|
+
source: plan.record.source,
|
|
969
|
+
tokenType: plan.record.type,
|
|
970
|
+
tokenTier: plan.record.tier,
|
|
971
|
+
...plan.item,
|
|
972
|
+
...(plan.op === 'replace-literal' && !plan.codeSpec?.property
|
|
973
|
+
? {
|
|
974
|
+
replaces: {
|
|
975
|
+
value: plan.item.from,
|
|
976
|
+
files: [...new Set([...report.changes, ...report.leftovers].map((entry) => entry.file))].sort(),
|
|
977
|
+
},
|
|
978
|
+
}
|
|
979
|
+
: {}),
|
|
980
|
+
body: `${plan.summary}. ${body}`,
|
|
981
|
+
tokenOp: {
|
|
982
|
+
op: plan.op,
|
|
983
|
+
batchId,
|
|
984
|
+
by: 'tool',
|
|
985
|
+
changed,
|
|
986
|
+
left,
|
|
987
|
+
summary: plan.summary,
|
|
988
|
+
...(plan.args ? { args: plan.args } : {}),
|
|
989
|
+
...(plan.mode ? { mode: plan.mode } : {}),
|
|
990
|
+
...(plan.values ? { values: plan.values } : {}),
|
|
991
|
+
expect: plan.expect,
|
|
992
|
+
tokenChanges: report.tokenChanges,
|
|
993
|
+
changes: report.changes.slice(0, MAX_ITEM_CHANGES),
|
|
994
|
+
...(report.changes.length > MAX_ITEM_CHANGES ? { changesTruncated: report.changes.length } : {}),
|
|
995
|
+
leftovers: report.leftovers,
|
|
996
|
+
...(report.notes ? { notes: report.notes } : {}),
|
|
997
|
+
...(report.noteCodes ? { noteCodes: report.noteCodes } : {}),
|
|
998
|
+
...(plan.tokenOpExtra ?? {}),
|
|
999
|
+
},
|
|
1000
|
+
status: left ? 'open' : 'resolved',
|
|
1001
|
+
createdAt: now,
|
|
1002
|
+
updatedAt: now,
|
|
1003
|
+
...(left ? {} : { resolvedAt: now }),
|
|
1004
|
+
}
|
|
1005
|
+
return { now, batchId, itemId, item }
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/** Record the prepared item (plus `extra` fields, e.g. a snapshot baseline) and its batch. */
|
|
1009
|
+
function commitRecord(root, design, plan, record, written, extra) {
|
|
1010
|
+
const { now, batchId, itemId } = record
|
|
1011
|
+
const item = extra ? { ...record.item, ...extra } : record.item
|
|
1012
|
+
const batch = {
|
|
1013
|
+
id: batchId,
|
|
1014
|
+
design,
|
|
1015
|
+
createdAt: now,
|
|
1016
|
+
itemIds: [itemId],
|
|
1017
|
+
kind: 'token-op',
|
|
1018
|
+
op: plan.op,
|
|
1019
|
+
summary: plan.summary,
|
|
1020
|
+
revert: {
|
|
1021
|
+
files: written.map((entry) => ({
|
|
1022
|
+
file: entry.file,
|
|
1023
|
+
beforeHash: entry.beforeHash,
|
|
1024
|
+
afterHash: entry.afterHash,
|
|
1025
|
+
undo: entry.undo,
|
|
1026
|
+
})),
|
|
1027
|
+
},
|
|
1028
|
+
}
|
|
1029
|
+
mutateReview(root, design, (review) => ({ ...review, items: [...review.items, item], batches: [...review.batches, batch] }), {
|
|
1030
|
+
create: true,
|
|
1031
|
+
})
|
|
1032
|
+
return { batchId, itemId, status: item.status }
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
/** Validation problems the project already has before an operation writes anything. */
|
|
1036
|
+
async function validationBaseline(root) {
|
|
1037
|
+
try {
|
|
1038
|
+
return new Set((await analyzeTokens({ root })).errors)
|
|
1039
|
+
} catch {
|
|
1040
|
+
return new Set()
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/**
|
|
1045
|
+
* Rebuild after an operation. An operation answers only for what it changed: a validation
|
|
1046
|
+
* problem that was there before it (`baseline`, e.g. an unrelated failing contrast pair) is
|
|
1047
|
+
* reported as a warning, never a reason to roll the operation back.
|
|
1048
|
+
*/
|
|
1049
|
+
async function rebuild(root, baseline = new Set()) {
|
|
1050
|
+
try {
|
|
1051
|
+
const result = await runTokenPipeline({ root })
|
|
1052
|
+
return { counts: result.counts, warnings: result.warnings }
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
if (!error?.validationErrors) throw error
|
|
1055
|
+
const fresh = error.validationErrors.filter((entry) => !baseline.has(entry))
|
|
1056
|
+
if (fresh.length) {
|
|
1057
|
+
const next = new Error(`Token validation failed (${fresh.length}):\n${fresh.map((entry) => ` - ${entry}`).join('\n')}`)
|
|
1058
|
+
next.validationErrors = fresh
|
|
1059
|
+
throw next
|
|
1060
|
+
}
|
|
1061
|
+
return {
|
|
1062
|
+
counts: error.counts,
|
|
1063
|
+
warnings: [
|
|
1064
|
+
...(error.warnings ?? []),
|
|
1065
|
+
`${error.validationErrors.length} validation problem(s) predate this change and were left as they are: ${error.validationErrors.join('; ')}`,
|
|
1066
|
+
],
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/** Throw before anything is written when the ledger cannot take the batch. */
|
|
1072
|
+
function assertLedgerWritable(root, design) {
|
|
1073
|
+
const file = reviewFilePath(root, design)
|
|
1074
|
+
let parsed
|
|
1075
|
+
try {
|
|
1076
|
+
parsed = readReviewFile(file)
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
fail(`cannot record the batch: ${error instanceof Error ? error.message : error}; nothing was changed`)
|
|
1079
|
+
}
|
|
1080
|
+
if (parsed && (parsed.version !== 1 || !Array.isArray(parsed.items))) {
|
|
1081
|
+
fail(`cannot record the batch: invalid review ledger shape in ${toPosix(relative(root, file))}; nothing was changed`)
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** Serialise a draft like its source file: same indentation and final newline. */
|
|
1086
|
+
function formatLike(before, json) {
|
|
1087
|
+
const indent = /\n([ \t]+)["}\]]/.exec(before)?.[1] ?? ' '
|
|
1088
|
+
const newline = before.endsWith('\n') || !before ? '\n' : ''
|
|
1089
|
+
return `${JSON.stringify(json, null, indent)}${newline}`
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/** Refuse a draft that would not build: alias cycles, missing aliases, duplicate CSS names. */
|
|
1093
|
+
function assertDraftBuilds(ctx, draft) {
|
|
1094
|
+
if (!draft.drafts.size) return
|
|
1095
|
+
const records = []
|
|
1096
|
+
try {
|
|
1097
|
+
for (const source of ctx.sources) {
|
|
1098
|
+
const json = draft.drafts.get(source.rel) ?? source.json
|
|
1099
|
+
walkTokens(json, [], {}, undefined, source.abs, ctx.root, records)
|
|
1100
|
+
}
|
|
1101
|
+
const seen = new Map()
|
|
1102
|
+
for (const record of records) {
|
|
1103
|
+
const key = keyOf(record)
|
|
1104
|
+
if (seen.has(record.cssName)) throw new Error(`${key} and ${seen.get(record.cssName)} would both be ${record.cssName}`)
|
|
1105
|
+
seen.set(record.cssName, key)
|
|
1106
|
+
}
|
|
1107
|
+
// var() references: resolveRecords does not track them for cycles, so check here.
|
|
1108
|
+
const byCss = new Map(records.map((record) => [record.cssName, record]))
|
|
1109
|
+
const byPath = new Map(records.map((record) => [keyOf(record), record]))
|
|
1110
|
+
const allNames = new Map([...byCss.keys()].map((name) => [name, name]))
|
|
1111
|
+
const edges = (record) => {
|
|
1112
|
+
if (record.alias) return byPath.has(record.alias) ? [byPath.get(record.alias)] : []
|
|
1113
|
+
if (typeof record.raw !== 'string') return []
|
|
1114
|
+
const names = []
|
|
1115
|
+
rewriteValueVars(record.raw, allNames, {
|
|
1116
|
+
emit: (start, end) => names.push(record.raw.slice(start, end)),
|
|
1117
|
+
leftover: () => {},
|
|
1118
|
+
})
|
|
1119
|
+
return names.map((name) => byCss.get(name)).filter(Boolean)
|
|
1120
|
+
}
|
|
1121
|
+
const state = new Map()
|
|
1122
|
+
const visit = (record, stack) => {
|
|
1123
|
+
const key = keyOf(record)
|
|
1124
|
+
if (state.get(key) === 'done') return
|
|
1125
|
+
if (state.get(key) === 'open') throw new Error(`circular token reference: ${[...stack, key].join(' -> ')}`)
|
|
1126
|
+
state.set(key, 'open')
|
|
1127
|
+
for (const next of edges(record)) visit(next, [...stack, key])
|
|
1128
|
+
state.set(key, 'done')
|
|
1129
|
+
}
|
|
1130
|
+
for (const record of records) visit(record, [])
|
|
1131
|
+
resolveRecords(records)
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
1134
|
+
failWhy('would-not-build', { error: reason }, `the result would not build, so nothing was changed: ${reason}`)
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
const refusalOf = (plan, report) => {
|
|
1139
|
+
if (plan.refusal) return plan.refusal
|
|
1140
|
+
const refusal = plan.refuse ? plan.refuse(report) : null
|
|
1141
|
+
if (!refusal) return null
|
|
1142
|
+
return typeof refusal === 'string' ? { message: refusal } : refusal
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/** The fields a refusal adds to a report: message, its translatable `why`, and details. */
|
|
1146
|
+
const refusalFields = (refusal) => ({
|
|
1147
|
+
refused: refusal.message,
|
|
1148
|
+
...(refusal.why ? { why: refusal.why } : {}),
|
|
1149
|
+
...(refusal.details ? { blockers: refusal.details } : {}),
|
|
1150
|
+
})
|
|
1151
|
+
|
|
1152
|
+
const hasCode = (plan) => Boolean(plan.codeSpec || plan.codeSteps?.length)
|
|
1153
|
+
const codeArgs = (plan) => (plan.codeSteps?.length ? { steps: plan.codeSteps } : { spec: plan.codeSpec })
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* `hooks.beforeWrite(item)` runs after the final plan, right before the first write, with the
|
|
1157
|
+
* review item the operation will record; the fields it returns are stored on that item (the
|
|
1158
|
+
* snapshot baseline of the screens the change affects). The other hooks are test seams.
|
|
1159
|
+
*/
|
|
1160
|
+
async function execute(root, build, { dryRun = false, design, hooks } = {}) {
|
|
1161
|
+
const ledger = dryRun ? (design ? resolveDesign(root, design) : undefined) : resolveDesign(root, design)
|
|
1162
|
+
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
|
|
1163
|
+
const ctx = await loadContext(root)
|
|
1164
|
+
const plan = await build(ctx)
|
|
1165
|
+
assertDraftBuilds(ctx, plan.draft)
|
|
1166
|
+
const codePlans = hasCode(plan) ? await planRewrites({ root, files: plan.files ?? ctx.scan, ...codeArgs(plan) }) : []
|
|
1167
|
+
// Files outside the project are never written; what the tool would change there is a leftover.
|
|
1168
|
+
const outsidePlans = hasCode(plan) ? await planOutside(root, plan.outsideFiles ?? ctx.outside, codeArgs(plan)) : []
|
|
1169
|
+
await hooks?.afterPlan?.({ attempt })
|
|
1170
|
+
const tokenFiles = [...plan.draft.drafts.entries()]
|
|
1171
|
+
.map(([rel, json]) => {
|
|
1172
|
+
const source = ctx.sources.find((entry) => entry.rel === rel)
|
|
1173
|
+
return { rel, abs: source.abs, before: source.text, hash: source.hash, after: formatLike(source.text, json) }
|
|
1174
|
+
})
|
|
1175
|
+
.filter((entry) => entry.after !== entry.before)
|
|
1176
|
+
for (const entry of tokenFiles) {
|
|
1177
|
+
if (formatLike(entry.before, JSON.parse(entry.before)) !== entry.before) {
|
|
1178
|
+
notesOf(plan).add('reformatted', { file: entry.rel }, `${entry.rel} was not in canonical JSON formatting; it is rewritten whole`)
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
const report = buildReport(plan, { codePlans: [...codePlans, ...outsidePlans], tokenFiles, dryRun, design: ledger })
|
|
1182
|
+
const refusal = refusalOf(plan, report)
|
|
1183
|
+
if (refusal) {
|
|
1184
|
+
const { refused, ...fields } = refusalFields(refusal)
|
|
1185
|
+
if (dryRun) return { ...report, refused, ...fields }
|
|
1186
|
+
fail(refused, { ...report, ...fields })
|
|
1187
|
+
}
|
|
1188
|
+
if (dryRun) return report
|
|
1189
|
+
if (!tokenFiles.length && !codePlans.some((entry) => entry.after !== entry.before)) {
|
|
1190
|
+
failWhy('nothing-to-change', {}, `nothing to change: ${plan.summary.toLowerCase()} would not modify any file`, report)
|
|
1191
|
+
}
|
|
1192
|
+
assertLedgerWritable(root, ledger)
|
|
1193
|
+
|
|
1194
|
+
// Everything is re-read and re-planned before the first write. Token sources are edited
|
|
1195
|
+
// as whole JSON documents: if one changed since it was parsed, start over.
|
|
1196
|
+
if (tokenFiles.some((entry) => sha256(readFileSync(entry.abs, 'utf8')) !== entry.hash)) continue
|
|
1197
|
+
const prepared = await prepareRewrites({ root, plans: codePlans, ...codeArgs(plan) })
|
|
1198
|
+
if (prepared.missing.length) continue
|
|
1199
|
+
// Re-parsed files may have produced different places: decide and report on the final plans.
|
|
1200
|
+
const finalReport = buildReport(plan, {
|
|
1201
|
+
codePlans: [...prepared.plans, ...outsidePlans],
|
|
1202
|
+
tokenFiles,
|
|
1203
|
+
dryRun: false,
|
|
1204
|
+
design: ledger,
|
|
1205
|
+
})
|
|
1206
|
+
const finalRefusal = refusalOf(plan, finalReport)
|
|
1207
|
+
if (finalRefusal) {
|
|
1208
|
+
const { refused, ...fields } = refusalFields(finalRefusal)
|
|
1209
|
+
fail(refused, { ...finalReport, ...fields })
|
|
1210
|
+
}
|
|
1211
|
+
const writes = [
|
|
1212
|
+
...tokenFiles.map((entry) => ({
|
|
1213
|
+
file: entry.rel,
|
|
1214
|
+
abs: entry.abs,
|
|
1215
|
+
before: entry.before,
|
|
1216
|
+
after: entry.after,
|
|
1217
|
+
beforeHash: entry.hash,
|
|
1218
|
+
afterHash: sha256(entry.after),
|
|
1219
|
+
undo: undoEdits(entry.before, entry.after),
|
|
1220
|
+
})),
|
|
1221
|
+
...writesFor(prepared.plans),
|
|
1222
|
+
]
|
|
1223
|
+
|
|
1224
|
+
const record = prepareRecord(ledger, plan, finalReport)
|
|
1225
|
+
const extra = (await hooks?.beforeWrite?.(record.item)) ?? undefined
|
|
1226
|
+
const written = []
|
|
1227
|
+
let built
|
|
1228
|
+
let recorded
|
|
1229
|
+
const baseline = await validationBaseline(root)
|
|
1230
|
+
try {
|
|
1231
|
+
writeAll(writes, { written, onWritten: hooks?.afterWrite })
|
|
1232
|
+
built = await rebuild(root, baseline)
|
|
1233
|
+
hooks?.beforeRecord?.()
|
|
1234
|
+
recorded = commitRecord(root, ledger, plan, record, written, extra)
|
|
1235
|
+
} catch (error) {
|
|
1236
|
+
if (error instanceof StaleFileError && !error.restoreConflicts) {
|
|
1237
|
+
// Someone saved a file between planning and writing; everything written was undone.
|
|
1238
|
+
restoreWrites(written)
|
|
1239
|
+
await rebuild(root).catch(() => {})
|
|
1240
|
+
continue
|
|
1241
|
+
}
|
|
1242
|
+
const conflicts = [...(error.restoreConflicts ?? []), ...restoreWrites(written)]
|
|
1243
|
+
let rebuildError
|
|
1244
|
+
try {
|
|
1245
|
+
await rebuild(root)
|
|
1246
|
+
} catch (rebuildFailure) {
|
|
1247
|
+
rebuildError = rebuildFailure instanceof Error ? rebuildFailure.message : String(rebuildFailure)
|
|
1248
|
+
}
|
|
1249
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1250
|
+
fail(`${plan.op} failed and was rolled back: ${message}`, {
|
|
1251
|
+
...(conflicts.length ? { notRestored: conflicts } : {}),
|
|
1252
|
+
...(rebuildError ? { rebuildError } : {}),
|
|
1253
|
+
})
|
|
1254
|
+
}
|
|
1255
|
+
const reparsed = prepared.plans.filter((entry) => entry.reparsed).map((entry) => entry.file)
|
|
1256
|
+
let verify
|
|
1257
|
+
try {
|
|
1258
|
+
verify = await verifyReviews({ root, designs: [ledger] })
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
verify = { error: error instanceof Error ? error.message : String(error) }
|
|
1261
|
+
}
|
|
1262
|
+
return {
|
|
1263
|
+
...finalReport,
|
|
1264
|
+
...recorded,
|
|
1265
|
+
...(reparsed.length ? { reparsed } : {}),
|
|
1266
|
+
rebuilt: built,
|
|
1267
|
+
verify,
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
failWhy('kept-changing', {}, 'files kept changing while the operation ran; nothing was changed; retry')
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
// ---------------------------------------------------------------------------------------
|
|
1274
|
+
// Revert
|
|
1275
|
+
|
|
1276
|
+
function findBatch(root, design, batchId) {
|
|
1277
|
+
const designs = design ? [resolveDesign(root, design)] : listDesignIds(root)
|
|
1278
|
+
for (const id of designs) {
|
|
1279
|
+
const review = readReviewFile(reviewFilePath(root, id))
|
|
1280
|
+
const batch = review?.batches?.find((entry) => entry.id === batchId)
|
|
1281
|
+
if (batch) return { design: id, batch }
|
|
1282
|
+
}
|
|
1283
|
+
fail(`batch not found: ${batchId}${design ? ` in ${design}` : ''}`)
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* The absolute path of a batch file, or a reason it may not be written. Revert data lives in
|
|
1288
|
+
* review.json, which is editable by hand, so it is never trusted: only relative paths in the
|
|
1289
|
+
* write scope (shared/writeScope.mjs, never through a symlink) that are token sources or
|
|
1290
|
+
* scanned files.
|
|
1291
|
+
*/
|
|
1292
|
+
function revertTarget(ctx, file) {
|
|
1293
|
+
if (typeof file !== 'string' || !file || file.includes('\0')) return { reason: 'invalid path' }
|
|
1294
|
+
const posix = file.replaceAll('\\', '/')
|
|
1295
|
+
if (isAbsolute(file) || posix.startsWith('/') || /^[a-zA-Z]:/.test(posix)) return { reason: 'path outside the project' }
|
|
1296
|
+
const target = ctx.scope.check(posix, { missing: true })
|
|
1297
|
+
if (!target.abs) return target
|
|
1298
|
+
const allowed = new Set([...ctx.sources.map((source) => source.abs), ...ctx.scan])
|
|
1299
|
+
if (!allowed.has(target.abs)) return { reason: 'not a token source or scanned file' }
|
|
1300
|
+
return target
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
async function revertLocked({ root, batch: batchId, design, force = false, dryRun = false }) {
|
|
1304
|
+
const id = required(batchId, '<batch>')
|
|
1305
|
+
const found = findBatch(root, design, id)
|
|
1306
|
+
const { batch } = found
|
|
1307
|
+
if (batch.kind !== 'token-op' || !Array.isArray(batch.revert?.files)) fail(`${id} is not a tool batch (nothing to revert)`)
|
|
1308
|
+
if (batch.revertedAt) failWhy('already-reverted', { batch: id, at: batch.revertedAt }, `${id} was already reverted at ${batch.revertedAt}`)
|
|
1309
|
+
const ctx = await loadContext(root)
|
|
1310
|
+
const files = batch.revert.files.map((entry) => {
|
|
1311
|
+
const target = revertTarget(ctx, entry?.file)
|
|
1312
|
+
if (!target.abs) return { file: String(entry?.file), ok: false, reason: target.reason }
|
|
1313
|
+
const { abs } = target
|
|
1314
|
+
const current = existsSync(abs) ? readFileSync(abs, 'utf8') : null
|
|
1315
|
+
if (current === null) return { file: entry.file, abs, ok: false, reason: 'file is missing' }
|
|
1316
|
+
if (sha256(current) !== entry.afterHash) return { file: entry.file, abs, ok: false, reason: 'changed since the batch' }
|
|
1317
|
+
let before
|
|
1318
|
+
try {
|
|
1319
|
+
before = applyEdits(current, Array.isArray(entry.undo) ? entry.undo : [])
|
|
1320
|
+
} catch {
|
|
1321
|
+
return { file: entry.file, abs, ok: false, reason: 'undo does not apply' }
|
|
1322
|
+
}
|
|
1323
|
+
if (sha256(before) !== entry.beforeHash) return { file: entry.file, abs, ok: false, reason: 'undo does not reproduce the original' }
|
|
1324
|
+
return { file: entry.file, abs, ok: true, before, after: before, beforeHash: entry.afterHash, afterHash: entry.beforeHash, current }
|
|
1325
|
+
})
|
|
1326
|
+
const unsafe = files.filter((entry) => !entry.ok && !entry.abs)
|
|
1327
|
+
if (unsafe.length) {
|
|
1328
|
+
fail(`refusing to revert ${id}: ${unsafe.map((entry) => `${entry.file} (${entry.reason})`).join(', ')}`)
|
|
1329
|
+
}
|
|
1330
|
+
const conflicts = files.filter((entry) => !entry.ok).map((entry) => ({ file: entry.file, reason: entry.reason }))
|
|
1331
|
+
const report = {
|
|
1332
|
+
op: 'revert',
|
|
1333
|
+
dryRun,
|
|
1334
|
+
design: found.design,
|
|
1335
|
+
batch: id,
|
|
1336
|
+
summary: batch.summary,
|
|
1337
|
+
files: files.filter((entry) => entry.ok).map((entry) => entry.file),
|
|
1338
|
+
conflicts,
|
|
1339
|
+
}
|
|
1340
|
+
if (conflicts.length && !force) {
|
|
1341
|
+
const message = `cannot revert ${id}: ${conflicts.map((entry) => `${entry.file} (${entry.reason})`).join(', ')}. Re-run with --force to revert only the unchanged files.`
|
|
1342
|
+
const why = { code: 'revert-conflicts', params: { files: conflicts.map((entry) => entry.file).join(', '), count: conflicts.length } }
|
|
1343
|
+
if (dryRun) return { ...report, refused: message, why }
|
|
1344
|
+
fail(message, { ...report, why })
|
|
1345
|
+
}
|
|
1346
|
+
if (dryRun) return report
|
|
1347
|
+
assertLedgerWritable(root, found.design)
|
|
1348
|
+
// writeAll checks `beforeHash` (= the batch's afterHash) and writes `after` (= the original).
|
|
1349
|
+
const writes = files
|
|
1350
|
+
.filter((entry) => entry.ok)
|
|
1351
|
+
.map((entry) => ({ file: entry.file, abs: entry.abs, before: entry.current, after: entry.before, beforeHash: entry.beforeHash, afterHash: entry.afterHash }))
|
|
1352
|
+
const written = []
|
|
1353
|
+
const now = new Date().toISOString()
|
|
1354
|
+
let built
|
|
1355
|
+
const baseline = await validationBaseline(root)
|
|
1356
|
+
try {
|
|
1357
|
+
writeAll(writes, { written })
|
|
1358
|
+
built = await rebuild(root, baseline)
|
|
1359
|
+
const itemIds = new Set(batch.itemIds ?? [])
|
|
1360
|
+
mutateReview(root, found.design, (review) => {
|
|
1361
|
+
const current = review.batches.find((entry) => entry.id === id)
|
|
1362
|
+
if (!current) throw new Error(`batch ${id} disappeared from the ledger`)
|
|
1363
|
+
if (current.revertedAt) throw new Error(`${id} was already reverted at ${current.revertedAt}`)
|
|
1364
|
+
return {
|
|
1365
|
+
...review,
|
|
1366
|
+
items: review.items.map((item) =>
|
|
1367
|
+
itemIds.has(item.id)
|
|
1368
|
+
? {
|
|
1369
|
+
...item,
|
|
1370
|
+
status: 'archived',
|
|
1371
|
+
archivedAt: now,
|
|
1372
|
+
updatedAt: now,
|
|
1373
|
+
...(item.tokenOp ? { tokenOp: { ...item.tokenOp, revertedAt: now } } : {}),
|
|
1374
|
+
}
|
|
1375
|
+
: item,
|
|
1376
|
+
),
|
|
1377
|
+
batches: review.batches.map((entry) =>
|
|
1378
|
+
entry.id === id ? { ...entry, revertedAt: now, ...(conflicts.length ? { revertSkipped: conflicts } : {}) } : entry,
|
|
1379
|
+
),
|
|
1380
|
+
}
|
|
1381
|
+
})
|
|
1382
|
+
} catch (error) {
|
|
1383
|
+
const notRestored = [...(error.restoreConflicts ?? []), ...restoreWrites(written)]
|
|
1384
|
+
let rebuildError
|
|
1385
|
+
try {
|
|
1386
|
+
await rebuild(root)
|
|
1387
|
+
} catch (rebuildFailure) {
|
|
1388
|
+
rebuildError = rebuildFailure instanceof Error ? rebuildFailure.message : String(rebuildFailure)
|
|
1389
|
+
}
|
|
1390
|
+
fail(`revert failed and was rolled back: ${error instanceof Error ? error.message : error}`, {
|
|
1391
|
+
...(notRestored.length ? { notRestored } : {}),
|
|
1392
|
+
...(rebuildError ? { rebuildError } : {}),
|
|
1393
|
+
})
|
|
1394
|
+
}
|
|
1395
|
+
return { ...report, revertedAt: now, rebuilt: built }
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/** Revert a tool batch (holds the project's token-operation lock). */
|
|
1399
|
+
export function revertBatch(options = {}) {
|
|
1400
|
+
const root = options.root ?? process.cwd()
|
|
1401
|
+
return locked(root, () => revertLocked({ ...options, root }))
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// ---------------------------------------------------------------------------------------
|
|
1405
|
+
// Public entry points
|
|
1406
|
+
|
|
1407
|
+
const BUILDERS = {
|
|
1408
|
+
rename: planRename,
|
|
1409
|
+
merge: planMerge,
|
|
1410
|
+
deprecate: planDeprecate,
|
|
1411
|
+
delete: planDelete,
|
|
1412
|
+
describe: planDescribe,
|
|
1413
|
+
set: planSet,
|
|
1414
|
+
create: planCreate,
|
|
1415
|
+
'replace-literal': planReplaceLiteral,
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
/**
|
|
1419
|
+
* Run one token operation. `args` (camelCase, shared by CLI and HTTP):
|
|
1420
|
+
* rename { token, to, alias?: false, reason? }
|
|
1421
|
+
* merge { token, into, keep?: 'target' | 'source', alias?: false, reason? }
|
|
1422
|
+
* deprecate { token, replacement? | noReplacement: true, reason?, mode?: 'mark-only' | 'replace-all' }
|
|
1423
|
+
* delete { token }
|
|
1424
|
+
* describe { token, description }
|
|
1425
|
+
* set { token, value }
|
|
1426
|
+
* create { token (dot path), value, tier, description, type? }
|
|
1427
|
+
* replace-literal { literal, token, scope?, property? }
|
|
1428
|
+
* revert { batch, force? }
|
|
1429
|
+
* plus { design?, dryRun? }.
|
|
1430
|
+
*/
|
|
1431
|
+
const BOOLEAN_ARGS = new Set(['dryRun', 'force', 'alias', 'noReplacement'])
|
|
1432
|
+
const STRING_ARGS = new Set([
|
|
1433
|
+
'token', 'to', 'into', 'keep', 'reason', 'replacement', 'mode', 'description', 'value', 'literal', 'scope', 'property', 'batch', 'design',
|
|
1434
|
+
'tier', 'type',
|
|
1435
|
+
])
|
|
1436
|
+
const ARG_HINTS = { noAlias: 'use "alias": false', 'dry-run': 'use "dryRun"', dry_run: 'use "dryRun"', no_replacement: 'use "noReplacement"' }
|
|
1437
|
+
|
|
1438
|
+
/** Reject unknown or mistyped arguments (HTTP bodies are not parsed by the CLI). */
|
|
1439
|
+
export function validateTokenOpArgs(args) {
|
|
1440
|
+
if (args === null || typeof args !== 'object' || Array.isArray(args)) {
|
|
1441
|
+
throw new TokenOpError('arguments must be a JSON object', { code: 'invalid-args' })
|
|
1442
|
+
}
|
|
1443
|
+
for (const [key, value] of Object.entries(args)) {
|
|
1444
|
+
if (value === undefined) continue
|
|
1445
|
+
if (BOOLEAN_ARGS.has(key)) {
|
|
1446
|
+
if (typeof value !== 'boolean') throw new TokenOpError(`${key} must be true or false, not ${JSON.stringify(value)}`, { code: 'invalid-args', argument: key })
|
|
1447
|
+
} else if (STRING_ARGS.has(key)) {
|
|
1448
|
+
if (typeof value !== 'string') throw new TokenOpError(`${key} must be a string, not ${JSON.stringify(value)}`, { code: 'invalid-args', argument: key })
|
|
1449
|
+
} else {
|
|
1450
|
+
throw new TokenOpError(`unknown argument: ${key}${ARG_HINTS[key] ? ` (${ARG_HINTS[key]})` : ''}`, { code: 'invalid-args', argument: key })
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return args
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
/**
|
|
1457
|
+
* Run one token operation. `args` (camelCase, shared by CLI and HTTP):
|
|
1458
|
+
* rename { token, to, alias?: false, reason? }
|
|
1459
|
+
* merge { token, into, keep?: 'target' | 'source', alias?: false, reason? }
|
|
1460
|
+
* deprecate { token, replacement? | noReplacement: true, reason?, mode?: 'mark-only' | 'replace-all' }
|
|
1461
|
+
* delete { token }
|
|
1462
|
+
* describe { token, description }
|
|
1463
|
+
* set { token, value }
|
|
1464
|
+
* create { token (dot path), value, tier, description, type? }
|
|
1465
|
+
* replace-literal { literal, token, scope?, property? }
|
|
1466
|
+
* revert { batch, force? }
|
|
1467
|
+
* plus { design?, dryRun? }. Booleans must be JSON booleans. The whole operation (plan,
|
|
1468
|
+
* write, rebuild, record) holds the project's token-operation lock, shared by every process.
|
|
1469
|
+
*/
|
|
1470
|
+
export async function runTokenOp({ root = process.cwd(), op, args = {}, hooks } = {}) {
|
|
1471
|
+
validateTokenOpArgs(args)
|
|
1472
|
+
if (op === 'revert') {
|
|
1473
|
+
return revertBatch({ root, batch: args.batch, design: args.design, force: args.force === true, dryRun: args.dryRun === true })
|
|
1474
|
+
}
|
|
1475
|
+
const builder = BUILDERS[op]
|
|
1476
|
+
if (!builder) fail(`unknown token operation: ${op ?? '(missing)'} (expected ${TOKEN_OPS.join(', ')})`)
|
|
1477
|
+
// `hooks.beforeWrite` takes the snapshot baseline (src/snapshots/toolOps.mjs); `afterPlan`,
|
|
1478
|
+
// `afterWrite` and `beforeRecord` are test seams for failure injection.
|
|
1479
|
+
return locked(root, () => execute(root, builder(args), { dryRun: args.dryRun === true, design: args.design, hooks }))
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// ---------------------------------------------------------------------------------------
|
|
1483
|
+
// Building blocks for composite tool operations (src/tokens/consolidate). A composite builder
|
|
1484
|
+
// returns the same plan shape as the builders above and runs through the same `execute`
|
|
1485
|
+
// (stale checks, atomic writes, rebuild, one item + one revertible batch).
|
|
1486
|
+
|
|
1487
|
+
export const tokenOpInternals = {
|
|
1488
|
+
createDraft,
|
|
1489
|
+
findRecord,
|
|
1490
|
+
keyOf,
|
|
1491
|
+
parsePath,
|
|
1492
|
+
addTokenToDraft,
|
|
1493
|
+
planMerge: (args) => planMerge(args),
|
|
1494
|
+
renameSpec,
|
|
1495
|
+
fail,
|
|
1496
|
+
failWhy,
|
|
1497
|
+
noteList,
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** Run a plan builder `(ctx) => plan` through `execute` while holding the token-operation lock. */
|
|
1501
|
+
export function runTokenPlan({ root = process.cwd(), build, dryRun = false, design, hooks, after } = {}) {
|
|
1502
|
+
return locked(root, async () => {
|
|
1503
|
+
const result = await execute(root, build, { dryRun, design, hooks })
|
|
1504
|
+
return after ? after(result) : result
|
|
1505
|
+
})
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
/** Run `fn` while holding the project's token-operation lock (timeouts become TokenOpError). */
|
|
1509
|
+
export function withTokenLock(root, fn) {
|
|
1510
|
+
return locked(root, fn)
|
|
1511
|
+
}
|