Compare commits

..
48 Commits
Author SHA1 Message Date
root-at-skic 7dde9ffffe Merge pull request '0.10.9: square Sync button on model, registry, decision and Graph pages' (#40) from fix/sync-button-width into main 2026-11-08 11:31:37 -08:00
root-at-skic f6f59fae67 0.10.9: square Sync button on model, registry, decision and Graph pages
aspect-ratio with a stretched height left the width at the icon's size.
Fixed sizes instead: 33px beside the model switch, 29px in the Graph
header.
2026-11-08 21:31:22 +02:00
root-at-skic 0752128789 Merge pull request '0.10.8: main.archify opens with its top-level panels collapsed' (#39) from feat/model-panels-collapsed into main 2026-11-08 11:06:10 -08:00
root-at-skic 517697197e Sync button sits in the view switch's row on every page
Model, registry and decision pages: next to the switch, not floating above
it. Graph page: after Export PNG (its header is built by graph.js a moment
later, so the button waits for it) instead of covering Export. Sized to
the controls beside it.
2026-11-08 20:59:16 +02:00
root-at-skic c71296b01a 0.10.8: main.archify opens with its top-level panels collapsed
Shared, Diagrams, Registries and Decisions start closed on the model page;
folders inside keep their own default. Open or closed is still kept in
the webview state while the page is open.
2026-11-08 20:48:35 +02:00
root-at-skic 86a8adf03b Merge pull request '0.10.7: Model | Graph | Source styled like 2D | 3D' (#38) from fix/mode-switch-style into main 2026-11-08 10:37:07 -08:00
root-at-skic 6153c7f145 0.10.7: Model | Graph | Source styled like 2D | 3D
Archify gives every toolbar button a 2.75rem minimum height and a painted
::before; the switch's segments are buttons, so they grew to full height.
Segments now keep 1.75rem inside a 2.75rem switch, like 2D | 3D. The high
contrast rule no longer turns a shared model's Sync button blue.
2026-11-08 20:35:48 +02:00
root-at-skic 885977c4aa Merge pull request '0.10.6: Sync sign-in comes back through 127.0.0.1' (#37) from fix/sync-signin-loopback into main 2026-11-08 10:06:32 -08:00
root-at-skic 95c6e60199 0.10.6: Sync sign-in comes back through 127.0.0.1
Browsers open a vscode:// link only after a click on the page. With a live
identity provider session the sign-in ran without one, so the editor kept
waiting. On the desktop the browser now returns to a one-off listener on
127.0.0.1; remote and web editors keep the URI handler.
2026-11-08 20:05:11 +02:00
root-at-skic b54304fef8 Merge pull request '0.10.5: icon-only Sync button that keeps its size and colour' (#36) from fix/sync-button-icon into main 2026-11-08 07:59:32 -08:00
root-at-skic 8407c9a956 0.10.5: icon-only Sync button that keeps its size and colour
On a diagram page it goes last in Archify's toolbar, after Export, instead
of floating over it. Every rule is !important and flex: none, so the page's
button styles, narrow windows and high contrast themes no longer squeeze it
or strip its colour.
2026-11-08 17:45:17 +02:00
root-at-skic c2d33780f9 Merge pull request '0.10.4: a real Sync button on every Archify page' (#35) from feat/sync-page-button into main 2026-11-07 07:07:15 -08:00
root-at-skic 90c7be06de 0.10.4: a real Sync button on every Archify page
A labelled Sync button sits top right on every Archify page, also in Source, and opens the Sync menu. On a shared model it turns green and reads Shared. The title-bar icon and the pre-share status bar entry are gone, with their settings.
2026-11-07 01:25:34 +02:00
root-at-skic 7d2d55543e Merge pull request '0.10.3: Sync button in the editor title bar' (#34) from feat/sync-title-button into main 2026-11-06 14:56:31 -08:00
root-at-skic c262bb06a7 0.10.3: Sync button in the editor title bar
Every Archify page and .archify text editor gets a Sync button top right that opens the Sync menu: sign in, share, join, server address. archify.sync.titleButton hides it. The status bar entry stays.
2026-11-07 00:52:07 +02:00
root-at-skic 63f0633daa Merge pull request '0.10.2: leaving Source hides the YAML editor' (#33) from fix/source-pane-hide into main 2026-11-06 14:17:34 -08:00
root-at-skic ef272e4d96 0.10.2: leaving Source hides the YAML editor
Going back from Source to Model, Diagram or View left the editor on the page under the picture when nothing had been edited, since the page was only replaced after a re-render. The pane now hides whenever Source is off.
2026-11-06 23:58:24 +02:00
root-at-skic f6097b1d00 Merge pull request '0.10.1: Archify Sync in the status bar, server address as a setting' (#32) from feat/sync-status-bar into main 2026-11-06 13:38:12 -08:00
root-at-skic 9ccd67b2dd 0.10.1: Archify Sync in the status bar, server address as a setting
In workspaces with Archify files, Archify Sync sits in the status bar and
opens a menu: sign in, share, join, server address, settings. The new
archify.sync.server setting (empty by default) is used without asking,
and in workspace settings gives a project one server.
archify.sync.statusBar hides the entry.
2026-11-06 23:21:56 +02:00
root-at-skic d02c331155 Merge pull request '0.10.0: Archify Sync, optional live collaboration on a model' (#31) from feature/archify-sync into main 2026-11-06 12:57:46 -08:00
root-at-skic c99f3e5fe8 0.10.0: Archify Sync, optional live collaboration on a model
Several people edit one model at once through a server you run yourself
(archify-vscode-ext-sync); the files stay ordinary files on each disk.
Sign-in through the browser, offline-first with later merge, teammates'
cursors in the Source view and text editors, and a Shared section on the
model page with people, versions, Compare and Restore.

Without a server nothing changes: the sync code is a separate bundle that
loads only when a model is shared, after a sign-in, or when a sync command
or invite link is used.
2026-11-06 22:55:01 +02:00
root-at-skic a9021312b0 Merge pull request '0.9.3: Graph from Source on main.archify works again' (#30) from fix/source-graph-switch into main 2026-11-04 03:34:35 -08:00
root-at-skic 2726a66113 0.9.3: Graph from Source on main.archify works again
On a main.archify page in Source, Graph built the Graph page but the
host held it back until Source closed, so nothing happened, and Model
then showed the held Graph page. Switching between the model and its
graph now leaves Source first, and the page forgets Source when Graph
replaces it, so Model on the Graph page comes back to the model.
2026-11-04 13:34:19 +02:00
root-at-skic a5a9f92e75 Merge pull request '0.9.2: Source view, schema checks without the YAML extension' (#29) from feat/source-view into main 2026-10-28 13:27:37 -07:00
root-at-skic 268c75cfae 0.9.2: fast-uri 3.1.9 and markdown-it 14.3.3 (npm audit)
fast-uri comes with ajv, which ships in extension.js from this release;
markdown-it is stubbed out of the Source bundle but was in the lockfile.
2026-10-27 23:47:50 +02:00
root-at-skic 27d4794ff8 0.9.2: Source view, schema checks without the YAML extension
Every Archify page can show its file's YAML in place. Diagrams get
Diagram | Graph | Source (Graph only inside a model), main.archify
Model | Graph | Source, registry and decision pages View | Source, and the
Graph page a Source segment. 2D | 3D moves left of that switch and hides
while Source shows.

The YAML opens in a CodeMirror editor inside the page (dist/source.js,
loaded on first use), themed with the page's colours. Edits go to the VS
Code document as WorkspaceEdits; outside changes come back to the page.
Undo and redo are the editor's own, since VS Code sends ⌘Z in a focused
webview to the webview; save and find stay VS Code's. Problems come from
the host only (what the Problems panel holds for the file) and are
counted on the Source segment; completion and hover come from the schema,
folded into one draft-07 document per diagram type.

The host now checks .archify files against the extension's schema with
ajv on the YAML as written, before archify validate, and checks
.archify-registry files against the registry schema for the first time.
Registry and decision pages become text editor providers. While Source
shows, new renders wait and appear when the picture comes back.

Show Source switches the page to Source; Open in Text Editor (the editor
title button) opens the text beside it, as Show Source did. The decision
schema is no longer given to the YAML extension. Fixed: YAML errors in
registry and decision files were reported on line 1; "Webview is
disposed" when a diagram closed mid-render; the model heading under the
toolbar in narrow editors.
2026-10-27 23:46:05 +02:00
root-at-skic 5bcd34b839 Merge pull request '0.9.1: republish for Open VSX' (#28) from rel/0.9.1 into main 2026-10-23 03:29:25 -07:00
root-at-skic 69b87833b7 0.9.1: republish so Open VSX carries the release 2026-10-23 13:29:14 +03:00
root-at-skic 058c0d17a8 Merge pull request '0.9.0: model graph with queries' (#27) from feat/model-graph into main 2026-10-21 13:08:35 -07:00
root-at-skic 8398c44ca8 Model graph: one head block with a consistent gutter and rhythm 2026-10-21 22:47:40 +03:00
root-at-skic 60ad7479fd Model graph: decision titles on two lines, refit after resize 2026-10-21 22:39:30 +03:00
root-at-skic bc9f55e2fa Model graph: decision and registry links on by default, placed near their elements 2026-10-21 22:33:02 +03:00
root-at-skic 27d1b4381c Model graph: theme toggle in the same pill as the switch and Export 2026-10-21 22:03:39 +03:00
root-at-skic 82dd10253b Model graph: toolbar on Archify's rules
- Archify's theme toggle: pill track, sliding knob, masked sun/moon icon
- buttons as quiet 0.5rem pills inside 0.5625rem controls, pressed state like Archify's, Export PNG as the filled 0.6875rem primary
- Model | Graph switch styled as the 2D | 3D switch's twin
2026-10-21 21:55:24 +03:00
root-at-skic 91fcde9fa5 Model graph: connection labels at the less crowded end 2026-10-21 21:47:08 +03:00
root-at-skic 17e07adb33 Model graph: layered layout and a cleaner look
- layered layout by type (clients left, data right), empty columns left out, barycenter row ordering; registries in a row above, decisions in a row below; Force layout as the alternative
- orthogonal connections with labels staggered next to their source; opaque tinted nodes hide lines behind them
- hover glow on elements and their connections; decision and registry links show for the selected element or all with Links
2026-10-21 21:45:42 +03:00
root-at-skic 3ed2d7eed8 Model graph: dark/light theme toggle on the page
- sun/moon button next to Export; the choice is remembered in the page state and written to the archify-theme key the diagram pages use
- explicit dark and light token sets; without a choice the page follows VS Code's theme as before
- Cytoscape restyles from the page tokens whenever the theme changes
2026-10-21 21:33:38 +03:00
root-at-skic 99ea076571 Model graph: decisions and registry files as nodes
- one node per decision (tag coloured by status) with decides links to its elements and supersedes links
- one node per registry file with defines links to its elements
- own legend chips, side panels (Open decision, Open registry), type:decision and type:registry
- walks and paths follow the diagrams' connections only; attached nodes follow their elements into a result
2026-10-21 20:46:05 +03:00
root-at-skic c8645b228b Model graph: the whole model as one graph with queries; 0.9.0
- Model | Graph switch on main.archify (Diagram | Graph on diagram pages, narrowed to that diagram)
- union graph of every element and connection, registry and inline, built from the model index
- query box: text, type:, diagram:, decision:, uses:, near:, from: to:, unused, shared, -shared
- side panel per element and connection with diagrams, registry line and decisions one click away
- legend chips, Fit, Layout, Labels, Export PNG; Cytoscape.js bundled as dist/graph.js
- command Archify | Open Model Graph; integration check; unit tests for graph and queries
2026-10-21 15:47:00 +03:00
root-at-skic 265f8c57f6 Merge pull request '0.8.1: New Registry command, creator order' (#26) from feat/new-registry into main 2026-10-20 01:23:03 -07:00
root-at-skic c66e819abe Archify | New Registry…; creators ordered Model, Registry, Diagram, Decision; 0.8.1 2026-10-20 10:55:00 +03:00
root-at-skic 2ba66c1ee2 Merge pull request '0.8.0: architecture decisions' (#25) from feat/decisions into main 2026-10-19 13:13:17 -07:00
root-at-skic ebf320a023 Architecture decisions: files, diagram references, views and panels
- *.archify-decision files: id (unique, words), title, status, date,
  elements, diagrams, supersedes, and prose; parsed, merged and link-checked
  in the model index; diagnostics on the file
- diagrams point at decisions with decisions: [...] on the diagram, nodes
  and edges; stripped before Archify, unknown ids reported, completion,
  hover and go-to-definition for the ids and for elements/diagrams/
  supersedes in decision files
- Decisions panel on the main.archify page; Decisions rail panel under a
  diagram (hover lights up the node or connection); decisions on element
  cards and in the element dialog; decision view for the file, with a
  lost-model note outside a model
- Archify | New Decision… command and template; editor schemas; the three
  New Model examples carry decisions; docs, changelog, 0.8.0
2026-10-19 23:13:05 +03:00
root-at-skic 33ebdd6328 Model page: title the registry files panel Registries; 0.7.2 2026-10-19 21:25:58 +03:00
root-at-skic 9684464630 Merge pull request '0.7.1: Registry panel lists registry files' (#23) from feat/registry-files into main 2026-10-19 10:59:47 -07:00
root-at-skic 094ca2925f Drop generated cards; registry descriptions become Elements tooltips
- resolveRefs no longer adds cards to a diagram; it returns node id →
  description, which the page sets as the tooltip of the matching row in
  Archify's Elements panel
- hand-written cards pass through unchanged; docs and changelog
2026-10-19 20:44:09 +03:00
root-at-skic de1a57e4c6 Model page: Registry panel lists registry files, elements inside each
- one collapsible header per .archify-registry file with its element
  count and an Open button that opens the registry view; files start
  collapsed, the Registry panel open
- view types moved to views/viewTypes.ts so the diagram page can open a
  registry without a circular import
- 0.7.1
2026-10-19 20:39:24 +03:00
root-at-skic 4382730343 Merge pull request 'Release 0.7.0: models (main.archify, registries, refs, links, model page)' (#22) from feat/model into main 2026-10-19 04:46:19 -07:00
86 changed files with 9419 additions and 243 deletions

No files matched your search

+89
View File
@@ -1,5 +1,94 @@
# Changelog
## 0.10.9 — 2026-11-08
- The Sync button is square again on the model, registry, decision and Graph pages (0.10.8 squeezed it narrow there).
## 0.10.8 — 2026-11-08
- **A model opens as its outline.** On `main.archify` the top-level panels (Shared, Diagrams, Registries, Decisions) start collapsed; open the one you need. What you open or close is kept while the page is open.
- **Sync button in line on every page.** On the model, registry and decision pages it sits next to Model | Graph | Source instead of floating above it, and on the Graph page it comes after Export PNG instead of covering it. It takes the height of the controls beside it.
## 0.10.7 — 2026-11-08
- **Model | Graph | Source looks like 2D | 3D.** The selected view is the same inset pill, the same height as the other toolbar controls.
- The Sync button of a shared model is green in high contrast themes too.
## 0.10.6 — 2026-11-08
- **Sync sign-in comes back by itself.** The browser now returns the sign-in to a one-off port on this machine (`127.0.0.1`) instead of a `vscode://` link. Browsers open such links only after a click, so when you were already signed in to the identity provider the editor kept waiting. Remote and web editors still use the link.
## 0.10.5 — 2026-11-08
- **Sync button fixed.** It is now an icon only (a cloud; green with a broadcast icon once the model is shared), the same size on every page and theme. On a diagram it sits in the toolbar after **Export** instead of over it; in narrow windows and high contrast themes it no longer shrinks or loses its colour.
## 0.10.4 — 2026-11-07
- **A real Sync button.** Every Archify page (diagram, model, graph, registry, decision, and in Source) shows a **Sync** button top right. It opens the Sync menu: sign in, share the model, join one, set the server address. On a model that is shared it turns green and reads **Shared**.
- Removed the small title-bar icon and the status bar entry shown before anything was shared, with their settings `archify.sync.titleButton` and `archify.sync.statusBar`. A shared model still shows its live state in the status bar.
## 0.10.3 — 2026-11-07
- **Sync button in the title bar.** Every Archify page (and `.archify` text editors) has a **Sync** button top right, next to *Open in Text Editor*: sign in, share a model, join one, set the server address. The status bar entry stays for those who show the status bar. `archify.sync.titleButton: false` hides the button.
## 0.10.2 — 2026-11-07
- Fixed: going back from **Source** to **Model**, **Diagram** or **View** left the YAML editor on the page under the picture when nothing had been edited. It now hides at once.
## 0.10.1 — 2026-11-06
- **Archify Sync is easier to find.** In workspaces with Archify files, **Archify Sync** sits in the status bar. Click it for a menu: sign in, share a model, join one, set the server address, open the settings. It shows the server you are signed in to, and the live state once a model is shared. `archify.sync.statusBar: false` hides it; nothing else changes without a server.
- **Server address as a setting.** `archify.sync.server` (empty by default, for example `https://archify.example.com`) is used by sign-in, share and the menu without asking. In the workspace settings it gives a whole project the same server. *Archify | Set Sync Server Address…* sets it.
## 0.10.0 — 2026-11-06
- **Archify Sync (optional).** Several people edit one model at once through a server you run yourself ([archify-vscode-ext-sync](https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext-sync)); the files stay ordinary files on each disk. Commands: *Sign in to Sync Server…*, *Share Model…*, *Copy Invite Link*, *Join Shared Model…*, *Publish Version…*, *Versions…*, *Stop Syncing Model…*. Sign-in through the browser (PKCE), sessions in VS Code's secret storage, an *Archify Sync* account provider. Edits from editors, pages, Git and agents go out at once; others' edits arrive in open editors with undo intact. Everything is kept on the machine first, so work goes on offline and merges later. Teammates' cursors show as named carets in the Source view and in VS Code's text editors, and stay on their word while others type. The status bar shows who is here; the model page gets a **Shared** section with people, the file each has open, and the latest versions with **Compare** and **Restore**.
- Without a server nothing changes: the sync code is a separate bundle that loads only when a model in the workspace is shared, after a sign-in, or when a sync command or invite link is used.
## 0.9.3 — 2026-11-04
- Fixed: on a `main.archify` page in Source, **Graph** did nothing, and **Model** then showed the Graph page instead of the model. Graph now leaves Source and opens at once, and **Model** on the Graph page comes back to the model, not to Source.
## 0.9.2 — 2026-10-27
- **Source view.** Every Archify page can show its file's YAML in place: **Diagram | Graph | Source** on diagrams (the old **Diagram | Graph** switch, now on every diagram; Graph only inside a model), **Model | Graph | Source** on `main.archify`, **View | Source** on registry and decision pages, and Source on the Graph page too. The YAML opens in an editor inside the page, under its toolbar and heading, in the page's own colours: line numbers, folding, brackets, multiple cursors, undo and redo, ⌘S/Ctrl+S saves. Problems are underlined as you type, listed under the editor (click the count to go to the next one) and counted on the **Source** segment, also while the picture shows. Completion and hover come from the schema of the file, with nothing else installed. Edits go to the VS Code document, so the tab's dirty dot, save, Git and the text editor stay in step. **Diagram** (or **Model**, **View**) brings the picture back as it was left; anything rendered meanwhile shows then.
- **2D | 3D** now sits left of the view switch (it says how the picture is drawn, the switch what is shown) and hides while Source shows; the 3D stage stops drawing meanwhile.
- **Schema checks without the YAML extension.** `.archify` files are checked against the extension's schema on the YAML as written, at once and with readable messages (`Unknown key "lable" in connections[4].`) on the key or value concerned; `archify validate` runs once the schema is satisfied. `.archify-registry` files are checked against the registry schema for the first time (types, unknown keys, ids). The decision schema is no longer handed to the YAML extension: decision files use the `decision` key twice by design, which it reported as an error in every file.
- **Commands.** *Archify | Show Source* switches the focused page to its Source view. The old behaviour, the YAML in VS Code's text editor beside the page, is *Archify | Open in Text Editor*, which is now the editor-title button.
- Registry and decision pages are text editors of their files (as diagram pages already were), so edits made there make the tab dirty and save with it.
- Fixed: a YAML error in a registry or decision file was reported on its first line instead of where it is.
- Fixed: an unhandled "Webview is disposed" error when a diagram closed while it was rendering. On `main.archify` pages with a diagram, the model heading no longer runs under the toolbar in narrow editors.
## 0.9.1 — 2026-10-23
- No functional change. Republished so that Open VSX carries the release: the 0.9.0 upload there was held under review while the `root-at-skic` namespace was still unverified, and a held upload is not released by the later ownership grant.
## 0.9.0 — 2026-10-21
- **Model graph.** A **Model | Graph** switch on the `main.archify` page (next to **Export** when the file has a diagram, top right otherwise) replaces the page with the whole model as one graph: every element any diagram draws plus every registry element, every connection between them, each once, drawn with Cytoscape.js in Archify's type colours. Registry elements have a solid border, inline ones a dashed border. **Decisions** and **registry files** are nodes as well: a decision is a tag coloured by status with dotted links to the elements and connections it is about and dashed links to what it supersedes; a registry links to the elements it defines. Layered layout by type (clients left, data right, registries above, decisions below, orthogonal connections) or a force layout; hover lights up an element and its connections; the dotted decision and registry links are shown by default; **Links** switches them to the selected element only. Drag, zoom, **Fit**, **Labels**, a dark/light theme toggle of its own (remembered, and shared with the diagram pages' theme key), legend chips that hide a type (decisions and registries included), **Export PNG**. The choice is remembered per file; the graph updates in place as the model changes.
- **Queries.** A query box narrows the graph: `database`, `type:backend`, `diagram:0200-*`, `decision:<id>`, `uses:api`, `near:api,2`, `from:web to:db` (shortest path), `unused`, `shared`, `-shared`, `type:decision`, `type:registry`; terms AND together, a leading `-` excludes; decisions and registries follow their elements into a result, and walks never pass through them; the count reads "9 of 14 elements"; **?** lists the forms and runs an example on click.
- **Side panel.** An element shows its description, type, registry file and line (**Registry** opens it), the diagrams that draw it, its connections and its decisions, each one click away; **Neighbours** queries around it. A connection shows its labels, diagrams and decisions. A decision node shows its status, text, the elements and connections it is about and **Open decision**; a registry node the elements it defines and **Open registry**.
- **Entry points.** On a diagram page inside a model the switch reads **Diagram | Graph** and opens the graph narrowed to `diagram:<that diagram>`. New command *Archify | Open Model Graph* in the editor title, the Command Palette and the Explorer menu, wherever *Open Model* is.
- Diagram summaries in the model index now carry every node and edge of a diagram (shared and inline), which the graph is built from.
## 0.8.1 — 2026-10-20
- **Archify | New Registry…** on a folder (also *File → New File…* and the Command Palette) creates an `.archify-registry` file from the template and opens it.
- The Archify entries in the Explorer menu and *File → New File…* come in the order New Model, New Registry, New Diagram, New Decision.
## 0.8.0 — 2026-10-19
- **Architecture decisions.** A model can hold decisions: one `*.archify-decision` file each, anywhere under the model root, with an id (unique in the model), title, status, date, the registry `elements` and `diagrams` it is about, `supersedes`, and prose for context, decision and consequences.
- **Diagrams point at decisions** with `decisions: [<id>]` on the diagram, on a component, node or participant, and on a connection, edge, flow, transition or message. The key is stripped before Archify renders. Unknown ids, and the key outside a model, are reported in Problems. Completion, hover and go-to-definition for decision ids; in decision files the same for `elements`, `diagrams` and `supersedes`.
- **Where they show.** A **Decisions** panel on the `main.archify` page (one list, live decisions first, superseded and rejected dimmed and last). A **Decisions** rail panel under a diagram with the decisions it points at or that name it; hovering a row lights up the node or connection it is attached to, clicking opens the decision. A decision view when a `.archify-decision` file is opened: status, date, context, decision, consequences, related decisions, the elements as cards, the diagrams with where the decision is attached. Decisions also appear on element cards and in the element dialog.
- **Authoring.** *Archify | New Decision…* on a folder inside a model creates a decision file from a template, with the id taken from the title. Editor schema for decision files and the new `decisions` key. A decision outside a model opens, but the page and Problems say it has lost its model.
- The three New Model examples carry decisions. Model page: the registry files panel is titled **Registries**.
## 0.7.1 — 2026-10-19
- **No generated cards.** The cards 0.7.0 generated under model diagrams from registry descriptions are gone; they repeated the Elements panel. The description now shows as the tooltip of the element's row in the Elements panel. Hand-written `cards:` are unchanged.
- **Model page, Registry panel:** lists the registry files of the model, one collapsible header per file with its element count and an **Open** button that opens the registry view; expand a file to see its elements as cards. Before, all elements of all files were shown in one grid.
## 0.7.0 — 2026-10-19
- **Models:** a folder with a `main.archify` at its top is a model, a set of diagrams that belong together. Opening `main.archify` shows the model page: name and description, the overview diagram if the file has one, the diagrams grouped by folder (click to open), and the registry with where each element is used.
+38 -13
View File
@@ -12,7 +12,7 @@ Free and open source. If it saves you time, you can [buy me a coffee](https://bu
| File | Format | What the extension does |
|---|---|---|
| **`name.archify`** | **YAML** (the main format) | Opens as the interactive diagram. Show Source, live updates, validation, completion, templates. |
| **`name.archify`** | **YAML** (the main format) | Opens as the interactive diagram, with a Source view for its YAML. Live updates, validation, completion, templates. |
| `name.architecture.json`, `name.workflow.json`, `name.sequence.json`, `name.dataflow.json`, `name.lifecycle.json` | JSON (Archify's own CLI format) | Opens as text, with a preview beside it and validation. For files produced by the Archify CLI or AI agents. |
| Rendered Archify `.html` | HTML | Read-only viewer instead of a browser. |
@@ -44,7 +44,7 @@ To write one by hand:
```
2. Click it in the Explorer: the diagram opens.
3. To edit, use **Show Source** in the editor title. The YAML opens beside the diagram, which re-renders as you type.
3. To edit, click **Source** in the diagram's toolbar (**Diagram | Graph | Source**). The YAML takes the picture's place, checked as you type; **Diagram** brings the picture back. To see the text and the picture side by side, use **Open in Text Editor** in the editor title instead: the diagram re-renders as you type.
The same file is in [examples/hello.archify](examples/hello.archify).
@@ -53,7 +53,7 @@ The same file is in [examples/hello.archify](examples/hello.archify).
A `.archify` file is an Archify diagram written in **YAML**. Its fields are those of Archify's diagram schema; the extension converts the YAML for the renderer, so you never handle JSON yourself. `diagram_type` selects the kind of diagram: `architecture`, `workflow`, `sequence`, `dataflow` or `lifecycle`.
- **Opening:** the **Archify Diagram** editor is the default for `.archify`. Use *Reopen Editor With… → Text Editor* to edit the YAML full-screen.
- **Completion:** with the [YAML extension](https://marketplace.visualstudio.com/items?itemName=redhat.vscode-yaml) (`redhat.vscode-yaml`) installed, `.archify` files get completion and hover from Archify's schemas. The schema follows `diagram_type`.
- **Completion:** in the Source view, `.archify` and `.archify-registry` files get completion and hover from Archify's schemas, with nothing else installed; the schema follows `diagram_type`. In VS Code's text editor the same comes from the [YAML extension](https://marketplace.visualstudio.com/items?itemName=redhat.vscode-yaml) (`redhat.vscode-yaml`), if installed.
`.archify` files from extension version 0.2.0 were written in JSON. They still open, because JSON is valid YAML, but new files should use YAML.
@@ -65,19 +65,20 @@ The Archify CLI and the AI agents that use it write diagrams as JSON, named `nam
- **New diagram from a template**: *Archify | New Diagram…* creates a starter `.archify` file for any of the five diagram kinds, or an everyday plan, in the chosen folder.
- **New model from an example**: *Archify | New Model…* creates a complete model folder from a C4 example (Standard Web App, E-Shop, Event-Based Integration).
- **Diagram editor**: `.archify` files open as the rendered diagram. **Show Source** opens the YAML beside it, and edits re-render live.
- **Model graph**: the **Graph** switch on any page of a model shows the whole model as one graph, with a query box (`type:database`, `uses:api`, `from:web to:db`, …), a side panel per element and PNG export. See [Models](#models).
- **Diagram editor**: `.archify` files open as the rendered diagram. **Source** shows the YAML in its place, in an editor inside the page: problems underlined as you type and counted on the switch, completion and hover from the schema, undo, and ⌘S/Ctrl+S to save. **Open in Text Editor** opens the YAML beside the diagram instead, and edits re-render live.
- **Live updates**: the diagram re-renders as you edit, and keeps the focus and route you selected (`#focus=…`, `#route=…`).
- **HTML viewer**: right-click a rendered `.html` file and choose **Archify | Open in HTML Viewer**, or use *Reopen Editor With… → Archify HTML Viewer*. For Archify HTML already open as text, a button appears in the editor title. The viewer reloads when the file changes on disk.
- **Problems**: YAML syntax errors, plus `archify validate`'s schema, layout and evidence problems, appear at the matching line of the `.archify` file.
- **Problems**: YAML syntax errors, schema problems (unknown keys, wrong types, missing fields, checked with the extension's own schema check on the YAML as written) and `archify validate`'s layout and evidence problems appear at the matching place in the `.archify` file. Registries are checked against their schema too.
- **Brand logos**: after `brand:` the editor suggests Archify's built-in brand IDs (PostgreSQL, Redis, Kafka, Docker, …). Typing an alias or product name finds them too, so `kafka` offers `apache-kafka`. An unknown brand is reported on its own line.
- **Schema help**: completion and hover from Archify's own schemas, through the YAML extension for `.archify` files.
- **Schema help**: completion and hover from Archify's own schemas: in the Source view built in, in the text editor through the YAML extension.
- **Source links**: in source-backed diagrams, clicking a source reference opens that file and line range in the editor. If the file is not in the workspace, the web link opens instead.
- **Export**: the diagram's own Export menu (PNG, SVG, share card, …) saves through a VS Code save dialog.
- **Commands**: *Archify | New Diagram…*, *Archify | New Model…*, *Archify | Open Model*, *Archify | Render to HTML File…*, *Archify | Open in Browser*, *Archify | Refresh Preview*, *Archify | Show Source*.
- **Commands**: *Archify | New Model…*, *Archify | New Registry…*, *Archify | New Diagram…*, *Archify | New Decision…*, *Archify | Open Model*, *Archify | Open Model Graph*, *Archify | Render to HTML File…*, *Archify | Open in Browser*, *Archify | Refresh Preview*, *Archify | Show Source* (switches the page to its Source view), *Archify | Open in Text Editor*.
## 3D view
Every diagram can also be seen in 3D. The **2D | 3D** switch next to **Export** in the diagram's toolbar shows which view you are in; click it to flip.
Every diagram can also be seen in 3D. The **2D | 3D** switch in the diagram's toolbar, left of **Diagram | Graph | Source**, shows which view you are in; click it to flip. It hides while Source shows, and **Diagram** returns to the 2D or 3D you left.
![The same diagram in the 3D view](docs/preview-3d.png)
@@ -111,22 +112,46 @@ online-shop/
people.archify-registry shared elements: one name for one thing
systems.archify-registry
containers.archify-registry
decisions/
0002-queue-between-api-and-worker.archify-decision
0100-context/online-shop.archify
0200-containers/online-shop.archify
0300-components/api.archify
```
- **The model page.** Click `main.archify` and you get the model's page: its name and description, the overview diagram if the file has one, then two collapsible panels: **Diagrams**, with a collapsible header per folder and a card per diagram (click to open), and **Registry**, the shared elements as cards with the diagrams each is used in. Open or closed is remembered per page.
- **The model page.** Click `main.archify` and you get the model's page: its name and description, the overview diagram if the file has one, then two collapsible panels: **Diagrams**, with a collapsible header per folder and a card per diagram (click to open), and **Registries**, one collapsible header per registry file (with an **Open** button for its view) and the file's elements as cards inside, each with the diagrams it is used in. Open or closed is remembered per page.
- **Shared elements.** A registry file defines an element once (`type`, `label`, `sublabel`, `brand`, `description`, …). A diagram draws it with `ref: api` plus `pos` and `size`; it may override `label`, `sublabel` and `tag`, and may still define unshared elements inline. Hover a `ref` for the description, F12 jumps to the registry, completion after `ref:` lists the elements, unknown names appear in Problems.
- **Links.** A registry element (or a component) with `diagram: 0300-components/api.archify` points at the diagram that explains it: double-click the node in the 2D view to open it.
- **Cards.** A model diagram without `cards` of its own shows one card per shared element it draws, from the registry descriptions. The model page shows the registry as the same cards, each with the diagrams it is used in.
- **Registry view.** A `.archify-registry` file opens as its elements, as cards. Click one and a dialog shows its description, where it is defined and the diagrams that use it; click a diagram to open it. **Show Source** opens the YAML beside it.
- **Descriptions.** Under a model diagram, hovering a row of the **Elements** panel shows the registry description of that element.
- **Decisions.** One `*.archify-decision` file per architecture decision: id, title, status, date, the registry elements and diagrams it is about, and prose for context, decision and consequences. Diagrams point at decisions with `decisions: [<id>]` on the diagram, a component or a connection. They show as a **Decisions** panel on the `main.archify` page, a **Decisions** rail panel under each diagram (hover lights up what the decision is attached to), on element cards and in the element dialog, and a decision opens as its own page. *Archify | New Decision…* creates one; links are checked in Problems.
- **Registry view.** A `.archify-registry` file opens as its elements, as cards. Click one and a dialog shows its description, where it is defined and the diagrams that use it; click a diagram to open it. **View | Source** at the top right switches to the YAML, checked against the registry schema as you type.
- **Elements and Connectors.** Under every diagram, Archify's node index is titled **Elements**, and a **Connectors** panel next to it lists every connection as "from → to" with its label. Hovering highlights the connector in the diagram; clicking keeps it highlighted and scrolls to it.
- **Starting one.** *Archify | New Model…* (right-click a folder) copies one of the shipped examples into a new folder, named as you choose: **C4 - Standard Web App** (single-page app, API, database, cache, storage, identity provider), **C4 - E-Shop** (web shop, API, worker, queue, payment and email providers) or **C4 - Event-Based Integration** (event bus, router, dead-letter queue, event store, consumers). Each has a registry and context, container and component diagrams. For an empty model, *Archify | New Diagram… → Model* creates just a `main.archify`.
- **Commands.** *Archify | Open Model* opens the model page of the current file, from the editor title, the Command Palette or the Explorer menu of a `.archify` or `.archify-registry` file.
- **The graph.** The **Model | Graph | Source** switch at the top of the `main.archify` page (next to **Export** when the file has a diagram) replaces the page with the whole model as one graph: every element any diagram draws plus every registry element, every connection between them, each once. Registry elements have a solid border, inline ones a dashed border; colours are Archify's type colours and the legend chips at the bottom hide or show a type. **Decisions** are nodes too (tags coloured by status, dotted links to the elements they are about, dashed links to what they supersede), and so are **registries** (one node per file, dotted links to the elements it defines); their chips hide them when the picture gets busy. The layout is **Layered** by default, like Archify's stack: clients on the left, data on the right, registries in a row above, decisions in a row below, connections drawn orthogonally; click the button for a **Force** layout instead. Drag nodes, scroll to zoom, **Fit** (or <kbd>0</kbd>) frames what matches, **Labels** toggles connection labels, the dotted **Links** from decisions and registries to their elements are on by default and can be switched off, in which case only the selected element's show (hovering an element lights up its connections), the sun/moon button switches the page between its dark and light theme (remembered, shared with the diagram pages' theme choice), **Export PNG** saves the picture. On a diagram page the switch reads **Diagram | Graph | Source** and Graph opens the graph already narrowed to that diagram; **Source** on the graph page goes back to `main.archify` in its Source view. *Archify | Open Model Graph* does the same from the Command Palette or Explorer.
- **Queries.** Type a few words in the box (<kbd>/</kbd> focuses it); matches stay bright, the rest dims, the count shows "9 of 14 elements". Terms combine with AND and a leading `-` excludes: `database` (id, label, sublabel, brand or type contain it), `type:backend`, `diagram:0200-*` (what those diagrams draw), `decision:<id>` (what a decision is about or is attached to), `uses:api` (an element and its neighbours), `near:api,2` (within two steps), `from:web to:db` (the shortest path, following the arrows first), `unused` (registry elements no diagram draws), `shared` and `-shared` (registry or inline elements only), `type:decision` and `type:registry` for the decision and registry nodes. Decisions and registries follow the elements they are attached to into a result; `-type:decision` or `-type:registry` leaves them out. Walks and paths follow the diagrams' connections only, so a registry is never a shortcut between its elements. The **?** button lists them; clicking an example runs it.
- **Side panel.** Click an element for its description, type, where it is defined (**Registry** opens the file at the line), the diagrams that draw it (click to open), its connections and its decisions (click to open). **Neighbours** runs `uses:` for it. Click a connection for its labels, the diagrams that draw it and its decisions. Click a decision node for its status, context and decision text, the elements and connections it is about, and **Open decision**; a registry node for the elements it defines, the ones no diagram draws yet, and **Open registry**.
- **Commands.** *Archify | Open Model* opens the model page of the current file, from the editor title, the Command Palette or the Explorer menu of a `.archify` or `.archify-registry` file; *Archify | Open Model Graph* opens the graph.
Formats in detail: [docs/model.md](docs/model.md). A full example: [examples/online-shop](examples/online-shop).
## Working together (Archify Sync)
Optional. Without a sync server the extension works exactly as described above and loads none of this.
[Archify Sync](https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext-sync) is a small server you run yourself (one container and PostgreSQL; a Helm chart is included). With it, a model is edited by several people at once, like a shared document, and its files stay ordinary files on each person's disk, so Git, agents and every page of this extension keep working.
- **Where.** Every Archify page (diagram, model, graph, registry, decision, also in Source) has a Sync button (a cloud) top right; on a diagram it sits after **Export**. It opens the Sync menu: sign in, share the model, join one, the server address, settings. On a shared model it turns green with a broadcast icon. The same menu is *Archify | Sync…* in the Command Palette.
- **Server address.** Set `archify.sync.server` once (Settings › Archify › Sync, or *Archify | Set Sync Server Address…*), for example `https://archify.example.com`. Put it in the workspace settings and everyone in the project uses the same server. Left empty, the address is asked for once and remembered.
- **Sign in.** *Archify | Sign in to Sync Server…* uses that address (or asks for it) and signs in through the browser; the session is kept in VS Code's secret storage and shows under **Accounts** as *Archify Sync*. A new server is set up first on its `/setup` page with the code from its log.
- **Share.** *Archify | Share Model…* (also on `main.archify` in the Explorer) puts the model on the server and writes a small `.archify-sync` file next to `main.archify`: the server and the model's id, no secrets. Commit it, and everyone who clones the repository and is a member opens the shared model.
- **Invite and join.** *Archify | Copy Invite Link* copies a link for the model; send it any way you like. Opening it (or *Archify | Join Shared Model…*) signs the person in, or up, and puts the files in an empty folder of their choice.
- **Live.** Edits in any editor, page, Source view, by Git or by an agent reach the others within a moment. Their edits arrive in your open editors with undo intact and are saved to disk; your own unsaved work stays unsaved. The status bar shows **Archify live · 3 here**; the model page gets a **Shared** section with who is here and in which file, and each diagram card says who has it open. In the Source view and in text editors, teammates' cursors show as coloured carets with their names.
- **Offline.** Every edit is kept on your machine first. Without a connection you keep working; edits on both sides merge when it is back, also after a restart, and also edits made while VS Code was closed.
- **Versions.** The server takes a snapshot after a pause in editing (0.1, 0.2, …). *Archify | Publish Version…* names the current state as a major version (1.0 "Q4 baseline"). The model page lists the latest versions with **Compare** (a diff per changed file) and **Restore** (brings the files back for everyone, as a new version; nothing is lost); *Archify | Versions…* lists them all.
- **Stop.** *Archify | Stop Syncing Model…* removes `.archify-sync` here and leaves the files as they are.
Only model files (`.archify`, `.archify-registry`, `.archify-decision`) are shared, and only below `main.archify`.
## Source evidence
A diagram that declares `meta.repository` and `sources` is verified against a local Git checkout whose `origin` and pinned commit match. The extension uses the Git top-level directory of the diagram file, or `archify.repoRoot` when set.
@@ -149,7 +174,7 @@ When verification fails, the default (`archify.sourceEvidence: "fallback"`) stil
## Security
Diagrams run in a webview with a strict content security policy. Only the page's own inline scripts and the extension's bundled 3D viewer run (via a per-render nonce), there is no network access for scripts or fetches, and links open through VS Code.
Diagrams run in a webview with a strict content security policy. Only the page's own inline scripts and the extension's bundled 3D viewer run (via a per-render nonce), there is no network access for scripts or fetches, and links open through VS Code. The extension itself talks to a network only for Archify Sync, and only to a server you sign in to or a model's `.archify-sync` file names, over HTTPS (plain HTTP only to this machine).
## Development
+58 -2
View File
@@ -64,9 +64,9 @@ components:
- Before Archify runs, the extension replaces each `ref` component with the registry element plus the diagram's own fields, drops `description` and `diagram`, and hands Archify an ordinary component.
- Connections, boundaries and everything else stay as they are and use the ids as before.
## Cards under a model diagram
## Descriptions under a model diagram
Archify shows `cards` (a coloured dot, a title, a few lines) below a diagram. A diagram inside a model that draws shared elements and defines no `cards` of its own gets one card per drawn element that has a `description` in the registry, in drawing order, with the dot colour of the element's type. Write your own `cards:` in the diagram to replace them.
Archify's **Elements** panel under a diagram lists its nodes. For a `ref` component the row's tooltip is the element's registry `description`. Archify's own `cards:` stay what they are: write them in the diagram when you want text blocks below it; nothing is generated.
## Links between diagrams
@@ -88,3 +88,59 @@ A diagram with `ref` components outside any model (no `main.archify` above it) r
## Starting a model
*Archify | New Model…* (right-click a folder, *File → New File…*, Command Palette) offers three complete examples: **C4 - Standard Web App**, **C4 - E-Shop** and **C4 - Event-Based Integration**. Pick one and a folder name; the example is copied into that folder with `model.id`, `model.name` and the overview title taken from the folder name (an example kept under its own name is copied as is). Each example has `registry/{people,systems,containers}.archify-registry` and diagrams under `0100-context`, `0200-containers` and `0300-components`; every registry element is used by at least one diagram and every diagram validates.
## Decisions
An architecture decision is one `*.archify-decision` file, anywhere under the model root (`decisions/` is the convention):
```yaml
schema_version: 1
decision:
id: queue-between-api-and-worker # unique in the model, any short string
title: A queue between the API and the worker
status: accepted # proposed | accepted | superseded | rejected
date: 2026-09-16
elements: [api, queue, worker] # registry ids
diagrams: [0200-containers/online-shop.archify]
supersedes: [] # ids of older decisions this one replaces
context: >
Why a decision was needed.
decision: >
What was decided.
consequences: >
What becomes easier, harder, or must change.
```
Ids are strings; an unquoted number such as `0001` is refused because YAML reads it as 1. A decision another decision supersedes shows as superseded whatever its own status says. Unknown elements, missing diagrams, duplicate ids, unknown statuses and dangling `supersedes` are problems on the decision file.
Diagrams point back at decisions with a `decisions` list of ids on the diagram itself, on a component (or node, participant, state) and on a connection (or edge, flow, transition, message):
```yaml
decisions: [postgres-as-source-of-truth]
components:
- ref: queue
pos: [460, 360]
size: [130, 60]
decisions: [queue-between-api-and-worker]
connections:
- { from: api, to: queue, label: enqueue, decisions: [queue-between-api-and-worker] }
```
The key is stripped before Archify renders. An unknown id is a problem at its line; outside a model the key is an error, like `ref`. The `main.archify` page lists all decisions; a diagram page lists the ones it points at or that name it; an element's card and dialog list the decisions about it. A `.archify-decision` file opens as its own page. Outside a model it still opens, with a note that it has lost its model.
## The model graph
The **Model | Graph** switch on the `main.archify` page replaces it with the whole model as one graph. It is built from the model index, not from Archify's renderer:
- **Nodes** are every element any diagram draws (`components`, `nodes`, `participants`, `states`), joined by id across diagrams, plus every registry element even when no diagram draws it yet. Registry elements carry their description, file and line; inline elements only what the diagram says. The same inline id in two diagrams is one node.
- **Edges** are every `connections`, `edges`, `flows`, `transitions` and `messages` entry between two nodes of the same diagram, keyed by `from>to`; the labels different diagrams give the same pair are joined with " / ". Direction is kept.
- **Decisions** reach nodes through `elements:` in the decision file and through `decisions:` on a node in a diagram; they reach edges through `decisions:` on a connection.
- **Decision nodes** (`decision:<id>`, type `decision`) carry the effective status, the context and decision text, and the diagrams the decision names; `decides` edges point at the elements it is about, `supersedes` edges at the decisions it replaces.
- **Registry nodes** (`registry:<file>`, type `registry`) stand for each `.archify-registry` file; `defines` edges point at its elements.
Walks (`uses:`, `near:`, `from: to:`) follow `connection` edges only. Decision and registry nodes join a result when an element they link to matches, and `-type:decision` or `-type:registry` removes them.
Queries run in the page against that graph; the forms are listed under **?** on the page and in the README. `uses:` and `near:` ignore direction; `from: to:` follows the arrows first and ignores them only when no directed path exists. Connections are shown when both ends match, so `type:backend` shows backend-to-backend connections only.
The switch is remembered per `main.archify` in the workspace. The graph page updates in place when a file of the model changes: elements that are still there keep their position, new ones are laid out around them.
+38
View File
@@ -18,6 +18,17 @@ const common = {
mainFields: ['module', 'main'],
};
// codemirror-json-schema formats schema descriptions with markdown-it and
// shiki (about 400 KB); a small stub does what our descriptions need.
const stubMarkdown = {
name: 'stub-markdown',
setup(build) {
build.onResolve({ filter: /utils\/markdown(\.js)?$/ }, (args) =>
args.importer.includes('codemirror-json-schema') ? { path: path.resolve('src/webview/source/markdownStub.ts') } : undefined,
);
},
};
if (tests) {
// Unit tests cover the modules that do not import 'vscode'; the
// integration suite runs inside VS Code, which provides it.
@@ -40,6 +51,14 @@ if (tests) {
outfile: 'dist/extension.js',
external: ['vscode'],
}),
// Archify Sync, loaded only when a model is shared (src/sync/loader.ts).
// ws's native speed-ups are optional and not shipped.
esbuild.context({
...common,
entryPoints: ['src/sync/index.ts'],
outfile: 'dist/sync.js',
external: ['vscode', 'bufferutil', 'utf-8-validate'],
}),
// Runs inside the Archify page in the webview; three.js is bundled in.
esbuild.context({
...common,
@@ -49,6 +68,25 @@ if (tests) {
entryPoints: ['src/viewer3d/index.ts'],
outfile: 'dist/viewer3d.js',
}),
// The Graph page of a model; Cytoscape.js is bundled in.
esbuild.context({
...common,
format: 'iife',
platform: 'browser',
target: 'es2022',
entryPoints: ['src/graph/index.ts'],
outfile: 'dist/graph.js',
}),
// The Source view; CodeMirror is bundled in. Loaded the first time Source is chosen.
esbuild.context({
...common,
format: 'iife',
platform: 'browser',
target: 'es2022',
entryPoints: ['src/webview/source/index.ts'],
outfile: 'dist/source.js',
plugins: [stubMarkdown],
}),
]);
if (watch) {
await Promise.all(contexts.map((ctx) => ctx.watch()));
@@ -3,6 +3,7 @@ diagram_type: architecture
meta:
title: Containers
output: containers.html
decisions: [postgres-as-source-of-truth]
components:
- ref: customer
pos: [40, 160]
@@ -22,6 +23,7 @@ components:
- ref: queue
pos: [460, 360]
size: [130, 60]
decisions: [queue-between-api-and-worker]
- ref: worker
pos: [670, 460]
size: [130, 60]
@@ -34,6 +36,6 @@ connections:
- { from: web, to: api, label: JSON }
- { from: api, to: cache, label: read }
- { from: api, to: db, label: SQL }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290] }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290], decisions: [queue-between-api-and-worker] }
- { from: queue, to: worker, label: poll }
- { from: worker, to: db, label: SQL, labelAt: [735, 420] }
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: postgres-as-source-of-truth
title: PostgreSQL as the single source of truth
status: accepted
date: 2026-09-02
elements: [db, api, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Orders, customers and the catalogue were spread over the
shop database and two spreadsheets kept by support.
Refunds were reconciled by hand every Monday.
decision: >
One PostgreSQL database owns orders, customers and the
catalogue. The API is the only writer. Everything else
(cache, search, reports) is derived and may be rebuilt.
consequences: >
Support loses the spreadsheets and gets the admin console.
Any new store must be declared derived or get its own
decision. Backups and migrations are the API team's job.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: queue-between-api-and-worker
title: A queue between the API and the worker
status: accepted
date: 2026-09-16
elements: [api, queue, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Order confirmation emails and invoices were sent inside
the checkout request. A slow mail provider made checkout
slow; a failing one made checkout fail.
decision: >
The API enqueues a job per side effect on SQS. One worker
service consumes the queue and does the slow work.
Checkout returns as soon as the order is stored.
consequences: >
Emails arrive seconds later, not instantly. Jobs must be
idempotent because SQS delivers at least once. The worker
is the second place that writes to the database.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: opensearch-for-product-search
title: OpenSearch for product search
status: proposed
date: 2026-10-19
elements: [api, worker, db]
diagrams: [0200-containers/online-shop.archify]
context: >
Catalogue search runs as SQL LIKE queries on the
database. Typos find nothing and the catalogue page is
the slowest page in the shop.
decision: >
Add a dedicated search service on OpenSearch. The API
queries it; the worker rebuilds the index from the
database after every catalogue change.
consequences: >
The index is derived data under decision 0001 and may be
rebuilt at any time. One more service to run. Search
results can lag the database by the rebuild interval.
+1139 -23
View File
File diff suppressed because it is too large. Load diff
+202 -27
View File
@@ -2,7 +2,7 @@
"name": "archify-vscode-ext",
"displayName": "Archify Diagram Viewer",
"description": "Archify diagrams in VS Code. Write diagrams as .archify files in YAML: they open as the interactive diagram, with live updates, validation, templates and completion. Also previews Archify's own JSON files (*.architecture.json, …) and opens rendered Archify HTML.",
"version": "0.7.0",
"version": "0.10.9",
"publisher": "root-at-skic",
"license": "MIT",
"sponsor": {
@@ -33,7 +33,9 @@
"registry",
"sequence",
"workflow",
"yaml"
"yaml",
"adr",
"decisions"
],
"main": "./dist/extension.js",
"activationEvents": [
@@ -42,19 +44,31 @@
"onLanguage:html",
"workspaceContains:**/*.{archify,architecture.json,workflow.json,sequence.json,dataflow.json,lifecycle.json}",
"onWebviewPanel:archify.preview",
"workspaceContains:**/*.archify-registry"
"workspaceContains:**/*.archify-registry",
"workspaceContains:**/*.archify-decision",
"onUri"
],
"contributes": {
"commands": [
{
"command": "archify.newModel",
"title": "Archify | New Model…",
"icon": "$(new-folder)"
},
{
"command": "archify.newRegistry",
"title": "Archify | New Registry…",
"icon": "$(symbol-field)"
},
{
"command": "archify.newDiagram",
"title": "Archify | New Diagram…",
"icon": "$(new-file)"
},
{
"command": "archify.newModel",
"title": "Archify | New Model…",
"icon": "$(new-folder)"
"command": "archify.newDecision",
"title": "Archify | New Decision…",
"icon": "$(law)"
},
{
"command": "archify.showPreview",
@@ -89,12 +103,72 @@
{
"command": "archify.showSource",
"title": "Archify | Show Source",
"icon": "$(code)"
},
{
"command": "archify.openInTextEditor",
"title": "Archify | Open in Text Editor",
"icon": "$(go-to-file)"
},
{
"command": "archify.openModel",
"title": "Archify | Open Model",
"icon": "$(symbol-structure)"
},
{
"command": "archify.openModelGraph",
"title": "Archify | Open Model Graph",
"icon": "$(type-hierarchy)"
},
{
"command": "archify.sync.signIn",
"title": "Archify | Sign in to Sync Server…",
"icon": "$(account)"
},
{
"command": "archify.sync.signOut",
"title": "Archify | Sign out of Sync Server",
"icon": "$(sign-out)"
},
{
"command": "archify.sync.share",
"title": "Archify | Share Model…",
"icon": "$(live-share)"
},
{
"command": "archify.sync.invite",
"title": "Archify | Copy Invite Link",
"icon": "$(person-add)"
},
{
"command": "archify.sync.join",
"title": "Archify | Join Shared Model…",
"icon": "$(link)"
},
{
"command": "archify.sync.publish",
"title": "Archify | Publish Version…",
"icon": "$(tag)"
},
{
"command": "archify.sync.versions",
"title": "Archify | Versions…",
"icon": "$(history)"
},
{
"command": "archify.sync.stop",
"title": "Archify | Stop Syncing Model…",
"icon": "$(debug-disconnect)"
},
{
"command": "archify.sync.menu",
"title": "Archify | Sync…",
"icon": "$(live-share)"
},
{
"command": "archify.sync.setServer",
"title": "Archify | Set Sync Server Address…",
"icon": "$(server)"
}
],
"menus": {
@@ -125,11 +199,35 @@
},
{
"command": "archify.showSource",
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry'"
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
},
{
"command": "archify.openInTextEditor",
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
},
{
"command": "archify.openModel",
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry'"
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
},
{
"command": "archify.openModelGraph",
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
},
{
"command": "archify.sync.invite",
"when": "archify.sync.active"
},
{
"command": "archify.sync.publish",
"when": "archify.sync.active"
},
{
"command": "archify.sync.versions",
"when": "archify.sync.active"
},
{
"command": "archify.sync.stop",
"when": "archify.sync.active"
}
],
"editor/title": [
@@ -149,8 +247,8 @@
"group": "navigation"
},
{
"command": "archify.showSource",
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry'",
"command": "archify.openInTextEditor",
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'",
"group": "navigation"
},
{
@@ -165,40 +263,65 @@
},
{
"command": "archify.openModel",
"when": "archify.inModel && (archify.isDiagramSource || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry') && !notebookEditorFocused",
"when": "archify.inModel && (archify.isDiagramSource || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision') && !notebookEditorFocused",
"group": "navigation@60"
},
{
"command": "archify.openModelGraph",
"when": "archify.inModel && (archify.isDiagramSource || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision') && !notebookEditorFocused",
"group": "navigation@61"
}
],
"explorer/context": [
{
"command": "archify.newDiagram",
"command": "archify.newModel",
"when": "explorerResourceIsFolder",
"group": "zzz_archify@1"
},
{
"command": "archify.newModel",
"command": "archify.newRegistry",
"when": "explorerResourceIsFolder",
"group": "zzz_archify@2"
},
{
"command": "archify.showPreview",
"when": "resourceFilename =~ /(\\.archify|\\.archify-registry|\\.(architecture|workflow|sequence|dataflow|lifecycle)\\.json)$/",
"command": "archify.newDiagram",
"when": "explorerResourceIsFolder",
"group": "zzz_archify@3"
},
{
"command": "archify.renderToHtml",
"when": "resourceFilename =~ /(\\.archify|\\.(architecture|workflow|sequence|dataflow|lifecycle)\\.json)$/",
"command": "archify.newDecision",
"when": "explorerResourceIsFolder",
"group": "zzz_archify@4"
},
{
"command": "archify.showPreview",
"when": "resourceFilename =~ /(\\.archify|\\.archify-registry|\\.archify-decision|\\.(architecture|workflow|sequence|dataflow|lifecycle)\\.json)$/",
"group": "zzz_archify@5"
},
{
"command": "archify.openHtmlViewer",
"when": "resourceExtname == .html",
"group": "zzz_archify@3"
"group": "zzz_archify@6"
},
{
"command": "archify.renderToHtml",
"when": "resourceFilename =~ /(\\.archify|\\.(architecture|workflow|sequence|dataflow|lifecycle)\\.json)$/",
"group": "zzz_archify@7"
},
{
"command": "archify.openModel",
"when": "resourceFilename =~ /\\.archify(-registry)?$/",
"group": "zzz_archify@5"
"when": "resourceFilename =~ /\\.archify(-registry|-decision)?$/",
"group": "zzz_archify@8"
},
{
"command": "archify.openModelGraph",
"when": "resourceFilename =~ /\\.archify(-registry|-decision)?$/",
"group": "zzz_archify@9"
},
{
"command": "archify.sync.share",
"when": "resourceFilename == main.archify",
"group": "archify@9"
}
],
"editor/title/context": [
@@ -210,12 +333,20 @@
],
"file/newFile": [
{
"command": "archify.newDiagram",
"group": "file"
"command": "archify.newModel",
"group": "file@1"
},
{
"command": "archify.newModel",
"group": "file"
"command": "archify.newRegistry",
"group": "file@2"
},
{
"command": "archify.newDiagram",
"group": "file@3"
},
{
"command": "archify.newDecision",
"group": "file@4"
}
]
},
@@ -254,6 +385,16 @@
],
"priority": "default"
},
{
"viewType": "archify.decision",
"displayName": "Archify Decision",
"selector": [
{
"filenamePattern": "*.archify-decision"
}
],
"priority": "default"
},
{
"viewType": "archify.htmlViewer",
"displayName": "Archify HTML Viewer",
@@ -373,6 +514,14 @@
"type": "string",
"default": "",
"description": "Node.js executable (18 or newer) used to run the renderer. Empty means the runtime bundled with VS Code."
},
"archify.sync.server": {
"type": "string",
"default": "",
"scope": "window",
"pattern": "^$|^https?://",
"patternErrorMessage": "An address such as https://archify.example.com",
"markdownDescription": "Address of your Archify Sync server, for example `https://archify.example.com`. The **Sync** button on Archify pages, *Sign in* and *Share Model* use it without asking. Set it in the workspace settings so everyone in the project uses the same server. Empty: asked once and remembered. Archify Sync is optional; see the README."
}
}
},
@@ -381,7 +530,8 @@
"id": "yaml",
"extensions": [
".archify",
".archify-registry"
".archify-registry",
".archify-decision"
]
}
],
@@ -394,6 +544,12 @@
"fileMatch": "*.archify-registry",
"url": "./schemas/archify-registry.schema.json"
}
],
"authentication": [
{
"id": "archify-sync",
"label": "Archify Sync"
}
]
},
"scripts": {
@@ -407,12 +563,14 @@
"test:integration": "node esbuild.mjs && node esbuild.mjs --tests && node test/integration/run.mjs"
},
"devDependencies": {
"@types/cytoscape": "^3.21.9",
"@types/cytoscape-fcose": "^2.2.5",
"@types/node": "^22.0.0",
"@types/three": "^0.186.0",
"@types/vscode": "~1.100.0",
"@types/ws": "^8.18.2",
"@vscode/test-electron": "^3.1.0",
"@vscode/vsce": "^3.0.0",
"ajv": "^8.20.0",
"esbuild": "^0.25.0",
"jsonc-parser": "^3.3.1",
"typescript": "^5.8.0"
@@ -422,7 +580,24 @@
},
"homepage": "https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext#readme",
"dependencies": {
"@codemirror/autocomplete": "^6.20.4",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.13.1",
"@codemirror/lint": "^6.9.7",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.15",
"@lezer/highlight": "^1.2.5",
"ajv": "^8.20.0",
"codemirror": "^6.0.2",
"codemirror-json-schema": "^0.8.1",
"cytoscape": "^3.34.4",
"cytoscape-fcose": "^2.2.0",
"lib0": "^0.2.119",
"three": "^0.186.1",
"yaml": "^2.9.1"
"ws": "^8.22.1",
"y-protocols": "^1.0.7",
"yaml": "^2.9.1",
"yjs": "^13.6.33"
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Archify architecture decision",
"description": "One architecture decision of a model. Diagrams point at it with `decisions: [<id>]`.",
"type": "object",
"additionalProperties": false,
"required": [
"decision"
],
"properties": {
"schema_version": {
"const": 1
},
"decision": {
"type": "string",
"description": "What was decided."
},
"context": {
"type": "string",
"description": "The situation and what forced a decision."
},
"consequences": {
"type": "string",
"description": "What becomes easier, harder, or must change."
}
}
}
+24
View File
@@ -219,6 +219,14 @@
"diagram": {
"type": "string",
"description": "Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it."
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
},
"anyOf": [
@@ -332,6 +340,14 @@
},
"width": {
"$ref": "common.schema.json#/$defs/relationshipWidth"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -363,6 +379,14 @@
"description": "What the model covers; shown on the model page."
}
}
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
+24
View File
@@ -180,6 +180,14 @@
},
"yOffset": {
"type": "number"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -256,6 +264,14 @@
},
"width": {
"$ref": "common.schema.json#/$defs/relationshipWidth"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -287,6 +303,14 @@
"description": "What the model covers; shown on the model page."
}
}
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
+24
View File
@@ -208,6 +208,14 @@
},
"yOffset": {
"type": "number"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -288,6 +296,14 @@
},
"width": {
"$ref": "common.schema.json#/$defs/relationshipWidth"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -319,6 +335,14 @@
"description": "What the model covers; shown on the model page."
}
}
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
+24
View File
@@ -144,6 +144,14 @@
},
"sources": {
"$ref": "common.schema.json#/$defs/sourceReferences"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -213,6 +221,14 @@
},
"note": {
"type": "string"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -270,6 +286,14 @@
"description": "What the model covers; shown on the model page."
}
}
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
+24
View File
@@ -331,6 +331,14 @@
},
"yOffset": {
"type": "number"
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -419,6 +427,14 @@
"width": {
"type": "number",
"minimum": 0.5
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
}
}
@@ -450,6 +466,14 @@
"description": "What the model covers; shown on the model page."
}
}
},
"decisions": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
},
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
}
},
"$defs": {
+39 -1
View File
@@ -25,11 +25,19 @@ const MODEL = {
};
const DIAGRAM_LINK = { type: 'string', description: 'Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it.' };
const DECISIONS = { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram.' };
const NODE_COLLECTIONS = ['components', 'nodes', 'participants', 'states'];
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'];
for (const file of fs.readdirSync(schemas)) {
if (!/^(architecture|workflow|sequence|dataflow|lifecycle)\.schema\.json$/.test(file)) continue;
const schema = read(file);
schema.properties.model = MODEL;
schema.properties.decisions = DECISIONS;
for (const key of [...NODE_COLLECTIONS, ...EDGE_COLLECTIONS]) {
const items = schema.properties[key]?.items;
if (items?.properties) items.properties.decisions = DECISIONS;
}
if (file === 'architecture.schema.json') {
const item = schema.properties.components.items;
item.properties.ref = { type: 'string', pattern: '^[a-zA-Z][a-zA-Z0-9_-]*$', description: 'A shared element from the model’s registry (*.archify-registry). Its type, label, sublabel, brand and sources come from there; the diagram adds pos/size and may override label, sublabel and tag.' };
@@ -76,4 +84,34 @@ const registry = {
},
};
write('archify-registry.schema.json', registry);
console.log('Patched editor schemas: model, ref, diagram; wrote archify-registry.schema.json');
const decision = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
title: 'Archify architecture decision',
description: 'One architecture decision of a model. Diagrams point at it with `decisions: [<id>]`.',
type: 'object',
additionalProperties: false,
required: ['decision'],
properties: {
schema_version: { const: 1 },
decision: {
type: 'object',
additionalProperties: false,
required: ['id', 'title'],
properties: {
id: { type: 'string', minLength: 1, description: 'Unique in the model. Any short string.' },
title: { type: 'string', minLength: 1 },
status: { enum: ['proposed', 'accepted', 'superseded', 'rejected'], description: 'A decision another one supersedes shows as superseded whatever this says.' },
date: { type: 'string', description: 'YYYY-MM-DD.' },
elements: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Registry element ids the decision is about.' },
diagrams: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Diagram paths (from the model root) the decision names.' },
supersedes: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Ids of older decisions this one replaces.' },
},
},
context: { type: 'string', description: 'The situation and what forced a decision.' },
decision: { type: 'string', description: 'What was decided.' },
consequences: { type: 'string', description: 'What becomes easier, harder, or must change.' },
},
};
write('archify-decision.schema.json', decision);
console.log('Patched editor schemas: model, ref, diagram, decisions; wrote archify-registry.schema.json and archify-decision.schema.json');
+3 -1
View File
@@ -3,6 +3,7 @@ import { HTML_VIEW_TYPE, HtmlViewerProvider } from '../views/htmlViewer';
import { ModelService } from '../model/service';
import { DiagramViewManager } from '../views/diagramView';
import { RegistryViewProvider } from '../views/registryView';
import { DecisionViewProvider } from '../views/decisionView';
/** What command handlers share: the extension context and the open views. */
export interface CommandContext {
@@ -10,6 +11,7 @@ export interface CommandContext {
views: DiagramViewManager;
htmlViewer: HtmlViewerProvider;
registry: RegistryViewProvider;
decision: DecisionViewProvider;
models: ModelService;
}
@@ -20,7 +22,7 @@ export function isHtmlUri(uri: vscode.Uri): boolean {
/** The file a command applies to: explicit argument, focused preview or viewer, then the text editor. */
export function targetUri(ctx: CommandContext, arg?: unknown): vscode.Uri | undefined {
if (arg instanceof vscode.Uri) return arg;
return ctx.views.activePreview?.uri ?? ctx.registry.activeUri ?? ctx.htmlViewer.activeUri ?? vscode.window.activeTextEditor?.document.uri;
return ctx.views.activePreview?.uri ?? ctx.registry.activeUri ?? ctx.decision.activeUri ?? ctx.htmlViewer.activeUri ?? vscode.window.activeTextEditor?.document.uri;
}
export function sourceUri(ctx: CommandContext, arg?: unknown): vscode.Uri | undefined {
+66 -1
View File
@@ -1,7 +1,10 @@
import * as vscode from 'vscode';
import { MODEL_EXAMPLES, mainFromExample } from '../language/examples';
import { diagramName, invalidNameReason } from '../language/templates';
import { MAIN_FILE } from '../model/format';
import { DECISION_EXT, slugify } from '../model/decisions';
import { MAIN_FILE, REGISTRY_EXT } from '../model/format';
import { REGISTRY_VIEW_TYPE } from '../views/registryView';
import { DECISION_VIEW_TYPE } from '../views/decisionView';
import { readText } from '../util/files';
import { DIAGRAM_EDITOR_VIEW_TYPE } from '../views/diagramView';
import { CommandContext, exists, targetUri } from './context';
@@ -30,6 +33,68 @@ export function modelCommands(ctx: CommandContext): vscode.Disposable[] {
await vscode.commands.executeCommand('vscode.openWith', vscode.Uri.joinPath(root, MAIN_FILE), DIAGRAM_EDITOR_VIEW_TYPE, vscode.ViewColumn.Active);
}),
// Opens the model's Graph page: every element and connection of the model in one picture, with a query box.
vscode.commands.registerCommand('archify.openModelGraph', async (arg?: unknown) => {
const uri = targetUri(ctx, arg);
const root = uri ? await ctx.models.rootOf(uri) : undefined;
if (!root) {
vscode.window.showInformationMessage(`Archify: this file is not inside a model (no ${MAIN_FILE} in a folder above it).`);
return;
}
await ctx.views.showGraph(root);
}),
// Creates a registry file in the clicked folder and opens it.
vscode.commands.registerCommand('archify.newRegistry', async (arg?: unknown) => {
const folder = await parentFolder(arg);
if (!folder) return;
const root = await ctx.models.rootOf(vscode.Uri.joinPath(folder, 'x'));
const name = await vscode.window.showInputBox({
title: 'Archify | New Registry',
prompt: `File name in ${vscode.workspace.asRelativePath(folder, true)}${root ? '' : ' (not inside a model: add a main.archify above it so diagrams can refer to its elements)'}`,
value: 'elements',
validateInput: async (value) =>
invalidNameReason(value) ?? ((await exists(vscode.Uri.joinPath(folder, `${diagramName(value).replace(/\.archify-registry$/i, '')}${REGISTRY_EXT}`))) ? `${diagramName(value)}${REGISTRY_EXT} already exists.` : undefined),
});
if (name === undefined) return;
const target = vscode.Uri.joinPath(folder, `${diagramName(name).replace(/\.archify-registry$/i, '')}${REGISTRY_EXT}`);
const template = await readText(vscode.Uri.joinPath(ctx.extension.extensionUri, 'templates', 'registry.archify-registry'));
await vscode.workspace.fs.writeFile(target, Buffer.from(template, 'utf8'));
await vscode.commands.executeCommand('vscode.openWith', target, REGISTRY_VIEW_TYPE);
}),
// Creates a decision file in the clicked folder of a model and opens it.
vscode.commands.registerCommand('archify.newDecision', async (arg?: unknown) => {
const folder = await parentFolder(arg);
if (!folder) return;
const root = await ctx.models.rootOf(vscode.Uri.joinPath(folder, 'x'));
if (!root) {
vscode.window.showWarningMessage(`Archify: ${vscode.workspace.asRelativePath(folder, true)} is not inside a model (no ${MAIN_FILE} in it or a folder above it). Decisions belong to a model.`);
return;
}
const index = await ctx.models.index(root);
const title = await vscode.window.showInputBox({
title: 'Archify | New Decision',
prompt: `Title of the decision (file goes into ${vscode.workspace.asRelativePath(folder, true)})`,
placeHolder: 'OpenSearch for product search',
validateInput: async (value) => {
if (!value.trim()) return 'Enter a title.';
const id = slugify(value);
if (index.decisions.decisions.has(id)) return `A decision with id "${id}" already exists in this model.`;
if (await exists(vscode.Uri.joinPath(folder, `${id}${DECISION_EXT}`))) return `${id}${DECISION_EXT} already exists.`;
return undefined;
},
});
if (title === undefined) return;
const id = slugify(title);
const target = vscode.Uri.joinPath(folder, `${id}${DECISION_EXT}`);
const template = await readText(vscode.Uri.joinPath(ctx.extension.extensionUri, 'templates', 'decision.archify-decision'));
const today = new Date().toISOString().slice(0, 10);
const text = template.replace('__ID__', id).replace('__TITLE__', JSON.stringify(title.trim())).replace('__DATE__', today);
await vscode.workspace.fs.writeFile(target, Buffer.from(text, 'utf8'));
await vscode.commands.executeCommand('vscode.openWith', target, DECISION_VIEW_TYPE);
}),
// Creates a new model folder from one of the shipped examples and opens its model page.
vscode.commands.registerCommand('archify.newModel', async (arg?: unknown) => {
const picked = await vscode.window.showQuickPick(
+16 -3
View File
@@ -1,8 +1,10 @@
import * as vscode from 'vscode';
import { isDecisionFile } from '../model/decisions';
import { isRegistryFile } from '../model/format';
import { isArchifyFile } from '../sources/detect';
import { DIAGRAM_EDITOR_VIEW_TYPE } from '../views/diagramView';
import { REGISTRY_VIEW_TYPE } from '../views/registryView';
import { DECISION_VIEW_TYPE } from '../views/decisionView';
import { CommandContext, isHtmlUri, openHtmlViewer, sourceUri } from './context';
export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
@@ -12,6 +14,7 @@ export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
if (!uri) return;
if (isHtmlUri(uri)) return openHtmlViewer(uri);
if (isRegistryFile(uri.path)) return vscode.commands.executeCommand('vscode.openWith', uri, REGISTRY_VIEW_TYPE);
if (isDecisionFile(uri.path)) return vscode.commands.executeCommand('vscode.openWith', uri, DECISION_VIEW_TYPE);
if (isArchifyFile(uri.path)) return vscode.commands.executeCommand('vscode.openWith', uri, DIAGRAM_EDITOR_VIEW_TYPE);
ctx.views.show(uri, vscode.window.activeTextEditor?.viewColumn ?? vscode.ViewColumn.Active);
}),
@@ -36,7 +39,17 @@ export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
vscode.commands.registerCommand('archify.refreshPreview', () => ctx.views.activePreview?.update(true)),
// On a page that has a Source view, show it; elsewhere open the text.
vscode.commands.registerCommand('archify.showSource', async () => {
const session = ctx.views.activePreview?.source ?? ctx.registry.activeView?.source ?? ctx.decision.activeView?.source;
if (session) {
session.reveal();
return;
}
await vscode.commands.executeCommand('archify.openInTextEditor');
}),
vscode.commands.registerCommand('archify.openInTextEditor', async () => {
const preview = ctx.views.activePreview;
if (preview?.isEditor) {
// The diagram is the editor; open the YAML text beside it.
@@ -48,9 +61,9 @@ export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
await vscode.window.showTextDocument(preview.uri, { viewColumn: column });
return;
}
const registry = ctx.registry.activeUri;
if (registry) {
await vscode.commands.executeCommand('vscode.openWith', registry, 'default', vscode.ViewColumn.Beside);
const page = ctx.registry.activeUri ?? ctx.decision.activeUri;
if (page) {
await vscode.commands.executeCommand('vscode.openWith', page, 'default', vscode.ViewColumn.Beside);
return;
}
const html = ctx.htmlViewer.activeUri;
+11 -1
View File
@@ -13,6 +13,9 @@ import { log } from './util/log';
import { HtmlViewerProvider } from './views/htmlViewer';
import { DiagramViewManager } from './views/diagramView';
import { RegistryViewProvider } from './views/registryView';
import { DecisionViewProvider } from './views/decisionView';
import { DECISION_SELECTOR, DecisionLanguage } from './language/decisionLanguage';
import { registerSync } from './sync/loader';
export function activate(context: vscode.ExtensionContext): void {
const models = new ModelService();
@@ -20,25 +23,32 @@ export function activate(context: vscode.ExtensionContext): void {
extension: context,
views: new DiagramViewManager(context, models),
htmlViewer: new HtmlViewerProvider(context.extensionUri),
registry: new RegistryViewProvider(models),
registry: new RegistryViewProvider(context, models),
decision: new DecisionViewProvider(context, models),
models,
};
const refs = new RefLanguage(models);
const decisions = new DecisionLanguage(models);
context.subscriptions.push(
models,
ctx.views,
ctx.htmlViewer,
ctx.registry,
ctx.decision,
new DiagnosticsController(context, models),
log(),
vscode.languages.registerCompletionItemProvider(BRAND_COMPLETION_SELECTOR, new BrandCompletionProvider(context.extensionPath), ' ', '"'),
vscode.languages.registerCompletionItemProvider(REF_SELECTOR, refs, ' ', '"'),
vscode.languages.registerHoverProvider(REF_SELECTOR, refs),
vscode.languages.registerDefinitionProvider(REF_SELECTOR, refs),
vscode.languages.registerCompletionItemProvider(DECISION_SELECTOR, decisions, ' ', '[', ',', '"'),
vscode.languages.registerHoverProvider(DECISION_SELECTOR, decisions),
vscode.languages.registerDefinitionProvider(DECISION_SELECTOR, decisions),
...viewCommands(ctx),
...newDiagramCommands(ctx),
...renderCommands(ctx),
...modelCommands(ctx),
...registerSync(context, models),
);
registerContextKeys(context, models);
}
+855
View File
@@ -0,0 +1,855 @@
import cytoscape, { Core, EdgeSingular, NodeSingular } from 'cytoscape';
import fcose from 'cytoscape-fcose';
import type { GraphEdge, GraphNode, ModelGraph } from '../model/graph';
import { QueryResult, runQuery } from '../model/graphQuery';
import { GRAPH_PAGE_STYLE } from './style';
import { layeredLayout } from './layout';
import type { ArchifyHost } from '../webview/host';
/**
* The Graph page of a model: the whole model as one graph, a query box that
* narrows it, a side panel for the selected element or connection. Runs in
* the webview; the extension hands the graph over through the bridge
* (`window.__archifyHost.graph`) and posts a new one when the model changes.
*/
type Host = ArchifyHost;
interface SavedView {
query?: string;
labels?: boolean;
hidden?: string[];
/** A theme chosen on the page; absent means follow VS Code. */
theme?: 'dark' | 'light';
/** Layered by type (default) or force-directed. */
layout?: 'layered' | 'force';
/** Show every decision and registry link, not only the selected element's. */
links?: boolean;
}
type Theme = 'dark' | 'light';
/** The theme in effect: the page's own choice, else VS Code's. */
function currentTheme(): Theme {
const chosen = document.documentElement.dataset.theme;
if (chosen === 'dark' || chosen === 'light') return chosen;
return document.body.classList.contains('vscode-light') ? 'light' : 'dark';
}
cytoscape.use(fcose);
const TYPE_COLORS: Record<string, string> = { frontend: '#22d3ee', backend: '#34d399', database: '#a78bfa', cloud: '#fbbf24', security: '#fb7185', messagebus: '#fb923c', external: '#94a3b8', decision: '#e879f9', registry: '#cbd5e1' };
const TYPE_ORDER = ['external', 'frontend', 'cloud', 'security', 'backend', 'messagebus', 'database', 'decision', 'registry'];
const STATUS_COLORS: Record<string, string> = { accepted: '#34d399', proposed: '#fbbf24', rejected: '#fb7185', superseded: '#94a3b8' };
const colorOf = (type: string | undefined) => TYPE_COLORS[type ?? ''] ?? '#94a3b8';
/** An opaque mix of two `#rrggbb` colours (`amount` of the first), so nodes hide the connections behind them. */
function mix(front: string, back: string, amount: number): string {
const f = parseInt(front.slice(1), 16);
const b = parseInt(back.replace(/^#/, '').padEnd(6, '0').slice(0, 6), 16);
const channel = (shift: number) => Math.round(((f >> shift) & 255) * amount + ((b >> shift) & 255) * (1 - amount));
return `rgb(${channel(16)}, ${channel(8)}, ${channel(0)})`;
}
/** `#rrggbb` form of a CSS colour, read through the canvas so `rgb()` and names work too. */
function toHex(color: string): string {
if (/^#[0-9a-f]{6}$/i.test(color)) return color;
const canvas = document.createElement('canvas').getContext('2d');
if (!canvas) return '#000000';
canvas.fillStyle = color;
return /^#[0-9a-f]{6}$/i.test(canvas.fillStyle) ? canvas.fillStyle : '#000000';
}
const nodeColor = (n: GraphNode) => (n.kind === 'decision' ? STATUS_COLORS[n.status ?? ''] ?? TYPE_COLORS.decision : colorOf(n.type));
/** Edge labels are drawn by default up to this many connections; above it they clutter. */
const LABELS_UP_TO = 40;
const PLACEHOLDER = 'database · type:backend · diagram:0200-* · uses:api · near:api,2 · from:web to:db · decision:<id> · unused · -shared';
const HELP: [string, string][] = [
['database', 'elements whose id, label, sublabel, brand or type contain the word'],
['type:backend', 'elements of that type'],
['diagram:0200-*', 'what the diagrams matching the path draw (glob)'],
['decision:<id>', 'what a decision is about or is attached to'],
['uses:api', 'an element and its neighbours'],
['near:api,2', 'an element and everything within two steps'],
['from:web to:db', 'the shortest path between two elements'],
['unused', 'registry elements no diagram draws'],
['shared', 'registry elements only; -shared: inline elements only'],
['-worker', 'a leading minus excludes; terms combine with AND'],
];
function el<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, text?: string): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function cssVar(name: string, fallback: string): string {
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return value || fallback;
}
/** Theme colours Cytoscape needs as literals: the page's tokens, read again whenever the theme changes. */
function palette() {
const dark = currentTheme() === 'dark';
return {
bg: cssVar('--ag-bg', dark ? '#0b1020' : '#ffffff'),
fg: cssVar('--ag-fg', dark ? '#e5e7eb' : '#1f2937'),
muted: cssVar('--ag-muted', dark ? '#9ca3af' : '#6b7280'),
panel: cssVar('--ag-panel', dark ? '#131c31' : '#f3f4f6'),
accent: cssVar('--ag-accent', '#22d3ee'),
edge: dark ? '#64748b' : '#94a3b8',
font: cssVar('--ag-font', 'system-ui, sans-serif'),
};
}
class GraphPage {
cy!: Core;
private graph: ModelGraph;
private readonly nodesById = new Map<string, GraphNode>();
private readonly edgesById = new Map<string, GraphEdge>();
private saved: SavedView;
private queryTimer: number | undefined;
private result: QueryResult | undefined;
private readonly hiddenTypes: Set<string>;
private readonly root = el('div', 'ag');
private readonly nameEl = el('div', 'ag-name');
private readonly kickerEl = el('div', 'ag-kicker');
private readonly queryInput = el('input', 'ag-query');
private readonly countEl = el('span', 'ag-count');
private readonly labelsButton = el('button', 'ag-button', 'Labels');
private readonly linksButton = el('button', 'ag-button', 'Links');
private readonly layoutButton = el('button', 'ag-button', 'Layered');
private readonly themeButton = el('button', 'ag-button ag-theme');
private readonly legend = el('div', 'ag-legend');
private readonly side = el('aside', 'ag-side');
private readonly main = el('div', 'ag-main');
private readonly canvas = el('div', 'ag-canvas');
private readonly help = el('div', 'ag-help');
constructor(private readonly host: Host, initial: { graph: ModelGraph; query?: string }) {
this.graph = initial.graph;
this.saved = (host.getState().graphView as SavedView | undefined) ?? {};
if (initial.query !== undefined) this.saved.query = initial.query;
if (this.saved.labels === undefined) this.saved.labels = initial.graph.edges.length <= LABELS_UP_TO;
if (this.saved.links === undefined) this.saved.links = true;
this.hiddenTypes = new Set(this.saved.hidden ?? []);
this.applyTheme(this.saved.theme ?? archifyThemePreference());
this.index();
this.buildChrome();
this.buildGraph(true);
this.syncLabels();
this.renderLegend();
this.syncLayoutButton();
this.queryInput.value = this.saved.query ?? '';
this.applyQuery();
this.showEmptySide();
this.listen();
}
// ---------------------------------------------------------------- data
private index(): void {
this.nodesById.clear();
this.edgesById.clear();
for (const n of this.graph.nodes) this.nodesById.set(n.id, n);
for (const e of this.graph.edges) this.edgesById.set(e.id, e);
}
private elements() {
const shorten = (text: string, max: number) => {
if (text.length <= max) return text;
const cut = text.slice(0, max - 1);
return `${cut.slice(0, Math.max(cut.lastIndexOf(' '), max - 16))}\u2026`;
};
const nodes = this.graph.nodes.map((n) => ({ group: 'nodes' as const, data: { id: n.id, label: n.kind === 'decision' ? shorten(n.label, 60) : n.label, type: n.type ?? '', kind: n.kind, shared: n.shared ? 1 : 0, color: nodeColor(n) } }));
// In the layered layout a label sits at the end of the connection where fewer connections meet, so a
// fan-out labels at its targets and a fan-in at its sources; what still shares an end is staggered.
const outCount = new Map<string, number>();
const inCount = new Map<string, number>();
for (const e of this.graph.edges) {
if (e.kind !== 'connection') continue;
outCount.set(e.from, (outCount.get(e.from) ?? 0) + 1);
inCount.set(e.to, (inCount.get(e.to) ?? 0) + 1);
}
const used = new Map<string, number>();
const edges = this.graph.edges.map((e) => {
const at = e.kind === 'connection' && (outCount.get(e.from) ?? 0) > (inCount.get(e.to) ?? 0) ? 'target' : 'source';
const key = `${at}:${at === 'source' ? e.from : e.to}`;
const index = used.get(key) ?? 0;
used.set(key, index + 1);
return { group: 'edges' as const, data: { id: e.id, source: e.from, target: e.to, kind: e.kind, label: e.labels.join(' / '), at, offset: 40 + (index % 3) * 34 } };
});
return [...nodes, ...edges];
}
/** A new graph from the extension: keep the positions of the elements that are still there. */
replace(graph: ModelGraph): void {
const positions = new Map<string, { x: number; y: number }>();
this.cy.nodes().forEach((n) => {
positions.set(n.id(), { ...n.position() });
});
const selected = this.cy.$(':selected').map((e) => e.id());
this.graph = graph;
this.index();
this.cy.elements().remove();
this.cy.add(this.elements());
let fresh = 0;
this.cy.nodes().forEach((n) => {
const at = positions.get(n.id());
if (at) n.position(at);
else fresh += 1;
});
if (fresh || this.saved.layout !== 'force') this.layout(false);
this.syncLinks();
this.renderLegend();
this.applyHidden();
this.applyQuery();
const again = this.cy.$(selected.map((id) => `#${CSS.escape(id)}`).join(','));
if (again.length) {
again.select();
this.showSide(again[0]);
} else this.showEmptySide();
this.kickerEl.textContent = `Model${graph.meta.id ? ` · ${graph.meta.id}` : ''}`;
this.nameEl.textContent = graph.meta.name || graph.meta.id || 'Untitled model';
}
// -------------------------------------------------------------- chrome
private buildChrome(): void {
const style = el('style');
style.textContent = GRAPH_PAGE_STYLE;
document.head.appendChild(style);
const top = el('header', 'ag-top');
const titles = el('div');
this.kickerEl.textContent = `Model${this.graph.meta.id ? ` · ${this.graph.meta.id}` : ''}`;
this.nameEl.textContent = this.graph.meta.name || this.graph.meta.id || 'Untitled model';
titles.append(this.kickerEl, this.nameEl);
const actions = el('div', 'ag-actions');
// Model | Graph | Source, as on the model page. Source goes back to the
// model page and opens it in Source (the page reads sourceView on load).
const sw = el('div', 'ag-switch');
sw.setAttribute('role', 'group');
sw.setAttribute('aria-label', 'View');
const segment = (label: string, title: string, on: boolean, action?: () => void) => {
const button = el('button', `ag-seg${on ? ' on' : ''}`, label);
button.type = 'button';
button.title = title;
button.setAttribute('aria-pressed', String(on));
if (action) button.addEventListener('click', action);
return button;
};
sw.append(
segment('Model', 'Back to the model page', false, () => this.host.post({ type: 'showModel' })),
segment('Graph', 'The model as one graph', true),
segment('Source', 'Edit the YAML of main.archify, checked as you type', false, () => {
this.host.setState({ sourceView: true });
this.host.post({ type: 'showModel' });
}),
);
const exportButton = el('button', 'ag-button ag-primary', 'Export PNG');
exportButton.type = 'button';
exportButton.title = 'Save the graph as it is on screen, as a PNG';
exportButton.addEventListener('click', () => this.exportPng());
this.themeButton.type = 'button';
this.themeButton.setAttribute('role', 'switch');
this.themeButton.append(el('span', 'ag-theme-track'), el('span', 'ag-theme-icon'), el('span', 'ag-sr', 'Dark theme'));
this.themeButton.addEventListener('click', () => this.setTheme(currentTheme() === 'dark' ? 'light' : 'dark'));
this.syncThemeButton();
actions.append(sw, this.themeButton, exportButton);
top.append(titles, actions);
const bar = el('div', 'ag-bar');
const wrap = el('div', 'ag-query-wrap');
this.queryInput.type = 'text';
this.queryInput.placeholder = PLACEHOLDER;
this.queryInput.spellcheck = false;
this.queryInput.setAttribute('aria-label', 'Query');
const clear = el('button', 'ag-clear', '×');
clear.type = 'button';
clear.title = 'Clear (Esc)';
clear.addEventListener('click', () => this.setQuery(''));
wrap.append(this.queryInput, clear);
const fit = el('button', 'ag-button', 'Fit');
fit.type = 'button';
fit.title = 'Fit the matching elements into view (0)';
fit.addEventListener('click', () => this.fit());
this.layoutButton.type = 'button';
this.layoutButton.addEventListener('click', () => {
this.saved.layout = this.saved.layout === 'force' ? 'layered' : 'force';
this.save();
this.layout(true);
this.syncLayoutButton();
});
this.linksButton.type = 'button';
this.linksButton.title = 'Links from decisions and registries to their elements: on for all, off for the selected element only';
this.linksButton.addEventListener('click', () => {
this.saved.links = !this.saved.links;
this.save();
this.syncLinks();
});
this.labelsButton.type = 'button';
this.labelsButton.title = 'Show or hide connection labels';
this.labelsButton.addEventListener('click', () => {
this.saved.labels = !this.saved.labels;
this.save();
this.syncLabels();
});
const helpButton = el('button', 'ag-button', '?');
helpButton.type = 'button';
helpButton.title = 'What can I type?';
helpButton.setAttribute('aria-expanded', 'false');
helpButton.addEventListener('click', () => {
this.help.hidden = !this.help.hidden;
helpButton.setAttribute('aria-expanded', String(!this.help.hidden));
});
bar.append(wrap, this.countEl, fit, this.layoutButton, this.labelsButton, this.linksButton, helpButton);
const cyHolder = el('div', 'ag-cy');
this.canvas.append(cyHolder, this.legend);
this.help.hidden = true;
this.help.appendChild(el('h3', '', 'Queries'));
const table = el('table');
for (const [example, meaning] of HELP) {
const row = el('tr');
const code = el('td', '', example);
code.title = 'Try it';
code.addEventListener('click', () => {
this.setQuery(example.includes('<id>') ? example.replace('<id>', this.graph.decisions[0]?.id ?? '') : example);
});
row.append(code, el('td', '', meaning));
table.appendChild(row);
}
this.help.appendChild(table);
this.help.appendChild(el('p', '', 'Matches stay bright, the rest dims. Connections show when both ends match. Click an element for its details; drag to move it; scroll to zoom. Press / to type a query. Layered puts clients on the left and data on the right, with registries before and decisions after; Links switches the dotted decision and registry links between all of them and the selected element\u2019s only.'));
this.main.append(this.canvas, this.side, this.help);
const head = el('div', 'ag-head');
head.append(top, bar);
this.root.append(head, this.main);
document.body.appendChild(this.root);
this.syncLabels();
}
private renderLegend(): void {
this.legend.textContent = '';
const counts = new Map<string, number>();
for (const n of this.graph.nodes) counts.set(n.type ?? 'other', (counts.get(n.type ?? 'other') ?? 0) + 1);
const types = [...counts.keys()].sort((a, b) => (TYPE_ORDER.indexOf(a) + 1 || 99) - (TYPE_ORDER.indexOf(b) + 1 || 99) || a.localeCompare(b));
for (const type of types) {
const chip = el('button', 'ag-chip');
chip.type = 'button';
chip.style.setProperty('--c', colorOf(type));
chip.setAttribute('aria-pressed', String(!this.hiddenTypes.has(type)));
chip.title = `Show or hide ${type} elements`;
chip.append(document.createTextNode(type), el('small', '', String(counts.get(type))));
chip.addEventListener('click', () => {
if (this.hiddenTypes.has(type)) this.hiddenTypes.delete(type);
else this.hiddenTypes.add(type);
chip.setAttribute('aria-pressed', String(!this.hiddenTypes.has(type)));
this.saved.hidden = [...this.hiddenTypes];
this.save();
this.applyHidden();
this.updateCount();
});
this.legend.appendChild(chip);
}
}
// --------------------------------------------------------------- graph
private buildGraph(first: boolean): void {
const holder = this.canvas.firstElementChild as HTMLElement;
this.cy = cytoscape({
container: holder,
elements: this.elements(),
style: this.stylesheet(),
wheelSensitivity: 0.2,
minZoom: 0.1,
maxZoom: 4,
});
this.applyHidden();
this.syncLinks();
this.layout(first);
this.cy.on('tap', 'node, edge', (event) => this.showSide(event.target as NodeSingular | EdgeSingular));
this.cy.on('tap', (event) => {
if (event.target === this.cy) this.showEmptySide();
});
// Hover lights up an element and its connections; selection also reveals its decision and registry links.
this.cy.on('mouseover', 'node', (event) => {
const node = event.target as NodeSingular;
node.addClass('hover');
node.connectedEdges('[kind = "connection"]').addClass('edge-hover');
});
this.cy.on('mouseout', 'node', (event) => {
const node = event.target as NodeSingular;
node.removeClass('hover');
node.connectedEdges().removeClass('edge-hover');
});
this.cy.on('select unselect', 'node', () => this.syncLinks());
}
/** Decision and registry links: all of them when Links is on, else those of the selected nodes. */
private syncLinks(): void {
const all = Boolean(this.saved.links);
this.linksButton.setAttribute('aria-pressed', String(all));
const meta = this.cy.edges('[kind != "connection"]');
meta.removeClass('shown');
if (all) meta.addClass('shown');
else this.cy.nodes(':selected').connectedEdges('[kind != "connection"]').addClass('shown');
}
private syncLayoutButton(): void {
const force = this.saved.layout === 'force';
this.layoutButton.textContent = force ? 'Force' : 'Layered';
this.layoutButton.title = force ? 'Force-directed layout; click for the layered one (clients left, data right)' : 'Layered by type; click for a force-directed layout';
}
private stylesheet(): cytoscape.StylesheetJson {
const p = palette();
const dark = currentTheme() === 'dark';
const bg = toHex(p.bg);
const fill = (amount: number) => (n: NodeSingular) => mix(String(n.data('color')), bg, amount);
return [
{ selector: 'node', style: { shape: 'round-rectangle', width: (n: NodeSingular) => Math.min(240, Math.max(110, String(n.data('label')).length * 7.6 + 40)), height: 46, 'background-color': fill(dark ? 0.16 : 0.1), 'border-width': 1.5, 'border-color': 'data(color)', 'border-opacity': 0.9, label: 'data(label)', color: p.fg, 'font-size': 13, 'font-weight': 600, 'font-family': p.font, 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'ellipsis', 'text-max-width': '210px', 'overlay-opacity': 0, 'underlay-color': 'data(color)', 'underlay-padding': 6, 'underlay-opacity': 0, 'underlay-shape': 'round-rectangle', 'transition-property': 'underlay-opacity, border-width', 'transition-duration': 120 } },
{ selector: 'node[shared = 0]', style: { 'border-style': 'dashed' } },
{ selector: 'node[kind = "decision"]', style: { shape: 'round-tag', height: (n: NodeSingular) => (String(n.data('label')).length > 30 ? 44 : 34), 'font-size': 11, 'font-weight': 500, 'background-color': fill(dark ? 0.12 : 0.08), 'text-wrap': 'wrap', 'text-max-width': '196px', 'line-height': 1.2, width: (n: NodeSingular) => Math.min(244, Math.max(120, String(n.data('label')).length * 6.4 + 48)) } },
{ selector: 'node[kind = "registry"]', style: { shape: 'cut-rectangle', height: 32, 'font-size': 11, 'font-weight': 500, 'font-family': 'ui-monospace, Menlo, monospace', 'border-width': 1, 'border-color': p.muted, 'background-color': mix(dark ? '#94a3b8' : '#64748b', bg, 0.08), width: (n: NodeSingular) => Math.min(220, Math.max(110, String(n.data('label')).length * 6.8 + 36)) } },
{ selector: 'node.hover', style: { 'underlay-opacity': dark ? 0.22 : 0.16, 'border-width': 2, 'background-color': fill(dark ? 0.28 : 0.18) } },
{ selector: 'edge', style: { width: 1.4, 'line-color': p.edge, 'line-opacity': 0.85, 'target-arrow-color': p.edge, 'target-arrow-shape': 'triangle', 'arrow-scale': 0.8, 'curve-style': 'bezier', label: '', 'font-size': 10, 'font-family': p.font, color: p.muted, 'text-background-color': p.bg, 'text-background-opacity': 1, 'text-background-padding': '3px', 'text-background-shape': 'round-rectangle', 'text-rotation': 'autorotate', 'transition-property': 'width, line-color', 'transition-duration': 120 } },
{ selector: 'edge.ortho', style: { 'curve-style': 'taxi', 'taxi-direction': 'auto', 'taxi-turn': '45%', 'taxi-turn-min-distance': 24, 'text-rotation': 'none', 'source-text-offset': 'data(offset)', 'source-text-rotation': 'none', 'source-text-background-color': p.bg, 'source-text-background-opacity': 1, 'source-text-background-padding': '3px', 'source-text-background-shape': 'round-rectangle', 'target-text-offset': 'data(offset)', 'target-text-rotation': 'none', 'target-text-background-color': p.bg, 'target-text-background-opacity': 1, 'target-text-background-padding': '3px', 'target-text-background-shape': 'round-rectangle' } },
{ selector: 'edge.edge-hover', style: { width: 2.4, 'line-color': p.fg, 'target-arrow-color': p.fg, 'line-opacity': 1, color: p.fg } },
{ selector: 'edge[kind != "connection"]', style: { display: 'none', width: 1, 'curve-style': 'bezier', 'line-style': 'dotted', 'target-arrow-shape': 'none', 'line-color': p.muted, 'line-opacity': 0.55 } },
{ selector: 'edge[kind = "supersedes"]', style: { 'line-style': 'dashed', 'line-color': TYPE_COLORS.decision, 'target-arrow-shape': 'triangle', 'target-arrow-color': TYPE_COLORS.decision } },
{ selector: 'edge[kind != "connection"].shown', style: { display: 'element' } },
{ selector: 'edge.labelled[kind = "connection"], edge.labelled[kind = "supersedes"]', style: { label: 'data(label)' } },
{ selector: 'edge.labelled.ortho[kind = "connection"][at = "source"]', style: { label: '', 'source-label': 'data(label)' } },
{ selector: 'edge.labelled.ortho[kind = "connection"][at = "target"]', style: { label: '', 'target-label': 'data(label)' } },
{ selector: '.dim', style: { opacity: 0.12, events: 'no' } },
{ selector: 'node.hit', style: { 'border-width': 2.5 } },
{ selector: 'edge.path', style: { width: 3, 'line-color': p.accent, 'target-arrow-color': p.accent, color: p.fg, 'line-opacity': 1 } },
{ selector: 'node:selected', style: { 'border-color': p.accent, 'border-width': 2.5, 'underlay-color': p.accent, 'underlay-opacity': dark ? 0.28 : 0.18, 'background-color': fill(dark ? 0.3 : 0.2) } },
{ selector: 'edge:selected', style: { width: 3, 'line-color': p.accent, 'target-arrow-color': p.accent, 'line-opacity': 1 } },
{ selector: '.hidden', style: { display: 'none' } },
] as unknown as cytoscape.StylesheetJson;
}
private layout(fresh: boolean): void {
const force = this.saved.layout === 'force';
this.cy.edges().toggleClass('ortho', !force);
if (force) {
this.cy
.elements()
.not('.hidden')
.layout({ name: 'fcose', animate: false, randomize: fresh, quality: 'default', nodeDimensionsIncludeLabels: true, nodeRepulsion: () => 9000, idealEdgeLength: (e: EdgeSingular) => (e.data('kind') === 'connection' ? 150 : 110), edgeElasticity: (e: EdgeSingular) => (e.data('kind') === 'connection' ? 0.2 : 0.08), gravity: 0.3, padding: 40, fit: true } as cytoscape.LayoutOptions)
.run();
return;
}
const positions = layeredLayout(this.graph.nodes, this.graph.edges);
this.cy.batch(() => {
this.cy.nodes().forEach((n) => {
const at = positions.get(n.id());
if (at) n.position(at);
});
});
this.cy.fit(this.cy.elements().not('.hidden'), 40);
}
// --------------------------------------------------------------- theme
/** Sets the page's own theme (or follows VS Code when undefined) without touching the saved choice. */
private applyTheme(theme: Theme | undefined): void {
if (theme) document.documentElement.dataset.theme = theme;
else delete document.documentElement.dataset.theme;
}
private setTheme(theme: Theme): void {
this.applyTheme(theme);
this.saved.theme = theme;
this.save();
try {
localStorage.setItem('archify-theme', theme); // the diagram pages read the same key
} catch {
// storage may be unavailable; the page state keeps the choice
}
this.restyle();
}
private syncThemeButton(): void {
const dark = currentTheme() === 'dark';
this.themeButton.dataset.on = dark ? 'dark' : 'light';
this.themeButton.setAttribute('aria-checked', String(dark));
this.themeButton.title = dark ? 'Dark theme on; switch to light' : 'Light theme on; switch to dark';
this.themeButton.setAttribute('aria-label', this.themeButton.title);
}
private restyle(): void {
this.cy?.style(this.stylesheet());
this.syncLabels();
this.syncThemeButton();
}
private applyHidden(): void {
this.cy.nodes().forEach((n) => {
n.toggleClass('hidden', this.hiddenTypes.has(String(n.data('type') || 'other')));
});
}
private syncLabels(): void {
const on = Boolean(this.saved.labels);
this.labelsButton.setAttribute('aria-pressed', String(on));
this.cy?.edges().toggleClass('labelled', on);
}
// --------------------------------------------------------------- query
private setQuery(text: string): void {
this.queryInput.value = text;
this.applyQuery();
this.queryInput.focus();
}
private applyQuery(): void {
const text = this.queryInput.value;
this.saved.query = text;
this.save();
this.result = runQuery(this.graph, text);
const { nodes, edges, path } = this.result;
const empty = !text.trim();
this.cy.batch(() => {
this.cy.elements().removeClass('dim hit path');
if (empty) return;
this.cy.nodes().forEach((n) => {
n.toggleClass('dim', !nodes.has(n.id())).toggleClass('hit', nodes.has(n.id()));
});
this.cy.edges().forEach((e) => {
e.toggleClass('dim', !edges.has(e.id()));
});
if (path) for (const id of edges) this.cy.$id(id).addClass('path');
});
this.updateCount();
}
private updateCount(): void {
const total = this.cy.nodes('[kind = "element"]').not('.hidden').length;
const r = this.result;
if (!r || !this.queryInput.value.trim()) {
this.countEl.textContent = `${total} elements · ${this.cy.edges('[kind = "connection"]').not('.hidden').length} connections`;
this.countEl.classList.remove('is-error');
return;
}
const shown = this.cy.nodes('.hit[kind = "element"]').not('.hidden').length;
this.countEl.textContent = r.message ? r.message : r.path ? `path of ${r.path.length} elements` : `${shown} of ${total} elements`;
this.countEl.classList.toggle('is-error', Boolean(r.message));
}
private fit(): void {
const hits = this.cy.nodes('.hit').not('.hidden');
const target = hits.length ? hits.union(hits.connectedEdges().not('.dim')) : this.cy.elements().not('.hidden');
this.cy.animate({ fit: { eles: target, padding: 40 }, duration: 250 });
}
// ---------------------------------------------------------------- side
private showEmptySide(): void {
this.side.textContent = '';
this.side.appendChild(el('p', 'ag-empty', 'Click an element or a connection.'));
const h3 = el('h3', '', 'This model');
this.side.appendChild(h3);
const elements = this.graph.nodes.filter((n) => n.kind === 'element');
const registries = this.graph.nodes.filter((n) => n.kind === 'registry');
const summary = el('p', '', `${elements.length} elements, ${this.graph.edges.filter((e) => e.kind === 'connection').length} connections, ${this.graph.diagrams.length} diagrams, ${registries.length} ${registries.length === 1 ? 'registry' : 'registries'}, ${this.graph.decisions.length} decisions.`);
this.side.appendChild(summary);
const unused = elements.filter((n) => n.shared && !n.diagrams.length).length;
if (unused) {
const hint = el('button', 'ag-link', `${unused} unused registry element${unused === 1 ? '' : 's'}`);
hint.type = 'button';
hint.addEventListener('click', () => this.setQuery('unused'));
this.side.appendChild(hint);
}
}
private showSide(target: NodeSingular | EdgeSingular): void {
if (!target.isNode()) {
this.showEdge(this.edgesById.get(target.id()));
return;
}
const node = this.nodesById.get(target.id());
if (node?.kind === 'decision') this.showDecision(node);
else if (node?.kind === 'registry') this.showRegistry(node);
else this.showNode(node);
}
private selectNode(id: string): void {
const n = this.cy.$id(id);
this.cy.elements().unselect();
n.select();
this.showSide(n as NodeSingular);
}
private elementLinks(ids: string[]): HTMLElement {
const holder = el('div');
for (const id of ids) {
const n = this.nodesById.get(id);
if (!n) continue;
const button = this.link(n.label, `Show ${n.id}`, () => this.selectNode(n.id));
const dot = el('span', 'ag-dot');
dot.style.setProperty('--c', nodeColor(n));
button.prepend(dot);
holder.appendChild(button);
}
return holder;
}
/** Side panel of a decision node: status, text, what it is about, and the file. */
private showDecision(node: GraphNode): void {
this.side.textContent = '';
const title = el('h2');
const dot = el('span', 'ag-dot');
dot.style.setProperty('--c', nodeColor(node));
title.append(dot, document.createTextNode(node.label));
this.side.appendChild(title);
this.side.appendChild(el('div', 'ag-id', ['decision', node.sublabel, node.status].filter(Boolean).join(' · ')));
if (node.description) this.side.appendChild(el('p', '', node.description));
const actions = el('div', 'ag-side-actions');
if (node.file) actions.appendChild(this.link('Open decision', `Open ${node.file}`, () => this.host.post({ type: 'openDecision', file: node.file })));
if (node.sublabel) actions.appendChild(this.link('What it touches', `Show everything decision ${node.sublabel} is about`, () => this.setQuery(`decision:${node.sublabel}`)));
this.side.appendChild(actions);
const about = this.graph.edges.filter((e) => e.kind === 'decides' && e.from === node.id).map((e) => e.to);
this.side.appendChild(el('h3', '', `About ${about.length} element${about.length === 1 ? '' : 's'}`));
this.side.appendChild(about.length ? this.elementLinks(about) : el('p', 'ag-empty', 'Names no element of this model.'));
const onEdges = this.graph.edges.filter((e) => e.kind === 'connection' && node.sublabel && e.decisions.includes(node.sublabel));
if (onEdges.length) {
this.side.appendChild(el('h3', '', 'On connections'));
const holder = el('div');
for (const e of onEdges) holder.appendChild(this.link(`${this.nodesById.get(e.from)?.label ?? e.from} → ${this.nodesById.get(e.to)?.label ?? e.to}`, e.id, () => { this.cy.elements().unselect(); this.cy.$id(e.id).select(); this.showEdge(e); }));
this.side.appendChild(holder);
}
if (node.diagrams.length) {
this.side.appendChild(el('h3', '', 'Diagrams it names'));
this.side.appendChild(this.diagramLinks(node.diagrams));
}
const related = this.graph.edges.filter((e) => e.kind === 'supersedes' && (e.from === node.id || e.to === node.id));
if (related.length) {
this.side.appendChild(el('h3', '', 'Related decisions'));
const holder = el('div');
for (const e of related) {
const otherId = e.from === node.id ? e.to : e.from;
const other = this.nodesById.get(otherId);
if (other) holder.appendChild(this.link(`${e.from === node.id ? 'supersedes' : 'superseded by'} ${other.label}`, other.sublabel ?? otherId, () => this.selectNode(otherId)));
}
this.side.appendChild(holder);
}
}
/** Side panel of a registry node: the file and the elements it defines. */
private showRegistry(node: GraphNode): void {
this.side.textContent = '';
const title = el('h2');
const dot = el('span', 'ag-dot');
dot.style.setProperty('--c', nodeColor(node));
title.append(dot, document.createTextNode(node.label));
this.side.appendChild(title);
this.side.appendChild(el('div', 'ag-id', `registry · ${node.file ?? ''}`));
const actions = el('div', 'ag-side-actions');
if (node.file) actions.appendChild(this.link('Open registry', `Open ${node.file}`, () => this.host.post({ type: 'openRegistry', file: node.file, line: 0 })));
this.side.appendChild(actions);
const ids = node.elements ?? [];
this.side.appendChild(el('h3', '', `Defines ${ids.length} element${ids.length === 1 ? '' : 's'}`));
this.side.appendChild(ids.length ? this.elementLinks(ids) : el('p', 'ag-empty', 'No elements yet.'));
const unused = ids.filter((id) => !(this.nodesById.get(id)?.diagrams.length));
if (unused.length) {
this.side.appendChild(el('h3', '', `${unused.length} not drawn by any diagram`));
this.side.appendChild(this.elementLinks(unused));
}
}
private link(text: string, title: string, onClick?: () => void, className = ''): HTMLButtonElement {
const button = el('button', `ag-link ${className}${onClick ? '' : ' is-static'}`);
button.type = 'button';
button.title = title;
button.appendChild(document.createTextNode(text));
if (onClick) button.addEventListener('click', onClick);
return button;
}
private decisionLinks(ids: string[]): HTMLElement {
const holder = el('div');
for (const id of ids) {
const d = this.graph.decisions.find((x) => x.id === id);
const button = this.link('', d ? `${d.title ?? d.id} (${d.status})` : id, d ? () => this.host.post({ type: 'openDecision', file: d.file }) : undefined, `is-${d?.status ?? 'unknown'}`);
button.prepend(el('span', 'ag-dot'));
button.appendChild(document.createTextNode([id, d?.title, d?.status].filter(Boolean).join(' · ')));
holder.appendChild(button);
}
return holder;
}
private diagramLinks(paths: string[]): HTMLElement {
const holder = el('div');
for (const path of paths) {
const d = this.graph.diagrams.find((x) => x.path === path);
holder.appendChild(this.link(path.replace(/\.archify$/, ''), d?.title ? `Open ${d.title} (${path})` : `Open ${path}`, () => this.host.post({ type: 'openDiagram', path })));
}
return holder;
}
private showNode(node: GraphNode | undefined): void {
if (!node) return;
this.side.textContent = '';
const title = el('h2');
const dot = el('span', 'ag-dot');
dot.style.setProperty('--c', colorOf(node.type));
title.append(dot, document.createTextNode(node.label));
this.side.appendChild(title);
this.side.appendChild(el('div', 'ag-id', [node.id, node.type, node.sublabel, node.brand ? `brand ${node.brand}` : undefined, node.shared ? 'registry' : 'inline'].filter(Boolean).join(' · ')));
this.side.appendChild(node.description ? el('p', '', node.description) : el('p', 'ag-empty', node.shared ? 'No description in the registry.' : 'Inline element: defined in the diagram, not in a registry.'));
const actions = el('div', 'ag-side-actions');
actions.appendChild(this.link('Neighbours', `Show ${node.id} and everything connected to it`, () => this.setQuery(`uses:${node.id}`)));
if (node.file) actions.appendChild(this.link('Registry', `Open ${node.file} at line ${(node.line ?? 0) + 1}`, () => this.host.post({ type: 'openRegistry', file: node.file, line: node.line ?? 0 })));
if (node.link) actions.appendChild(this.link('Explained by', `Open ${node.link}`, () => this.host.post({ type: 'openDiagram', path: node.link })));
this.side.appendChild(actions);
this.side.appendChild(el('h3', '', `Used in ${node.diagrams.length} diagram${node.diagrams.length === 1 ? '' : 's'}`));
this.side.appendChild(node.diagrams.length ? this.diagramLinks(node.diagrams) : el('p', 'ag-empty', 'Not drawn by any diagram yet.'));
const connected = this.graph.edges.filter((e) => e.kind === 'connection' && (e.from === node.id || e.to === node.id));
this.side.appendChild(el('h3', '', `${connected.length} connection${connected.length === 1 ? '' : 's'}`));
const list = el('div');
for (const e of connected) {
const other = e.from === node.id ? e.to : e.from;
const otherLabel = this.nodesById.get(other)?.label ?? other;
const text = e.from === node.id ? `→ ${otherLabel}` : `← ${otherLabel}`;
list.appendChild(this.link(e.labels.length ? `${text} · ${e.labels.join(' / ')}` : text, `${e.from} → ${e.to}`, () => {
const edge = this.cy.$id(e.id);
this.cy.elements().unselect();
edge.select();
this.showEdge(e);
}));
}
this.side.appendChild(list);
if (node.decisions.length) {
this.side.appendChild(el('h3', '', 'Decisions'));
this.side.appendChild(this.decisionLinks(node.decisions));
}
}
private showEdge(edge: GraphEdge | undefined): void {
if (!edge) return;
this.side.textContent = '';
const from = this.nodesById.get(edge.from);
const to = this.nodesById.get(edge.to);
const title = el('h2');
title.textContent = `${from?.label ?? edge.from} → ${to?.label ?? edge.to}`;
this.side.appendChild(title);
this.side.appendChild(el('div', 'ag-id', `${edge.from} → ${edge.to}${edge.labels.length ? ` · ${edge.labels.join(' / ')}` : ''}`));
const ends = el('div', 'ag-side-actions');
for (const end of [from, to]) {
if (!end) continue;
const button = this.link(end.label, `Show ${end.id}`, () => {
const n = this.cy.$id(end.id);
this.cy.elements().unselect();
n.select();
this.showNode(end);
});
const dot = el('span', 'ag-dot');
dot.style.setProperty('--c', colorOf(end.type));
button.prepend(dot);
ends.appendChild(button);
}
this.side.appendChild(ends);
this.side.appendChild(el('h3', '', `Drawn in ${edge.diagrams.length} diagram${edge.diagrams.length === 1 ? '' : 's'}`));
this.side.appendChild(this.diagramLinks(edge.diagrams));
if (edge.decisions.length) {
this.side.appendChild(el('h3', '', 'Decisions'));
this.side.appendChild(this.decisionLinks(edge.decisions));
}
}
// -------------------------------------------------------------- export
private exportPng(): void {
const blob = this.cy.png({ output: 'blob', full: true, scale: 2, bg: palette().bg });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = `${this.graph.meta.id || 'model'}-graph.png`;
anchor.hidden = true;
document.body.appendChild(anchor);
anchor.click(); // the bridge turns the download into a VS Code save dialog
setTimeout(() => {
anchor.remove();
URL.revokeObjectURL(url);
}, 1000);
}
// -------------------------------------------------------------- events
private listen(): void {
this.queryInput.addEventListener('input', () => {
window.clearTimeout(this.queryTimer);
this.queryTimer = window.setTimeout(() => this.applyQuery(), 120);
});
this.queryInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
window.clearTimeout(this.queryTimer);
this.applyQuery();
this.fit();
} else if (event.key === 'Escape') {
if (this.queryInput.value) this.setQuery('');
else this.queryInput.blur();
}
});
window.addEventListener('keydown', (event) => {
const target = event.target as HTMLElement | null;
const typing = target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName));
if (typing || event.metaKey || event.ctrlKey || event.altKey) return;
if (event.key === '/') {
event.preventDefault();
this.queryInput.focus();
this.queryInput.select();
} else if (event.key === '0') this.fit();
else if (event.key === 'Escape') {
this.cy.elements().unselect();
this.showEmptySide();
this.help.hidden = true;
}
});
let resizeTimer: number | undefined;
window.addEventListener('resize', () => {
this.cy.resize();
window.clearTimeout(resizeTimer);
resizeTimer = window.setTimeout(() => this.cy.fit(this.cy.elements().not('.hidden'), 40), 150);
});
new MutationObserver(() => this.restyle()).observe(document.body, { attributes: true, attributeFilter: ['class'] });
window.addEventListener('message', (event) => {
const message = event.data || {};
if (message.type === 'graph' && message.graph) this.replace(message.graph as ModelGraph);
if (message.type === 'query' && typeof message.query === 'string') this.setQuery(message.query);
});
}
private save(): void {
this.host.setState({ graphView: { query: this.saved.query, labels: this.saved.labels, hidden: this.saved.hidden ?? [], theme: this.saved.theme, layout: this.saved.layout, links: this.saved.links } });
}
}
/** The theme the Archify diagram pages last used, when they stored one. */
function archifyThemePreference(): Theme | undefined {
try {
const value = localStorage.getItem('archify-theme');
return value === 'dark' || value === 'light' ? value : undefined;
} catch {
return undefined;
}
}
function start(): void {
const host = window.__archifyHost;
if (!host?.graph) return;
// Exposed for the integration harness; nothing in the page depends on it.
(window as unknown as { __archifyGraphPage?: GraphPage }).__archifyGraphPage = new GraphPage(host, host.graph);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
else start();
+88
View File
@@ -0,0 +1,88 @@
import type { GraphEdge, GraphNode } from '../model/graph';
/**
* Layered layout: a column per element type in Archify's stack order
* (clients on the left, data on the right), empty columns left out, rows
* ordered to shorten the connections; registries in a row above the
* columns, decisions in a row below. Deterministic, so the picture is stable.
*/
const COLUMN_ORDER = ['external', 'frontend', 'cloud', 'security', 'backend', 'other', 'messagebus', 'database'];
const STATUS_ORDER = ['accepted', 'proposed', 'superseded', 'rejected'];
export interface LayoutOptions {
columnGap: number;
rowGap: number;
}
export type Positions = Map<string, { x: number; y: number }>;
function columnOf(node: GraphNode): number {
if (node.kind === 'registry') return -1;
if (node.kind === 'decision') return COLUMN_ORDER.length;
const i = COLUMN_ORDER.indexOf(node.type ?? 'other');
return i < 0 ? COLUMN_ORDER.indexOf('other') : i;
}
export function layeredLayout(nodes: GraphNode[], edges: GraphEdge[], options: LayoutOptions = { columnGap: 230, rowGap: 84 }): Positions {
const columns = new Map<number, GraphNode[]>();
const registries = nodes.filter((n) => n.kind === 'registry').sort((a, b) => a.label.localeCompare(b.label));
const decisions = nodes.filter((n) => n.kind === 'decision').sort((a, b) => STATUS_ORDER.indexOf(a.status ?? '') - STATUS_ORDER.indexOf(b.status ?? '') || a.label.localeCompare(b.label));
for (const n of nodes) if (n.kind === 'element') columns.set(columnOf(n), [...(columns.get(columnOf(n)) ?? []), n]);
const order = new Map<string, number>();
const neighbours = new Map<string, string[]>();
for (const e of edges) {
if (e.kind === 'supersedes') continue;
neighbours.set(e.from, [...(neighbours.get(e.from) ?? []), e.to]);
neighbours.set(e.to, [...(neighbours.get(e.to) ?? []), e.from]);
}
// Start from a stable order: elements by label, decisions by status, registries by file.
for (const [col, list] of columns) {
list.sort((a, b) => {
if (a.kind === 'decision' && b.kind === 'decision') return STATUS_ORDER.indexOf(a.status ?? '') - STATUS_ORDER.indexOf(b.status ?? '') || a.label.localeCompare(b.label);
return a.label.localeCompare(b.label);
});
list.forEach((n, i) => order.set(n.id, i));
columns.set(col, list);
}
// Barycenter sweeps: each node moves towards the average row of what it is connected to.
const keys = [...columns.keys()].sort((a, b) => a - b);
for (let sweep = 0; sweep < 4; sweep += 1) {
const sequence = sweep % 2 === 0 ? keys : [...keys].reverse();
for (const col of sequence) {
const list = columns.get(col)!;
const weight = new Map<string, number>();
for (const n of list) {
const rows = (neighbours.get(n.id) ?? []).map((id) => order.get(id)).filter((r): r is number => r !== undefined);
weight.set(n.id, rows.length ? rows.reduce((a, b) => a + b, 0) / rows.length : order.get(n.id)!);
}
list.sort((a, b) => weight.get(a.id)! - weight.get(b.id)! || order.get(a.id)! - order.get(b.id)!);
list.forEach((n, i) => order.set(n.id, i));
}
}
const positions: Positions = new Map();
const tallest = Math.max(1, ...[...columns.values()].map((list) => list.length));
// Empty columns are left out, so the picture is as wide as the types the model uses.
const used = keys.filter((col) => columns.get(col)!.length);
used.forEach((col, index) => {
const list = columns.get(col)!;
const offset = ((tallest - list.length) * options.rowGap) / 2;
list.forEach((n, i) => positions.set(n.id, { x: index * options.columnGap, y: offset + i * options.rowGap }));
});
const width = Math.max(0, used.length - 1) * options.columnGap;
// Registries and decisions sit above or below the elements they link to: at the mean x of those
// elements, pushed apart only as far as needed so they do not overlap.
const spread = (list: GraphNode[], y: number, gap: number) => {
const wanted = list.map((n) => {
const xs = (neighbours.get(n.id) ?? []).map((id) => positions.get(id)?.x).filter((x): x is number => x !== undefined);
return { n, x: xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : width / 2 };
});
wanted.sort((a, b) => a.x - b.x || a.n.label.localeCompare(b.n.label));
for (let i = 1; i < wanted.length; i += 1) wanted[i].x = Math.max(wanted[i].x, wanted[i - 1].x + gap);
for (let i = wanted.length - 2; i >= 0; i -= 1) wanted[i].x = Math.min(wanted[i].x, wanted[i + 1].x - gap);
for (const { n, x } of wanted) positions.set(n.id, { x, y });
};
spread(registries, -options.rowGap * 1.6, 200);
spread(decisions, tallest * options.rowGap + options.rowGap * 0.6, 250);
return positions;
}
+95
View File
@@ -0,0 +1,95 @@
/** Page styles of the graph view. VS Code's theme variables, Archify's type colours. */
export const GRAPH_PAGE_STYLE = `
:root { --ag-bg: var(--vscode-editor-background, #0b1020); --ag-fg: var(--vscode-foreground, #e5e7eb); --ag-muted: var(--vscode-descriptionForeground, #9ca3af);
--ag-panel: var(--vscode-editorWidget-background, #111a2e); --ag-border: var(--vscode-editorWidget-border, rgba(128,128,128,.35)); --ag-accent: var(--vscode-textLink-foreground, #22d3ee);
--ag-input: var(--vscode-input-background, #1f2937); --ag-input-fg: var(--vscode-input-foreground, #e5e7eb); --ag-input-border: var(--vscode-input-border, var(--ag-border));
--ag-error: var(--vscode-errorForeground, #f87171); --ag-font: var(--vscode-font-family, system-ui, sans-serif); --ag-mono: var(--vscode-editor-font-family, ui-monospace, Menlo, monospace);
--ag-frontend: #22d3ee; --ag-backend: #34d399; --ag-database: #a78bfa; --ag-cloud: #fbbf24; --ag-security: #fb7185; --ag-messagebus: #fb923c; --ag-external: #94a3b8; --ag-decision: #e879f9; --ag-registry: #cbd5e1; }
/* A theme chosen on the page overrides VS Code's; without one the VS Code variables above apply. */
:root[data-theme="dark"] { --ag-bg: #0b1020; --ag-fg: #e5e7eb; --ag-muted: #9ca3af; --ag-panel: #111a2e; --ag-border: rgba(148, 163, 184, 0.28); --ag-accent: #22d3ee; --ag-input: #0f172a; --ag-input-fg: #e5e7eb; --ag-input-border: rgba(148, 163, 184, 0.28); --ag-error: #f87171; color-scheme: dark; }
:root[data-theme="light"] { --ag-bg: #ffffff; --ag-fg: #0f172a; --ag-muted: #64748b; --ag-panel: #f8fafc; --ag-border: rgba(15, 23, 42, 0.14); --ag-accent: #0e7490; --ag-input: #ffffff; --ag-input-fg: #0f172a; --ag-input-border: rgba(15, 23, 42, 0.2); --ag-error: #b91c1c; --ag-external: #64748b; --ag-registry: #94a3b8; color-scheme: light; }
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--ag-bg); color: var(--ag-fg); font-family: var(--ag-font); font-size: 13px; }
:root { --ag-gutter: 1.5rem; }
.ag { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100%; }
/* One head block: title row and query row share a background and a single rule below. */
.ag-head { background: color-mix(in srgb, var(--ag-panel) 55%, var(--ag-bg)); border-bottom: 1px solid var(--ag-border); }
.ag-top { display: flex; align-items: center; gap: 1rem; padding: 1.1rem var(--ag-gutter) 0.6rem; }
.ag-kicker { font-size: 0.6875rem; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ag-accent); margin-bottom: 0.2rem; }
.ag-name { font-weight: 700; font-size: 1.25rem; line-height: 1.2; letter-spacing: -0.015em; }
.ag-actions { margin-left: auto; display: flex; align-items: center; gap: 0.5rem; }
.ag-bar .ag-button { min-height: 2rem; }
/* Toolbar controls follow Archify's: quiet pills (0.5rem) inside 0.5625rem buttons, one filled primary action (0.6875rem), the 2D | 3D switch's twin. */
.ag-switch { position: relative; isolation: isolate; display: inline-flex; padding: 0 0.25rem; border: 0; border-radius: 0.5625rem; background: transparent; color: var(--ag-muted); font: inherit; }
.ag-switch::before { content: ""; position: absolute; z-index: -1; inset: 0.25rem 0; border-radius: 0.6875rem; background: color-mix(in srgb, var(--ag-panel) 78%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ag-border) 85%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); }
.ag-switch:hover::before { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ag-fg) 22%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); }
.ag-seg { display: inline-flex; align-items: center; height: 1.75rem; margin: 0.25rem 0; padding: 0 0.7rem; border: 0; border-radius: 0.5rem; background: transparent; color: inherit; font: inherit; font-weight: 550; font-size: 0.8125rem; cursor: pointer; transition: background 0.15s, color 0.15s; }
.ag-seg.on { cursor: default; }
.ag-seg:focus-visible { outline: 2px solid var(--ag-accent); outline-offset: 1px; }
.ag-seg.on { color: var(--ag-bg); background: var(--ag-fg); box-shadow: 0 1px 2px rgba(15, 23, 42, 0.12), 0 6px 16px -8px rgba(15, 23, 42, 0.4); }
.ag-seg:hover:not(.on) { color: var(--ag-fg); }
.ag-button { position: relative; isolation: isolate; display: inline-flex; align-items: center; gap: 0.4rem; font: inherit; font-size: 0.8125rem; font-weight: 500; min-height: 2.25rem; padding: 0.25rem 0.58rem; border-radius: 0.5625rem; border: 0; background: transparent; color: var(--ag-muted); cursor: pointer; white-space: nowrap; transition: color 0.15s; }
.ag-button::before { content: ""; position: absolute; z-index: -1; inset: 0.25rem 0; border-radius: 0.5rem; background: transparent; transition: background 0.15s, box-shadow 0.15s; }
.ag-button:hover { color: var(--ag-fg); }
.ag-button:hover::before { background: color-mix(in srgb, var(--ag-fg) 6%, transparent); }
.ag-button[aria-pressed="true"] { color: var(--ag-fg); }
.ag-button[aria-pressed="true"]::before { background: color-mix(in srgb, var(--ag-fg) 8%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ag-fg) 14%, transparent); }
.ag-button:focus-visible { outline: 2px solid var(--ag-accent); outline-offset: -4px; }
.ag-primary { color: var(--ag-bg); font-weight: 600; padding: 0.25rem 0.9rem; }
.ag-primary::before { inset: 0.25rem 0; border-radius: 0.6875rem; background: var(--ag-fg); box-shadow: 0 1px 2px rgba(15, 23, 42, 0.12), 0 6px 16px -8px rgba(15, 23, 42, 0.4); }
.ag-primary:hover { color: var(--ag-bg); }
.ag-primary:hover::before { background: color-mix(in srgb, var(--ag-fg) 86%, var(--ag-bg)); }
/* Theme toggle: Archify's own, a pill track with a knob that slides and carries the sun or moon. */
.ag-theme { width: 4rem; padding: 0; justify-content: center; }
/* The same outer pill as the Model | Graph switch and Export, so the three line up; Archify's track and knob inside it. */
.ag-theme::before { inset: 0.25rem 0; border-radius: 0.6875rem; background: color-mix(in srgb, var(--ag-panel) 78%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ag-border) 85%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); }
.ag-theme:hover::before { background: color-mix(in srgb, var(--ag-panel) 78%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ag-fg) 22%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); }
.ag-theme-track { position: absolute; z-index: 0; inset: 0.6875rem 0.5625rem; border-radius: 999px; background: color-mix(in srgb, var(--ag-fg) 9%, transparent); box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.08); transition: background 0.15s; }
.ag-theme:hover .ag-theme-track { background: color-mix(in srgb, var(--ag-fg) 13%, transparent); }
.ag-theme::after { content: ""; position: absolute; z-index: 1; top: 50%; left: 0.6875rem; width: 1.125rem; height: 1.125rem; border-radius: 50%; background: var(--ag-panel); box-shadow: 0 1px 2px rgba(15, 23, 42, 0.18), 0 2px 6px rgba(15, 23, 42, 0.12); transform: translateY(-50%); transition: left 0.22s cubic-bezier(0.22, 1, 0.36, 1); }
.ag-theme[data-on="dark"] .ag-theme-track { background: rgba(148, 163, 184, 0.16); }
.ag-theme[data-on="dark"]::after { left: calc(100% - 0.6875rem - 1.125rem); background: #3b4a63; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); }
.ag-theme-icon { position: absolute; z-index: 2; top: 50%; left: calc(0.6875rem + 0.1875rem); width: 0.75rem; height: 0.75rem; color: var(--ag-cloud); background: currentColor; transform: translateY(-50%); transition: left 0.22s cubic-bezier(0.22, 1, 0.36, 1); -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='10' cy='10' r='3.1'/%3E%3Cpath d='M10 2.2v1.4M10 16.4v1.4M2.2 10h1.4M16.4 10h1.4M4.5 4.5l1 1M14.5 14.5l1 1M15.5 4.5l-1 1M5.5 14.5l-1 1'/%3E%3C/g%3E%3C/svg%3E") center / contain no-repeat; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='10' cy='10' r='3.1'/%3E%3Cpath d='M10 2.2v1.4M10 16.4v1.4M2.2 10h1.4M16.4 10h1.4M4.5 4.5l1 1M14.5 14.5l1 1M15.5 4.5l-1 1M5.5 14.5l-1 1'/%3E%3C/g%3E%3C/svg%3E") center / contain no-repeat; }
.ag-theme[data-on="dark"] .ag-theme-icon { left: calc(100% - 0.6875rem - 1.125rem + 0.1875rem); color: #c7d2fe; -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cpath d='M15.2 12.7A6.3 6.3 0 017.3 4.8a6.3 6.3 0 107.9 7.9Z' fill='none' stroke='black' stroke-width='1.7' stroke-linejoin='round'/%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cpath d='M15.2 12.7A6.3 6.3 0 017.3 4.8a6.3 6.3 0 107.9 7.9Z' fill='none' stroke='black' stroke-width='1.7' stroke-linejoin='round'/%3E%3C/svg%3E"); }
.ag-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.ag-bar { display: flex; align-items: center; gap: 0.5rem; padding: 0.35rem var(--ag-gutter) 0.9rem; flex-wrap: wrap; }
.ag-query-wrap { flex: 1 1 18rem; display: flex; align-items: center; gap: 0.5rem; min-width: 0; background: var(--ag-input); border: 1px solid var(--ag-input-border); border-radius: 0.5625rem; padding: 0 0.6rem; }
.ag-query-wrap:focus-within { border-color: var(--ag-accent); }
.ag-query { flex: 1; min-width: 0; height: 2.125rem; border: 0; background: transparent; color: var(--ag-input-fg); font-family: var(--ag-mono); font-size: 0.875rem; outline: none; }
.ag-query::placeholder { color: var(--ag-muted); opacity: 0.8; }
.ag-clear { border: 0; background: transparent; color: var(--ag-muted); font-size: 1rem; cursor: pointer; padding: 0 0.1rem; }
.ag-clear:hover { color: var(--ag-fg); }
.ag-count { font-family: var(--ag-mono); font-size: 0.8125rem; color: var(--ag-muted); white-space: nowrap; margin: 0 0.35rem 0 0.25rem; }
.ag-count.is-error { color: var(--ag-error); }
.ag-main { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) 20rem; min-height: 0; }
.ag-main.is-side-hidden { grid-template-columns: minmax(0, 1fr); }
.ag-canvas { position: relative; min-width: 0; min-height: 0; }
.ag-cy { position: absolute; inset: 0; }
.ag-legend { position: absolute; left: var(--ag-gutter); bottom: 1rem; display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap; z-index: 2; max-width: calc(100% - 2 * var(--ag-gutter)); }
.ag-chip { display: inline-flex; align-items: center; gap: 0.4rem; font: inherit; font-size: 0.75rem; padding: 0.2rem 0.6rem; border-radius: 999px; border: 1px solid var(--ag-border); background: color-mix(in srgb, var(--ag-panel) 85%, transparent); color: var(--ag-fg); cursor: pointer; backdrop-filter: blur(6px); }
.ag-chip::before { content: ""; width: 0.55rem; height: 0.55rem; border-radius: 2px; background: var(--c); }
.ag-chip[aria-pressed="false"] { opacity: 0.45; text-decoration: line-through; }
.ag-chip small { color: var(--ag-muted); font-family: var(--ag-mono); }
.ag-side { border-left: 1px solid var(--ag-border); background: var(--ag-panel); overflow: auto; padding: 1.1rem var(--ag-gutter) 1.5rem; min-width: 0; }
.ag-side h2 { margin: 0; font-size: 1.0625rem; font-weight: 700; display: flex; align-items: center; gap: 0.5rem; }
.ag-dot { display: inline-block; width: 0.6rem; height: 0.6rem; border-radius: 50%; background: var(--c, var(--ag-external)); flex: none; }
.ag-id { font-family: var(--ag-mono); color: var(--ag-muted); font-size: 0.75rem; margin: 0.25rem 0 0.8rem; word-break: break-all; }
.ag-side p { margin: 0 0 0.8rem; line-height: 1.5; white-space: pre-line; }
.ag-side h3 { margin: 0.9rem 0 0.4rem; font-size: 0.6875rem; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ag-muted); font-weight: 700; }
.ag-link { display: inline-flex; align-items: baseline; gap: 0.35rem; line-height: 1.4; font: inherit; font-family: var(--ag-mono); font-size: 0.75rem; padding: 0.15rem 0.55rem; margin: 0 0.3rem 0.35rem 0; border: 1px solid var(--ag-border); border-radius: 999px; background: transparent; color: var(--ag-fg); cursor: pointer; text-align: left; max-width: 100%; }
.ag-link:hover { border-color: var(--ag-accent); }
.ag-link.is-static { cursor: default; }
.ag-link.is-static:hover { border-color: var(--ag-border); }
.ag-link.is-accepted .ag-dot { background: var(--ag-backend); } .ag-link.is-proposed .ag-dot { background: var(--ag-cloud); } .ag-link.is-rejected .ag-dot { background: var(--ag-security); } .ag-link.is-superseded .ag-dot { background: var(--ag-external); }
.ag-empty { color: var(--ag-muted); }
.ag-side-actions { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.6rem; }
.ag-help { position: absolute; top: 0.5rem; right: 20.75rem; z-index: 5; width: min(26rem, calc(100% - 2rem)); max-height: calc(100% - 1rem); overflow: auto; padding: 0.9rem 1rem; border: 1px solid var(--ag-border); border-radius: 0.6875rem; background: var(--ag-panel); box-shadow: 0 16px 40px rgba(0,0,0,.35); }
.ag-main.is-side-hidden .ag-help { right: 0.75rem; }
.ag-help h3 { margin: 0 0 0.5rem; font-size: 0.8125rem; }
.ag-help table { border-collapse: collapse; width: 100%; font-size: 0.8125rem; }
.ag-help td { padding: 0.25rem 0.4rem 0.25rem 0; vertical-align: top; border-top: 1px solid var(--ag-border); }
.ag-help td:first-child { font-family: var(--ag-mono); white-space: nowrap; color: var(--ag-accent); cursor: pointer; }
.ag-help td:first-child:hover { text-decoration: underline; }
.ag-help p { margin: 0.6rem 0 0; color: var(--ag-muted); font-size: 0.75rem; }
@media (max-width: 760px) { .ag-main { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; } .ag-side { border-left: 0; border-top: 1px solid var(--ag-border); max-height: 40%; } .ag-help { right: 0.75rem; } }
`;
+102
View File
@@ -0,0 +1,102 @@
import * as vscode from 'vscode';
import { Decision, DECISION_STATUSES, effectiveStatus, isDecisionFile } from '../model/decisions';
import { ModelIndex, ModelService } from '../model/service';
/** Diagrams (decisions: […]) and decision files (elements: […], diagrams: […], supersedes: […]). */
export const DECISION_SELECTOR: vscode.DocumentSelector = [{ pattern: '**/*.archify' }, { pattern: '**/*.archify-decision' }];
type ListKey = 'decisions' | 'elements' | 'diagrams' | 'supersedes';
/** Which list the cursor is in on a `key: [a, b, …` line, and what has been typed of the current item. */
export function listValueAt(linePrefix: string, fileName: string): { key: ListKey; typed: string } | undefined {
const keys = isDecisionFile(fileName) ? ['elements', 'diagrams', 'supersedes'] : ['decisions'];
const match = new RegExp(`(?:^|[\\s{,])(${keys.join('|')}):\\s*\\[([^\\]]*)$`).exec(linePrefix);
if (match) {
const items = match[2].split(',');
return { key: match[1] as ListKey, typed: items[items.length - 1].replace(/^[\s"']+/, '') };
}
// Block list item under the key: " - 00" (the key is on a line above; the caller checks).
return undefined;
}
/** The list item under a position on a flow-list line, with its range. */
export function listItemAt(line: string, character: number, fileName: string): { key: ListKey; value: string; start: number; end: number } | undefined {
const keys = isDecisionFile(fileName) ? ['elements', 'diagrams', 'supersedes'] : ['decisions'];
const match = new RegExp(`(?:^|[\\s{,])(${keys.join('|')}):\\s*\\[([^\\]]*)\\]?`).exec(line);
if (!match) return undefined;
const listStart = match.index + match[0].indexOf('[') + 1;
const re = /[^,\s"'\]]+/g;
const inner = match[2];
let m: RegExpExecArray | null;
while ((m = re.exec(inner))) {
const start = listStart + m.index;
const end = start + m[0].length;
if (character >= start && character <= end) return { key: match[1] as ListKey, value: m[0], start, end };
}
return undefined;
}
function describeDecision(d: Decision, index: ModelIndex): vscode.MarkdownString {
const md = new vscode.MarkdownString();
const { status, supersededBy } = effectiveStatus(d, index.decisions.decisions);
md.appendMarkdown(`**${d.id}**${d.title ? ` · ${d.title}` : ''} \`${status}\`${supersededBy ? ` by ${supersededBy}` : ''}${d.date ? ` · ${d.date}` : ''}\n\n`);
if (d.decision) md.appendMarkdown(`${d.decision.trim()}\n\n`);
md.appendMarkdown(`*${d.file}*`);
return md;
}
/** Completion, hover and go-to-definition for decision ids in diagrams and for links inside decision files. */
export class DecisionLanguage implements vscode.CompletionItemProvider, vscode.HoverProvider, vscode.DefinitionProvider {
constructor(private readonly models: ModelService) {}
async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.CompletionItem[] | undefined> {
const at = listValueAt(document.lineAt(position.line).text.slice(0, position.character), document.fileName);
if (!at) return undefined;
const index = await this.models.indexFor(document.uri);
if (!index) return undefined;
const range = new vscode.Range(position.translate(0, -at.typed.length), position);
const item = (label: string, description: string | undefined, detail: string, doc?: vscode.MarkdownString) => {
const it = new vscode.CompletionItem({ label, description }, vscode.CompletionItemKind.Reference);
it.detail = detail;
it.documentation = doc;
it.filterText = `${label} ${description ?? ''}`;
it.range = range;
return it;
};
if (at.key === 'decisions' || at.key === 'supersedes') {
return [...index.decisions.decisions.values()].map((d) => item(d.id, d.title, effectiveStatus(d, index.decisions.decisions).status, describeDecision(d, index)));
}
if (at.key === 'elements') {
return [...index.registry.elements.values()].map((e) => item(e.id, e.label, [e.type, e.sublabel].filter(Boolean).join(' · ')));
}
return index.diagrams.map((d) => item(d.relativePath, d.title, d.kind ?? 'diagram'));
}
async provideHover(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Hover | undefined> {
const hit = listItemAt(document.lineAt(position.line).text, position.character, document.fileName);
if (!hit || (hit.key !== 'decisions' && hit.key !== 'supersedes')) return undefined;
const index = await this.models.indexFor(document.uri);
const range = new vscode.Range(position.line, hit.start, position.line, hit.end);
const d = index?.decisions.decisions.get(hit.value);
if (!index) return new vscode.Hover(`\`${hit.value}\` cannot be resolved: this file is not inside a model.`, range);
if (!d) return new vscode.Hover(`Unknown decision \`${hit.value}\`: no .archify-decision file of this model defines it.`, range);
return new vscode.Hover(describeDecision(d, index), range);
}
async provideDefinition(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Location | undefined> {
const hit = listItemAt(document.lineAt(position.line).text, position.character, document.fileName);
if (!hit) return undefined;
const index = await this.models.indexFor(document.uri);
if (!index) return undefined;
if (hit.key === 'decisions' || hit.key === 'supersedes') {
const d = index.decisions.decisions.get(hit.value);
return d ? new vscode.Location(vscode.Uri.joinPath(index.root, ...d.file.split('/')), new vscode.Position(d.lines.id, 2)) : undefined;
}
if (hit.key === 'elements') {
const e = index.registry.elements.get(hit.value);
return e ? new vscode.Location(vscode.Uri.joinPath(index.root, ...e.file.split(/[\\/]/)), new vscode.Position(e.line, 2)) : undefined;
}
const diagram = index.diagrams.find((d) => d.relativePath === hit.value);
return diagram ? new vscode.Location(vscode.Uri.joinPath(index.root, ...diagram.relativePath.split('/')), new vscode.Position(0, 0)) : undefined;
}
}
+64 -2
View File
@@ -3,12 +3,14 @@ import * as vscode from 'vscode';
import { ArchifyDiagnostic, isEvidenceError, validate } from '../archify/cli';
import { evidenceMode, runtimeFor } from '../archify/runtime';
import { ModelProblem, isRegistryFile, parseRegistry } from '../model/format';
import { isDecisionFile, parseDecision } from '../model/decisions';
import { prepareDiagram } from '../model/prepare';
import { ModelService } from '../model/service';
import { isArchifyFile } from '../sources/detect';
import { log } from '../util/log';
import path from 'node:path';
import { diagnosticPointer, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from './jsonPointer';
import { DIAGRAM_SCHEMA, REGISTRY_SCHEMA, SchemaChecker, SchemaProblem, readSchemas } from './schemaCheck';
const JSON_LANGUAGES = new Set(['json', 'jsonc']);
@@ -32,6 +34,7 @@ export class DiagnosticsController implements vscode.Disposable {
private readonly timers = new Map<string, NodeJS.Timeout>();
private readonly sequence = new Map<string, number>();
private readonly disposables: vscode.Disposable[];
private checker: SchemaChecker | undefined;
constructor(
private readonly context: vscode.ExtensionContext,
@@ -53,6 +56,22 @@ export class DiagnosticsController implements vscode.Disposable {
this.revalidateAll();
}
/** Our schemas, compiled on first use. */
private schemas(): SchemaChecker {
this.checker ??= new SchemaChecker(readSchemas(vscode.Uri.joinPath(this.context.extensionUri, 'schemas').fsPath));
return this.checker;
}
private schemaDiagnostic(doc: vscode.TextDocument, problem: SchemaProblem): vscode.Diagnostic {
const diagnostic = new vscode.Diagnostic(
new vscode.Range(doc.positionAt(problem.from), doc.positionAt(problem.to)),
problem.message,
vscode.DiagnosticSeverity.Error,
);
diagnostic.source = 'archify';
return diagnostic;
}
private enabled(uri: vscode.Uri): boolean {
return vscode.workspace.getConfiguration('archify', uri).get<boolean>('validation.enabled', true);
}
@@ -70,7 +89,7 @@ export class DiagnosticsController implements vscode.Disposable {
}
private schedule(doc: vscode.TextDocument, delay: number): void {
if (!JSON_LANGUAGES.has(doc.languageId) && !isArchifyFile(doc.fileName) && !isRegistryFile(doc.fileName)) return;
if (!JSON_LANGUAGES.has(doc.languageId) && !isArchifyFile(doc.fileName) && !isRegistryFile(doc.fileName) && !isDecisionFile(doc.fileName)) return;
const key = doc.uri.toString();
clearTimeout(this.timers.get(key));
this.timers.set(key, setTimeout(() => void this.validate(doc), delay));
@@ -91,6 +110,10 @@ export class DiagnosticsController implements vscode.Disposable {
await this.validateRegistry(doc, seq);
return;
}
if (isDecisionFile(doc.fileName)) {
await this.validateDecision(doc, seq);
return;
}
if (isArchifyFile(doc.fileName)) {
// Nothing else reports YAML syntax errors in .archify files, and a file
// that does not parse has no diagram to validate yet.
@@ -131,6 +154,17 @@ export class DiagnosticsController implements vscode.Disposable {
}
}
if (isArchifyFile(doc.fileName)) {
// The schema check sees the source as written and answers at once; a
// file that fails it would fail archify validate the same way, so that
// runs only on files the schema accepts.
const schemaProblems = this.schemas().check(text, DIAGRAM_SCHEMA);
if (schemaProblems.length) {
this.collection.set(doc.uri, [...modelDiagnostics, ...schemaProblems.map((problem) => this.schemaDiagnostic(doc, problem))]);
return;
}
}
try {
const runtime = await runtimeFor(this.context, doc.uri);
const result = await validate(runtime, source.type, source.json);
@@ -179,11 +213,36 @@ export class DiagnosticsController implements vscode.Disposable {
}
/** A registry file: its own YAML and element problems, plus duplicates across the model. */
private async validateDecision(doc: vscode.TextDocument, seq: number): Promise<void> {
const text = doc.getText();
const root = await this.models.rootOf(doc.uri);
const rel = root ? path.relative(root.fsPath, doc.uri.fsPath).split(path.sep).join('/') : path.basename(doc.uri.fsPath);
const problems: ModelProblem[] = [...parseDecision(text, rel).problems];
if (root) {
try {
const index = await this.models.index(root);
for (const problem of index.decisions.problems) {
if (problem.file === rel && !problems.some((p) => p.message === problem.message)) problems.push(problem);
}
} catch {
// The index reports its own failures when the model page opens.
}
} else {
problems.push({ message: `This decision has lost its model: no main.archify above ${path.basename(doc.uri.fsPath)}, so its elements and diagrams cannot be resolved.`, severity: 'warning', line: 0 });
}
if (seq !== this.sequence.get(doc.uri.toString()) || doc.isClosed) return;
this.collection.set(doc.uri, problems.map((problem) => this.modelDiagnostic(doc, text, 'yaml', problem)));
}
private async validateRegistry(doc: vscode.TextDocument, seq: number): Promise<void> {
const text = doc.getText();
const root = await this.models.rootOf(doc.uri);
const rel = root ? path.relative(root.fsPath, doc.uri.fsPath) : path.basename(doc.uri.fsPath);
const problems: ModelProblem[] = [...parseRegistry(text, rel).problems];
// The schema adds what the parser does not check (types, unknown keys,
// ids); a file the parser already rejects as a whole gets no second opinion.
const shapeless = problems.some((p) => /not valid YAML|must be a mapping|needs an "elements" mapping/.test(p.message));
const schemaProblems = shapeless ? [] : this.schemas().check(text, REGISTRY_SCHEMA);
if (root) {
try {
const index = await this.models.index(root);
@@ -197,7 +256,10 @@ export class DiagnosticsController implements vscode.Disposable {
problems.push({ message: `This registry is not inside a model: no main.archify above ${path.basename(doc.uri.fsPath)}.`, severity: 'warning', line: 0 });
}
if (seq !== this.sequence.get(doc.uri.toString()) || doc.isClosed) return;
this.collection.set(doc.uri, problems.map((problem) => this.modelDiagnostic(doc, text, 'yaml', problem)));
this.collection.set(doc.uri, [
...problems.map((problem) => this.modelDiagnostic(doc, text, 'yaml', problem)),
...schemaProblems.map((problem) => this.schemaDiagnostic(doc, problem)),
]);
}
dispose(): void {
+85
View File
@@ -0,0 +1,85 @@
import { DIAGRAM_SCHEMA, REGISTRY_SCHEMA } from './schemaCheck';
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
/**
* Schemas for completion and hover in the Source view. The editor's schema
* library reads one draft-07 document, while ours are 2020-12 files that
* refer to each other; so the referenced files are folded into `$defs` and
* 2020-12 tuples become draft-07 ones. Problems never come from these
* copies (the host checks with the originals), only suggestions.
*/
export class EditorSchemas {
private readonly cache = new Map<string, object>();
constructor(private readonly schemas: Record<string, object>) {}
/** The schema for a file kind; for diagrams the one of its diagram_type. */
forSource(kind: 'diagram' | 'registry' | 'decision', text: string): { key: string; schema: object } | undefined {
if (kind === 'decision') return undefined;
if (kind === 'registry') return this.get(REGISTRY_SCHEMA);
const type = /^diagram_type:\s*["']?([a-z]+)/m.exec(text)?.[1];
const name = type && this.schemas[`${type}.schema.json`] ? `${type}.schema.json` : DIAGRAM_SCHEMA;
return this.get(name);
}
private get(name: string): { key: string; schema: object } | undefined {
if (!this.schemas[name]) return undefined;
if (!this.cache.has(name)) this.cache.set(name, bundleSchema(this.schemas, name));
return { key: name, schema: this.cache.get(name)! };
}
}
const defKey = (file: string) => `file:${file}`;
/** One self-contained draft-07 shaped schema for `root` and every file it refers to. */
export function bundleSchema(schemas: Record<string, object>, root: string): object {
const files = new Set<string>([root]);
const queue = [root];
while (queue.length) {
const file = queue.shift()!;
for (const ref of refsOf(schemas[file] as Json)) {
const target = ref.split('#')[0];
if (target && !files.has(target) && schemas[target]) {
files.add(target);
queue.push(target);
}
}
}
const base = (file: string) => (file === root ? '#' : `#/$defs/${defKey(file)}`);
const rewrite = (node: Json, file: string): Json => {
if (Array.isArray(node)) return node.map((item) => rewrite(item, file));
if (!node || typeof node !== 'object') return node;
const out: { [key: string]: Json } = {};
for (const [key, value] of Object.entries(node)) {
if (key === '$ref' && typeof value === 'string') {
const [target, pointer = ''] = value.split('#');
out.$ref = `${base(target || file)}${pointer}`;
} else if (key !== '$schema' && key !== '$id') {
out[key] = rewrite(value, file);
}
}
if (out.prefixItems) {
if (out.items === false) out.additionalItems = false;
else if (out.items !== undefined) out.additionalItems = out.items;
out.items = out.prefixItems;
delete out.prefixItems;
}
return out;
};
const bundled = rewrite(schemas[root] as Json, root) as { [key: string]: Json };
const defs = { ...((bundled.$defs as { [key: string]: Json } | undefined) ?? {}) };
for (const file of files) if (file !== root) defs[defKey(file)] = rewrite(schemas[file] as Json, file);
return { ...bundled, $defs: defs };
}
function refsOf(node: Json, out: string[] = []): string[] {
if (Array.isArray(node)) node.forEach((item) => refsOf(item, out));
else if (node && typeof node === 'object') {
for (const [key, value] of Object.entries(node)) {
if (key === '$ref' && typeof value === 'string') out.push(value);
else refsOf(value, out);
}
}
return out;
}
+148
View File
@@ -0,0 +1,148 @@
import fs from 'node:fs';
import path from 'node:path';
import Ajv2020, { ErrorObject, ValidateFunction } from 'ajv/dist/2020';
import { LineCounter, Node, isMap, isScalar, isSeq, parseDocument } from 'yaml';
/** A schema problem placed on the YAML node it is about; offsets into the text. */
export interface SchemaProblem {
from: number;
to: number;
message: string;
/** 'yaml' for a syntax error (only the first is reported), 'schema' otherwise. */
kind: 'yaml' | 'schema';
}
/** Schema file names in schemas/ that a file kind is checked against. */
export const DIAGRAM_SCHEMA = 'archify.schema.json';
export const REGISTRY_SCHEMA = 'archify-registry.schema.json';
/** Reads every *.schema.json of a folder: file name → schema. */
export function readSchemas(folder: string): Record<string, object> {
return Object.fromEntries(
fs
.readdirSync(folder)
.filter((name) => name.endsWith('.schema.json'))
.map((name) => [name, JSON.parse(fs.readFileSync(path.join(folder, name), 'utf8')) as object]),
);
}
/**
* Checks YAML text against our JSON Schemas (draft 2020-12, with ajv), so the
* Source view and the Problems panel see the same problems whether or not a
* YAML extension is installed. Schemas refer to each other by file name.
*/
export class SchemaChecker {
private readonly ajv = new Ajv2020({ allErrors: true, strict: false });
private readonly compiled = new Map<string, ValidateFunction | undefined>();
constructor(schemas: Record<string, object>) {
for (const [name, schema] of Object.entries(schemas)) this.ajv.addSchema(schema, name);
}
private validator(name: string): ValidateFunction | undefined {
if (!this.compiled.has(name)) this.compiled.set(name, this.ajv.getSchema(name));
return this.compiled.get(name);
}
check(text: string, schema: string): SchemaProblem[] {
const doc = parseDocument(text, { lineCounter: new LineCounter(), prettyErrors: false, uniqueKeys: false });
if (doc.errors.length) {
// Later syntax errors are usually echoes of the first.
const error = doc.errors[0];
return [{ from: error.pos[0], to: Math.max(error.pos[1], error.pos[0] + 1), message: `YAML: ${error.message.split('\n')[0]}`, kind: 'yaml' }];
}
const validate = this.validator(schema);
if (!validate || validate(doc.toJS())) return [];
return collapse(validate.errors ?? []).map((error) => {
const [from, to] = rangeFor(doc.contents, error, text.length);
return { from, to, message: describe(error), kind: 'schema' as const };
});
}
}
/** oneOf/anyOf/if produce a cascade; keep the errors a person can act on. */
function collapse(errors: ErrorObject[]): ErrorObject[] {
const seen = new Set<string>();
return errors
.filter((e) => !['if', 'oneOf', 'anyOf', 'allOf'].includes(e.keyword))
.filter((e) => {
const key = `${e.instancePath}|${e.keyword}|${JSON.stringify(e.params)}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** "/connections/4/label" → "connections[4].label". */
export function readablePointer(pointer: string): string {
if (!pointer) return 'the file';
return pointer
.split('/')
.slice(1)
.map((part) => (/^\d+$/.test(part) ? `[${part}]` : `.${part.replace(/~1/g, '/').replace(/~0/g, '~')}`))
.join('')
.replace(/^\./, '');
}
function describe(e: ErrorObject): string {
const where = readablePointer(e.instancePath);
const params = e.params as Record<string, unknown>;
switch (e.keyword) {
case 'additionalProperties':
return `Unknown key "${params.additionalProperty}" in ${where}.`;
case 'required':
return `"${params.missingProperty}" is required in ${where}.`;
case 'enum':
return `${where} must be one of: ${(params.allowedValues as unknown[]).join(', ')}.`;
case 'const':
return `${where} must be ${JSON.stringify(params.allowedValue)}.`;
case 'type': {
const type = String(params.type);
return `${where} must be ${type === 'array' ? 'a list' : type === 'object' ? 'a mapping' : `a ${type}`}.`;
}
case 'minItems':
case 'maxItems': {
const limit = Number(params.limit);
return `${where} needs ${e.keyword === 'minItems' ? 'at least' : 'at most'} ${limit} item${limit === 1 ? '' : 's'}.`;
}
case 'propertyNames':
return `"${params.propertyName}" in ${where} is not a valid id: start with a letter; letters, digits, - and _ after.`;
default:
return `${where} ${e.message ?? 'is not valid'}.`;
}
}
function keyText(key: unknown): string {
return isScalar(key) ? String(key.value) : String(key);
}
/** The node an error is about: the offending key for unknown keys, else the value. */
function rangeFor(root: Node | null, error: ErrorObject, length: number): [number, number] {
const parts = error.instancePath.split('/').slice(1).map((p) => p.replace(/~1/g, '/').replace(/~0/g, '~'));
let node: unknown = root;
let keyNode: Node | null = null;
for (const part of parts) {
if (isMap(node)) {
const pair = node.items.find((p) => keyText(p.key) === part);
if (!pair) break;
keyNode = pair.key as Node;
node = pair.value;
} else if (isSeq(node)) {
keyNode = null;
node = node.items[Number(part)];
} else break;
}
const params = error.params as Record<string, unknown>;
const extra = params.additionalProperty ?? params.propertyName;
if (extra !== undefined && isMap(node)) {
const pair = node.items.find((p) => keyText(p.key) === String(extra));
const range = (pair?.key as Node | undefined)?.range;
if (range) return [range[0], range[1]];
}
if (error.keyword === 'required' && keyNode?.range) return [keyNode.range[0], keyNode.range[1]];
const target = (node as Node | undefined)?.range ? (node as Node) : keyNode;
if (!target?.range) return [0, Math.min(1, length)];
// A block mapping or list spans many lines; mark its first character only.
if ((isMap(target) || isSeq(target)) && !target.flow) return [target.range[0], target.range[0] + 1];
return [target.range[0], Math.max(target.range[1], target.range[0] + 1)];
}
+185
View File
@@ -0,0 +1,185 @@
import { LineCounter, isMap, isScalar, isSeq, parseDocument } from 'yaml';
import { ModelProblem, Registry } from './format';
/**
* Architecture decisions of a model (see docs/model.md): one
* `*.archify-decision` file per decision, anywhere under the model root.
* Pure functions, no VS Code imports.
*/
export const DECISION_EXT = '.archify-decision';
export const DECISION_STATUSES = ['proposed', 'accepted', 'superseded', 'rejected'] as const;
export type DecisionStatus = (typeof DECISION_STATUSES)[number];
export interface Decision {
id: string;
title?: string;
status?: string;
date?: string;
/** Registry element ids the decision is about. */
elements: string[];
/** Diagram paths (relative to the model root) the decision names. */
diagrams: string[];
/** Ids of older decisions this one replaces. */
supersedes: string[];
context?: string;
decision?: string;
consequences?: string;
/** Decision file relative to the model root, and 0-based lines for diagnostics. */
file: string;
line: number;
lines: { id: number; status: number; elements: number[]; diagrams: number[]; supersedes: number[] };
}
export function isDecisionFile(fileName: string): boolean {
return fileName.endsWith(DECISION_EXT);
}
const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim().length > 0 ? v : v !== undefined && v !== null && typeof v !== 'object' ? String(v) : undefined);
/** "OpenSearch for product search" → "opensearch-for-product-search". */
export function slugify(title: string): string {
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
return slug || 'decision';
}
/** Parses one decision file. Problems carry 0-based lines. */
export function parseDecision(text: string, file: string): { decision?: Decision; problems: ModelProblem[] } {
const problems: ModelProblem[] = [];
// prettyErrors would put line numbers into the messages; the line counter gives them without.
const lines = new LineCounter();
const doc = parseDocument(text, { prettyErrors: false, uniqueKeys: false, lineCounter: lines });
for (const error of doc.errors) {
problems.push({ message: `Decision is not valid YAML: ${error.message.split('\n')[0]}`, severity: 'error', file, line: lines.linePos(error.pos[0]).line - 1 });
}
if (doc.errors.length) return { problems };
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
const root = doc.contents;
if (!isMap(root)) {
problems.push({ message: 'A decision file is a mapping with a "decision" block and context, decision and consequences.', severity: 'error', file, line: 0 });
return { problems };
}
const headNode = root.get('decision', true);
if (!isMap(headNode)) {
problems.push({ message: 'A decision needs a "decision" block with id, title and status.', severity: 'error', file, line: 0, pointer: '/decision' });
return { problems };
}
const headPair = root.items.find((pair) => isScalar(pair.key) && pair.key.value === 'decision');
const headLine = headPair && isScalar(headPair.key) ? lineOf(headPair.key.range?.[0]) : 0;
const keyLine = (key: string) => {
const pair = headNode.items.find((p) => isScalar(p.key) && p.key.value === key);
return pair && isScalar(pair.key) ? lineOf(pair.key.range?.[0]) : headLine;
};
const list = (key: string): { values: string[]; lines: number[] } => {
const node = headNode.get(key, true);
const values: string[] = [];
const lines: number[] = [];
if (isSeq(node)) {
for (const item of node.items) {
if (!isScalar(item)) continue;
if (typeof item.value === 'number') {
problems.push({ message: `"${item.value}" in ${key} is a number to YAML. Quote it or use words.`, severity: 'error', file, line: lineOf(item.range?.[0]), pointer: `/decision/${key}` });
continue;
}
if (str(item.value)) {
values.push(String(item.value));
lines.push(lineOf(item.range?.[0]));
}
}
} else if (node !== undefined) {
problems.push({ message: `"${key}" must be a list.`, severity: 'error', file, line: keyLine(key), pointer: `/decision/${key}` });
}
return { values, lines };
};
const head = headNode.toJSON() as Record<string, unknown>;
if (typeof head.id === 'number') {
problems.push({ message: `decision.id ${head.id} is a number to YAML (0001 becomes 1). Quote it ("${head.id}") or use words.`, severity: 'error', file, line: keyLine('id'), pointer: '/decision/id' });
return { problems };
}
const id = str(head.id);
if (!id) {
problems.push({ message: 'decision.id is missing.', severity: 'error', file, line: headLine, pointer: '/decision/id' });
return { problems };
}
const status = str(head.status);
if (status && !(DECISION_STATUSES as readonly string[]).includes(status)) {
problems.push({ message: `Unknown status "${status}"; one of ${DECISION_STATUSES.join(', ')}.`, severity: 'error', file, line: keyLine('status'), pointer: '/decision/status' });
}
const elements = list('elements');
const diagrams = list('diagrams');
const supersedes = list('supersedes');
const body = root.toJSON() as Record<string, unknown>;
return {
problems,
decision: {
id,
title: str(head.title),
status,
date: str(head.date),
elements: elements.values,
diagrams: diagrams.values,
supersedes: supersedes.values,
context: str(body.context),
decision: str(body.decision),
consequences: str(body.consequences),
file,
line: headLine,
lines: { id: keyLine('id'), status: keyLine('status'), elements: elements.lines, diagrams: diagrams.lines, supersedes: supersedes.lines },
},
};
}
export interface DecisionSet {
decisions: Map<string, Decision>;
files: string[];
problems: ModelProblem[];
}
/** Merges parsed decision files; an id used twice is an error on the second file. */
export function mergeDecisions(parts: { file: string; decision?: Decision; problems: ModelProblem[] }[]): DecisionSet {
const decisions = new Map<string, Decision>();
const problems: ModelProblem[] = [];
for (const part of parts) {
problems.push(...part.problems);
if (!part.decision) continue;
const existing = decisions.get(part.decision.id);
if (existing) {
problems.push({ message: `Decision "${part.decision.id}" is defined twice (also in ${existing.file}).`, severity: 'error', file: part.file, line: part.decision.lines.id });
continue;
}
decisions.set(part.decision.id, part.decision);
}
return { decisions, files: parts.map((p) => p.file), problems };
}
/** The status the pages show: a decision another one supersedes is superseded, whatever its file says. */
export function effectiveStatus(decision: Decision, all: Map<string, Decision>): { status: string; supersededBy?: string } {
for (const other of all.values()) {
if (other !== decision && other.supersedes.includes(decision.id) && other.status !== 'rejected') return { status: 'superseded', supersededBy: other.id };
}
return { status: decision.status ?? 'proposed' };
}
/** Link checks across the model: elements, diagrams and supersedes must exist. */
export function validateDecisions(set: DecisionSet, registry: Registry | undefined, diagramPaths: Set<string>): ModelProblem[] {
const problems: ModelProblem[] = [];
for (const d of set.decisions.values()) {
d.elements.forEach((id, i) => {
if (!registry?.elements.has(id)) problems.push({ message: `Unknown element "${id}": no registry of this model defines it.`, severity: 'error', file: d.file, line: d.lines.elements[i], pointer: `/decision/elements/${i}` });
});
d.diagrams.forEach((path, i) => {
if (!diagramPaths.has(path)) problems.push({ message: `Diagram "${path}" does not exist in this model.`, severity: 'error', file: d.file, line: d.lines.diagrams[i], pointer: `/decision/diagrams/${i}` });
});
d.supersedes.forEach((id, i) => {
if (!set.decisions.has(id)) problems.push({ message: `Decision "${id}" (in supersedes) does not exist in this model.`, severity: 'error', file: d.file, line: d.lines.supersedes[i], pointer: `/decision/supersedes/${i}` });
else if (id === d.id) problems.push({ message: 'A decision cannot supersede itself.', severity: 'error', file: d.file, line: d.lines.supersedes[i], pointer: `/decision/supersedes/${i}` });
});
}
return problems;
}
/** Sort for lists: live decisions newest first, superseded and rejected last. */
export function sortDecisions(decisions: Decision[], all: Map<string, Decision>): Decision[] {
const rank = (d: Decision) => (['superseded', 'rejected'].includes(effectiveStatus(d, all).status) ? 1 : 0);
return [...decisions].sort((a, b) => rank(a) - rank(b) || (b.date ?? '').localeCompare(a.date ?? '') || a.id.localeCompare(b.id));
}
+131 -54
View File
@@ -1,4 +1,4 @@
import { isMap, isScalar, parseDocument, parse as parseYaml } from 'yaml';
import { LineCounter, isMap, isScalar, parse as parseYaml, parseDocument } from 'yaml';
/**
* The model file formats (see docs/model.md): `main.archify` with a `model`
@@ -55,42 +55,6 @@ export interface Registry {
problems: ModelProblem[];
}
/** Archify card dot colour for a component type (the colours Archify gives the nodes). */
const DOT_BY_TYPE: Record<string, string> = {
frontend: 'cyan',
backend: 'emerald',
database: 'violet',
cloud: 'amber',
security: 'rose',
messagebus: 'orange',
external: 'slate',
};
export function dotForType(type?: string): string {
return DOT_BY_TYPE[type ?? ''] ?? 'slate';
}
export interface Card {
dot: string;
title: string;
items: string[];
}
/**
* Archify info cards for registry elements: one per element that has a
* description, titled by its label. What a diagram gets below itself when
* it draws shared elements and defines no cards of its own.
*/
export function cardsFromElements(elements: Iterable<RegistryElement>): Card[] {
const cards: Card[] = [];
for (const element of elements) {
if (!element.description) continue;
const items = [element.description.trim()];
cards.push({ dot: dotForType(element.type), title: element.label ?? element.id, items });
}
return cards;
}
export function isMainFile(fileName: string): boolean {
return (fileName.split(/[\\/]/).pop() ?? '') === MAIN_FILE;
}
@@ -119,9 +83,11 @@ export function hasDiagramBody(doc: unknown): boolean {
export function parseRegistry(text: string, file: string): { elements: RegistryElement[]; problems: ModelProblem[] } {
const problems: ModelProblem[] = [];
const elements: RegistryElement[] = [];
const doc = parseDocument(text, { prettyErrors: false, uniqueKeys: false });
// prettyErrors would put line numbers into the messages; the line counter gives them without.
const lines = new LineCounter();
const doc = parseDocument(text, { prettyErrors: false, uniqueKeys: false, lineCounter: lines });
for (const error of doc.errors) {
problems.push({ message: `Registry is not valid YAML: ${error.message.split('\n')[0]}`, severity: 'error', file, line: error.linePos?.[0].line ? error.linePos[0].line - 1 : 0 });
problems.push({ message: `Registry is not valid YAML: ${error.message.split('\n')[0]}`, severity: 'error', file, line: lines.linePos(error.pos[0]).line - 1 });
}
if (doc.errors.length) return { elements, problems };
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
@@ -186,6 +152,19 @@ export function mergeRegistries(parts: { elements: RegistryElement[]; problems:
return { elements, files: parts.map((p) => p.file), problems };
}
/** Where a diagram attaches a decision: the diagram itself, a node or an edge. */
export type DecisionAttachment = { kind: 'diagram' } | { kind: 'node'; id: string } | { kind: 'edge'; from: string; to: string; label?: string };
export interface DecisionRef {
id: string;
pointer: string;
attachedTo: DecisionAttachment;
}
/** Collections whose items may carry `decisions` (and `diagram` links), per diagram kind. */
const NODE_COLLECTIONS = ['components', 'nodes', 'participants', 'states'] as const;
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'] as const;
export interface ResolvedDiagram {
/** The diagram as Archify expects it: refs expanded, model block and links removed. */
diagram: Obj;
@@ -196,32 +175,86 @@ export interface ResolvedDiagram {
links: Map<string, string>;
/** Registry element ids used by this diagram. */
used: Set<string>;
/** Node id → registry description, for the Elements panel. */
descriptions: Map<string, string>;
/** Decisions the diagram points at, with where they are attached. */
decisionRefs: DecisionRef[];
}
export interface ResolveOptions {
/** Undefined when the diagram is not inside a model. */
registry?: Registry;
/** Known decision ids of the model; undefined outside a model or when unknown. */
decisions?: Set<string>;
fileName: string;
}
/** Strips `decisions` keys from a diagram and collects what they point at. Mutates `diagram`. */
function takeDecisionRefs(diagram: Obj, options: ResolveOptions, problems: ModelProblem[]): DecisionRef[] {
const refs: DecisionRef[] = [];
const take = (owner: Obj, pointer: string, attachedTo: DecisionAttachment) => {
if (!('decisions' in owner)) return;
const raw = owner.decisions;
delete owner.decisions;
const ids = Array.isArray(raw) ? raw : [raw];
ids.forEach((value, i) => {
const id = value === undefined || value === null ? undefined : String(value);
if (!id) return;
const at = `${pointer}/decisions/${i}`;
if (typeof value === 'number') {
problems.push({ message: `Decision id ${value} is a number to YAML (0001 becomes 1). Quote it ("${value}") or use words.`, severity: 'error', pointer: at });
return;
}
if (!options.registry) {
problems.push({ message: `Decision "${id}" cannot be resolved: ${options.fileName.split(/[\\/]/).pop()} is not inside a model (no ${MAIN_FILE} above it).`, severity: 'error', pointer: at });
} else if (options.decisions && !options.decisions.has(id)) {
problems.push({ message: `Unknown decision "${id}": no .archify-decision file of this model defines it.`, severity: 'error', pointer: at });
}
refs.push({ id, pointer: at, attachedTo });
});
};
take(diagram, '', { kind: 'diagram' });
for (const key of NODE_COLLECTIONS) {
const items = diagram[key];
if (!Array.isArray(items)) continue;
diagram[key] = items.map((item, index) => {
if (!isObj(item)) return item;
const copy = { ...item };
take(copy, `/${key}/${index}`, { kind: 'node', id: str(copy.id) ?? str(copy.ref) ?? String(index) });
return copy;
});
}
for (const key of EDGE_COLLECTIONS) {
const items = diagram[key];
if (!Array.isArray(items)) continue;
diagram[key] = items.map((item, index) => {
if (!isObj(item)) return item;
const copy = { ...item };
take(copy, `/${key}/${index}`, { kind: 'edge', from: str(copy.from) ?? '', to: str(copy.to) ?? '', label: str(copy.label) });
return copy;
});
}
return refs;
}
/**
* Expands `ref` components from the registry and strips what Archify does
* not know. Component order and indexes are kept, so Archify's diagnostics
* (JSON pointers) still point at the right component in the source file.
* A diagram without `cards` of its own gets cards from the descriptions of
* the shared elements it draws, so the registry text shows under the diagram.
*/
export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiagram {
const problems: ModelProblem[] = [];
const refs = new Map<number, RegistryElement>();
const links = new Map<string, string>();
const used = new Set<string>();
if (!isObj(doc)) return { diagram: {}, problems, refs, links, used };
const descriptions = new Map<string, string>();
if (!isObj(doc)) return { diagram: {}, problems, refs, links, used, descriptions, decisionRefs: [] };
const diagram: Obj = { ...doc };
delete diagram.model;
const decisionRefs = takeDecisionRefs(diagram, options, problems);
const { registry } = options;
const components = Array.isArray(doc.components) ? doc.components : undefined;
if (!components) return { diagram, problems, refs, links, used };
const components = Array.isArray(diagram.components) ? diagram.components : undefined;
if (!components) return { diagram, problems, refs, links, used, descriptions, decisionRefs };
diagram.components = components.map((raw, index) => {
if (!isObj(raw)) return raw;
@@ -248,6 +281,7 @@ export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiag
}
used.add(ref);
refs.set(index, element);
if (element.description) descriptions.set(id, element.description.trim());
for (const key of Object.keys(own)) {
if ((COPIED_FIELDS as readonly string[]).includes(key) && !(OVERRIDABLE_FIELDS as readonly string[]).includes(key)) {
problems.push({
@@ -267,14 +301,7 @@ export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiag
if (link) links.set(id, link);
return merged;
});
if (diagram.cards === undefined && refs.size) {
const seen = new Set<string>();
const elements: RegistryElement[] = [];
for (const element of refs.values()) if (!seen.has(element.id)) { seen.add(element.id); elements.push(element); }
const cards = cardsFromElements(elements);
if (cards.length) diagram.cards = cards;
}
return { diagram, problems, refs, links, used };
return { diagram, problems, refs, links, used, descriptions, decisionRefs };
}
/** Group of a diagram inside a model: '' for the root folder, else the folder path with '/' separators. */
@@ -284,12 +311,35 @@ export function groupOf(relativePath: string): string {
return parts.join('/');
}
/** A node as a diagram declares it: a `ref` to the registry, or an inline element. */
export interface DiagramNode {
id: string;
ref?: string;
type?: string;
label?: string;
sublabel?: string;
brand?: string;
}
/** A connection, edge, flow, transition or message between two nodes of a diagram. */
export interface DiagramEdge {
from: string;
to: string;
label?: string;
}
export interface DiagramSummary {
relativePath: string;
group: string;
kind?: string;
title?: string;
used: string[];
/** Decisions the diagram points at. */
decisions: DecisionRef[];
/** Every node the diagram draws, shared or inline, in file order. */
nodes: DiagramNode[];
/** Every edge between two of those nodes. */
edges: DiagramEdge[];
parseError?: string;
}
@@ -299,13 +349,40 @@ export function summarizeDiagram(text: string, relativePath: string): DiagramSum
try {
doc = parseYaml(text, { prettyErrors: false, uniqueKeys: false });
} catch (error) {
return { relativePath, group: groupOf(relativePath), used: [], parseError: error instanceof Error ? error.message.split('\n')[0] : String(error) };
return { relativePath, group: groupOf(relativePath), used: [], decisions: [], nodes: [], edges: [], parseError: error instanceof Error ? error.message.split('\n')[0] : String(error) };
}
const obj = isObj(doc) ? doc : {};
const meta = isObj(obj.meta) ? obj.meta : {};
const components = Array.isArray(obj.components) ? obj.components : [];
const used = [...new Set(components.map((c) => (isObj(c) ? str(c.ref) : undefined)).filter((r): r is string => !!r))];
return { relativePath, group: groupOf(relativePath), kind: str(obj.diagram_type), title: str(meta.title), used };
const decisions = takeDecisionRefs({ ...obj }, { registry: { elements: new Map(), files: [], problems: [] }, fileName: relativePath }, []);
const nodes: DiagramNode[] = [];
const seen = new Set<string>();
for (const key of NODE_COLLECTIONS) {
const items = obj[key];
if (!Array.isArray(items)) continue;
for (const item of items) {
if (!isObj(item)) continue;
const ref = str(item.ref);
const id = str(item.id) ?? ref;
if (!id || seen.has(id)) continue;
seen.add(id);
nodes.push({ id, ref, type: str(item.type), label: str(item.label), sublabel: str(item.sublabel), brand: str(item.brand) });
}
}
const edges: DiagramEdge[] = [];
for (const key of EDGE_COLLECTIONS) {
const items = obj[key];
if (!Array.isArray(items)) continue;
for (const item of items) {
if (!isObj(item)) continue;
const from = str(item.from);
const to = str(item.to);
if (!from || !to || !seen.has(from) || !seen.has(to)) continue;
edges.push({ from, to, label: str(item.label) });
}
}
return { relativePath, group: groupOf(relativePath), kind: str(obj.diagram_type), title: str(meta.title), used, decisions, nodes, edges };
}
/** Groups in display order: the root group first, then folders in path order. */
+196
View File
@@ -0,0 +1,196 @@
import { Decision, DecisionSet, effectiveStatus } from './decisions';
import { DecisionAttachment, DiagramSummary, ModelMeta, Registry } from './format';
/**
* The model as one graph: every element any diagram draws (and every registry
* element, drawn or not), every connection any diagram has between two of
* them, each once. Pure: built from the model index, no VS Code imports, so
* the webview bundle and the unit tests share it.
*/
export type GraphNodeKind = 'element' | 'decision' | 'registry';
export type GraphEdgeKind = 'connection' | 'decides' | 'defines' | 'supersedes';
export interface GraphNode {
id: string;
/** An element of the model, a decision (`decision:<id>`) or a registry file (`registry:<file>`). */
kind: GraphNodeKind;
label: string;
sublabel?: string;
type?: string;
brand?: string;
/** Defined in a registry (true) or inline in one diagram (false). */
shared: boolean;
description?: string;
/** Registry file and 0-based line, for shared elements. */
file?: string;
line?: number;
/** Diagram that explains the element, relative to the model root. */
link?: string;
/** Diagrams that draw it, relative paths in path order. */
diagrams: string[];
/** Decisions about it: named by the decision, or attached to its node in a diagram. */
decisions: string[];
/** Decision nodes: the effective status. */
status?: string;
/** Registry nodes: ids of the elements the file defines. */
elements?: string[];
}
export interface GraphEdge {
/** `from>to`, unique in the graph. */
id: string;
/** A connection drawn by a diagram, or a link to a decision or registry node. */
kind: GraphEdgeKind;
from: string;
to: string;
/** Distinct labels the diagrams give this connection. */
labels: string[];
diagrams: string[];
decisions: string[];
}
export interface GraphDecision {
id: string;
title?: string;
status: string;
file: string;
}
export interface GraphDiagram {
path: string;
title?: string;
kind?: string;
}
export interface ModelGraph {
meta: ModelMeta;
nodes: GraphNode[];
edges: GraphEdge[];
decisions: GraphDecision[];
diagrams: GraphDiagram[];
}
export interface GraphInput {
meta: ModelMeta;
registry: Registry;
diagrams: DiagramSummary[];
decisions: DecisionSet;
decisionUsage: Map<string, { path: string; attachedTo: DecisionAttachment }[]>;
}
export const edgeId = (from: string, to: string): string => `${from}>${to}`;
export const decisionNodeId = (id: string): string => `decision:${id}`;
export const registryNodeId = (file: string): string => `registry:${file}`;
function pushUnique(list: string[], value: string): void {
if (!list.includes(value)) list.push(value);
}
export function buildGraph(input: GraphInput): ModelGraph {
const nodes = new Map<string, GraphNode>();
const edges = new Map<string, GraphEdge>();
// Registry elements first: shared, and present even when no diagram draws them yet.
for (const e of input.registry.elements.values()) {
nodes.set(e.id, {
id: e.id,
kind: 'element',
label: e.label ?? e.id,
sublabel: e.sublabel,
type: e.type,
brand: e.brand,
shared: true,
description: e.description?.trim() || undefined,
file: e.file,
line: e.line,
link: e.diagram,
diagrams: [],
decisions: [],
});
}
const diagrams = [...input.diagrams].filter((d) => !d.parseError).sort((a, b) => a.relativePath.localeCompare(b.relativePath));
for (const d of diagrams) {
for (const n of d.nodes) {
let node = nodes.get(n.id);
if (!node) {
const element = n.ref ? input.registry.elements.get(n.ref) : undefined;
node = element
? { ...nodes.get(element.id)!, id: n.id, label: n.label ?? element.label ?? n.id, sublabel: n.sublabel ?? element.sublabel, diagrams: [], decisions: [] }
: { id: n.id, kind: 'element', label: n.label ?? n.ref ?? n.id, sublabel: n.sublabel, type: n.type, brand: n.brand, shared: false, diagrams: [], decisions: [] };
nodes.set(n.id, node);
}
pushUnique(node.diagrams, d.relativePath);
}
for (const e of d.edges) {
const id = edgeId(e.from, e.to);
let edge = edges.get(id);
if (!edge) {
edge = { id, kind: 'connection', from: e.from, to: e.to, labels: [], diagrams: [], decisions: [] };
edges.set(id, edge);
}
if (e.label) pushUnique(edge.labels, e.label);
pushUnique(edge.diagrams, d.relativePath);
}
}
const all = input.decisions.decisions;
for (const d of all.values()) for (const id of d.elements) nodes.get(id)?.decisions && pushUnique(nodes.get(id)!.decisions, d.id);
for (const [decisionId, uses] of input.decisionUsage) {
if (!all.has(decisionId)) continue;
for (const use of uses) {
if (use.attachedTo.kind === 'node') {
const node = nodes.get(use.attachedTo.id);
if (node) pushUnique(node.decisions, decisionId);
} else if (use.attachedTo.kind === 'edge') {
const edge = edges.get(edgeId(use.attachedTo.from, use.attachedTo.to));
if (edge) pushUnique(edge.decisions, decisionId);
}
}
}
const decisionRow = (d: Decision): GraphDecision => ({ id: d.id, title: d.title, status: effectiveStatus(d, all).status, file: d.file });
// Registry files as nodes, each linked to the elements it defines.
const byFile = new Map<string, string[]>();
for (const e of input.registry.elements.values()) byFile.set(e.file, [...(byFile.get(e.file) ?? []), e.id]);
for (const file of input.registry.files) if (!byFile.has(file)) byFile.set(file, []);
for (const [file, ids] of byFile) {
const id = registryNodeId(file);
nodes.set(id, { id, kind: 'registry', label: file.replace(/\.archify-registry$/, ''), type: 'registry', shared: true, file, diagrams: [], decisions: [], elements: ids });
for (const element of ids) {
const edge = edgeId(id, element);
edges.set(edge, { id: edge, kind: 'defines', from: id, to: element, labels: [], diagrams: [], decisions: [] });
}
}
// Decisions as nodes, linked to the elements and connections they are about, and to what they supersede.
for (const d of all.values()) {
const id = decisionNodeId(d.id);
const row = decisionRow(d);
nodes.set(id, { id, kind: 'decision', label: d.title ?? d.id, sublabel: d.id, type: 'decision', shared: true, description: [d.context, d.decision].filter(Boolean).join('\n\n') || undefined, file: d.file, line: 0, diagrams: [...d.diagrams], decisions: [], status: row.status });
}
for (const node of [...nodes.values()]) {
if (node.kind !== 'element') continue;
for (const decision of node.decisions) {
if (!all.has(decision)) continue;
const edge = edgeId(decisionNodeId(decision), node.id);
edges.set(edge, { id: edge, kind: 'decides', from: decisionNodeId(decision), to: node.id, labels: [], diagrams: [], decisions: [] });
}
}
for (const d of all.values()) {
for (const other of d.supersedes) {
if (!all.has(other)) continue;
const edge = edgeId(decisionNodeId(d.id), decisionNodeId(other));
edges.set(edge, { id: edge, kind: 'supersedes', from: decisionNodeId(d.id), to: decisionNodeId(other), labels: ['supersedes'], diagrams: [], decisions: [] });
}
}
return {
meta: input.meta,
nodes: [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id)),
edges: [...edges.values()].sort((a, b) => a.id.localeCompare(b.id)),
decisions: [...all.values()].map(decisionRow).sort((a, b) => a.id.localeCompare(b.id)),
diagrams: diagrams.map((d) => ({ path: d.relativePath, title: d.title, kind: d.kind })),
};
}
+251
View File
@@ -0,0 +1,251 @@
import { GraphEdge, GraphNode, ModelGraph } from './graph';
/**
* The graph page's query box. A few words, no language to learn: terms are
* ANDed, a leading `-` excludes, `key:value` terms filter by a field or walk
* the graph. Pure, shared by the webview bundle and the unit tests.
*
* database label, id, sublabel, brand or type contain it
* type:backend elements of that type
* diagram:0200-* drawn by a diagram whose path matches (glob)
* decision:<id> what the decision is about or attached to
* uses:api api and its neighbours
* near:api,2 api and everything within two steps
* from:web to:db the shortest path between two elements
* unused registry elements no diagram draws
* shared / -shared registry elements / inline elements
*/
export interface QueryTerm {
key: string;
value: string;
negate: boolean;
}
export interface QueryResult {
/** Ids of the elements that match. Every element when the query is empty. */
nodes: Set<string>;
/** Ids of the connections shown: both ends match, or the path found. */
edges: Set<string>;
/** The path found by `from: to:`, in order. */
path?: string[];
/** Why the result is empty or partial, when it is. */
message?: string;
terms: QueryTerm[];
}
const WALK_KEYS = new Set(['uses', 'near', 'from', 'to']);
const FIELD_KEYS = new Set(['type', 'diagram', 'decision', 'shared', 'unused', 'text']);
export function parseQuery(text: string): QueryTerm[] {
const tokens = text.trim().split(/\s+/).filter(Boolean);
const terms: QueryTerm[] = [];
for (let i = 0; i < tokens.length; i += 1) {
let token = tokens[i];
const negate = token.startsWith('-') && token.length > 1;
if (negate) token = token.slice(1);
const colon = token.indexOf(':');
let key = colon > 0 ? token.slice(0, colon).toLowerCase() : token.toLowerCase();
let value = colon > 0 ? token.slice(colon + 1) : '';
if (colon > 0 && !WALK_KEYS.has(key) && !FIELD_KEYS.has(key)) {
key = 'text';
value = token;
} else if (colon < 0 && key !== 'shared' && key !== 'unused') {
key = 'text';
value = token;
}
// `near:api 2` is also accepted: a bare number after near is the hop count.
if (key === 'near' && !value.includes(',') && /^\d+$/.test(tokens[i + 1] ?? '')) {
value = `${value},${tokens[i + 1]}`;
i += 1;
}
if (!value && key === 'text') continue;
terms.push({ key, value, negate });
}
return terms;
}
const lower = (s: string | undefined) => (s ?? '').toLowerCase();
const isElement = (n: GraphNode) => n.kind === 'element';
const isConnection = (e: GraphEdge) => e.kind === 'connection';
/** An element by id, then by id or label ignoring case. Decision and registry nodes are not walked from. */
export function findNode(graph: ModelGraph, ref: string): GraphNode | undefined {
const elements = graph.nodes.filter(isElement);
const exact = elements.find((n) => n.id === ref);
if (exact) return exact;
const l = ref.toLowerCase();
return elements.find((n) => n.id.toLowerCase() === l) ?? elements.find((n) => n.label.toLowerCase() === l);
}
function globToRegExp(pattern: string): RegExp {
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
return new RegExp(`^${escaped}$`, 'i');
}
function diagramMatches(path: string, pattern: string): boolean {
const bare = path.replace(/\.archify$/, '');
const wanted = pattern.replace(/\.archify$/, '');
if (wanted.includes('*') || wanted.includes('?')) return globToRegExp(wanted).test(bare) || globToRegExp(wanted).test(path);
const l = wanted.toLowerCase();
return bare.toLowerCase() === l || bare.toLowerCase().startsWith(`${l}/`) || bare.toLowerCase().startsWith(l) || bare.toLowerCase().includes(`/${l}`);
}
/** Element-to-element adjacency over the diagrams' connections; decision and registry links do not count as steps. */
function neighbours(graph: ModelGraph): Map<string, Set<string>> {
const map = new Map<string, Set<string>>();
for (const n of graph.nodes) map.set(n.id, new Set());
for (const e of graph.edges.filter(isConnection)) {
map.get(e.from)?.add(e.to);
map.get(e.to)?.add(e.from);
}
return map;
}
function within(graph: ModelGraph, start: string, hops: number): Set<string> {
const adjacency = neighbours(graph);
let frontier = new Set([start]);
const seen = new Set([start]);
for (let i = 0; i < hops; i += 1) {
const next = new Set<string>();
for (const id of frontier) for (const other of adjacency.get(id) ?? []) if (!seen.has(other)) { seen.add(other); next.add(other); }
frontier = next;
if (!frontier.size) break;
}
return seen;
}
/** Shortest path by breadth-first search; directed first, then ignoring direction. */
export function shortestPath(graph: ModelGraph, from: string, to: string): { nodes: string[]; edges: string[] } | undefined {
const attempt = (directed: boolean) => {
const out = new Map<string, { to: string; edge: GraphEdge }[]>();
for (const n of graph.nodes) out.set(n.id, []);
for (const e of graph.edges.filter(isConnection)) {
out.get(e.from)?.push({ to: e.to, edge: e });
if (!directed) out.get(e.to)?.push({ to: e.from, edge: e });
}
const previous = new Map<string, { from: string; edge: GraphEdge }>();
const queue = [from];
const seen = new Set([from]);
while (queue.length) {
const id = queue.shift()!;
if (id === to) break;
for (const step of out.get(id) ?? []) {
if (seen.has(step.to)) continue;
seen.add(step.to);
previous.set(step.to, { from: id, edge: step.edge });
queue.push(step.to);
}
}
if (!seen.has(to)) return undefined;
const nodes = [to];
const edges: string[] = [];
let at = to;
while (at !== from) {
const step = previous.get(at)!;
edges.unshift(step.edge.id);
nodes.unshift(step.from);
at = step.from;
}
return { nodes, edges };
};
if (from === to) return { nodes: [from], edges: [] };
return attempt(true) ?? attempt(false);
}
export function runQuery(graph: ModelGraph, text: string): QueryResult {
const terms = parseQuery(text);
const everything = new Set(graph.nodes.map((n) => n.id));
let result = new Set(everything);
const notes: string[] = [];
let from: string | undefined;
let to: string | undefined;
let pathEdges: Set<string> | undefined;
let path: string[] | undefined;
const matching = (term: QueryTerm): Set<string> | undefined => {
const v = term.value;
switch (term.key) {
case 'text': {
const l = v.toLowerCase();
return new Set(graph.nodes.filter((n) => [n.id, n.label, n.sublabel, n.brand, n.type].some((f) => lower(f).includes(l))).map((n) => n.id));
}
case 'type':
return new Set(graph.nodes.filter((n) => lower(n.type) === v.toLowerCase()).map((n) => n.id));
case 'diagram':
return new Set(graph.nodes.filter((n) => n.diagrams.some((d) => diagramMatches(d, v))).map((n) => n.id));
case 'decision': {
const ids = new Set(graph.nodes.filter((n) => n.decisions.includes(v)).map((n) => n.id));
for (const e of graph.edges) if (e.decisions.includes(v)) { ids.add(e.from); ids.add(e.to); }
if (!graph.decisions.some((d) => d.id === v)) notes.push(`No decision "${v}" in this model.`);
else ids.add(`decision:${v}`);
return ids;
}
case 'shared':
return new Set(graph.nodes.filter((n) => isElement(n) && n.shared).map((n) => n.id));
case 'unused':
return new Set(graph.nodes.filter((n) => isElement(n) && n.shared && n.diagrams.length === 0).map((n) => n.id));
case 'uses':
case 'near': {
const [ref, hopsText] = term.key === 'near' ? v.split(',') : [v, '1'];
const node = findNode(graph, ref);
if (!node) { notes.push(`No element "${ref}".`); return new Set(); }
const hops = Math.max(1, Math.min(Number(hopsText) || 1, 50));
return within(graph, node.id, hops);
}
case 'from':
from = v;
return undefined;
case 'to':
to = v;
return undefined;
}
return undefined;
};
const negated: Set<string>[] = [];
for (const term of terms) {
const ids = matching(term);
if (!ids) continue;
if (term.negate) {
negated.push(ids);
for (const id of ids) result.delete(id);
} else result = new Set([...result].filter((id) => ids.has(id)));
}
// Decisions and registries follow their elements: a matching element brings the nodes attached to it.
if (terms.length) {
for (const e of graph.edges) {
if (isConnection(e)) continue;
if (result.has(e.to) && graph.nodes.some((n) => n.id === e.from && !isElement(n))) result.add(e.from);
}
for (const ids of negated) for (const id of ids) result.delete(id);
}
if (from || to) {
if (!from || !to) notes.push('A path needs both from: and to:.');
else {
const a = findNode(graph, from);
const b = findNode(graph, to);
if (!a || !b) notes.push(`No element "${!a ? from : to}".`);
else {
const found = shortestPath(graph, a.id, b.id);
if (!found) notes.push(`No path from ${a.id} to ${b.id}.`);
else {
path = found.nodes;
pathEdges = new Set(found.edges);
result = new Set(found.nodes.filter((id) => result.has(id)));
}
}
if (!path) result = new Set();
}
}
const edges = new Set<string>();
for (const e of graph.edges) {
if (!result.has(e.from) || !result.has(e.to)) continue;
if (pathEdges && !pathEdges.has(e.id)) continue;
edges.add(e.id);
}
return { nodes: result, edges, path, message: notes[0], terms };
}
+89 -5
View File
@@ -1,6 +1,18 @@
import { DiagramSummary, RegistryElement } from './format';
import { Decision, effectiveStatus, sortDecisions } from './decisions';
import { DecisionAttachment, DiagramSummary, RegistryElement } from './format';
import { ModelIndex } from './service';
/** A decision as the lists show it. */
export interface DecisionRow {
id: string;
title?: string;
/** Status shown: superseded when another decision supersedes it. */
status: string;
supersededBy?: string;
date?: string;
file: string;
}
/** A diagram an element is used in, as the pages show it. */
export interface UsedIn {
path: string;
@@ -22,6 +34,8 @@ export interface ElementCard {
file: string;
line: number;
usedIn: UsedIn[];
/** Decisions about this element, from the decision files and from diagram attachments. */
decisions: DecisionRow[];
}
/** What the model page shows; serialised into the webview. */
@@ -31,10 +45,27 @@ export interface ModelPanel {
hasDiagram: boolean;
groups: { group: string; diagrams: { path: string; title?: string; kind?: string; parseError?: string }[] }[];
registry: ElementCard[];
decisions: DecisionRow[];
problems: string[];
nested: string[];
}
/** What the decision page (one .archify-decision file) shows. */
export interface DecisionPanel {
file: string;
inModel: boolean;
model?: { id?: string; name?: string };
decision?: DecisionRow & { context?: string; decision?: string; consequences?: string; supersedes: DecisionRow[] };
/** Decisions that supersede this one. */
supersededBy: DecisionRow[];
elements: ElementCard[];
/** Diagrams the decision names. */
diagrams: UsedIn[];
/** Diagrams that point at the decision, with where. */
referencedBy: { path: string; title?: string; kind?: string; attachedTo: DecisionAttachment }[];
problems: string[];
}
/** What the registry page (one .archify-registry file) shows. */
export interface RegistryPanel {
/** The registry file, relative to the model root (or its base name outside a model). */
@@ -52,7 +83,22 @@ function usedIn(id: string, usage: Map<string, string[]>, diagrams: DiagramSumma
});
}
export function elementCard(e: RegistryElement, usage: Map<string, string[]>, diagrams: DiagramSummary[]): ElementCard {
export function decisionRow(d: Decision, all: Map<string, Decision>): DecisionRow {
const { status, supersededBy } = effectiveStatus(d, all);
return { id: d.id, title: d.title, status, supersededBy, date: d.date, file: d.file };
}
/** Decisions about an element: named by the decision, or attached to its node in some diagram. */
function decisionsOfElement(id: string, index: Pick<ModelIndex, 'decisions' | 'decisionUsage'> | undefined): DecisionRow[] {
if (!index) return [];
const all = index.decisions.decisions;
const ids = new Set<string>();
for (const d of all.values()) if (d.elements.includes(id)) ids.add(d.id);
for (const [decisionId, uses] of index.decisionUsage) if (uses.some((u) => u.attachedTo.kind === 'node' && u.attachedTo.id === id) && all.has(decisionId)) ids.add(decisionId);
return sortDecisions([...ids].map((x) => all.get(x)!), all).map((d) => decisionRow(d, all));
}
export function elementCard(e: RegistryElement, usage: Map<string, string[]>, diagrams: DiagramSummary[], index?: Pick<ModelIndex, 'decisions' | 'decisionUsage'>): ElementCard {
return {
id: e.id,
label: e.label,
@@ -64,22 +110,25 @@ export function elementCard(e: RegistryElement, usage: Map<string, string[]>, di
file: e.file,
line: e.line,
usedIn: usedIn(e.id, usage, diagrams),
decisions: decisionsOfElement(e.id, index),
};
}
const byId = (a: { id: string }, b: { id: string }) => a.id.localeCompare(b.id);
export function panelFromIndex(index: ModelIndex): ModelPanel {
const registry = [...index.registry.elements.values()].sort(byId).map((e) => elementCard(e, index.usage, index.diagrams));
const registry = [...index.registry.elements.values()].sort(byId).map((e) => elementCard(e, index.usage, index.diagrams, index));
const all = index.decisions.decisions;
return {
meta: index.meta,
decisions: sortDecisions([...all.values()], all).map((d) => decisionRow(d, all)),
hasDiagram: index.mainHasDiagram,
groups: index.groups.map((g) => ({
group: g.group,
diagrams: g.diagrams.map((d) => ({ path: d.relativePath, title: d.title, kind: d.kind, parseError: d.parseError })),
})),
registry,
problems: index.registry.problems.map((p) => (p.file ? `${p.file}: ${p.message}` : p.message)),
problems: [...index.registry.problems, ...index.decisions.problems].map((p) => (p.file ? `${p.file}: ${p.message}` : p.message)),
nested: index.nested,
};
}
@@ -89,7 +138,7 @@ export function registryPanelFromIndex(index: ModelIndex, file: string): Registr
const elements = [...index.registry.elements.values()]
.filter((e) => e.file === file)
.sort((a, b) => a.line - b.line)
.map((e) => elementCard(e, index.usage, index.diagrams));
.map((e) => elementCard(e, index.usage, index.diagrams, index));
return {
file,
inModel: true,
@@ -108,3 +157,38 @@ export function registryPanelStandalone(file: string, parsed: { elements: Regist
problems: parsed.problems.map((p) => p.message),
};
}
/** The decision page of one file inside a model. */
export function decisionPanelFromIndex(index: ModelIndex, file: string): DecisionPanel {
const all = index.decisions.decisions;
const d = [...all.values()].find((x) => x.file === file);
const problems = index.decisions.problems.filter((p) => p.file === file).map((p) => p.message);
const base = { file, inModel: true, model: { id: index.meta.id, name: index.meta.name }, problems };
if (!d) return { ...base, supersededBy: [], elements: [], diagrams: [], referencedBy: [] };
const rows = (ids: string[]) => ids.filter((id) => all.has(id)).map((id) => decisionRow(all.get(id)!, all));
const elements = d.elements.filter((id) => index.registry.elements.has(id)).map((id) => elementCard(index.registry.elements.get(id)!, index.usage, index.diagrams, index));
const summary = (path: string) => index.diagrams.find((x) => x.relativePath === path);
return {
...base,
decision: { ...decisionRow(d, all), context: d.context, decision: d.decision, consequences: d.consequences, supersedes: rows(d.supersedes) },
supersededBy: [...all.values()].filter((x) => x.supersedes.includes(d.id)).map((x) => decisionRow(x, all)),
elements,
diagrams: d.diagrams.map((path) => ({ path, title: summary(path)?.title, kind: summary(path)?.kind })),
referencedBy: (index.decisionUsage.get(d.id) ?? []).map((u) => ({ path: u.path, title: summary(u.path)?.title, kind: summary(u.path)?.kind, attachedTo: u.attachedTo })),
};
}
/** The decision page of a file outside a model: the text only, and a note that it has lost its model. */
export function decisionPanelStandalone(file: string, parsed: { decision?: Decision; problems: { message: string }[] }): DecisionPanel {
const d = parsed.decision;
return {
file,
inModel: false,
decision: d ? { id: d.id, title: d.title, status: d.status ?? 'proposed', date: d.date, file, context: d.context, decision: d.decision, consequences: d.consequences, supersedes: d.supersedes.map((id) => ({ id, status: 'unknown', file: '' })) } : undefined,
supersededBy: [],
elements: [],
diagrams: d ? d.diagrams.map((path) => ({ path })) : [],
referencedBy: [],
problems: parsed.problems.map((p) => p.message),
};
}
+39 -5
View File
@@ -1,6 +1,8 @@
import path from 'node:path';
import * as vscode from 'vscode';
import { DiagramSource, readDiagramSource } from '../sources/detect';
import { ModelProblem, Registry, resolveRefs } from './format';
import { DecisionAttachment, ModelProblem, Registry, resolveRefs } from './format';
import { effectiveStatus } from './decisions';
import { ModelService } from './service';
/**
@@ -16,6 +18,18 @@ export interface PreparedDiagram {
problems: ModelProblem[];
/** Node id → diagram path relative to the model root. */
links: Map<string, string>;
/** Node id → registry description. */
descriptions: Map<string, string>;
/** Decisions of this diagram for the Decisions rail panel: pointed at by the diagram, or naming it. */
decisions: DiagramDecision[];
}
export interface DiagramDecision {
id: string;
title?: string;
status: string;
file: string;
attachedTo: DecisionAttachment[];
}
/**
@@ -26,12 +40,32 @@ export interface PreparedDiagram {
export async function prepareDiagram(models: ModelService, uri: vscode.Uri, text: string): Promise<PreparedDiagram | undefined> {
const source = readDiagramSource(text, uri.path);
if (!source) return undefined;
const found = await models.registryFor(uri);
const resolved = resolveRefs(source.diagram, { registry: found?.registry, fileName: uri.path });
const index = await models.indexFor(uri);
const found = index ? { root: index.root, registry: index.registry } : undefined;
const resolved = resolveRefs(source.diagram, { registry: found?.registry, decisions: index ? new Set(index.decisions.decisions.keys()) : undefined, fileName: uri.path });
// Only diagrams that use refs (or carry a model block) need the resolved form.
const changed = resolved.refs.size > 0 || resolved.problems.length > 0 || 'model' in source.diagram || resolved.links.size > 0;
const changed = resolved.refs.size > 0 || resolved.problems.length > 0 || 'model' in source.diagram || resolved.links.size > 0 || resolved.decisionRefs.length > 0;
const prepared: DiagramSource = changed
? { ...source, diagram: resolved.diagram, json: JSON.stringify(resolved.diagram, null, 2) }
: source;
return { source: prepared, root: found?.root, registry: found?.registry, problems: resolved.problems, links: resolved.links };
// Decisions for the rail: the ones this diagram points at, plus the ones that name this diagram.
const decisions: DiagramDecision[] = [];
if (index) {
const rel = path.relative(index.root.fsPath, uri.fsPath).split(path.sep).join('/');
const byId = new Map<string, DiagramDecision>();
const add = (id: string, attachedTo?: DecisionAttachment) => {
const d = index.decisions.decisions.get(id);
if (!d) return;
let row = byId.get(id);
if (!row) {
row = { id, title: d.title, status: effectiveStatus(d, index.decisions.decisions).status, file: d.file, attachedTo: [] };
byId.set(id, row);
decisions.push(row);
}
if (attachedTo && !row.attachedTo.some((a) => JSON.stringify(a) === JSON.stringify(attachedTo))) row.attachedTo.push(attachedTo);
};
for (const ref of resolved.decisionRefs) add(ref.id, ref.attachedTo);
for (const d of index.decisions.decisions.values()) if (d.diagrams.includes(rel)) add(d.id, { kind: 'diagram' });
}
return { source: prepared, root: found?.root, registry: found?.registry, problems: resolved.problems, links: resolved.links, descriptions: resolved.descriptions, decisions };
}
+27 -3
View File
@@ -2,6 +2,7 @@ import path from 'node:path';
import * as vscode from 'vscode';
import { log } from '../util/log';
import {
DecisionAttachment,
DiagramSummary,
MAIN_FILE,
ModelMeta,
@@ -17,6 +18,7 @@ import {
summarizeDiagram,
} from './format';
import { parse as parseYaml } from 'yaml';
import { DECISION_EXT, DecisionSet, isDecisionFile, mergeDecisions, parseDecision, validateDecisions } from './decisions';
/**
* Finds models in the workspace and keeps what they contain. A model is the
@@ -36,6 +38,10 @@ export interface ModelIndex {
groups: { group: string; diagrams: DiagramSummary[] }[];
/** Element id → diagrams (relative paths) that refer to it. */
usage: Map<string, string[]>;
/** The model's decisions, with link problems already checked. */
decisions: DecisionSet;
/** Decision id → diagrams that point at it, with where. */
decisionUsage: Map<string, { path: string; attachedTo: DecisionAttachment }[]>;
/** Nested main.archify files found below the root; not supported. */
nested: string[];
}
@@ -71,7 +77,7 @@ export class ModelService implements vscode.Disposable {
private readonly disposables: vscode.Disposable[];
constructor() {
const watcher = vscode.workspace.createFileSystemWatcher(`**/*{.archify,${REGISTRY_EXT}}`);
const watcher = vscode.workspace.createFileSystemWatcher(`**/*{.archify,${REGISTRY_EXT},${DECISION_EXT}}`);
const changed = (uri: vscode.Uri) => void this.onFileChanged(uri);
this.disposables = [
watcher,
@@ -80,7 +86,7 @@ export class ModelService implements vscode.Disposable {
watcher.onDidChange(changed),
vscode.workspace.onDidChangeTextDocument((event) => {
// Registry edits in the editor should re-render open diagrams before a save.
if (isRegistryFile(event.document.fileName) || isMainFile(event.document.fileName)) changed(event.document.uri);
if (isRegistryFile(event.document.fileName) || isMainFile(event.document.fileName) || isDecisionFile(event.document.fileName)) changed(event.document.uri);
}),
this.changeEmitter,
];
@@ -118,6 +124,12 @@ export class ModelService implements vscode.Disposable {
return found ?? undefined;
}
/** The model index of the model a file belongs to, or undefined outside a model. */
async indexFor(uri: vscode.Uri): Promise<ModelIndex | undefined> {
const root = await this.rootOf(uri);
return root ? this.index(root) : undefined;
}
/** The registry of the model a file belongs to, or undefined outside a model. */
async registryFor(uri: vscode.Uri): Promise<{ root: vscode.Uri; registry: Registry } | undefined> {
const root = await this.rootOf(uri);
@@ -175,7 +187,19 @@ export class ModelService implements vscode.Disposable {
}
const usage = new Map<string, string[]>();
for (const d of diagrams) for (const id of d.used) usage.set(id, [...(usage.get(id) ?? []), d.relativePath]);
return { root, main, meta, mainHasDiagram, registry, diagrams, groups: sortedGroups(diagrams), usage, nested };
const decisionFiles = await vscode.workspace.findFiles(new vscode.RelativePattern(root, `**/*${DECISION_EXT}`), SKIP);
const decisionParts = await Promise.all(
decisionFiles.sort((a, b) => a.fsPath.localeCompare(b.fsPath)).map(async (file) => {
const rel = path.relative(root.fsPath, file.fsPath).split(path.sep).join('/');
return { file: rel, ...parseDecision(await readText(file), rel) };
}),
);
const decisions = mergeDecisions(decisionParts);
decisions.problems.push(...validateDecisions(decisions, registry, new Set(diagrams.map((d) => d.relativePath))));
const decisionUsage = new Map<string, { path: string; attachedTo: DecisionAttachment }[]>();
for (const d of diagrams) for (const ref of d.decisions) decisionUsage.set(ref.id, [...(decisionUsage.get(ref.id) ?? []), { path: d.relativePath, attachedTo: ref.attachedTo }]);
return { root, main, meta, mainHasDiagram, registry, diagrams, groups: sortedGroups(diagrams), usage, decisions, decisionUsage, nested };
}
dispose(): void {
+102
View File
@@ -0,0 +1,102 @@
import {
ApiError,
Invite,
JoinResponse,
Member,
PROTOCOL_VERSION,
ServerInfo,
Space,
TokenResponse,
Version,
VersionFiles,
} from './protocol';
export class SyncApiError extends Error {
constructor(readonly status: number, readonly code: string, message: string) {
super(message);
}
}
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
/**
* The server address as the extension keeps it: http(s), no trailing slash.
* Plain http is refused except on this machine; tokens travel on it.
*/
export function checkServerUrl(raw: string): { url?: string; problem?: string } {
let url: URL;
try {
url = new URL(raw.trim());
} catch {
return { problem: 'Enter the server address, for example https://archify.example.com' };
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') return { problem: 'The address starts with https://' };
if (url.protocol === 'http:' && !LOOPBACK.has(url.hostname)) return { problem: 'Use https://. Plain http:// is only for a server on this machine.' };
return { url: `${url.origin}${url.pathname.replace(/\/+$/, '')}` };
}
export function syncSocketUrl(server: string, space: string): string {
return `${server.replace(/^http/, 'ws')}/v1/spaces/${space}/sync?v=${PROTOCOL_VERSION}`;
}
/** Reads `server` and `invite` from an invite link: `https://…/join/<token>` or the extension's `…/join?server=&invite=`. */
export function parseInviteLink(raw: string): { server: string; invite: string } | undefined {
try {
const url = new URL(raw.trim());
const server = url.searchParams.get('server');
const invite = url.searchParams.get('invite');
if (server && invite) return { server: server.replace(/\/+$/, ''), invite };
const match = /^(.*)\/join\/([A-Za-z0-9_-]{20,})\/?$/.exec(url.pathname);
if (match && (url.protocol === 'https:' || url.protocol === 'http:')) return { server: `${url.origin}${match[1]}`, invite: match[2] };
} catch {
// not a URL
}
return undefined;
}
/** The server's HTTP API. `token` gives a fresh access token for calls that need one. */
export class SyncApi {
constructor(readonly server: string, private readonly token?: (force?: boolean) => Promise<string | undefined>) {}
private async request<T>(method: string, path: string, body?: unknown, signedIn = true): Promise<T> {
const send = async (force: boolean) => {
const headers: Record<string, string> = { accept: 'application/json' };
if (body !== undefined) headers['content-type'] = 'application/json';
if (signedIn) {
const token = await this.token?.(force);
if (!token) throw new SyncApiError(401, 'unauthorized', 'Sign in to the sync server first.');
headers.authorization = `Bearer ${token}`;
}
return fetch(`${this.server}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
};
let response = await send(false);
// The access token may have expired between the check and the call.
if (response.status === 401 && signedIn) response = await send(true);
const text = await response.text();
if (!response.ok) {
let error: Partial<ApiError> = {};
try {
error = JSON.parse(text) as ApiError;
} catch {
// not JSON
}
throw new SyncApiError(response.status, error.error ?? 'http', error.message ?? `The server answered ${response.status}.`);
}
return (text ? JSON.parse(text) : undefined) as T;
}
info = () => this.request<ServerInfo>('GET', '/v1/info', undefined, false);
exchangeCode = (code: string, codeVerifier: string, redirectUri: string) =>
this.request<TokenResponse>('POST', '/v1/auth/token', { grant_type: 'authorization_code', code, code_verifier: codeVerifier, redirect_uri: redirectUri }, false);
refresh = (refreshToken: string) => this.request<TokenResponse>('POST', '/v1/auth/token', { grant_type: 'refresh_token', refresh_token: refreshToken }, false);
logout = (refreshToken: string) => this.request<void>('POST', '/v1/auth/logout', { refresh_token: refreshToken }, false);
spaces = () => this.request<Space[]>('GET', '/v1/spaces');
createSpace = (name: string) => this.request<Space>('POST', '/v1/spaces', { name });
members = (space: string) => this.request<Member[]>('GET', `/v1/spaces/${space}/members`);
invite = (space: string) => this.request<Invite>('POST', `/v1/spaces/${space}/invites`, {});
acceptInvite = (token: string) => this.request<JoinResponse>('POST', `/v1/invites/${encodeURIComponent(token)}/accept`);
versions = (space: string) => this.request<Version[]>('GET', `/v1/spaces/${space}/versions`);
publish = (space: string, name: string) => this.request<Version>('POST', `/v1/spaces/${space}/versions`, { name });
versionFiles = (space: string, version: number) => this.request<VersionFiles>('GET', `/v1/spaces/${space}/versions/${version}/files`);
restore = (space: string, version: number) => this.request<Version>('POST', `/v1/spaces/${space}/versions/${version}/restore`);
}
+239
View File
@@ -0,0 +1,239 @@
import * as crypto from 'node:crypto';
import * as http from 'node:http';
import * as vscode from 'vscode';
import { SyncApi, SyncApiError } from './api';
import { Account, TokenResponse } from './protocol';
export const AUTH_PROVIDER_ID = 'archify-sync';
const SECRET_KEY = 'archifySync.sessions';
const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
interface StoredSession {
id: string;
server: string;
accessToken: string;
/** Epoch ms. */
expiresAt: number;
refreshToken: string;
account: Account;
}
interface PendingSignIn {
resolve: (code: string) => void;
reject: (error: Error) => void;
}
/**
* "Archify Sync" in the Accounts menu: one session per server. Sign-in runs
* in the browser and comes back through the extension's URI handler with a
* one-time code, exchanged with a PKCE verifier. Tokens live in SecretStorage.
* Refresh tokens are single use, so refreshes are serialised per server and
* read the latest stored session first (another window may have refreshed).
*/
export class SyncAuth implements vscode.AuthenticationProvider, vscode.Disposable {
private readonly changed = new vscode.EventEmitter<vscode.AuthenticationProviderAuthenticationSessionsChangeEvent>();
readonly onDidChangeSessions = this.changed.event;
private readonly pending = new Map<string, PendingSignIn>();
private readonly refreshing = new Map<string, Promise<string | undefined>>();
private readonly disposables: vscode.Disposable[];
constructor(private readonly context: vscode.ExtensionContext, private readonly log: vscode.LogOutputChannel) {
this.disposables = [
vscode.authentication.registerAuthenticationProvider(AUTH_PROVIDER_ID, 'Archify Sync', this, { supportsMultipleAccounts: true }),
// Another window signed in or out.
context.secrets.onDidChange((e) => {
if (e.key === SECRET_KEY) this.changed.fire({ added: [], removed: [], changed: [] });
}),
];
}
private async load(): Promise<StoredSession[]> {
try {
return JSON.parse((await this.context.secrets.get(SECRET_KEY)) ?? '[]') as StoredSession[];
} catch {
return [];
}
}
private async save(sessions: StoredSession[]): Promise<void> {
await this.context.secrets.store(SECRET_KEY, JSON.stringify(sessions));
}
private toSession(s: StoredSession): vscode.AuthenticationSession {
return {
id: s.id,
accessToken: s.accessToken,
account: { id: s.account.id, label: `${s.account.display_name} (${new URL(s.server).host})` },
scopes: [s.server],
};
}
async getSessions(scopes?: readonly string[]): Promise<vscode.AuthenticationSession[]> {
const server = scopes?.[0];
return (await this.load()).filter((s) => !server || s.server === server).map((s) => this.toSession(s));
}
async createSession(scopes: readonly string[]): Promise<vscode.AuthenticationSession> {
const server = scopes[0];
if (!server) throw new Error('Archify Sync: say which server to sign in to.');
return this.toSession(await this.signIn(server));
}
async removeSession(id: string): Promise<void> {
const sessions = await this.load();
const gone = sessions.find((s) => s.id === id);
if (!gone) return;
await this.save(sessions.filter((s) => s.id !== id));
new SyncApi(gone.server).logout(gone.refreshToken).catch(() => undefined);
this.changed.fire({ added: [], removed: [this.toSession(gone)], changed: [] });
}
async session(server: string): Promise<StoredSession | undefined> {
return (await this.load()).find((s) => s.server === server);
}
async servers(): Promise<string[]> {
return [...new Set((await this.load()).map((s) => s.server))];
}
/** Signs in through the browser; with an invite, the page also offers to make an account. */
async signIn(server: string, invite?: string): Promise<StoredSession> {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const state = crypto.randomBytes(16).toString('base64url');
// On the desktop the browser comes back to a port on this machine: no
// click needed, and it reaches this window. Remote and web editors use
// the extension's URI handler (vscode://…/auth) instead.
const loopback = vscode.env.remoteName === undefined && vscode.env.uiKind === vscode.UIKind.Desktop ? await this.listen().catch(() => undefined) : undefined;
const redirectUri = loopback
? `http://127.0.0.1:${loopback.port}/auth`
: (await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://${this.context.extension.id}/auth`))).toString(true);
const query = new URLSearchParams({
response_type: 'code',
redirect_uri: redirectUri,
state,
code_challenge: challenge,
code_challenge_method: 'S256',
});
if (invite) query.set('invite', invite);
const code = await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: `Archify: signing in to ${new URL(server).host} in the browser…`, cancellable: true },
(_progress, cancel) =>
new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('The sign-in took too long. Try again.')), SIGN_IN_TIMEOUT_MS);
const done = () => {
clearTimeout(timer);
this.pending.delete(state);
loopback?.close();
};
this.pending.set(state, {
resolve: (c) => (done(), resolve(c)),
reject: (e) => (done(), reject(e)),
});
cancel.onCancellationRequested(() => this.pending.get(state)?.reject(new Error('Sign-in cancelled.')));
void vscode.env.openExternal(vscode.Uri.parse(`${server}/authorize?${query}`, true)).then((opened) => {
if (!opened) this.pending.get(state)?.reject(new Error('The browser did not open.'));
});
}),
);
const tokens = await new SyncApi(server).exchangeCode(code, verifier, redirectUri);
const session = await this.store(server, tokens);
await this.context.globalState.update('archifySync.used', true);
this.log.info(`sync: signed in to ${server} as ${tokens.account.name}`);
return session;
}
/** A one-off HTTP listener on 127.0.0.1 for the browser's way back; closed when the sign-in ends. */
private listen(): Promise<{ port: number; close: () => void }> {
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
const known = url.pathname === '/auth' && this.pending.has(url.searchParams.get('state') ?? '');
res.writeHead(known ? 200 : 404, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
res.end(
known
? '<!doctype html><meta charset="utf-8"><title>Archify Sync</title><body style="font:15px system-ui;margin:48px auto;max-width:420px"><h2>Signed in</h2><p>You can close this tab and go back to the editor.</p></body>'
: 'Not found',
);
if (known) this.completeSignIn(url.searchParams);
});
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const address = server.address();
if (!address || typeof address === 'string') return reject(new Error('no port'));
resolve({ port: address.port, close: () => server.close() });
});
});
}
/** The browser came back: `…/auth?code=&state=`. */
handleAuthUri(uri: vscode.Uri): void {
this.completeSignIn(new URLSearchParams(uri.query));
}
private completeSignIn(query: URLSearchParams): void {
const state = query.get('state') ?? '';
const code = query.get('code');
const pending = this.pending.get(state);
if (!pending) {
this.log.warn('sync: a sign-in came back that this window did not start');
return;
}
if (code) pending.resolve(code);
else pending.reject(new Error(query.get('error_description') ?? 'The sign-in was not completed.'));
}
private async store(server: string, tokens: TokenResponse, id?: string): Promise<StoredSession> {
const session: StoredSession = {
id: id ?? crypto.randomUUID(),
server,
accessToken: tokens.access_token,
expiresAt: Date.now() + tokens.expires_in * 1000,
refreshToken: tokens.refresh_token,
account: tokens.account,
};
const others = (await this.load()).filter((s) => s.server !== server);
await this.save([...others, session]);
const event = id ? { added: [], removed: [], changed: [this.toSession(session)] } : { added: [this.toSession(session)], removed: [], changed: [] };
this.changed.fire(event);
return session;
}
/** A valid access token for the server, refreshed when close to expiry; undefined without a session. */
accessToken(server: string, force = false): Promise<string | undefined> {
const running = this.refreshing.get(server);
if (running) return running;
const work = this.freshToken(server, force).finally(() => this.refreshing.delete(server));
this.refreshing.set(server, work);
return work;
}
private async freshToken(server: string, force: boolean): Promise<string | undefined> {
const session = await this.session(server);
if (!session) return undefined;
if (!force && session.expiresAt - 60_000 > Date.now()) return session.accessToken;
try {
const tokens = await new SyncApi(server).refresh(session.refreshToken);
return (await this.store(server, tokens, session.id)).accessToken;
} catch (error) {
if (error instanceof SyncApiError && error.status === 401) {
// Expired, or signed out elsewhere: the person signs in again.
const latest = await this.session(server);
if (latest && latest.refreshToken !== session.refreshToken) return latest.accessToken;
await this.removeSession(session.id);
this.log.warn(`sync: the session for ${server} ended; sign in again`);
return undefined;
}
// Offline: keep the old token; the connection waits and tries again.
this.log.info(`sync: could not refresh the token for ${server} (${String(error)})`);
return session.accessToken;
}
}
dispose(): void {
for (const pending of this.pending.values()) pending.reject(new Error('Closed.'));
for (const d of this.disposables) d.dispose();
this.changed.dispose();
}
}
+197
View File
@@ -0,0 +1,197 @@
import WebSocket from 'ws';
import * as Y from 'yjs';
import * as awarenessProtocol from 'y-protocols/awareness';
import * as syncProtocol from 'y-protocols/sync';
import * as decoding from 'lib0/decoding';
import * as encoding from 'lib0/encoding';
const MESSAGE_SYNC = 0;
const MESSAGE_AWARENESS = 1;
const MESSAGE_QUERY_AWARENESS = 3;
export type ConnectionState =
| 'connecting'
| 'online'
| 'offline'
/** No session for the server, or the server refused it. */
| 'signed-out'
/** The server no longer lets this account in (removed from the space). */
| 'forbidden'
/** The server speaks another protocol version. */
| 'outdated';
export interface ConnectionOptions {
url: string;
/** A fresh access token; `force` after the server refused the last one. */
token: (force: boolean) => Promise<string | undefined>;
doc: Y.Doc;
awareness: awarenessProtocol.Awareness;
onState: (state: ConnectionState) => void;
/** After the first full exchange of each connection. */
onSynced: () => void;
log: (message: string) => void;
}
/**
* One space's WebSocket to the server: the y-websocket protocol (sync step 1
* and 2, updates, awareness), reconnecting with backoff. Edits made while
* offline go out on reconnect through the state-vector exchange.
*/
export class LiveConnection {
state: ConnectionState = 'connecting';
synced = false;
private socket?: WebSocket;
private attempt = 0;
private timer?: NodeJS.Timeout;
private closed = false;
private forceToken = false;
constructor(private readonly options: ConnectionOptions) {
options.doc.on('update', this.onDocUpdate);
options.awareness.on('update', this.onAwarenessUpdate);
void this.connect();
}
/** Connects at once, e.g. after signing in. */
reconnectNow(): void {
if (this.closed || this.state === 'online' || this.state === 'connecting') return;
clearTimeout(this.timer);
this.attempt = 0;
void this.connect();
}
private setState(state: ConnectionState): void {
if (this.state === state) return;
this.state = state;
this.options.onState(state);
}
private async connect(): Promise<void> {
if (this.closed) return;
this.setState('connecting');
let token: string | undefined;
try {
token = await this.options.token(this.forceToken);
} catch (error) {
this.options.log(`sync: no token (${String(error)})`);
}
this.forceToken = false;
if (this.closed) return;
if (!token) {
this.setState('signed-out');
return;
}
const socket = new WebSocket(this.options.url, { headers: { authorization: `Bearer ${token}` }, handshakeTimeout: 10_000 });
socket.binaryType = 'arraybuffer';
this.socket = socket;
let refused = false;
socket.on('open', () => {
const step1 = encoding.createEncoder();
encoding.writeVarUint(step1, MESSAGE_SYNC);
syncProtocol.writeSyncStep1(step1, this.options.doc);
this.send(encoding.toUint8Array(step1));
if (this.options.awareness.getLocalState() !== null) this.sendAwareness([this.options.doc.clientID]);
});
socket.on('message', (data: ArrayBuffer) => this.receive(new Uint8Array(data)));
socket.on('unexpected-response', (_request, response) => {
refused = true;
const status = response.statusCode ?? 0;
this.options.log(`sync: the server refused the connection (${status})`);
if (status === 401) {
// Try once more with a refreshed token; without a session, stop.
this.forceToken = true;
this.setState('signed-out');
this.schedule(true);
} else if (status === 403 || status === 404) {
this.setState('forbidden');
} else if (status === 426) {
this.setState('outdated');
} else {
this.setState('offline');
this.schedule();
}
socket.terminate();
});
socket.on('error', (error) => this.options.log(`sync: ${error.message}`));
socket.on('close', () => {
if (this.socket !== socket) return;
this.socket = undefined;
this.synced = false;
const others = [...this.options.awareness.getStates().keys()].filter((id) => id !== this.options.doc.clientID);
awarenessProtocol.removeAwarenessStates(this.options.awareness, others, this);
if (this.closed || refused) return;
this.setState('offline');
this.schedule();
});
}
/** Backoff: 0.5 s doubling to 30 s, with jitter. */
private schedule(once = false): void {
if (this.closed) return;
clearTimeout(this.timer);
if (once && this.attempt > 0) return;
const delay = Math.min(30_000, 500 * 2 ** this.attempt) * (0.75 + Math.random() / 2);
this.attempt++;
this.timer = setTimeout(() => void this.connect(), delay);
}
private receive(bytes: Uint8Array): void {
const decoder = decoding.createDecoder(bytes);
const type = decoding.readVarUint(decoder);
if (type === MESSAGE_SYNC) {
const reply = encoding.createEncoder();
encoding.writeVarUint(reply, MESSAGE_SYNC);
const sub = syncProtocol.readSyncMessage(decoder, reply, this.options.doc, this);
if (encoding.length(reply) > 1) this.send(encoding.toUint8Array(reply));
if (sub === syncProtocol.messageYjsSyncStep2 && !this.synced) {
this.synced = true;
this.attempt = 0;
this.setState('online');
this.options.onSynced();
}
} else if (type === MESSAGE_AWARENESS) {
awarenessProtocol.applyAwarenessUpdate(this.options.awareness, decoding.readVarUint8Array(decoder), this);
} else if (type === MESSAGE_QUERY_AWARENESS) {
this.sendAwareness([...this.options.awareness.getStates().keys()]);
}
}
private send(bytes: Uint8Array): void {
if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(bytes);
}
private sendAwareness(clients: number[]): void {
const message = encoding.createEncoder();
encoding.writeVarUint(message, MESSAGE_AWARENESS);
encoding.writeVarUint8Array(message, awarenessProtocol.encodeAwarenessUpdate(this.options.awareness, clients));
this.send(encoding.toUint8Array(message));
}
private readonly onDocUpdate = (update: Uint8Array, origin: unknown) => {
if (origin === this) return;
const message = encoding.createEncoder();
encoding.writeVarUint(message, MESSAGE_SYNC);
syncProtocol.writeUpdate(message, update);
this.send(encoding.toUint8Array(message));
};
private readonly onAwarenessUpdate = (
{ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] },
origin: unknown,
) => {
if (origin === this) return;
this.sendAwareness([...added, ...updated, ...removed]);
};
dispose(): void {
this.closed = true;
clearTimeout(this.timer);
// Tell the others this editor left before closing.
awarenessProtocol.removeAwarenessStates(this.options.awareness, [this.options.doc.clientID], 'dispose');
this.options.doc.off('update', this.onDocUpdate);
this.options.awareness.off('update', this.onAwarenessUpdate);
this.socket?.close();
this.socket = undefined;
}
}
+140
View File
@@ -0,0 +1,140 @@
import * as vscode from 'vscode';
import { normalizeEol, offsetOf, positionOf } from '../util/textDiff';
import type { LiveCursor, LiveSelection } from './liveBridge';
/** One colour per person, the same in every window. */
const COLORS = ['#e5534b', '#57ab5a', '#539bf5', '#c69026', '#b083f0', '#39c5cf', '#e0823d', '#d16d9e'];
export function colorFor(id: string): string {
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
return COLORS[hash % COLORS.length];
}
/** What the text-editor side needs from the shared models. */
export interface CursorSource {
cursors(file: vscode.Uri): LiveCursor[];
setCursor(file: vscode.Uri, selection: LiveSelection | undefined): boolean;
}
interface Styles {
caret: vscode.TextEditorDecorationType;
selection: vscode.TextEditorDecorationType;
}
/**
* Cursors in VS Code's text editors: yours go to the others as you move, and
* theirs are drawn as a coloured caret with their name and a tinted selection.
*/
export class EditorCursors implements vscode.Disposable {
private readonly styles = new Map<string, Styles>();
private readonly disposables: vscode.Disposable[] = [];
private timer: ReturnType<typeof setTimeout> | undefined;
private pending: vscode.TextEditor | undefined;
constructor(private readonly source: CursorSource) {
this.disposables.push(
vscode.window.onDidChangeTextEditorSelection((event) => this.moved(event.textEditor)),
vscode.window.onDidChangeActiveTextEditor((editor) => editor && this.moved(editor)),
vscode.window.onDidChangeVisibleTextEditors(() => this.render()),
vscode.workspace.onDidChangeTextDocument((event) => {
if (vscode.window.visibleTextEditors.some((e) => e.document === event.document)) this.render();
}),
);
}
/** Sent at most every 80 ms; the last position wins. */
private moved(editor: vscode.TextEditor): void {
if (editor.document.uri.scheme !== 'file') return;
this.pending = editor;
if (this.timer) return;
this.timer = setTimeout(() => {
this.timer = undefined;
const e = this.pending;
this.pending = undefined;
if (!e || e.document.isClosed) return;
const text = normalizeEol(e.document.getText());
const { anchor, active } = e.selection;
this.source.setCursor(e.document.uri, {
anchor: offsetOf(text, anchor.line, anchor.character),
head: offsetOf(text, active.line, active.character),
});
}, 80);
}
private stylesFor(color: string): Styles {
let found = this.styles.get(color);
if (!found) {
found = {
caret: vscode.window.createTextEditorDecorationType({
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
// A zero-width caret and the name above it; the CSS rides in textDecoration,
// the usual way to place a decoration without moving the text.
before: {
contentText: '',
textDecoration: `none; position: absolute; display: inline-block; height: 1.25em; border-left: 2px solid ${color}; margin-left: -1px; z-index: 1;`,
},
}),
selection: vscode.window.createTextEditorDecorationType({
backgroundColor: `${color}38`,
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
}),
};
this.styles.set(color, found);
}
return found;
}
/** Draws everyone's cursors in the visible editors of shared files. */
render(): void {
for (const editor of vscode.window.visibleTextEditors) {
if (editor.document.uri.scheme !== 'file') continue;
const cursors = this.source.cursors(editor.document.uri);
const text = normalizeEol(editor.document.getText());
const at = (offset: number) => {
const { line, character } = positionOf(text, Math.max(0, Math.min(offset, text.length)));
return new vscode.Position(line, character);
};
const byColor = new Map<string, { carets: vscode.DecorationOptions[]; selections: vscode.Range[] }>();
for (const c of cursors) {
let group = byColor.get(c.color);
if (!group) byColor.set(c.color, (group = { carets: [], selections: [] }));
const head = at(c.head);
group.carets.push({
range: new vscode.Range(head, head),
hoverMessage: new vscode.MarkdownString(`**${c.name.replace(/[\\`*_[\]<>]/g, '')}** is here`),
renderOptions: {
after: {
contentText: c.name,
color: '#fff',
backgroundColor: c.color,
fontWeight: '500',
textDecoration: 'none; position: absolute; transform: translateY(-1.15em); font-size: 0.75em; padding: 0 4px; border-radius: 3px; white-space: nowrap; pointer-events: none; z-index: 2; opacity: 0.9;',
},
},
});
if (c.anchor !== c.head) {
const [from, to] = c.anchor < c.head ? [c.anchor, c.head] : [c.head, c.anchor];
group.selections.push(new vscode.Range(at(from), at(to)));
}
}
for (const color of byColor.keys()) this.stylesFor(color);
// Every colour is set, so a person who left or moved away disappears.
for (const [color, styles] of this.styles) {
const group = byColor.get(color);
editor.setDecorations(styles.caret, group?.carets ?? []);
editor.setDecorations(styles.selection, group?.selections ?? []);
}
}
}
dispose(): void {
clearTimeout(this.timer);
for (const styles of this.styles.values()) {
styles.caret.dispose();
styles.selection.dispose();
}
this.styles.clear();
for (const d of this.disposables.splice(0)) d.dispose();
}
}
+230
View File
@@ -0,0 +1,230 @@
import * as vscode from 'vscode';
import * as Y from 'yjs';
import { normalizeEol, positionOf } from '../util/textDiff';
import { FILES_MAP } from './protocol';
import { applyToYText, safeChange } from './textSync';
const MODEL_GLOB = '**/*.{archify,archify-registry,archify-decision}';
const SKIP_GLOB = '{**/node_modules/**,**/.git/**}';
const MODEL_FILE = /\.(archify|archify-registry|archify-decision)$/i;
/** A model-root-relative path the bridge accepts: POSIX, no `..`, a model file. */
export function isSafeModelPath(path: string): boolean {
if (!MODEL_FILE.test(path) || path.startsWith('/') || path.includes('\\')) return false;
return path.split('/').every((part) => part !== '' && part !== '.' && part !== '..' && part !== '.git' && part !== 'node_modules');
}
/**
* Keeps a model's files and the space's Y.Text per file the same.
*
* Local edits (any editor, the Source view, a drag on a diagram, git, an
* agent) become minimal Y.Text edits. Remote edits go back as WorkspaceEdits
* for open documents, so undo, dirty state and the pages stay right, and as
* file writes for closed ones. Each side compares texts before writing, so
* an edit coming back from the other side ends as a no-op instead of an echo.
*/
export class FileBridge implements vscode.Disposable {
readonly files: Y.Map<Y.Text>;
private readonly disposables: vscode.Disposable[] = [];
private queue: Promise<void> = Promise.resolve();
private listening = false;
/**
* Text the bridge last wrote per file. Its own write comes back as a change
* event, possibly after the document moved on; pushing it then would undo
* the newer edit, so it is skipped once.
*/
private readonly written = new Map<string, string>();
constructor(
private readonly root: vscode.Uri,
private readonly doc: Y.Doc,
/** Transaction origin of edits made here. */
private readonly origin: object,
private readonly log: vscode.LogOutputChannel,
) {
this.files = doc.getMap<Y.Text>(FILES_MAP);
}
/** The model-relative path of a file in this model, else undefined. */
relative(uri: vscode.Uri): string | undefined {
if (uri.scheme !== this.root.scheme) return undefined;
const base = this.root.path.endsWith('/') ? this.root.path : `${this.root.path}/`;
if (!uri.path.startsWith(base)) return undefined;
const rel = uri.path.slice(base.length);
return isSafeModelPath(rel) ? rel : undefined;
}
uriOf(rel: string): vscode.Uri {
return vscode.Uri.joinPath(this.root, ...rel.split('/'));
}
/** Remote edits start going to disk; with `local`, local edits start going out. */
start(local: boolean): void {
if (!this.disposables.length) {
const observer = (events: Y.YEvent<Y.AbstractType<unknown>>[], txn: Y.Transaction) => {
if (txn.origin === this.origin) return;
const paths = new Set<string>();
for (const event of events) {
if (event.target === this.files) for (const key of event.changes.keys.keys()) paths.add(key);
else if (typeof event.path[0] === 'string') paths.add(event.path[0]);
}
for (const path of paths) this.enqueue(() => this.writeOut(path));
};
this.files.observeDeep(observer);
this.disposables.push({ dispose: () => this.files.unobserveDeep(observer) });
}
if (local && !this.listening) {
this.listening = true;
const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(this.root, MODEL_GLOB));
this.disposables.push(
vscode.workspace.onDidChangeTextDocument((e) => {
const rel = this.relative(e.document.uri);
if (rel && e.contentChanges.length) this.pushLocal(rel, normalizeEol(e.document.getText()));
}),
watcher,
watcher.onDidCreate((uri) => this.enqueue(() => this.pushFromDisk(uri))),
watcher.onDidChange((uri) => this.enqueue(() => this.pushFromDisk(uri))),
watcher.onDidDelete((uri) => {
const rel = this.relative(uri);
if (rel && this.files.has(rel)) this.enqueue(async () => {
// Gone for good, not an editor's save-by-rename.
if (!(await exists(uri))) this.doc.transact(() => this.files.delete(rel), this.origin);
});
}),
);
}
}
private pushLocal(rel: string, text: string): void {
if (this.written.get(rel) === text) {
this.written.delete(rel);
return;
}
this.push(rel, text);
}
/** One file's text into the document. */
push(rel: string, text: string): void {
const existing = this.files.get(rel);
if (existing instanceof Y.Text) {
if (existing.toString() !== text) this.doc.transact(() => applyToYText(existing, text), this.origin);
return;
}
this.doc.transact(() => {
const created = new Y.Text();
created.insert(0, text);
this.files.set(rel, created);
}, this.origin);
}
private async pushFromDisk(uri: vscode.Uri): Promise<void> {
const rel = this.relative(uri);
// Open documents report through their change events.
if (!rel || vscode.workspace.textDocuments.some((d) => d.uri.toString() === uri.toString())) return;
const text = await readDisk(uri);
if (text !== undefined) this.pushLocal(rel, normalizeEol(text));
}
/** The model files as they are now: open editors' text, else the disk. */
async scan(): Promise<Map<string, string>> {
const found = await vscode.workspace.findFiles(new vscode.RelativePattern(this.root, MODEL_GLOB), SKIP_GLOB);
const out = new Map<string, string>();
for (const uri of found) {
const rel = this.relative(uri);
if (!rel) continue;
const open = vscode.workspace.textDocuments.find((d) => d.uri.toString() === uri.toString());
const text = open ? open.getText() : await readDisk(uri);
if (text !== undefined) out.set(rel, normalizeEol(text));
}
return out;
}
/**
* Brings changes made while the extension was not running into the
* document (git pull, an edit in another tool). With `deleteMissing`,
* files in the document but gone from disk are removed.
*/
async pushAll(deleteMissing: boolean): Promise<void> {
const local = await this.scan();
for (const [rel, text] of local) this.push(rel, text);
if (deleteMissing) {
const gone = [...this.files.keys()].filter((rel) => !local.has(rel));
if (gone.length) this.doc.transact(() => gone.forEach((rel) => this.files.delete(rel)), this.origin);
}
}
/** Writes every file of the document to disk; then sends local files the document lacks. */
async pullAll(): Promise<void> {
for (const rel of this.files.keys()) await this.enqueue(() => this.writeOut(rel));
const local = await this.scan();
for (const [rel, text] of local) if (!this.files.has(rel)) this.push(rel, text);
}
private enqueue(work: () => Promise<void>): Promise<void> {
this.queue = this.queue.then(work).catch((error) => this.log.error(`sync: ${error instanceof Error ? error.message : String(error)}`));
return this.queue;
}
/** The document's text of one file onto disk or into its open editor. */
private async writeOut(rel: string): Promise<void> {
if (!isSafeModelPath(rel)) {
this.log.warn(`sync: ignored a file outside the model: ${rel}`);
return;
}
const uri = this.uriOf(rel);
const value = this.files.get(rel);
if (!(value instanceof Y.Text)) {
if (await exists(uri)) await vscode.workspace.fs.delete(uri, { useTrash: true });
return;
}
const text = value.toString();
const open = vscode.workspace.textDocuments.find((d) => d.uri.toString() === uri.toString());
if (open) {
const current = normalizeEol(open.getText());
const change = safeChange(current, text);
if (!change) return;
const wasDirty = open.isDirty;
const from = positionOf(current, change.from);
const to = positionOf(current, change.to);
this.written.set(rel, text);
const edit = new vscode.WorkspaceEdit();
edit.replace(uri, new vscode.Range(from.line, from.character, to.line, to.character), change.insert);
if (!(await vscode.workspace.applyEdit(edit))) {
this.log.warn(`sync: could not apply a teammate's edit to ${rel}`);
return;
}
// Teammates' edits land on disk, where git sees them; the person's own unsaved work stays unsaved.
if (!wasDirty) await open.save();
return;
}
const disk = await readDisk(uri);
const eol = disk?.includes('\r\n') ? '\r\n' : '\n';
const out = eol === '\n' ? text : text.replace(/\n/g, '\r\n');
if (disk === out) return;
this.written.set(rel, text);
await vscode.workspace.fs.createDirectory(vscode.Uri.joinPath(uri, '..'));
await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(out));
}
dispose(): void {
for (const d of this.disposables.splice(0)) d.dispose();
this.listening = false;
}
}
async function exists(uri: vscode.Uri): Promise<boolean> {
try {
await vscode.workspace.fs.stat(uri);
return true;
} catch {
return false;
}
}
async function readDisk(uri: vscode.Uri): Promise<string | undefined> {
try {
return new TextDecoder('utf-8').decode(await vscode.workspace.fs.readFile(uri));
} catch {
return undefined;
}
}
+625
View File
@@ -0,0 +1,625 @@
// Archify Sync in the extension: live, shared models. Bundled on its own
// (dist/sync.js) and loaded only when a model is shared or a sync command
// runs, so the extension without a server works exactly as before.
import * as vscode from 'vscode';
import { MAIN_FILE } from '../model/format';
import type { ModelService } from '../model/service';
import { SyncApi, SyncApiError, checkServerUrl, parseInviteLink } from './api';
import { SyncAuth } from './auth';
import { LiveSpace, StartMode } from './liveSpace';
import { LINK_FILE, Link, PROTOCOL_VERSION, Version, formatLink, parseLink, versionLabel } from './protocol';
import { EditorCursors } from './cursors';
import type { LiveAction, LiveBridge, LiveCursor, LivePanel, LiveProvider, LiveSelection } from './liveBridge';
import { VERSION_SCHEME, VersionContent, compareVersion, restoreVersion, showVersions } from './versions';
export const SYNC_COMMANDS = [
'archify.sync.signIn',
'archify.sync.signOut',
'archify.sync.share',
'archify.sync.invite',
'archify.sync.join',
'archify.sync.publish',
'archify.sync.versions',
'archify.sync.stop',
'archify.sync.menu',
'archify.sync.setServer',
] as const;
const SKIP = '{**/node_modules/**,**/.git/**}';
/** How long the model page's list of versions is reused before it is asked for again. */
const VERSIONS_TTL_MS = 20_000;
export class SyncFeature implements vscode.Disposable, LiveProvider {
private readonly auth: SyncAuth;
private readonly spaces = new Map<string, LiveSpace>();
private readonly status = vscode.window.createStatusBarItem('archify.sync', vscode.StatusBarAlignment.Left, 50);
private readonly content: VersionContent;
private readonly disposables: vscode.Disposable[] = [];
private readonly versionCache = new Map<string, { at: number; versions: Promise<Version[]> }>();
private readonly editorCursors: EditorCursors;
private cursorTimer: ReturnType<typeof setTimeout> | undefined;
/** Servers with a session on this machine, for the status bar before any model is shared. */
private signedIn: string[] = [];
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
private readonly log: vscode.LogOutputChannel,
private readonly bridge?: LiveBridge,
) {
this.auth = new SyncAuth(context, log);
this.content = new VersionContent((space) => {
const live = [...this.spaces.values()].find((s) => s.link.space === space);
return live ? this.api(live.link.server) : undefined;
});
this.status.name = 'Archify Sync';
this.status.command = 'archify.sync.menu';
const links = vscode.workspace.createFileSystemWatcher(`**/${LINK_FILE}`);
this.disposables.push(
this.auth,
this.status,
links,
links.onDidCreate((uri) => void this.open(uri, 'open')),
links.onDidDelete((uri) => this.close(vscode.Uri.joinPath(uri, '..'), false)),
vscode.workspace.registerTextDocumentContentProvider(VERSION_SCHEME, this.content),
this.auth.onDidChangeSessions(() => {
for (const space of this.spaces.values()) space.reconnect();
void this.refreshSignedIn();
}),
vscode.workspace.onDidChangeConfiguration((e) => e.affectsConfiguration('archify.sync') && this.render()),
);
this.editorCursors = new EditorCursors({ cursors: (file) => this.cursors(file), setCursor: (file, selection) => this.setCursorIn(file, selection) });
this.disposables.push(this.editorCursors);
bridge?.setProvider(this);
}
/** Opens every shared model in the workspace. */
async start(): Promise<void> {
const found = await vscode.workspace.findFiles(`**/${LINK_FILE}`, SKIP, 50);
await Promise.all(found.map((uri) => this.open(uri, 'open')));
await this.refreshSignedIn();
}
private async refreshSignedIn(): Promise<void> {
this.signedIn = await this.auth.servers();
this.render();
}
private api(server: string): SyncApi {
return new SyncApi(server, (force) => this.auth.accessToken(server, force));
}
private async open(linkUri: vscode.Uri, mode: StartMode): Promise<LiveSpace | undefined> {
const root = vscode.Uri.joinPath(linkUri, '..');
if (this.spaces.has(root.toString())) return this.spaces.get(root.toString());
let link: Link | undefined;
try {
link = parseLink(new TextDecoder().decode(await vscode.workspace.fs.readFile(linkUri)));
} catch {
return undefined;
}
if (!link) {
this.log.warn(`sync: ${vscode.workspace.asRelativePath(linkUri)} is not a valid link file`);
return undefined;
}
if (!checkServerUrl(link.server).url) {
this.log.warn(`sync: ${vscode.workspace.asRelativePath(linkUri)} names a server that is not https: ${link.server}`);
return undefined;
}
const space = new LiveSpace(root, link, mode, {
context: this.context,
auth: this.auth,
log: this.log,
onChange: () => this.render(),
onCursors: () => this.cursorsMoved(),
});
this.spaces.set(root.toString(), space);
try {
await space.start();
} catch (error) {
this.log.error(`sync: ${link.name ?? root.fsPath} did not start: ${String(error)}`);
}
this.render();
return space;
}
private close(root: vscode.Uri, forget: boolean): void {
const space = this.spaces.get(root.toString());
if (!space) return;
this.spaces.delete(root.toString());
if (forget) space.forget();
else space.dispose();
this.render();
}
private render(): void {
const spaces = [...this.spaces.values()];
if (!spaces.length) {
this.status.hide();
void vscode.commands.executeCommand('setContext', 'archify.sync.active', false);
this.bridge?.changed();
return;
}
void vscode.commands.executeCommand('setContext', 'archify.sync.active', true);
const signedOut = spaces.filter((s) => s.state === 'signed-out');
const offline = spaces.filter((s) => s.state !== 'online' && s.state !== 'signed-out');
const people = new Set(spaces.flatMap((s) => s.people().map((p) => p.user.id)));
if (signedOut.length) {
this.status.text = '$(account) Archify: sign in';
this.status.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');
} else if (offline.length) {
this.status.text = offline.some((s) => s.state === 'connecting') ? '$(sync~spin) Archify connecting' : '$(cloud-offline) Archify offline';
this.status.backgroundColor = undefined;
} else {
this.status.text = `$(broadcast) Archify live · ${people.size} here`;
this.status.backgroundColor = undefined;
}
const tooltip = new vscode.MarkdownString(undefined, true);
for (const s of spaces) {
const who = s.people().map((p) => `${p.user.name}${p.file ? ` (${p.file})` : ''}`).join(', ');
tooltip.appendMarkdown(`**${s.name}**: ${s.state}${who ? ` \n${who}` : ''}\n\n`);
}
tooltip.appendMarkdown('Edits are kept on this machine first and sent when online.');
this.status.tooltip = tooltip;
this.status.show();
this.bridge?.changed();
}
// ------------------------------------------------- the model page's Live section
private versionsOf(space: LiveSpace, fresh = false): Promise<Version[]> {
const cached = this.versionCache.get(space.link.space);
if (!fresh && cached && Date.now() - cached.at < VERSIONS_TTL_MS) return cached.versions;
const versions = this.api(space.link.server).versions(space.link.space);
this.versionCache.set(space.link.space, { at: Date.now(), versions });
versions.catch(() => this.versionCache.delete(space.link.space));
return versions;
}
/** After a publish or a restore: the page shows the new version. */
private versionsChanged(space: LiveSpace): void {
this.versionCache.delete(space.link.space);
this.bridge?.changed(space.root);
}
async panel(root: vscode.Uri): Promise<LivePanel | undefined> {
const space = this.spaces.get(root.toString());
if (!space) return undefined;
const me = (space.awareness.getLocalState() as { user?: { id?: string } } | null)?.user?.id;
const panel: LivePanel = {
name: space.name,
host: new URL(space.link.server).host,
state: space.state,
people: space.people().map((p) => ({ name: p.user.name, file: p.file, me: p.user.id === me })),
};
if (space.state === 'signed-out' || space.state === 'forbidden') return panel;
try {
const versions = await this.versionsOf(space);
const label = new Map(versions.map((v) => [v.id, versionLabel(v)]));
panel.versions = versions.map((v) => ({
id: v.id,
label: versionLabel(v),
kind: v.kind,
name: v.name ?? undefined,
at: v.created_at,
restoredFrom: v.restored_from !== null ? label.get(v.restored_from) : undefined,
}));
} catch (error) {
panel.versionsProblem = space.state === 'online' ? `Versions could not be loaded: ${error instanceof Error ? error.message : String(error)}` : 'Versions show when the server can be reached.';
}
return panel;
}
/** Cursors drawn at most every 50 ms, however many people move. */
private cursorsMoved(): void {
if (this.cursorTimer) return;
this.cursorTimer = setTimeout(() => {
this.cursorTimer = undefined;
this.bridge?.cursorsChanged();
this.editorCursors.render();
}, 50);
}
private spaceOf(file: vscode.Uri): LiveSpace | undefined {
for (const space of this.spaces.values()) {
const root = space.root.path.endsWith('/') ? space.root.path : `${space.root.path}/`;
if (file.scheme === space.root.scheme && file.path.startsWith(root)) return space;
}
return undefined;
}
cursors(file: vscode.Uri): LiveCursor[] {
return this.spaceOf(file)?.cursors(file) ?? [];
}
setCursor(file: vscode.Uri, selection: LiveSelection | undefined): void {
this.setCursorIn(file, selection);
}
private setCursorIn(file: vscode.Uri, selection: LiveSelection | undefined): boolean {
return this.spaceOf(file)?.setCursor(file, selection) ?? false;
}
async act(root: vscode.Uri, action: LiveAction): Promise<void> {
const space = this.spaces.get(root.toString());
if (!space) return;
try {
switch (action.kind) {
case 'publish':
await this.publish(space);
break;
case 'invite':
await this.invite(space);
break;
case 'signIn':
if (await this.checkServer(space.link.server)) await this.auth.signIn(space.link.server);
break;
case 'versions':
await showVersions(space, this.api(space.link.server), this.content);
this.versionsChanged(space);
break;
case 'compare':
case 'restore': {
const version = (await this.versionsOf(space)).find((v) => v.id === action.version);
if (!version) throw new Error('That version is no longer listed.');
if (action.kind === 'compare') await compareVersion(space, version, this.content);
else if (await restoreVersion(space, this.api(space.link.server), version)) this.versionsChanged(space);
break;
}
}
} catch (error) {
this.report(error);
}
}
// ------------------------------------------------------------- commands
async run(command: (typeof SYNC_COMMANDS)[number], ...args: unknown[]): Promise<void> {
try {
switch (command) {
case 'archify.sync.signIn':
await this.signInCommand();
break;
case 'archify.sync.signOut':
await this.signOut();
break;
case 'archify.sync.share':
await this.share(args[0]);
break;
case 'archify.sync.invite':
await this.invite(args[0]);
break;
case 'archify.sync.join':
await this.join(typeof args[0] === 'string' ? args[0] : undefined);
break;
case 'archify.sync.publish':
await this.publish(args[0]);
break;
case 'archify.sync.versions': {
const space = await this.pickSpace(args[0]);
if (space) {
await showVersions(space, this.api(space.link.server), this.content);
this.versionsChanged(space);
}
break;
}
case 'archify.sync.stop':
await this.stop(args[0]);
break;
case 'archify.sync.menu':
await this.menu();
break;
case 'archify.sync.setServer':
await this.setServer();
break;
}
} catch (error) {
this.report(error);
}
}
private report(error: unknown): void {
const message = error instanceof Error ? error.message : String(error);
if (/cancelled/i.test(message)) return;
this.log.error(`sync: ${message}`);
void vscode.window.showErrorMessage(`Archify Sync: ${message}`);
}
/** The invite and sign-in links: `…/auth?code=&state=`, `…/join?server=&invite=`. */
async handleUri(uri: vscode.Uri): Promise<void> {
if (uri.path === '/auth') this.auth.handleAuthUri(uri);
else if (uri.path === '/join') await this.run('archify.sync.join', uri.toString(true));
}
/** The server from the archify.sync.server setting, or asked for (and remembered). */
private async askServer(): Promise<string | undefined> {
return configuredServer() ?? this.promptServer();
}
private async promptServer(): Promise<string | undefined> {
const last = configuredServer() ?? this.context.globalState.get<string>('archifySync.lastServer');
const value = await vscode.window.showInputBox({
title: 'Archify | Sync server',
prompt: 'The address of the Archify Sync server',
placeHolder: 'https://archify.example.com',
value: last,
ignoreFocusOut: true,
validateInput: (v) => checkServerUrl(v).problem,
});
return value === undefined ? undefined : checkServerUrl(value).url;
}
/** Checks the server answers and speaks this protocol; offers its setup page when it is new. */
private async checkServer(server: string): Promise<boolean> {
const info = await new SyncApi(server).info();
if (info.protocol !== PROTOCOL_VERSION) {
throw new Error(`${info.name} speaks protocol ${info.protocol}; this extension speaks ${PROTOCOL_VERSION}. Update ${info.protocol > PROTOCOL_VERSION ? 'the extension' : 'the server'}.`);
}
if (!info.set_up) {
const open = await vscode.window.showInformationMessage(
`${info.name} is new: its first admin sets it up with the first-start code from the server's log.`,
'Open setup page',
);
if (open) await vscode.env.openExternal(vscode.Uri.parse(`${server}/setup`));
return false;
}
await this.context.globalState.update('archifySync.lastServer', server);
return true;
}
/** Writes archify.sync.server: in the workspace when the workspace sets it, otherwise for the user. */
private async setServer(): Promise<void> {
const server = await this.promptServer();
if (!server) return;
const config = vscode.workspace.getConfiguration('archify.sync');
const inWorkspace = config.inspect<string>('server')?.workspaceValue !== undefined;
await config.update('server', server, inWorkspace ? vscode.ConfigurationTarget.Workspace : vscode.ConfigurationTarget.Global);
vscode.window.showInformationMessage(`Archify Sync: server set to ${new URL(server).host}${inWorkspace ? ' for this workspace' : ''}.`);
}
private async signInCommand(): Promise<void> {
const server = await this.askServer();
if (!server || !(await this.checkServer(server))) return;
const session = await this.auth.signIn(server);
vscode.window.showInformationMessage(`Archify: signed in to ${new URL(server).host} as ${session.account.display_name}.`);
}
private async signOut(): Promise<void> {
const servers = await this.auth.servers();
if (!servers.length) {
vscode.window.showInformationMessage('Archify: not signed in to a sync server.');
return;
}
const server = servers.length === 1 ? servers[0] : await vscode.window.showQuickPick(servers, { title: 'Archify | Sign out of' });
const session = server ? await this.auth.session(server) : undefined;
if (session) await this.auth.removeSession(session.id);
}
/** A server with a session: the only one, a picked one, or a new sign-in. */
private async serverWithSession(): Promise<string | undefined> {
const servers = await this.auth.servers();
if (servers.length === 1) return servers[0];
if (servers.length > 1) {
const pick = await vscode.window.showQuickPick([...servers, '$(add) Another server…'], { title: 'Archify | Share to which server?' });
if (pick && !pick.startsWith('$(add)')) return pick;
if (!pick) return undefined;
}
const server = await this.askServer();
if (!server || !(await this.checkServer(server))) return undefined;
await this.auth.signIn(server);
return server;
}
/** The model root a command applies to: the argument, the active file, or a pick. */
private async modelRoot(arg: unknown): Promise<vscode.Uri | undefined> {
const uri = arg instanceof vscode.Uri ? arg : vscode.window.activeTextEditor?.document.uri ?? activeTabUri();
const root = uri ? await this.models.rootOf(uri) : undefined;
if (root) return root;
const mains = await vscode.workspace.findFiles(`**/${MAIN_FILE}`, SKIP, 50);
if (mains.length === 1) return vscode.Uri.joinPath(mains[0], '..');
const pick = await vscode.window.showQuickPick(
mains.map((m) => ({ label: vscode.workspace.asRelativePath(vscode.Uri.joinPath(m, '..')), root: vscode.Uri.joinPath(m, '..') })),
{ title: 'Archify | Which model?' },
);
return pick?.root;
}
private async pickSpace(arg: unknown): Promise<LiveSpace | undefined> {
if (arg instanceof LiveSpace) return arg;
const spaces = [...this.spaces.values()];
if (!spaces.length) {
vscode.window.showInformationMessage('Archify: no model in this workspace is shared. Share one with "Archify: Share Model…".');
return undefined;
}
const uri = arg instanceof vscode.Uri ? arg : vscode.window.activeTextEditor?.document.uri ?? activeTabUri();
const root = uri ? await this.models.rootOf(uri) : undefined;
const here = root && this.spaces.get(root.toString());
if (here) return here;
if (spaces.length === 1) return spaces[0];
const pick = await vscode.window.showQuickPick(spaces.map((s) => ({ label: s.name, description: new URL(s.link.server).host, space: s })), {
title: 'Archify | Which shared model?',
});
return pick?.space;
}
private async share(arg: unknown): Promise<void> {
const root = await this.modelRoot(arg);
if (!root) return;
if (this.spaces.has(root.toString())) {
await this.invite(root);
return;
}
const server = await this.serverWithSession();
if (!server) return;
const index = await this.models.index(root).catch(() => undefined);
const name = await vscode.window.showInputBox({
title: 'Archify | Share Model',
prompt: `Name of the shared model on ${new URL(server).host}`,
value: index?.meta.name ?? root.path.split('/').pop(),
validateInput: (v) => (v.trim() ? undefined : 'Give it a name.'),
});
if (!name) return;
const space = await this.api(server).createSpace(name.trim());
const linkUri = vscode.Uri.joinPath(root, LINK_FILE);
await vscode.workspace.fs.writeFile(linkUri, new TextEncoder().encode(formatLink({ server, space: space.id, name: space.name })));
await this.open(linkUri, 'share');
const next = await vscode.window.showInformationMessage(
`Archify: ${space.name} is shared. Edits now go to everyone you invite.`,
'Copy invite link',
);
if (next) await this.invite(root);
}
private async invite(arg: unknown): Promise<void> {
const space = await this.pickSpace(arg);
if (!space) return;
const invite = await this.api(space.link.server).invite(space.link.space);
await vscode.env.clipboard.writeText(invite.url);
vscode.window.showInformationMessage(
`Archify: invite link for ${space.name} copied. It works until ${new Date(invite.expires_at).toLocaleDateString()}; send it through any channel.`,
);
}
private async join(raw?: string): Promise<void> {
const text =
raw ??
(await vscode.window.showInputBox({
title: 'Archify | Join Shared Model',
prompt: 'Paste the invite link',
ignoreFocusOut: true,
validateInput: (v) => (parseInviteLink(v) ? undefined : 'This is not an Archify invite link.'),
}));
if (!text) return;
const parsed = parseInviteLink(text);
const server = parsed && checkServerUrl(parsed.server).url;
if (!parsed || !server) throw new Error('This is not an Archify invite link.');
if (!(await this.checkServer(server))) return;
const folder = await vscode.window.showOpenDialog({
title: 'Archify | Folder for the shared model',
openLabel: 'Put the model here',
canSelectFiles: false,
canSelectFolders: true,
defaultUri: vscode.workspace.workspaceFolders?.[0]?.uri,
});
const root = folder?.[0];
if (!root) return;
const existing = await vscode.workspace.findFiles(new vscode.RelativePattern(root, '**/*.{archify,archify-registry,archify-decision}'), SKIP, 1);
if (existing.length) {
throw new Error('That folder already holds Archify files. Pick an empty folder for the shared model.');
}
if (!(await this.auth.session(server))) await this.auth.signIn(server, parsed.invite);
const joined = await this.api(server).acceptInvite(parsed.invite);
const linkUri = vscode.Uri.joinPath(root, LINK_FILE);
await vscode.workspace.fs.writeFile(linkUri, new TextEncoder().encode(formatLink({ server, space: joined.space.id, name: joined.space.name })));
const inWorkspace = vscode.workspace.getWorkspaceFolder(root);
if (inWorkspace) {
await this.open(linkUri, 'join');
vscode.window.showInformationMessage(`Archify: you joined ${joined.space.name}. Its files are arriving in ${vscode.workspace.asRelativePath(root)}.`);
return;
}
const open = await vscode.window.showInformationMessage(
`Archify: you joined ${joined.space.name}. Open its folder to start working together.`,
'Open folder',
'Open in new window',
);
if (open) await vscode.commands.executeCommand('vscode.openFolder', root, { forceNewWindow: open === 'Open in new window' });
}
private async publish(arg: unknown): Promise<void> {
const space = await this.pickSpace(arg);
if (!space) return;
const name = await vscode.window.showInputBox({
title: `Archify | Publish ${space.name}`,
prompt: 'Name this version, for example "Q4 baseline"',
validateInput: (v) => (v.trim() ? undefined : 'Give the version a name.'),
});
if (!name) return;
const version = await this.api(space.link.server).publish(space.link.space, name.trim());
this.versionsChanged(space);
vscode.window.showInformationMessage(`Archify: published ${version.major}.${version.minor} "${version.name}" of ${space.name}.`);
}
private async stop(arg: unknown): Promise<void> {
const space = await this.pickSpace(arg);
if (!space) return;
const ok = await vscode.window.showWarningMessage(
`Stop syncing ${space.name} here?`,
{ modal: true, detail: `The files stay as they are. ${LINK_FILE} is removed, and edits here no longer go to the others. The model stays on the server.` },
'Stop syncing',
);
if (ok !== 'Stop syncing') return;
this.close(space.root, true);
await vscode.workspace.fs.delete(vscode.Uri.joinPath(space.root, LINK_FILE)).then(undefined, () => undefined);
}
private async menu(): Promise<void> {
const spaces = [...this.spaces.values()];
const signedOut = spaces.find((s) => s.state === 'signed-out');
const servers = await this.auth.servers();
const configured = configuredServer();
type Item = vscode.QuickPickItem & { run?: () => Promise<void> };
const items: Item[] = [];
if (signedOut) {
items.push({
label: `$(account) Sign in to ${new URL(signedOut.link.server).host}`,
run: async () => {
if (await this.checkServer(signedOut.link.server)) await this.auth.signIn(signedOut.link.server);
},
});
} else if (!servers.length) {
items.push({
label: '$(account) Sign in…',
description: configured ? new URL(configured).host : 'asks for the server address',
run: () => this.signInCommand(),
});
}
items.push(
{ label: '$(live-share) Share a model…', run: () => this.share(undefined) },
{ label: '$(link) Join a shared model…', description: 'with an invite link', run: () => this.join(undefined) },
);
if (spaces.length) {
items.push(
{ label: 'Shared models', kind: vscode.QuickPickItemKind.Separator },
{ label: '$(person-add) Copy invite link…', run: () => this.invite(undefined) },
{ label: '$(tag) Publish version…', run: () => this.publish(undefined) },
{ label: '$(history) Versions…', run: () => this.run('archify.sync.versions') },
{ label: '$(debug-disconnect) Stop syncing a model…', run: () => this.stop(undefined) },
);
}
items.push(
{ label: 'Settings', kind: vscode.QuickPickItemKind.Separator },
{ label: '$(server) Server address…', description: configured ? new URL(configured).host : 'not set', run: () => this.setServer() },
{ label: '$(settings-gear) Open Sync settings', run: async () => void vscode.commands.executeCommand('workbench.action.openSettings', 'archify.sync') },
{ label: '$(output) Show log', run: async () => this.log.show() },
);
if (servers.length) items.push({ label: '$(sign-out) Sign out…', description: servers.map((s) => new URL(s).host).join(', '), run: () => this.signOut() });
const pick = await vscode.window.showQuickPick(items, { title: 'Archify Sync' });
await pick?.run?.();
}
dispose(): void {
clearTimeout(this.cursorTimer);
this.bridge?.setProvider(undefined);
for (const space of this.spaces.values()) space.dispose();
this.spaces.clear();
for (const d of this.disposables) d.dispose();
}
}
/** archify.sync.server when it holds a usable address. */
function configuredServer(): string | undefined {
const value = vscode.workspace.getConfiguration('archify.sync').get<string>('server', '').trim();
return value ? checkServerUrl(value).url : undefined;
}
/** The file behind the active tab when it is a custom editor (the Archify pages). */
function activeTabUri(): vscode.Uri | undefined {
const input = vscode.window.tabGroups.activeTabGroup.activeTab?.input;
return input instanceof vscode.TabInputCustom || input instanceof vscode.TabInputText ? input.uri : undefined;
}
export { SyncApiError };
+110
View File
@@ -0,0 +1,110 @@
import * as vscode from 'vscode';
// What the model page shows of a shared model. Lives in the main bundle; the
// sync bundle plugs in as the provider once it loads. Without it, the model
// page has no Live section and nothing else changes.
export interface LivePerson {
name: string;
/** Model-relative path of the file the person has open. */
file?: string;
me?: boolean;
}
export interface LiveVersion {
id: number;
label: string;
kind: 'snapshot' | 'publish' | 'restore';
name?: string;
/** ISO time. */
at: string;
restoredFrom?: string;
}
export interface LivePanel {
name: string;
host: string;
state: 'connecting' | 'online' | 'offline' | 'signed-out' | 'forbidden' | 'outdated';
people: LivePerson[];
versions?: LiveVersion[];
versionsProblem?: string;
}
/** Someone else's cursor in a file, as offsets into its "\n" text. */
export interface LiveCursor {
name: string;
color: string;
anchor: number;
head: number;
}
/** A selection as offsets into a file's "\n" text. */
export interface LiveSelection {
anchor: number;
head: number;
}
export type LiveAction =
| { kind: 'publish' }
| { kind: 'invite' }
| { kind: 'signIn' }
| { kind: 'versions' }
| { kind: 'compare'; version: number }
| { kind: 'restore'; version: number };
export interface LiveProvider {
panel(root: vscode.Uri): Promise<LivePanel | undefined>;
act(root: vscode.Uri, action: LiveAction): Promise<void>;
/** Others' cursors in a shared file; empty when the file is not shared. */
cursors(file: vscode.Uri): LiveCursor[];
/** This person's cursor in a page's Source view; undefined when it closes. */
setCursor(file: vscode.Uri, selection: LiveSelection | undefined): void;
}
class LiveBridge implements vscode.Disposable {
private provider: LiveProvider | undefined;
private readonly emitter = new vscode.EventEmitter<vscode.Uri | undefined>();
/** A model root whose Live section changed; undefined for all of them. */
readonly onDidChange = this.emitter.event;
private readonly cursorEmitter = new vscode.EventEmitter<void>();
/** Someone's cursor moved somewhere; ask `cursors` for the file you show. */
readonly onDidChangeCursors = this.cursorEmitter.event;
setProvider(provider: LiveProvider | undefined): void {
this.provider = provider;
this.emitter.fire(undefined);
this.cursorEmitter.fire();
}
changed(root?: vscode.Uri): void {
this.emitter.fire(root);
}
async panel(root: vscode.Uri): Promise<LivePanel | undefined> {
return this.provider?.panel(root);
}
async act(root: vscode.Uri, action: LiveAction): Promise<void> {
await this.provider?.act(root, action);
}
cursorsChanged(): void {
this.cursorEmitter.fire();
}
cursors(file: vscode.Uri): LiveCursor[] {
return this.provider?.cursors(file) ?? [];
}
setCursor(file: vscode.Uri, selection: LiveSelection | undefined): void {
this.provider?.setCursor(file, selection);
}
dispose(): void {
this.emitter.dispose();
this.cursorEmitter.dispose();
}
}
export const liveBridge = new LiveBridge();
export type { LiveBridge };
+231
View File
@@ -0,0 +1,231 @@
import * as path from 'node:path';
import * as vscode from 'vscode';
import * as Y from 'yjs';
import { Awareness } from 'y-protocols/awareness';
import { syncSocketUrl } from './api';
import { SyncAuth } from './auth';
import { ConnectionState, LiveConnection } from './connection';
import { FileBridge } from './fileBridge';
import { OfflineStore } from './offlineStore';
import { colorFor } from './cursors';
import type { LiveCursor, LiveSelection } from './liveBridge';
import { Link } from './protocol';
/** How a space starts: as found in the workspace, just shared from here, or just joined. */
export type StartMode = 'open' | 'share' | 'join';
/** Edits loaded from the offline copy; not stored again. */
const FROM_COPY = Symbol('offline copy');
const COMPACT_AFTER = 200;
export interface Presence {
user: { id: string; name: string };
/** Model-relative path of the file the person has in front of them. */
file?: string;
/** Where the person's cursor is: Yjs relative positions, so it stays put while others type. */
cursor?: { file: string; anchor: unknown; head: unknown };
}
/**
* One shared model in this window: the Yjs document, its offline copy, the
* connection to the server, the bridge to the files, and presence.
*/
export class LiveSpace implements vscode.Disposable {
readonly doc = new Y.Doc();
readonly awareness = new Awareness(this.doc);
private readonly store: OfflineStore;
private readonly local = { origin: 'local' };
private readonly bridge: FileBridge;
private connection?: LiveConnection;
private readonly disposables: vscode.Disposable[] = [];
private hadCopy = false;
private firstSync = true;
constructor(
readonly root: vscode.Uri,
readonly link: Link,
private readonly mode: StartMode,
private readonly services: {
context: vscode.ExtensionContext;
auth: SyncAuth;
log: vscode.LogOutputChannel;
onChange: () => void;
/** Someone's cursor moved. */
onCursors?: () => void;
},
) {
const dir = path.join(services.context.globalStorageUri.fsPath, 'sync');
this.store = new OfflineStore(dir, link.space);
this.bridge = new FileBridge(root, this.doc, this.local, services.log);
}
get state(): ConnectionState {
return this.connection?.state ?? 'connecting';
}
get name(): string {
return this.link.name ?? path.basename(this.root.fsPath);
}
/** Distinct people in the space, this one included. */
people(): Presence[] {
const seen = new Map<string, Presence>();
for (const state of this.awareness.getStates().values()) {
const p = state as Partial<Presence>;
if (p.user?.id) seen.set(p.user.id, { user: p.user, file: p.file });
}
return [...seen.values()];
}
/** Puts this person's cursor in a shared file; false when the file is not part of this model. */
setCursor(uri: vscode.Uri, selection: LiveSelection | undefined): boolean {
const rel = this.bridge.relative(uri);
if (!rel) return false;
const current = this.awareness.getLocalState() as Presence | null;
if (!current) return true;
if (!selection) {
// Only the file the cursor is in can take it away.
if (current.cursor?.file === rel) this.awareness.setLocalStateField('cursor', undefined);
return true;
}
const text = this.doc.getMap<Y.Text>('files').get(rel);
if (!(text instanceof Y.Text)) return true;
const at = (offset: number) => Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, Math.max(0, Math.min(offset, text.length))));
this.awareness.setLocalStateField('cursor', { file: rel, anchor: at(selection.anchor), head: at(selection.head) });
return true;
}
/** Other people's cursors in a file, as offsets into its text here. */
cursors(uri: vscode.Uri): LiveCursor[] {
const rel = this.bridge.relative(uri);
if (!rel) return [];
const found: LiveCursor[] = [];
for (const [client, state] of this.awareness.getStates()) {
if (client === this.doc.clientID) continue;
const p = state as Partial<Presence>;
if (!p.user?.id || p.cursor?.file !== rel) continue;
const index = (json: unknown) => {
try {
return Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(json), this.doc)?.index;
} catch {
return undefined;
}
};
const anchor = index(p.cursor.anchor);
const head = index(p.cursor.head);
if (anchor === undefined || head === undefined) continue;
found.push({ name: p.user.name, color: colorFor(p.user.id), anchor, head });
}
return found;
}
async start(): Promise<void> {
const { log } = this.services;
this.hadCopy = this.store.exists();
for (const update of this.store.load()) Y.applyUpdate(this.doc, update, FROM_COPY);
// Registered before the connection's listener, so every edit is on disk before it is sent.
this.doc.on('update', (update: Uint8Array, origin: unknown) => {
if (origin === FROM_COPY) return;
this.store.append(update);
if (this.store.pending >= COMPACT_AFTER) this.compact();
});
if (this.hadCopy) {
// Edits made while the extension was not running (git pull, another tool).
await this.bridge.pushAll(true);
} else if (this.mode === 'share') {
await this.bridge.pushAll(false);
}
// Without a copy, local edits wait for the server's files, so a file
// does not start twice (once here, once there) and lose one side.
this.bridge.start(this.hadCopy || this.mode === 'share');
const session = await this.services.auth.session(this.link.server);
if (session) this.awareness.setLocalState({ user: { id: session.account.id, name: session.account.display_name } } satisfies Presence);
this.disposables.push(
vscode.window.onDidChangeActiveTextEditor(() => this.updateFile()),
vscode.window.tabGroups.onDidChangeTabs(() => this.updateFile()),
{ dispose: () => this.awareness.destroy() },
);
this.updateFile();
let people = '';
this.awareness.on('change', () => {
// Cursors move all the time; the status bar and pages only care who is where.
const now = JSON.stringify(this.people());
if (now !== people) {
people = now;
this.services.onChange();
}
this.services.onCursors?.();
});
this.connection = new LiveConnection({
url: syncSocketUrl(this.link.server, this.link.space),
token: (force) => this.services.auth.accessToken(this.link.server, force),
doc: this.doc,
awareness: this.awareness,
onState: (state) => {
log.info(`sync: ${this.name} is ${state}`);
this.services.onChange();
},
onSynced: () => void this.synced(),
log: (message) => log.info(message),
});
}
private async synced(): Promise<void> {
if (!this.firstSync) return;
this.firstSync = false;
if (!this.hadCopy && this.mode !== 'share') {
// First time here: the server's files come to disk, then local-only files go up.
await this.bridge.pullAll();
this.bridge.start(true);
this.hadCopy = true;
}
this.compact();
}
private compact(): void {
try {
this.store.compact(Y.encodeStateAsUpdate(this.doc));
} catch (error) {
this.services.log.warn(`sync: could not compact the offline copy (${String(error)})`);
}
}
private updateFile(): void {
const current = this.awareness.getLocalState() as Presence | null;
if (!current) return;
// The text editor, or the tab of an Archify page (the model page, a diagram, a registry).
const input = vscode.window.tabGroups.activeTabGroup.activeTab?.input;
const tab = input instanceof vscode.TabInputCustom || input instanceof vscode.TabInputText ? input.uri : undefined;
const uri = vscode.window.activeTextEditor?.document.uri ?? tab;
const file = uri ? this.bridge.relative(uri) : undefined;
if (current.file !== file) this.awareness.setLocalState({ ...current, file });
}
/** After signing in again. */
reconnect(): void {
void this.services.auth.session(this.link.server).then((session) => {
if (session && !this.awareness.getLocalState()) {
this.awareness.setLocalState({ user: { id: session.account.id, name: session.account.display_name } } satisfies Presence);
}
this.connection?.reconnectNow();
});
}
/** Stops syncing this model here and forgets the offline copy. */
forget(): void {
this.dispose();
this.store.remove();
}
dispose(): void {
this.connection?.dispose();
this.connection = undefined;
this.bridge.dispose();
for (const d of this.disposables.splice(0)) d.dispose();
if (this.store.pending) this.compact();
this.doc.destroy();
}
}
+54
View File
@@ -0,0 +1,54 @@
import * as path from 'node:path';
import * as vscode from 'vscode';
import type { ModelService } from '../model/service';
import { log } from '../util/log';
import type { SyncFeature } from './index';
import { liveBridge } from './liveBridge';
// Kept in step with SYNC_COMMANDS in ./index (which lives in the other bundle).
const COMMANDS = [
'archify.sync.signIn',
'archify.sync.signOut',
'archify.sync.share',
'archify.sync.invite',
'archify.sync.join',
'archify.sync.publish',
'archify.sync.versions',
'archify.sync.stop',
'archify.sync.menu',
'archify.sync.setServer',
] as const;
/**
* Archify Sync is optional. This registers its commands and the URI handler,
* and loads dist/sync.js (Yjs, the WebSocket) only when it is needed: a model
* in the workspace is shared, someone signed in on this machine, or a sync
* command or link runs. Without that, nothing else happens.
*/
export function registerSync(context: vscode.ExtensionContext, models: ModelService): vscode.Disposable[] {
let feature: Promise<SyncFeature> | undefined;
const load = (): Promise<SyncFeature> =>
(feature ??= (async () => {
// A runtime path, so esbuild leaves the sync bundle out of this one.
const bundle = path.join(__dirname, 'sync.js');
const mod = require(bundle) as typeof import('./index');
const sync = new mod.SyncFeature(context, models, log(), liveBridge);
context.subscriptions.push(sync);
await sync.start();
return sync;
})());
void (async () => {
const used = context.globalState.get<boolean>('archifySync.used') === true;
const shared = used || (await vscode.workspace.findFiles('**/.archify-sync', '{**/node_modules/**,**/.git/**}', 1)).length > 0;
if (shared) load().catch((error) => log().error(`sync: did not start: ${String(error)}`));
})();
return [
liveBridge,
...COMMANDS.map((id) =>
vscode.commands.registerCommand(id, async (...args: unknown[]) => (await load()).run(id, ...args)),
),
vscode.window.registerUriHandler({ handleUri: async (uri) => (await load()).handleUri(uri) }),
];
}
+68
View File
@@ -0,0 +1,68 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
/**
* The offline copy of one shared model: the last compacted Yjs state and a
* log of every update since, each written before it is sent. Lets people
* keep working while the server is away and catch up afterwards.
*/
export class OfflineStore {
private readonly statePath: string;
private readonly logPath: string;
private logged = 0;
constructor(dir: string, id: string) {
fs.mkdirSync(dir, { recursive: true });
this.statePath = path.join(dir, `${id}.state`);
this.logPath = path.join(dir, `${id}.log`);
}
exists(): boolean {
return fs.existsSync(this.statePath) || fs.existsSync(this.logPath);
}
/** Updates to apply in order: the state, then the log. A torn last entry is skipped. */
load(): Uint8Array[] {
const out: Uint8Array[] = [];
if (fs.existsSync(this.statePath)) out.push(new Uint8Array(fs.readFileSync(this.statePath)));
if (fs.existsSync(this.logPath)) {
const log = fs.readFileSync(this.logPath);
let at = 0;
while (at + 4 <= log.length) {
const length = log.readUInt32LE(at);
if (at + 4 + length > log.length) break;
out.push(new Uint8Array(log.subarray(at + 4, at + 4 + length)));
at += 4 + length;
this.logged++;
}
}
return out;
}
/** Appends one update; synchronous, so it is on disk before the caller sends it. */
append(update: Uint8Array): void {
const head = Buffer.alloc(4);
head.writeUInt32LE(update.length);
fs.appendFileSync(this.logPath, Buffer.concat([head, update]));
this.logged++;
}
/** Updates in the log since the last compaction. */
get pending(): number {
return this.logged;
}
/** Replaces state and log with one encoded state. */
compact(state: Uint8Array): void {
const tmp = `${this.statePath}.tmp`;
fs.writeFileSync(tmp, state);
fs.renameSync(tmp, this.statePath);
fs.rmSync(this.logPath, { force: true });
this.logged = 0;
}
remove(): void {
fs.rmSync(this.statePath, { force: true });
fs.rmSync(this.logPath, { force: true });
}
}
+60
View File
@@ -0,0 +1,60 @@
// What the extension and the Archify Sync server agree on. Mirrors
// `packages/protocol` (generated from Rust) in archify-vscode-ext-sync; keep
// both in step when the protocol changes.
export const PROTOCOL_VERSION = 1;
/** Root map of a space's Yjs document: model-root-relative POSIX path → Y.Text. */
export const FILES_MAP = 'files';
/** The link file in a model root: names server and space, holds no secrets. */
export const LINK_FILE = '.archify-sync';
export type OrgRole = 'admin' | 'member';
export type SpaceRole = 'owner' | 'editor';
export type VersionKind = 'snapshot' | 'publish' | 'restore';
export interface ApiError { error: string; message: string }
export interface Account { id: string; organisation_id: string; name: string; display_name: string; role: OrgRole }
export interface TokenResponse { access_token: string; expires_in: number; refresh_token: string; account: Account }
export interface ServerInfo { name: string; version: string; protocol: number; set_up: boolean }
export interface Space { id: string; name: string; role: SpaceRole; created_at: string }
export interface Member { account_id: string; name: string; display_name: string; role: SpaceRole }
export interface Invite { token: string; url: string; expires_at: string }
export interface JoinResponse { space: Space }
export interface Version {
id: number;
major: number;
minor: number;
kind: VersionKind;
name: string | null;
created_by: string | null;
created_at: string;
restored_from: number | null;
}
export interface VersionFiles { version: Version; files: { path: string; text: string }[] }
/** The contents of `.archify-sync`. */
export interface Link {
server: string;
space: string;
name?: string;
}
export function parseLink(text: string): Link | undefined {
try {
const value = JSON.parse(text) as Partial<Link>;
if (typeof value.server === 'string' && typeof value.space === 'string' && /^[0-9a-f-]{36}$/i.test(value.space)) {
return { server: value.server.replace(/\/+$/, ''), space: value.space, name: typeof value.name === 'string' ? value.name : undefined };
}
} catch {
// not a link
}
return undefined;
}
export function formatLink(link: Link): string {
return `${JSON.stringify({ server: link.server, space: link.space, name: link.name }, null, 2)}\n`;
}
export function versionLabel(v: Version): string {
return `${v.major}.${v.minor}`;
}
+33
View File
@@ -0,0 +1,33 @@
import * as Y from 'yjs';
import { TextChange, minimalChange } from '../util/textDiff';
const isHigh = (code: number) => code >= 0xd800 && code <= 0xdbff;
const isLow = (code: number) => code >= 0xdc00 && code <= 0xdfff;
/**
* `minimalChange`, widened so it never splits a surrogate pair: Yjs would
* replace half a pair with U+FFFD, and every copy would get the broken text.
*/
export function safeChange(before: string, after: string): TextChange | undefined {
const change = minimalChange(before, after);
if (!change) return undefined;
let { from, to } = change;
let endAfter = after.length - (before.length - to);
// A common start ending in a high surrogate, or a common end starting with
// a low one, would split a pair: take the whole character into the change.
if (from > 0 && isHigh(before.charCodeAt(from - 1))) from--;
if (to < before.length && isLow(before.charCodeAt(to))) {
to++;
endAfter++;
}
return { from, to, insert: after.slice(from, endAfter) };
}
/** Makes the Y.Text read `after` with one minimal edit; false when it already does. */
export function applyToYText(text: Y.Text, after: string): boolean {
const change = safeChange(text.toString(), after);
if (!change) return false;
if (change.to > change.from) text.delete(change.from, change.to - change.from);
if (change.insert) text.insert(change.from, change.insert);
return true;
}
+100
View File
@@ -0,0 +1,100 @@
import * as vscode from 'vscode';
import { SyncApi } from './api';
import { LiveSpace } from './liveSpace';
import { Version, VersionFiles, versionLabel } from './protocol';
export const VERSION_SCHEME = 'archify-sync-version';
/** Read-only documents of a version's files: `archify-sync-version:/<space>/<version>/<path>`. */
export class VersionContent implements vscode.TextDocumentContentProvider {
private readonly cache = new Map<string, Promise<VersionFiles>>();
constructor(private readonly api: (space: string) => SyncApi | undefined) {}
files(space: string, version: number): Promise<VersionFiles> {
const key = `${space}/${version}`;
let found = this.cache.get(key);
if (!found) {
const api = this.api(space);
if (!api) return Promise.reject(new Error('This model is not shared from here.'));
found = api.versionFiles(space, version);
found.catch(() => this.cache.delete(key));
this.cache.set(key, found);
}
return found;
}
async provideTextDocumentContent(uri: vscode.Uri): Promise<string> {
const [, space, version, ...rest] = uri.path.split('/');
const files = await this.files(space, Number(version));
return files.files.find((f) => f.path === rest.join('/'))?.text ?? '';
}
}
function describe(v: Version): vscode.QuickPickItem & { version: Version } {
const when = new Date(v.created_at).toLocaleString();
const kind = v.kind === 'publish' ? 'published' : v.kind === 'restore' ? `restored ${v.restored_from ?? ''}`.trim() : 'snapshot';
return {
label: `${v.kind === 'publish' ? '$(tag)' : v.kind === 'restore' ? '$(history)' : '$(circle-small)'} ${versionLabel(v)}${v.name ? ` ${v.name}` : ''}`,
description: kind,
detail: when,
version: v,
};
}
/** Versions of a space: pick one, then compare with the files here or restore it. */
export async function showVersions(space: LiveSpace, api: SyncApi, content: VersionContent): Promise<void> {
const versions = await api.versions(space.link.space);
if (!versions.length) {
vscode.window.showInformationMessage(`Archify: ${space.name} has no versions yet. One is taken on its own after a pause in editing.`);
return;
}
const picked = await vscode.window.showQuickPick(versions.map(describe), { title: `Archify | Versions of ${space.name}`, placeHolder: 'Pick a version' });
if (!picked) return;
const v = picked.version;
const action = await vscode.window.showQuickPick(
[
{ label: '$(diff) Compare with the files here', id: 'compare' },
{ label: '$(history) Restore this version', id: 'restore', detail: 'Brings these files back for everyone, as a new version. Nothing is lost.' },
],
{ title: `Archify | ${versionLabel(v)}${v.name ? ` ${v.name}` : ''}` },
);
if (action?.id === 'compare') await compareVersion(space, v, content);
if (action?.id === 'restore') await restoreVersion(space, api, v);
}
/** Asks, then brings back a version's files for everyone as a new version. */
export async function restoreVersion(space: LiveSpace, api: SyncApi, v: Version): Promise<boolean> {
const ok = await vscode.window.showWarningMessage(
`Restore ${versionLabel(v)} of ${space.name} for everyone?`,
{ modal: true, detail: 'The files go back to this version for everyone in the space. It becomes a new version; the history stays.' },
'Restore',
);
if (ok !== 'Restore') return false;
const restored = await api.restore(space.link.space, v.id);
vscode.window.showInformationMessage(`Archify: restored ${versionLabel(v)} as ${versionLabel(restored)}.`);
return true;
}
/** Lists the files that differ from a version and opens the diff of the one picked. */
export async function compareVersion(space: LiveSpace, v: Version, content: VersionContent): Promise<void> {
const files = await content.files(space.link.space, v.id);
const here = new Map<string, string>();
for (const [rel, text] of space.doc.getMap<{ toString(): string }>('files').entries()) here.set(rel, text.toString());
const paths = [...new Set([...files.files.map((f) => f.path), ...here.keys()])].sort();
const changed = paths
.map((p) => ({ path: p, then: files.files.find((f) => f.path === p)?.text, now: here.get(p) }))
.filter((f) => f.then !== f.now);
if (!changed.length) {
vscode.window.showInformationMessage(`Archify: the files here are the same as ${versionLabel(v)}.`);
return;
}
const pick = await vscode.window.showQuickPick(
changed.map((f) => ({ label: f.path, description: f.then === undefined ? 'added since' : f.now === undefined ? 'removed since' : 'changed', path: f.path })),
{ title: `Archify | Changes since ${versionLabel(v)}`, placeHolder: `${changed.length} file(s) differ` },
);
if (!pick) return;
const left = vscode.Uri.from({ scheme: VERSION_SCHEME, path: `/${space.link.space}/${v.id}/${pick.path}` });
const right = vscode.Uri.joinPath(space.root, ...pick.path.split('/'));
await vscode.commands.executeCommand('vscode.diff', left, right, `${pick.path} (${versionLabel(v)} ↔ here)`);
}
+64
View File
@@ -0,0 +1,64 @@
// Text helpers shared by the host and the Source view in the page. The page's
// editor always works in "\n" text; documents may use "\r\n".
export interface TextChange {
from: number;
to: number;
insert: string;
}
/** The text with "\r\n" turned into "\n". */
export function normalizeEol(text: string): string {
return text.replace(/\r\n/g, '\n');
}
/**
* The smallest single change that turns `before` into `after`: the common
* start and end are kept, so a cursor outside the change stays put.
*/
export function minimalChange(before: string, after: string): TextChange | undefined {
if (before === after) return undefined;
let start = 0;
const max = Math.min(before.length, after.length);
while (start < max && before.charCodeAt(start) === after.charCodeAt(start)) start++;
let endBefore = before.length;
let endAfter = after.length;
while (endBefore > start && endAfter > start && before.charCodeAt(endBefore - 1) === after.charCodeAt(endAfter - 1)) {
endBefore--;
endAfter--;
}
return { from: start, to: endBefore, insert: after.slice(start, endAfter) };
}
/** Line and character of an offset into "\n" text. */
export function positionOf(text: string, offset: number): { line: number; character: number } {
const clamped = Math.max(0, Math.min(offset, text.length));
let line = 0;
let lineStart = 0;
for (let i = text.indexOf('\n'); i !== -1 && i < clamped; i = text.indexOf('\n', i + 1)) {
line++;
lineStart = i + 1;
}
return { line, character: clamped - lineStart };
}
/** Offset into "\n" text of a line and character (clamped to the line). */
export function offsetOf(text: string, line: number, character: number): number {
let start = 0;
for (let l = 0; l < line; l++) {
const next = text.indexOf('\n', start);
if (next === -1) return text.length;
start = next + 1;
}
const end = text.indexOf('\n', start);
return Math.min(start + Math.max(0, character), end === -1 ? text.length : end);
}
/** Applies changes given in the coordinates of `text` (as one editor transaction reports them). */
export function applyChanges(text: string, changes: TextChange[]): string {
let out = text;
for (const change of [...changes].sort((a, b) => b.from - a.from)) {
out = out.slice(0, change.from) + change.insert + out.slice(change.to);
}
return out;
}
+13 -16
View File
@@ -2,6 +2,7 @@ import { layerMarkup, rasterize } from './raster';
import { CameraState, Layers, Stage } from './stage';
import { DiagramModel, readModel } from './svgModel';
import { STYLE } from './style';
import type { ArchifyHost } from '../webview/host';
/**
* 3D mode for the Archify viewer. It adds a 2D | 3D switch to Archify's
@@ -12,12 +13,7 @@ import { STYLE } from './style';
* follows Archify's animations as they play.
*/
interface Host {
defaultView: '2d' | '3d';
post(message: unknown): void;
getState(): Record<string, unknown>;
setState(patch: Record<string, unknown>): void;
}
type Host = ArchifyHost;
interface SavedView {
active?: boolean;
@@ -25,12 +21,6 @@ interface SavedView {
camera?: CameraState;
}
declare global {
interface Window {
__archifyHost?: Host;
}
}
const REDRAW_MS = 220;
const MARGIN = 80;
/** Texture pixels per SVG unit; more costs memory and upload time for little gain. */
@@ -68,13 +58,20 @@ class Viewer3D {
this.interceptViewerControls();
if (this.saved.active ?? host.defaultView === '3d') this.setActive(true);
else this.syncButtons();
// The Source view hides the picture; the stage stops drawing meanwhile.
window.addEventListener('archify-source', (event) => {
if (!this.active || !this.stage) return;
if ((event as CustomEvent<{ on: boolean }>).detail.on) this.stage.stop();
else this.stage.start();
});
}
// -------------------------------------------------------------- chrome
/**
* The 2D | 3D switch: Export's twin in the toolbar. Both states are always
* visible, the filled half is the current one, a click flips it.
* The 2D | 3D switch in the toolbar, left of Diagram | Graph | Source (it
* says how the picture is drawn, that one what is shown). Both states are
* always visible, the filled half is the current one, a click flips it.
*/
private buildSwitch(): HTMLButtonElement {
const button = document.createElement('button');
@@ -89,8 +86,8 @@ class Viewer3D {
event.stopPropagation();
this.setActive(!this.active);
});
const exportWrap = document.querySelector('.toolbar .export-wrap');
if (exportWrap?.parentElement) exportWrap.parentElement.insertBefore(button, exportWrap);
const anchor = document.querySelector('.toolbar #archify-mode-switch') ?? document.querySelector('.toolbar .export-wrap');
if (anchor?.parentElement) anchor.parentElement.insertBefore(button, anchor);
else document.querySelector('.toolbar')?.appendChild(button);
return button;
}
+173
View File
@@ -0,0 +1,173 @@
import path from 'node:path';
import * as vscode from 'vscode';
import { isDecisionFile, parseDecision } from '../model/decisions';
import { isMainFile, isRegistryFile } from '../model/format';
import { DecisionPanel, decisionPanelFromIndex, decisionPanelStandalone } from '../model/panel';
import { ModelService } from '../model/service';
import { readText } from '../util/files';
import { log } from '../util/log';
import { sourceScriptUri } from '../webview/viewer3d';
import { SourceSession } from './sourceSession';
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
import { decisionPage, makeNonce } from '../webview/page';
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
export { DECISION_VIEW_TYPE };
class DecisionView implements vscode.Disposable {
private seq = 0;
private timer: NodeJS.Timeout | undefined;
private last: string | undefined;
root: vscode.Uri | undefined;
private readonly disposables: vscode.Disposable[] = [];
/** The Source view; while it shows, a new page waits in `heldHtml`. */
readonly source: SourceSession;
private heldHtml: string | undefined;
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
readonly panel: vscode.WebviewPanel,
readonly uri: vscode.Uri,
) {
this.source = new SourceSession(context, panel, uri, 'decision', (shown) => {
if (!shown && this.heldHtml !== undefined) {
const html = this.heldHtml;
this.heldHtml = undefined;
this.panel.webview.html = html;
}
});
this.disposables.push(
this.source,
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
if (this.source.handle(message)) return;
if (message.type === 'openDiagram') return void this.openInModel(message.path, DIAGRAM_EDITOR_VIEW_TYPE);
if (message.type === 'openRegistry') return void this.openRegistryLine(message.file, message.line);
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
void handleWebviewMessage(message, this.uri, this.panel);
}),
);
void this.update();
}
private async openInModel(relativePath: string, viewType: string): Promise<void> {
if (!this.root) return;
const target = vscode.Uri.joinPath(this.root, ...relativePath.split('/'));
try {
await vscode.workspace.fs.stat(target);
} catch {
vscode.window.showWarningMessage(`Archify: ${relativePath} does not exist in this model.`);
return;
}
await vscode.commands.executeCommand('vscode.openWith', target, viewType, vscode.ViewColumn.Active);
}
private async openRegistryLine(file: string, line?: number): Promise<void> {
if (!this.root) return;
const target = vscode.Uri.joinPath(this.root, ...file.split('/'));
const column = this.panel.viewColumn === vscode.ViewColumn.One ? vscode.ViewColumn.Two : vscode.ViewColumn.One;
const at = Math.max(line ?? 0, 0);
await vscode.window.showTextDocument(target, { viewColumn: column, selection: new vscode.Range(at, 0, at, 0) });
}
scheduleUpdate(): void {
clearTimeout(this.timer);
this.timer = setTimeout(() => void this.update(), 300);
}
async update(): Promise<void> {
clearTimeout(this.timer);
const seq = ++this.seq;
let decision: DecisionPanel;
try {
this.root = await this.models.rootOf(this.uri);
if (this.root) {
const rel = path.relative(this.root.fsPath, this.uri.fsPath).split(path.sep).join('/');
decision = decisionPanelFromIndex(await this.models.index(this.root), rel);
} else {
const name = path.basename(this.uri.path);
decision = decisionPanelStandalone(name, parseDecision(await readText(this.uri), name));
}
} catch (error) {
log().warn(`Decision view failed for ${this.uri.fsPath}: ${error instanceof Error ? error.message : String(error)}`);
return;
}
if (seq !== this.seq) return;
const fingerprint = JSON.stringify(decision);
if (fingerprint === this.last) return;
this.last = fingerprint;
const html = decisionPage(
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), source: { scriptUri: sourceScriptUri(this.panel.webview, this.context.extensionUri), left: 'View' } },
decision,
);
if (this.source.shown) this.heldHtml = html;
else this.panel.webview.html = html;
}
dispose(): void {
clearTimeout(this.timer);
for (const d of this.disposables.splice(0)) d.dispose();
}
}
/** Custom editor for .archify-decision files: the decision as a page, with its elements and diagrams. */
export class DecisionViewProvider implements vscode.CustomTextEditorProvider, vscode.Disposable {
private readonly views = new Set<DecisionView>();
private active: DecisionView | undefined;
private readonly disposables: vscode.Disposable[];
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
) {
this.disposables = [
vscode.window.registerCustomEditorProvider(DECISION_VIEW_TYPE, this, {
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
supportsMultipleEditorsPerDocument: true,
}),
models.onDidChangeModel(({ root }) => {
for (const view of this.views) if (view.root?.toString() === root.toString()) view.scheduleUpdate();
}),
vscode.workspace.onDidChangeTextDocument((event) => {
if (!isDecisionFile(event.document.fileName) && !isRegistryFile(event.document.fileName) && !isMainFile(event.document.fileName)) return;
for (const view of this.views) if (!view.root && view.uri.toString() === event.document.uri.toString()) view.scheduleUpdate();
}),
];
}
/** File shown in the focused decision view, if any. */
get activeUri(): vscode.Uri | undefined {
return this.active?.uri;
}
/** The view of the focused page, if any. */
get activeView(): { source: SourceSession } | undefined {
return this.active;
}
// A text editor provider: the page edits the file's own TextDocument (in
// its Source view), so dirty state, save and undo are VS Code's.
async resolveCustomTextEditor(document: vscode.TextDocument, panel: vscode.WebviewPanel): Promise<void> {
panel.webview.options = { enableScripts: true };
const view = new DecisionView(this.context, this.models, panel, document.uri);
this.views.add(view);
const onViewState = () => {
if (panel.active) this.active = view;
else if (this.active === view) this.active = undefined;
if (panel.active) void vscode.commands.executeCommand('setContext', 'archify.inModel', Boolean(view.root));
};
panel.onDidChangeViewState(onViewState);
onViewState();
panel.onDidDispose(() => {
this.views.delete(view);
if (this.active === view) this.active = undefined;
view.dispose();
});
}
dispose(): void {
for (const view of this.views) view.dispose();
this.views.clear();
for (const d of this.disposables.splice(0)) d.dispose();
}
}
+201 -22
View File
@@ -2,7 +2,8 @@ import path from 'node:path';
import * as vscode from 'vscode';
import { renderDiagram } from '../archify/cli';
import { evidenceMode, runtimeFor } from '../archify/runtime';
import { isMainFile, isRegistryFile } from '../model/format';
import { MAIN_FILE, isMainFile, isRegistryFile } from '../model/format';
import { buildGraph } from '../model/graph';
import { ModelPanel, panelFromIndex } from '../model/panel';
import { prepareDiagram } from '../model/prepare';
import { ModelService } from '../model/service';
@@ -11,18 +12,30 @@ import { readText } from '../util/files';
import { log } from '../util/log';
import { viewerTheme } from '../util/settings';
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
import { makeNonce, messagePage, modelPage, prepareDiagramHtml } from '../webview/page';
import { viewer3dOption, viewerRoots } from '../webview/viewer3d';
import { graphPage, makeNonce, messagePage, modelPage, prepareDiagramHtml } from '../webview/page';
import { graphScriptUri, sourceScriptUri, viewer3dOption, viewerRoots } from '../webview/viewer3d';
import { liveBridge } from '../sync/liveBridge';
import { SourceSession } from './sourceSession';
export const PREVIEW_VIEW_TYPE = 'archify.preview';
/** Default editor for .archify files: the rendered diagram. */
export const DIAGRAM_EDITOR_VIEW_TYPE = 'archify.diagram';
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, PREVIEW_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
export { DIAGRAM_EDITOR_VIEW_TYPE, PREVIEW_VIEW_TYPE };
interface PreviewState {
uri: string;
hash?: string;
/** main.archify only: the Graph page is shown instead of the model page. */
graph?: boolean;
}
/** What a preview asks of its manager. */
interface PreviewHost {
/** Opens the Graph page of the model at `root`, with a query to start from. */
openGraph(root: vscode.Uri, query?: string): Promise<void>;
}
const GRAPH_MODE_KEY = 'archify.graphMode';
class DiagramPreview implements vscode.Disposable {
private seq = 0;
private hash: string | undefined;
@@ -34,10 +47,22 @@ class DiagramPreview implements vscode.Disposable {
readonly onDidDispose = this.onDisposeEmitter.event;
/** Root of the model this file belongs to, once known. */
root: vscode.Uri | undefined;
/** main.archify: show the Graph page instead of the model page. Remembered per file across reloads. */
private graph = false;
private graphQuery: string | undefined;
/** True while the webview shows the Graph page, which takes model updates as messages. */
private graphShown = false;
/** The Source view of a .archify file; while it shows, new HTML waits in `heldHtml`. */
readonly source: SourceSession | undefined;
private heldHtml: string | undefined;
private disposed = false;
/** main.archify: the model page has its Live slot and takes `live` messages. */
private liveShown = false;
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
private readonly host: PreviewHost,
readonly panel: vscode.WebviewPanel,
readonly uri: vscode.Uri,
state?: PreviewState,
@@ -45,27 +70,74 @@ class DiagramPreview implements vscode.Disposable {
readonly isEditor = false,
) {
this.hash = state?.hash;
this.graph = state?.graph ?? this.graphModes()[uri.toString()] === true;
panel.webview.options = { enableScripts: true, localResourceRoots: viewerRoots(this.context.extensionUri) };
if (!isEditor) {
panel.iconPath = vscode.Uri.joinPath(context.extensionUri, 'media', 'preview.svg');
panel.title = `Preview ${path.basename(uri.path)}`;
}
if (isArchifyFile(uri.path)) {
this.source = new SourceSession(context, panel, uri, 'diagram', (shown) => {
// Back from Source: show what was rendered meanwhile.
if (!shown && this.heldHtml !== undefined) {
const html = this.heldHtml;
this.heldHtml = undefined;
this.liveShown = false;
this.panel.webview.html = html;
}
});
this.disposables.push(this.source);
}
this.disposables.push(
panel.onDidDispose(() => this.dispose()),
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
if (this.source?.handle(message)) return;
if (message.type === 'hash') {
this.hash = message.hash;
return;
}
if (message.type === 'openDiagram') {
void this.openLinked(message.path);
void this.openLinked(message.path, DIAGRAM_EDITOR_VIEW_TYPE);
return;
}
if (message.type === 'openRegistry') {
void this.openLinked(message.file, REGISTRY_VIEW_TYPE);
return;
}
if (message.type === 'openDecision') {
void this.openLinked(message.file, DECISION_VIEW_TYPE);
return;
}
if (message.type === 'showGraph') {
if (isMainFile(this.uri.path)) this.setGraph(true, message.query);
else if (this.root) void this.host.openGraph(this.root, message.query);
return;
}
if (message.type === 'showModel') {
this.setGraph(false);
return;
}
if (message.type === 'liveReady') {
this.liveShown = true;
void this.postLive();
return;
}
if (message.type === 'liveAction') {
if (this.root) void liveBridge.act(this.root, message.action);
return;
}
void handleWebviewMessage(message, this.uri, this.panel);
}),
);
if (isMainFile(uri.path)) {
this.disposables.push(liveBridge.onDidChange((root) => {
if (!root || (this.root && root.toString() === this.root.toString())) void this.postLive();
}));
}
if (uri.scheme === 'file') {
const watcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(vscode.Uri.file(path.dirname(uri.fsPath)), path.basename(uri.fsPath)),
@@ -81,22 +153,93 @@ class DiagramPreview implements vscode.Disposable {
void this.update();
}
/** The Live section of a shared model's page; nothing when the model is not shared. */
private async postLive(): Promise<void> {
if (!this.liveShown || !this.root || this.disposed) return;
const live = await liveBridge.panel(this.root).catch(() => undefined);
if (this.liveShown) this.post({ type: 'live', live });
}
/** Posts to the webview; a panel closed mid-update is not an error. */
private post(message: unknown): void {
Promise.resolve(this.panel.webview.postMessage(message)).catch(() => undefined);
}
/** Replaces the page, unless Source is open in it: then the page waits until it closes. */
private setHtml(html: string): void {
if (this.disposed) return;
if (this.source?.shown) {
this.heldHtml = html;
return;
}
this.heldHtml = undefined;
this.liveShown = false;
this.panel.webview.html = html;
}
/** Page option for the Source view, on .archify files. */
private sourceOption(left: 'Model' | 'Diagram'): { scriptUri: string; left: 'Model' | 'Diagram' } | undefined {
return this.source ? { scriptUri: sourceScriptUri(this.panel.webview, this.context.extensionUri), left } : undefined;
}
private state(): PreviewState {
return { uri: this.uri.toString(), hash: this.hash };
return { uri: this.uri.toString(), hash: this.hash, graph: this.graph };
}
private graphModes(): Record<string, boolean> {
return this.context.workspaceState.get<Record<string, boolean>>(GRAPH_MODE_KEY, {});
}
/** Switches a main.archify editor between its model page and the Graph page. */
setGraph(on: boolean, query?: string): void {
// Leaving Source for another page: drop what it held, or that page would
// wait for a sourceClose that never comes and show up later instead.
this.heldHtml = undefined;
this.source?.leave();
this.graph = on;
this.graphQuery = query;
const modes = this.graphModes();
if (on) modes[this.uri.toString()] = true;
else delete modes[this.uri.toString()];
void this.context.workspaceState.update(GRAPH_MODE_KEY, modes);
this.lastHtml = undefined;
this.rendered = false;
if (!on) this.graphShown = false;
else if (this.graphShown && query !== undefined) this.post({ type: 'query', query });
void this.update(true);
}
/** The Graph page of the model, or an update of it when it is already showing. */
private showGraphPage(index: Awaited<ReturnType<ModelService['index']>>): void {
const graph = buildGraph(index);
const fingerprint = `graph\u0000${JSON.stringify(graph)}`;
if (fingerprint === this.lastHtml && this.graphShown) return;
this.lastHtml = fingerprint;
this.rendered = false;
if (this.graphShown) {
this.post({ type: 'graph', graph });
return;
}
this.graphShown = true;
this.setHtml(graphPage(
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() },
{ graph, query: this.graphQuery, scriptUri: graphScriptUri(this.panel.webview, this.context.extensionUri) },
));
this.graphQuery = undefined;
}
private showMessage(title: string, body: string, detail?: string): void {
this.lastHtml = undefined;
this.panel.webview.html = messagePage(
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() },
this.setHtml(messagePage(
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state(), source: this.sourceOption('Diagram') },
title,
body,
detail,
);
));
}
/** Opens a diagram of the model, given its path relative to the model root. */
private async openLinked(relativePath: string): Promise<void> {
private async openLinked(relativePath: string, viewType: string): Promise<void> {
if (!this.root) return;
const target = vscode.Uri.joinPath(this.root, ...relativePath.split('/'));
try {
@@ -105,7 +248,7 @@ class DiagramPreview implements vscode.Disposable {
vscode.window.showWarningMessage(`Archify: ${relativePath} does not exist in this model.`);
return;
}
await vscode.commands.executeCommand('vscode.openWith', target, DIAGRAM_EDITOR_VIEW_TYPE, vscode.ViewColumn.Active);
await vscode.commands.executeCommand('vscode.openWith', target, viewType, vscode.ViewColumn.Active);
}
private showModelPage(model: ModelPanel): void {
@@ -113,7 +256,8 @@ class DiagramPreview implements vscode.Disposable {
if (fingerprint === this.lastHtml) return;
this.lastHtml = fingerprint;
this.rendered = false;
this.panel.webview.html = modelPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() }, model);
this.graphShown = false;
this.setHtml(modelPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state(), source: this.sourceOption('Model') }, model));
}
scheduleUpdate(): void {
@@ -124,6 +268,7 @@ class DiagramPreview implements vscode.Disposable {
async update(force = false): Promise<void> {
clearTimeout(this.timer);
if (this.disposed) return;
const seq = ++this.seq;
let text: string;
try {
@@ -138,7 +283,13 @@ class DiagramPreview implements vscode.Disposable {
if (main) {
this.root = vscode.Uri.file(path.dirname(this.uri.fsPath));
try {
model = panelFromIndex(await this.models.index(this.root));
const index = await this.models.index(this.root);
if (seq !== this.seq) return;
if (this.graph) {
this.showGraphPage(index);
return;
}
model = panelFromIndex(index);
} catch (error) {
log().warn(`Model index failed for ${this.root.fsPath}: ${error instanceof Error ? error.message : String(error)}`);
}
@@ -151,6 +302,7 @@ class DiagramPreview implements vscode.Disposable {
}
if (seq !== this.seq) return;
if (!main) this.root = prepared?.root;
this.graphShown = false;
if (!prepared) {
if (model) {
this.showModelPage(model);
@@ -176,7 +328,7 @@ class DiagramPreview implements vscode.Disposable {
if (!result.ok || !result.html) {
log().warn(`Render failed for ${this.uri.fsPath}: ${result.error}`);
if (this.rendered && this.lastHtml) {
void this.panel.webview.postMessage({
this.post({
type: 'notice',
notice: { kind: 'error', text: `Render failed; showing the last successful render.\n${firstLines(result.error)}` },
});
@@ -195,20 +347,28 @@ class DiagramPreview implements vscode.Disposable {
notice: result.evidenceNotice ? { kind: 'warning', text: result.evidenceNotice } : undefined,
viewer3d: viewer3dOption(this.panel.webview, this.context.extensionUri),
links: Object.fromEntries(prepared.links),
descriptions: Object.fromEntries(prepared.descriptions),
decisions: prepared.decisions,
model,
graphSwitch: main ? { left: 'Model' } : prepared.root ? { left: 'Diagram', query: `diagram:${path.relative(prepared.root.fsPath, this.uri.fsPath).split(path.sep).join('/')}` } : undefined,
source: this.sourceOption(main ? 'Model' : 'Diagram'),
});
// Nonces differ per render, so compare the renderer output instead.
const fingerprint = `${viewerTheme()}\u0000${result.evidenceNotice ?? ''}\u0000${JSON.stringify([model ?? null, [...prepared.links]])}\u0000${result.html}`;
const fingerprint = `${viewerTheme()}\u0000${result.evidenceNotice ?? ''}\u0000${JSON.stringify([model ?? null, [...prepared.links], [...prepared.descriptions], prepared.decisions])}\u0000${result.html}`;
if (!force && this.rendered && fingerprint === this.lastHtml) {
void this.panel.webview.postMessage({ type: 'notice', notice: undefined });
this.post({ type: 'notice', notice: undefined });
return;
}
this.lastHtml = fingerprint;
this.rendered = true;
this.panel.webview.html = html;
this.setHtml(html);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
// Renders in flight check the sequence after every await; this ends them.
this.seq++;
clearTimeout(this.timer);
this.onDisposeEmitter.fire();
this.onDisposeEmitter.dispose();
@@ -276,10 +436,29 @@ export class DiagramViewManager
return [...this.previews.values(), ...this.editors].filter((preview) => preview.uri.toString() === key);
}
private readonly host: PreviewHost = { openGraph: (root, query) => this.showGraph(root, query) };
/** Opening a .archify file lands here: the diagram is the editor. */
async resolveCustomTextEditor(document: vscode.TextDocument, panel: vscode.WebviewPanel): Promise<void> {
panel.webview.options = { enableScripts: true, localResourceRoots: viewerRoots(this.context.extensionUri) };
this.track(new DiagramPreview(this.context, this.models, panel, document.uri, undefined, true));
this.track(new DiagramPreview(this.context, this.models, this.host, panel, document.uri, undefined, true));
}
/** Opens the model's main.archify as its Graph page, with a query to start from. */
async showGraph(root: vscode.Uri, query?: string): Promise<void> {
const main = vscode.Uri.joinPath(root, MAIN_FILE);
await vscode.commands.executeCommand('vscode.openWith', main, DIAGRAM_EDITOR_VIEW_TYPE, vscode.ViewColumn.Active);
const key = main.toString();
const deadline = Date.now() + 5000;
for (;;) {
const editor = [...this.editors].find((e) => e.uri.toString() === key && e.panel.active) ?? [...this.editors].find((e) => e.uri.toString() === key);
if (editor) {
editor.setGraph(true, query);
return;
}
if (Date.now() > deadline) return;
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
show(uri: vscode.Uri, viewColumn: vscode.ViewColumn, preserveFocus = false): void {
@@ -294,7 +473,7 @@ export class DiagramViewManager
{ viewColumn, preserveFocus },
{ enableScripts: true, retainContextWhenHidden: true, enableFindWidget: true, localResourceRoots: viewerRoots(this.context.extensionUri) },
);
this.track(new DiagramPreview(this.context, this.models, panel, uri));
this.track(new DiagramPreview(this.context, this.models, this.host, panel, uri));
}
async deserializeWebviewPanel(panel: vscode.WebviewPanel, state: PreviewState | undefined): Promise<void> {
@@ -302,7 +481,7 @@ export class DiagramViewManager
panel.dispose();
return;
}
this.track(new DiagramPreview(this.context, this.models, panel, vscode.Uri.parse(state.uri), state));
this.track(new DiagramPreview(this.context, this.models, this.host, panel, vscode.Uri.parse(state.uri), state));
}
private track(preview: DiagramPreview): void {
+36 -15
View File
@@ -5,17 +5,13 @@ import { RegistryPanel, registryPanelFromIndex, registryPanelStandalone } from '
import { ModelService } from '../model/service';
import { readText } from '../util/files';
import { log } from '../util/log';
import { sourceScriptUri } from '../webview/viewer3d';
import { SourceSession } from './sourceSession';
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
import { makeNonce, registryPage } from '../webview/page';
import { DIAGRAM_EDITOR_VIEW_TYPE } from './diagramView';
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
/** Default editor for .archify-registry files: the elements as cards, each with where it is used. */
export const REGISTRY_VIEW_TYPE = 'archify.registry';
class RegistryDocument implements vscode.CustomDocument {
constructor(readonly uri: vscode.Uri) {}
dispose(): void {}
}
export { REGISTRY_VIEW_TYPE };
class RegistryView implements vscode.Disposable {
private seq = 0;
@@ -23,16 +19,30 @@ class RegistryView implements vscode.Disposable {
private last: string | undefined;
root: vscode.Uri | undefined;
private readonly disposables: vscode.Disposable[] = [];
/** The Source view; while it shows, a new page waits in `heldHtml`. */
readonly source: SourceSession;
private heldHtml: string | undefined;
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
readonly panel: vscode.WebviewPanel,
readonly uri: vscode.Uri,
) {
this.source = new SourceSession(context, panel, uri, 'registry', (shown) => {
if (!shown && this.heldHtml !== undefined) {
const html = this.heldHtml;
this.heldHtml = undefined;
this.panel.webview.html = html;
}
});
this.disposables.push(
this.source,
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
if (this.source.handle(message)) return;
if (message.type === 'openDiagram') return void this.openInModel(message.path, DIAGRAM_EDITOR_VIEW_TYPE);
if (message.type === 'openRegistry') return void this.openRegistryLine(message.file, message.line);
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
void handleWebviewMessage(message, this.uri, this.panel);
}),
);
@@ -84,7 +94,12 @@ class RegistryView implements vscode.Disposable {
const fingerprint = JSON.stringify(registry);
if (fingerprint === this.last) return;
this.last = fingerprint;
this.panel.webview.html = registryPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce() }, registry);
const html = registryPage(
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), source: { scriptUri: sourceScriptUri(this.panel.webview, this.context.extensionUri), left: 'View' } },
registry,
);
if (this.source.shown) this.heldHtml = html;
else this.panel.webview.html = html;
}
dispose(): void {
@@ -93,12 +108,15 @@ class RegistryView implements vscode.Disposable {
}
}
export class RegistryViewProvider implements vscode.CustomReadonlyEditorProvider<RegistryDocument>, vscode.Disposable {
export class RegistryViewProvider implements vscode.CustomTextEditorProvider, vscode.Disposable {
private readonly views = new Set<RegistryView>();
private active: RegistryView | undefined;
private readonly disposables: vscode.Disposable[];
constructor(private readonly models: ModelService) {
constructor(
private readonly context: vscode.ExtensionContext,
private readonly models: ModelService,
) {
this.disposables = [
vscode.window.registerCustomEditorProvider(REGISTRY_VIEW_TYPE, this, {
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
@@ -121,13 +139,16 @@ export class RegistryViewProvider implements vscode.CustomReadonlyEditorProvider
return this.active?.uri;
}
openCustomDocument(uri: vscode.Uri): RegistryDocument {
return new RegistryDocument(uri);
/** The view of the focused page, if any. */
get activeView(): { source: SourceSession } | undefined {
return this.active;
}
async resolveCustomEditor(document: RegistryDocument, panel: vscode.WebviewPanel): Promise<void> {
// A text editor provider: the page edits the file's own TextDocument (in
// its Source view), so dirty state, save and undo are VS Code's.
async resolveCustomTextEditor(document: vscode.TextDocument, panel: vscode.WebviewPanel): Promise<void> {
panel.webview.options = { enableScripts: true };
const view = new RegistryView(this.models, panel, document.uri);
const view = new RegistryView(this.context, this.models, panel, document.uri);
this.views.add(view);
const onViewState = () => {
if (panel.active) this.active = view;
+229
View File
@@ -0,0 +1,229 @@
import * as vscode from 'vscode';
import { EditorSchemas } from '../language/editorSchemas';
import { readSchemas } from '../language/schemaCheck';
import { liveBridge } from '../sync/liveBridge';
import { log } from '../util/log';
import { TextChange, normalizeEol, offsetOf, positionOf } from '../util/textDiff';
/** Page → host messages of the Source view. */
export type SourceMessage =
| { type: 'sourceReady' }
| { type: 'sourceOpen' }
| { type: 'sourceClose' }
| { type: 'sourceEdit'; base: string; text: string; changes: TextChange[] }
| { type: 'sourceSelection'; anchor: number; head: number };
export type SourceKind = 'diagram' | 'registry' | 'decision';
const CHECKS: Record<SourceKind, string> = {
diagram: 'YAML · checked against the Archify schema and the model',
registry: 'YAML · checked against the registry schema and the model',
decision: 'YAML · checked as a decision of the model',
};
let editorSchemas: EditorSchemas | undefined;
function schemasFor(context: vscode.ExtensionContext): EditorSchemas {
editorSchemas ??= new EditorSchemas(readSchemas(vscode.Uri.joinPath(context.extensionUri, 'schemas').fsPath));
return editorSchemas;
}
export function isSourceMessage(message: { type?: string }): message is SourceMessage {
return (
message.type === 'sourceReady' ||
message.type === 'sourceOpen' ||
message.type === 'sourceClose' ||
message.type === 'sourceEdit' ||
message.type === 'sourceSelection'
);
}
/**
* The host half of a page's Source view. The document stays VS Code's: page
* edits become WorkspaceEdits (so dirty state, save, undo and Git work as
* for any file), and changes from anywhere else (undo, the text editor, git)
* go back to the page. Problems are whatever the Problems panel holds for the
* file, sent as offsets; the page shows their count on the Source switch even
* while the picture is shown.
*/
export class SourceSession implements vscode.Disposable {
/** True while the page shows Source; the view must not replace its HTML then. */
shown = false;
/** Texts our own edits will produce, oldest first; their change events are not echoed. */
private readonly expected: string[] = [];
private queue: Promise<void> = Promise.resolve();
private schemaKey: string | undefined;
private readonly disposables: vscode.Disposable[];
constructor(
private readonly context: vscode.ExtensionContext,
private readonly panel: vscode.WebviewPanel,
readonly uri: vscode.Uri,
readonly kind: SourceKind,
/** Called when Source opens or closes, so the view can hold or apply its HTML. */
private readonly onShown: (shown: boolean) => void,
) {
const same = (uri: vscode.Uri) => uri.toString() === this.uri.toString();
this.disposables = [
vscode.languages.onDidChangeDiagnostics((event) => {
if (event.uris.some(same)) void this.postDiagnostics();
}),
vscode.workspace.onDidChangeTextDocument((event) => {
if (!same(event.document.uri) || !event.contentChanges.length) return;
this.post({ type: 'sourceDirty', dirty: event.document.isDirty });
if (this.shown) this.syncFrom(event.document);
}),
vscode.workspace.onDidSaveTextDocument((doc) => {
if (same(doc.uri)) this.post({ type: 'sourceDirty', dirty: false });
}),
// Teammates' cursors, when the model is shared (Archify Sync); nothing otherwise.
liveBridge.onDidChangeCursors(() => this.postCursors()),
];
}
/** Asks the page to show its Source view (Archify | Show Source). */
reveal(): void {
this.post({ type: 'setView', view: 'source' });
}
/** The page is being replaced by another one (the Graph page): Source is no longer shown. */
leave(): void {
this.setShown(false);
}
/** Handles a Source message from the page; false for any other message. */
handle(message: { type?: string }): boolean {
if (!isSourceMessage(message)) return false;
switch (message.type) {
case 'sourceReady':
void this.postDiagnostics();
break;
case 'sourceOpen':
this.setShown(true);
void this.sendText(true);
break;
case 'sourceClose':
this.setShown(false);
liveBridge.setCursor(this.uri, undefined);
break;
case 'sourceEdit':
this.edit(message);
break;
case 'sourceSelection':
liveBridge.setCursor(this.uri, { anchor: message.anchor, head: message.head });
break;
}
return true;
}
private setShown(shown: boolean): void {
if (this.shown === shown) return;
this.shown = shown;
this.onShown(shown);
}
private lastCursors = '[]';
private postCursors(): void {
if (!this.shown) return;
const cursors = liveBridge.cursors(this.uri);
const key = JSON.stringify(cursors);
if (key === this.lastCursors) return;
this.lastCursors = key;
this.post({ type: 'sourceCursors', cursors });
}
private post(message: unknown): void {
Promise.resolve(this.panel.webview.postMessage(message)).catch(() => undefined);
}
private document(): Promise<vscode.TextDocument> {
return Promise.resolve(vscode.workspace.openTextDocument(this.uri));
}
private async sendText(withDiagnostics: boolean): Promise<void> {
const doc = await this.document();
const text = normalizeEol(doc.getText());
this.expected.length = 0;
this.schemaKey = undefined;
this.post({ type: 'sourceText', text, schema: this.schemaChange(text), checks: CHECKS[this.kind] });
this.post({ type: 'sourceDirty', dirty: doc.isDirty });
this.lastCursors = '';
this.postCursors();
if (withDiagnostics) await this.postDiagnostics();
}
/** The editor schema when it differs from the one the page has (a diagram's type may change), else undefined. */
private schemaChange(text: string): { key: string; schema: object } | null | undefined {
const next = schemasFor(this.context).forSource(this.kind, text);
const key = next?.key ?? '';
if (key === this.schemaKey) return undefined;
this.schemaKey = key;
return next ?? null;
}
private syncFrom(doc: vscode.TextDocument): void {
const text = normalizeEol(doc.getText());
const index = this.expected.indexOf(text);
if (index !== -1) {
// Our own edit coming back; anything older is settled too.
this.expected.splice(0, index + 1);
return;
}
this.post({ type: 'sourceText', text, schema: this.schemaChange(text), checks: CHECKS[this.kind] });
}
private edit(message: Extract<SourceMessage, { type: 'sourceEdit' }>): void {
this.expected.push(message.text);
const schema = this.schemaChange(message.text);
if (schema !== undefined) this.post({ type: 'sourceSchema', schema });
this.queue = this.queue.then(async () => {
try {
const doc = await this.document();
const current = normalizeEol(doc.getText());
if (current === message.text) return;
const edit = new vscode.WorkspaceEdit();
// Positions come from "\n" text; VS Code turns inserted text into the document's line endings.
const at = (text: string, offset: number) => {
const { line, character } = positionOf(text, offset);
return new vscode.Position(line, character);
};
if (current === message.base) {
for (const change of message.changes) edit.replace(this.uri, new vscode.Range(at(current, change.from), at(current, change.to)), change.insert);
} else {
// The document moved on under the page (rare): the page's text wins.
edit.replace(this.uri, new vscode.Range(at(current, 0), at(current, current.length)), message.text);
}
if (!(await vscode.workspace.applyEdit(edit))) {
log().warn(`Source edit was not applied to ${this.uri.fsPath}`);
void this.sendText(false);
}
} catch (error) {
log().error(`Source edit failed for ${this.uri.fsPath}: ${error instanceof Error ? error.message : String(error)}`);
}
});
}
/** Problems of the file as offsets into its "\n" text, and their count for the switch. */
async postDiagnostics(): Promise<void> {
const diagnostics = vscode.languages.getDiagnostics(this.uri);
let items: unknown[] = [];
if (this.shown && diagnostics.length) {
const text = normalizeEol((await this.document()).getText());
items = diagnostics.map((d) => ({
from: offsetOf(text, d.range.start.line, d.range.start.character),
to: offsetOf(text, d.range.end.line, d.range.end.character),
severity: d.severity === vscode.DiagnosticSeverity.Error ? 'error' : d.severity === vscode.DiagnosticSeverity.Warning ? 'warning' : 'info',
message: d.message,
source: d.source,
}));
}
const count = diagnostics.filter((d) => d.severity === vscode.DiagnosticSeverity.Error || d.severity === vscode.DiagnosticSeverity.Warning).length;
this.post({ type: 'sourceDiagnostics', items, count });
}
dispose(): void {
if (this.shown) liveBridge.setCursor(this.uri, undefined);
for (const d of this.disposables.splice(0)) d.dispose();
}
}
+8
View File
@@ -0,0 +1,8 @@
/** Custom editor view types, in one place so views can refer to each other without importing each other. */
export const PREVIEW_VIEW_TYPE = 'archify.preview';
/** Default editor for .archify files: the rendered diagram. */
export const DIAGRAM_EDITOR_VIEW_TYPE = 'archify.diagram';
/** Default editor for .archify-registry files: the elements as cards. */
export const REGISTRY_VIEW_TYPE = 'archify.registry';
/** Default editor for .archify-decision files: the decision as a page. */
export const DECISION_VIEW_TYPE = 'archify.decision';
+20
View File
@@ -0,0 +1,20 @@
import type { ModelGraph } from '../model/graph';
/**
* What the bridge script (page.ts) exposes to the bundled page scripts as
* `window.__archifyHost`: they cannot call acquireVsCodeApi a second time.
*/
export interface ArchifyHost {
defaultView: '2d' | '3d';
post(message: unknown): void;
getState(): Record<string, unknown>;
setState(patch: Record<string, unknown>): void;
/** The Graph page's data, present on that page only. */
graph?: { graph: ModelGraph; query?: string };
}
declare global {
interface Window {
__archifyHost?: ArchifyHost;
}
}
+42
View File
@@ -2,6 +2,7 @@ import path from 'node:path';
import * as vscode from 'vscode';
import { repoRootFor } from '../archify/runtime';
import { log } from '../util/log';
import type { LiveAction } from '../sync/liveBridge';
export type WebviewMessage =
| { type: 'hash'; hash: string }
@@ -11,6 +12,13 @@ export type WebviewMessage =
| { type: 'openSource'; path: string; line?: number; endLine?: number; href?: string }
| { type: 'openDiagram'; path: string }
| { type: 'openRegistry'; file: string; line?: number }
| { type: 'openDecision'; file: string }
| { type: 'showGraph'; query?: string }
| { type: 'showModel' }
| { type: 'liveReady' }
| { type: 'liveAction'; action: LiveAction }
| { type: 'syncMenu' }
| { type: 'syncReady' }
| { type: 'error'; message: string };
/** Column for opening files next to a webview without covering it. */
@@ -60,6 +68,28 @@ async function openSource(
vscode.window.showWarningMessage(`Archify: source file "${message.path}" was not found in the workspace.`);
}
/**
* Whether the file's model is shared: an .archify-sync file next to its
* main.archify. Read from disk, so the sync bundle stays unloaded.
*/
async function isShared(file: vscode.Uri): Promise<boolean> {
const folder = vscode.workspace.getWorkspaceFolder(file);
let dir = vscode.Uri.joinPath(file, '..');
for (let depth = 0; depth < 16; depth++) {
if (await exists(vscode.Uri.joinPath(dir, '.archify-sync'))) return true;
if (await exists(vscode.Uri.joinPath(dir, 'main.archify'))) return false;
const parent = vscode.Uri.joinPath(dir, '..');
if (!folder || dir.path === folder.uri.path || parent.path === dir.path) return false;
dir = parent;
}
return false;
}
async function postSyncState(file: vscode.Uri, panel: vscode.WebviewPanel): Promise<void> {
const shared = file.scheme === 'file' && (await isShared(file));
await Promise.resolve(panel.webview.postMessage({ type: 'syncState', shared })).catch(() => undefined);
}
export async function handleWebviewMessage(
message: WebviewMessage,
context: vscode.Uri,
@@ -93,8 +123,20 @@ export async function handleWebviewMessage(
case 'error':
vscode.window.showErrorMessage(`Archify: ${message.message}`);
break;
case 'syncReady':
await postSyncState(context, panel);
break;
case 'syncMenu':
await vscode.commands.executeCommand('archify.sync.menu');
// Share or Stop may have changed it.
await postSyncState(context, panel);
break;
case 'hash':
case 'openDiagram':
case 'showGraph':
case 'showModel':
case 'liveReady':
case 'liveAction':
// Handled by the view, which knows the model root.
break;
}
+638 -21
View File
@@ -18,11 +18,25 @@ export interface PageOptions {
links?: Record<string, string>;
/** The model page: metadata above the diagram, the diagram list and registry below. */
model?: ModelPanel;
/** Node id → registry description, shown as tooltips in the Elements panel. */
descriptions?: Record<string, string>;
/** Registry page: the elements of one .archify-registry file. */
registry?: RegistryPanel;
/** Decision page: one .archify-decision file. */
decision?: DecisionPanel;
/** Diagram page: decisions of this diagram, for the Decisions rail panel. */
decisions?: DiagramDecision[];
/** Pages inside a model get a switch to the model's Graph page; `left` names the page they are on. */
graphSwitch?: { left: 'Model' | 'Diagram'; query?: string };
/** Pages of a file that can be edited in place: the Source view's script, and the name of the page's own view. */
source?: { scriptUri: string; left: 'Model' | 'Diagram' | 'View' };
/** The Graph page: the model as one graph, the bundled script that draws it, and the query to start with. */
graph?: { graph: ModelGraph; query?: string; scriptUri: string };
}
import type { ModelPanel, RegistryPanel } from '../model/panel';
import type { ModelGraph } from '../model/graph';
import type { DecisionPanel, ModelPanel, RegistryPanel } from '../model/panel';
import type { DiagramDecision } from '../model/prepare';
export function makeNonce(): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
@@ -77,6 +91,12 @@ function bridgeScript(options: PageOptions): string {
links: options.links ?? {},
model: options.model,
registry: options.registry,
decision: options.decision,
decisions: options.decisions || [],
descriptions: options.descriptions || {},
graphSwitch: options.graphSwitch,
source: options.source,
graph: options.graph ? { graph: options.graph.graph, query: options.graph.query } : undefined,
};
return `(function () {
var config = ${scriptJson(config)};
@@ -100,7 +120,8 @@ function bridgeScript(options: PageOptions): string {
defaultView: config.defaultView || '2d',
post: post,
getState: function () { return vscode.getState() || {}; },
setState: function (patch) { vscode.setState(Object.assign({}, vscode.getState() || {}, patch)); }
setState: function (patch) { vscode.setState(Object.assign({}, vscode.getState() || {}, patch)); },
graph: config.graph
};
function saveBlobUrl(url, filename) {
@@ -187,8 +208,10 @@ function bridgeScript(options: PageOptions): string {
}, true);
// Collapsible panels of the model page; open/closed is kept in the webview state.
// The model page's top-level panels start closed: a model opens as its outline.
function panelStates() { return (vscode.getState() || {}).modelPanels || {}; }
function panel(key, className, title, count, defaultOpen) {
// count: a number or a short text such as "3 files".
var details = el('details', 'archify-model-panel ' + className);
var saved = panelStates()[key];
details.open = saved === undefined ? defaultOpen : saved;
@@ -230,12 +253,48 @@ function bridgeScript(options: PageOptions): string {
});
} else used.appendChild(el('span', 'archify-model-item-meta', 'not used yet'));
list.appendChild(used);
if (element.decisions && element.decisions.length) {
var decided = el('li', 'archify-model-card-used');
element.decisions.forEach(function (row) { decided.appendChild(decisionChip(row)); });
list.appendChild(decided);
}
card.appendChild(list);
card.addEventListener('click', function () { openElementModal(element); });
card.addEventListener('keydown', function (event) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openElementModal(element); } });
return card;
}
// A decision as a chip (id, title, status) that opens its page.
function decisionChip(row) {
var chip = el('button', 'archify-model-used-link archify-decision-chip is-' + row.status, '');
chip.type = 'button';
chip.appendChild(el('span', 'archify-decision-dot'));
chip.appendChild(document.createTextNode(row.id + (row.title ? ' · ' + row.title : '')));
chip.title = 'Decision ' + row.id + (row.title ? ': ' + row.title : '') + ' (' + row.status + ')';
chip.addEventListener('click', function (event) { event.stopPropagation(); if (row.file) post({ type: 'openDecision', file: row.file }); });
return chip;
}
function statusBadge(row) {
var badge = el('span', 'archify-decision-status is-' + row.status, row.status + (row.supersededBy ? ' by ' + row.supersededBy : ''));
return badge;
}
// A decision as a row in a list: id, title, status, date; click opens it.
function decisionRowItem(row) {
var item = el('li', 'archify-model-item archify-decision-item is-' + row.status);
var button = el('button', 'archify-model-open archify-decision-open');
button.type = 'button';
button.title = row.file || row.id;
var line = el('span', 'archify-decision-line');
line.appendChild(el('span', 'archify-decision-id', row.id));
line.appendChild(el('span', 'archify-model-item-title', row.title || ''));
line.appendChild(statusBadge(row));
if (row.date) line.appendChild(el('span', 'archify-model-item-meta', row.date));
button.appendChild(line);
button.addEventListener('click', function () { if (row.file) post({ type: 'openDecision', file: row.file }); });
item.appendChild(button);
return item;
}
// Modal: one element, where it is defined and the diagrams that use it.
function openElementModal(element) {
closeElementModal();
@@ -288,6 +347,12 @@ function bridgeScript(options: PageOptions): string {
});
modal.appendChild(list);
}
if (element.decisions && element.decisions.length) {
modal.appendChild(el('h3', 'archify-model-title', 'Decisions · ' + element.decisions.length));
var decisions = el('ul', 'archify-model-list archify-decision-list');
element.decisions.forEach(function (row) { decisions.appendChild(decisionRowItem(row)); });
modal.appendChild(decisions);
}
backdrop.appendChild(modal);
backdrop.addEventListener('click', function (event) { if (event.target === backdrop) closeElementModal(); });
document.body.appendChild(backdrop);
@@ -321,6 +386,139 @@ function bridgeScript(options: PageOptions): string {
document.body.appendChild(body);
}
// The decision page: one .archify-decision file.
function renderDecision(page) {
if (!page) return;
var d = page.decision;
var head = el('section', 'archify-model archify-model-head');
head.appendChild(el('div', 'archify-model-kicker', 'Decision' + (page.model && page.model.id ? ' · ' + page.model.id : '') + (d ? ' · ' + d.id : '')));
head.appendChild(el('h1', 'archify-model-name', d && d.title ? d.title : page.file));
if (d) {
var meta = el('p', 'archify-decision-meta');
meta.appendChild(statusBadge(d));
if (d.date) meta.appendChild(el('span', 'archify-model-item-meta', d.date));
meta.appendChild(el('span', 'archify-model-item-meta', page.file));
head.appendChild(meta);
}
if (!page.inModel) head.appendChild(el('p', 'archify-model-problem', 'This decision has lost its model: there is no main.archify in a folder above it, so its elements and diagrams cannot be resolved.'));
page.problems.forEach(function (problem) { head.appendChild(el('p', 'archify-model-problem', problem)); });
document.body.appendChild(head);
var body = el('section', 'archify-model archify-model-body');
if (d) {
[['Context', d.context], ['Decision', d.decision], ['Consequences', d.consequences]].forEach(function (pair) {
if (!pair[1]) return;
var section = el('section', 'archify-decision-section');
section.appendChild(el('h2', 'archify-model-title', pair[0]));
section.appendChild(el('p', 'archify-decision-text', pair[1].trim()));
body.appendChild(section);
});
if (d.supersedes.length || page.supersededBy.length) {
var rel = el('section', 'archify-decision-section');
rel.appendChild(el('h2', 'archify-model-title', 'Related decisions'));
var relList = el('ul', 'archify-model-list archify-decision-list');
d.supersedes.forEach(function (row) { var item = decisionRowItem(row); item.firstChild.insertBefore(el('span', 'archify-model-item-meta', 'supersedes'), item.firstChild.firstChild); relList.appendChild(item); });
page.supersededBy.forEach(function (row) { var item = decisionRowItem(row); item.firstChild.insertBefore(el('span', 'archify-model-item-meta', 'superseded by'), item.firstChild.firstChild); relList.appendChild(item); });
rel.appendChild(relList);
body.appendChild(rel);
}
}
if (page.elements.length) {
var elementsPanel = panel('decision:elements', 'archify-model-registry', 'Elements', page.elements.length, true);
var cards = el('div', 'cards archify-model-cards');
page.elements.forEach(function (element) { cards.appendChild(elementCard(element)); });
elementsPanel.appendChild(cards);
body.appendChild(elementsPanel);
}
var diagramRows = [];
page.diagrams.forEach(function (use) { diagramRows.push({ path: use.path, title: use.title, kind: use.kind, how: 'named by the decision' }); });
page.referencedBy.forEach(function (use) {
var how = use.attachedTo.kind === 'node' ? 'on ' + use.attachedTo.id : use.attachedTo.kind === 'edge' ? 'on ' + use.attachedTo.from + ' \u2192 ' + use.attachedTo.to : 'on the diagram';
var existing = diagramRows.filter(function (r) { return r.path === use.path; })[0];
if (existing) existing.how += ', ' + how; else diagramRows.push({ path: use.path, title: use.title, kind: use.kind, how: how });
});
if (diagramRows.length) {
var diagramsPanel = panel('decision:diagrams', 'archify-model-diagrams', 'Diagrams', diagramRows.length, true);
var list = el('ul', 'archify-model-list');
diagramRows.forEach(function (row) {
var item = el('li', 'archify-model-item');
var button = el('button', 'archify-model-open');
button.type = 'button';
button.title = row.path;
button.appendChild(el('span', 'archify-model-item-title', row.title || row.path.split('/').pop()));
button.appendChild(el('span', 'archify-model-item-meta', (row.kind || 'diagram') + ' \u00b7 ' + row.path + ' \u00b7 ' + row.how));
button.addEventListener('click', function () { if (page.inModel) post({ type: 'openDiagram', path: row.path }); });
item.appendChild(button);
list.appendChild(item);
});
diagramsPanel.appendChild(list);
body.appendChild(diagramsPanel);
}
document.body.appendChild(body);
}
// Decisions rail panel on a diagram page: the decisions this diagram points
// at or that name it. Hover lights up what the decision is attached to.
function renderDecisionsRail() {
var rows = config.decisions || [];
var outline = document.getElementById('node-outline');
var svg = document.querySelector('.diagram-container > svg');
if (!rows.length || !outline || !svg || document.getElementById('archify-decisions')) return;
var nav = el('nav', 'node-outline no-print archify-connectors archify-decisions');
nav.id = 'archify-decisions';
var head = el('div', 'node-outline-head');
head.appendChild(el('strong', '', 'Decisions'));
head.appendChild(el('span', 'node-outline-count', String(rows.length)));
nav.appendChild(head);
var list = el('ol', 'node-outline-list');
var group = el('li', 'node-outline-group');
var items = el('ul');
function targets(row) {
var found = [];
row.attachedTo.forEach(function (a) {
if (a.kind === 'node') Array.prototype.push.apply(found, svg.querySelectorAll('[data-node-id="' + a.id + '"]'));
if (a.kind === 'edge') Array.prototype.push.apply(found, svg.querySelectorAll('[data-edge-from="' + a.from + '"][data-edge-to="' + a.to + '"]'));
});
return found;
}
function mark(row, on) { targets(row).forEach(function (t) { if (on) t.setAttribute('data-archify-hit', ''); else t.removeAttribute('data-archify-hit'); }); }
rows.forEach(function (row) {
var item = el('li');
var button = el('button', 'node-outline-item archify-decision-rail-item is-' + row.status);
button.type = 'button';
button.style.setProperty('--outline-tone', 'var(--text-muted)');
var where = row.attachedTo.map(function (a) { return a.kind === 'node' ? a.id : a.kind === 'edge' ? a.from + ' \u2192 ' + a.to : 'diagram'; }).join(', ');
button.title = row.id + (row.title ? ': ' + row.title : '') + ' (' + row.status + ')' + (where ? ' \u00b7 ' + where : '');
var dot = el('span', 'node-outline-dot');
dot.setAttribute('aria-hidden', 'true');
button.appendChild(dot);
button.appendChild(el('strong', '', row.id + (row.title ? ' \u00b7 ' + row.title : '')));
button.appendChild(el('small', '', row.status + (where ? ' \u00b7 ' + where : '')));
button.addEventListener('pointerenter', function () { mark(row, true); });
button.addEventListener('pointerleave', function () { mark(row, false); });
button.addEventListener('focus', function () { mark(row, true); });
button.addEventListener('blur', function () { mark(row, false); });
button.addEventListener('click', function () { post({ type: 'openDecision', file: row.file }); });
item.appendChild(button);
items.appendChild(item);
});
group.appendChild(items);
list.appendChild(group);
nav.appendChild(list);
var connectors = document.getElementById('archify-connectors');
(connectors || outline).insertAdjacentElement('afterend', nav);
var archify = window.Archify;
if (archify && archify.readerLayout && typeof archify.readerLayout.schedule === 'function') archify.readerLayout.schedule();
}
// Elements: registry descriptions as tooltips on Archify's node index rows.
function describeElements() {
var items = document.querySelectorAll('#node-outline .node-outline-item[data-outline-node]');
Array.prototype.forEach.call(items, function (item) {
var text = config.descriptions[item.getAttribute('data-outline-node')];
if (text) item.title = text;
});
}
// Connectors: a rail panel next to Archify's Elements index, read from the
// SVG's edges. Hover highlights the connector, click keeps it highlighted.
function renderConnectors() {
@@ -421,8 +619,13 @@ function bridgeScript(options: PageOptions): string {
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(head, anchor); else document.body.appendChild(head);
var body = el('section', 'archify-model archify-model-body');
// Live: filled by the host when the model is shared (Archify Sync); hidden otherwise.
var live = el('div', 'archify-live');
live.id = 'archify-live';
live.hidden = true;
body.appendChild(live);
var count = model.groups.reduce(function (n, g) { return n + g.diagrams.length; }, 0);
var diagramsPanel = panel('diagrams', 'archify-model-diagrams', 'Diagrams', count, true);
var diagramsPanel = panel('diagrams', 'archify-model-diagrams', 'Diagrams', count, false);
body.appendChild(diagramsPanel);
if (!count) diagramsPanel.appendChild(el('p', 'archify-model-empty', 'No diagrams yet. Add .archify files next to main.archify or in subfolders.'));
model.groups.forEach(function (group) {
@@ -438,6 +641,7 @@ function bridgeScript(options: PageOptions): string {
var button = el('button', 'archify-model-open');
button.type = 'button';
button.title = diagram.path;
button.setAttribute('data-path', diagram.path);
button.appendChild(el('span', 'archify-model-item-title', diagram.title || diagram.path.split('/').pop()));
button.appendChild(el('span', 'archify-model-item-meta', diagram.parseError ? 'does not parse: ' + diagram.parseError : (diagram.kind || 'diagram') + ' · ' + diagram.path));
button.addEventListener('click', function () { post({ type: 'openDiagram', path: diagram.path }); });
@@ -446,20 +650,232 @@ function bridgeScript(options: PageOptions): string {
});
holder.appendChild(list);
});
// Registry elements as Archify info cards: the same cards a diagram shows below itself.
// Registry: one collapsible header per registry file, its elements as cards inside.
if (model.registry.length) {
var registryPanel = panel('registry', 'archify-model-registry', 'Registry', model.registry.length, false);
var files = [];
var byFile = {};
model.registry.forEach(function (element) {
if (!byFile[element.file]) { byFile[element.file] = []; files.push(element.file); }
byFile[element.file].push(element);
});
files.sort();
var registryPanel = panel('registry', 'archify-model-registry', 'Registries', files.length + (files.length === 1 ? ' file' : ' files'), false);
body.appendChild(registryPanel);
var cards = el('div', 'cards archify-model-cards');
model.registry.forEach(function (element) { cards.appendChild(elementCard(element)); });
registryPanel.appendChild(cards);
files.forEach(function (file) {
var elements = byFile[file].slice().sort(function (a, b) { return a.line - b.line; });
var filePanel = panel('registry:' + file, 'archify-model-folder archify-model-registry-file', file.replace(/\.archify-registry$/, ''), elements.length + (elements.length === 1 ? ' element' : ' elements'), false);
var open = el('button', 'archify-model-used-link archify-model-open-file', 'Open');
open.type = 'button';
open.title = 'Open ' + file;
open.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); post({ type: 'openRegistry', file: file, line: 0 }); });
filePanel.firstChild.appendChild(open);
var cards = el('div', 'cards archify-model-cards');
elements.forEach(function (element) { cards.appendChild(elementCard(element)); });
filePanel.appendChild(cards);
registryPanel.appendChild(filePanel);
});
}
// Decisions: one list, live ones first, superseded and rejected dimmed and last.
if (model.decisions && model.decisions.length) {
var decisionsPanel = panel('decisions', 'archify-model-decisions', 'Decisions', model.decisions.length, false);
body.appendChild(decisionsPanel);
var decisionList = el('ul', 'archify-model-list archify-decision-list');
model.decisions.forEach(function (row) { decisionList.appendChild(decisionRowItem(row)); });
decisionsPanel.appendChild(decisionList);
}
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(body, anchor.nextSibling); else document.body.appendChild(body);
post({ type: 'liveReady' });
}
var LIVE_STATE = {
online: 'Live',
connecting: 'Connecting\u2026',
offline: 'Offline \u00b7 edits are kept here and sent when the server is back',
'signed-out': 'Signed out \u00b7 edits are kept here until you sign in',
forbidden: 'No access \u00b7 you are no longer a member of this model',
outdated: 'The server needs a newer extension',
};
var KIND_LABEL = { snapshot: 'snapshot', publish: 'published', restore: 'restored' };
function liveButton(label, title, action) {
var button = el('button', 'archify-model-used-link archify-live-action', label);
button.type = 'button';
button.title = title;
button.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); post({ type: 'liveAction', action: action }); });
return button;
}
function when(iso) {
var date = new Date(iso);
if (isNaN(date.getTime())) return '';
var seconds = (Date.now() - date.getTime()) / 1000;
if (seconds < 60) return 'just now';
if (seconds < 3600) return Math.floor(seconds / 60) + ' min ago';
if (seconds < 86400) return Math.floor(seconds / 3600) + ' h ago';
return date.toLocaleDateString();
}
// The Live section of a shared model: who is here, the state, and versions.
function renderLive(info) {
var holder = document.getElementById('archify-live');
if (!holder) return;
holder.textContent = '';
document.querySelectorAll('.archify-live-here').forEach(function (n) { n.remove(); });
if (!info) { holder.hidden = true; return; }
holder.hidden = false;
var others = info.people.filter(function (p) { return !p.me; });
var livePanel = panel('live', 'archify-model-live is-' + info.state, 'Shared \u00b7 ' + info.name, others.length ? others.length + 1 + ' here' : info.host, false);
var status = el('div', 'archify-live-status');
status.appendChild(el('span', 'archify-live-dot'));
status.appendChild(el('span', 'archify-live-state', (LIVE_STATE[info.state] || info.state) + (info.state === 'online' ? ' on ' + info.host : '')));
if (info.state === 'signed-out') status.appendChild(liveButton('Sign in', 'Sign in to ' + info.host, { kind: 'signIn' }));
var actions = el('span', 'archify-live-actions');
actions.appendChild(liveButton('Publish version', 'Name the current state as a version', { kind: 'publish' }));
actions.appendChild(liveButton('Copy invite link', 'Copy a link that lets someone join this model', { kind: 'invite' }));
status.appendChild(actions);
livePanel.appendChild(status);
var people = el('ul', 'archify-live-people');
info.people.forEach(function (person) {
var item = el('li', 'archify-live-person' + (person.me ? ' is-me' : ''));
item.appendChild(el('strong', '', person.me ? person.name + ' (you)' : person.name));
if (person.file) item.appendChild(el('small', '', person.file));
people.appendChild(item);
});
livePanel.appendChild(people);
// Who is in which diagram, on the diagram rows.
others.forEach(function (person) {
if (!person.file) return;
document.querySelectorAll('.archify-model-open[data-path]').forEach(function (button) {
if (button.getAttribute('data-path') !== person.file) return;
var meta = button.querySelector('.archify-live-here');
if (!meta) { meta = el('span', 'archify-live-here', ''); button.appendChild(meta); }
meta.textContent = (meta.textContent ? meta.textContent.replace(/ here$/, '') + ', ' : '') + person.name + ' here';
});
});
var versions = info.versions || [];
var head = el('div', 'archify-live-versions-head');
head.appendChild(el('span', 'archify-model-summary-title', 'Versions'));
if (versions.length > 8) head.appendChild(liveButton('All ' + versions.length + '\u2026', 'Pick from every version', { kind: 'versions' }));
livePanel.appendChild(head);
if (info.versionsProblem) livePanel.appendChild(el('p', 'archify-model-empty archify-live-note', info.versionsProblem));
else if (!versions.length) livePanel.appendChild(el('p', 'archify-model-empty archify-live-note', 'No versions yet. One is taken on its own after a pause in editing.'));
var list = el('ul', 'archify-live-versions');
versions.slice(0, 8).forEach(function (v) {
var item = el('li', 'archify-live-version is-' + v.kind);
item.appendChild(el('strong', 'archify-live-version-label', v.label));
item.appendChild(el('span', 'archify-decision-status archify-live-kind', KIND_LABEL[v.kind] + (v.restoredFrom ? ' ' + v.restoredFrom : '')));
if (v.name) item.appendChild(el('span', 'archify-live-version-name', v.name));
item.appendChild(el('small', 'archify-live-version-when', when(v.at)));
var buttons = el('span', 'archify-live-actions');
buttons.appendChild(liveButton('Compare', 'Compare ' + v.label + ' with the files here', { kind: 'compare', version: v.id }));
buttons.appendChild(liveButton('Restore', 'Bring back ' + v.label + ' for everyone, as a new version', { kind: 'restore', version: v.id }));
item.appendChild(buttons);
list.appendChild(item);
});
livePanel.appendChild(list);
holder.appendChild(livePanel);
}
// What the page shows: Diagram | Graph | Source (Model | Graph | Source on
// main.archify, View | Source on registry and decision pages). It sits
// left of Export in Archify's toolbar, after 2D | 3D, which only says how
// the picture is drawn; on our own pages it sits top right. Graph opens the
// model's Graph page; Source puts the file's YAML in place of the picture.
var sourceOn = false;
var syncModeSwitch = function () {};
function renderModeSwitch() {
var sw = config.graphSwitch;
var src = config.source;
if ((!sw && !src) || document.getElementById('archify-mode-switch')) return;
var group = el('div', 'archify-mode-switch');
group.id = 'archify-mode-switch';
group.setAttribute('role', 'group');
group.setAttribute('aria-label', 'View');
function segment(label, title, action) {
var button = el('button', 'archify-mode-seg', label);
button.type = 'button';
button.title = title;
button.addEventListener('click', function (event) { event.stopPropagation(); action(); });
group.appendChild(button);
return button;
}
var name = (src && src.left) || sw.left;
var left = segment(name, name === 'View' ? 'Show the page' : 'Show the ' + name.toLowerCase(), function () { setSource(false); });
if (sw) segment('Graph', 'Open the model as one graph, with a query box', function () {
// On main.archify the Graph page replaces this one; coming back must
// show the model, not Source. Other pages open the graph beside them.
if (sourceOn && config.model) vscode.setState(Object.assign({}, vscode.getState() || {}, { sourceView: false }));
post({ type: 'showGraph', query: sw.query });
});
var source = src ? segment('Source', 'Edit the YAML of this file, checked as you type', function () { setSource(true); }) : null;
if (source) {
var badge = el('span', 'archify-source-badge');
badge.id = 'archify-source-badge';
badge.hidden = true;
source.appendChild(badge);
}
syncModeSwitch = function () {
left.classList.toggle('on', !sourceOn);
left.setAttribute('aria-pressed', String(!sourceOn));
if (source) {
source.classList.toggle('on', sourceOn);
source.setAttribute('aria-pressed', String(sourceOn));
}
};
syncModeSwitch();
var exportWrap = document.querySelector('.toolbar .export-wrap');
var head = document.querySelector('.archify-model-head');
if (exportWrap && exportWrap.parentNode) exportWrap.parentNode.insertBefore(group, exportWrap);
else {
var row = el('div', 'archify-model-switch-row');
row.appendChild(group);
if (head) head.insertBefore(row, head.firstChild);
else document.body.insertBefore(row, document.body.firstChild);
}
}
// The Source view lives in dist/source.js, loaded the first time it is chosen.
function setSource(on) {
if (!config.source || on === sourceOn) return;
sourceOn = on;
vscode.setState(Object.assign({}, vscode.getState() || {}, { sourceView: on }));
syncModeSwitch();
if (!on) {
if (window.__archifySource) window.__archifySource.close();
return;
}
if (window.__archifySource) {
window.__archifySource.open();
return;
}
var script = document.createElement('script');
script.src = config.source.scriptUri;
script.onload = function () { if (sourceOn && window.__archifySource) window.__archifySource.open(); };
script.onerror = function () {
sourceOn = false;
syncModeSwitch();
post({ type: 'error', message: 'The Source view could not be loaded.' });
};
document.head.appendChild(script);
}
function showProblemCount(count) {
var badge = document.getElementById('archify-source-badge');
if (!badge) return;
badge.hidden = !count;
badge.textContent = count ? String(count) : '';
badge.title = count ? count + (count === 1 ? ' problem' : ' problems') + ' in the source' : '';
}
window.addEventListener('message', function (event) {
var message = event.data || {};
if (message.type === 'notice') showNotice(message.notice);
if (message.type === 'sourceDiagnostics') showProblemCount(message.count);
if (message.type === 'setView') setSource(message.view === 'source');
if (message.type === 'live') renderLive(message.live);
});
function onReady(fn) {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
@@ -467,7 +883,88 @@ function bridgeScript(options: PageOptions): string {
}
if (config.model) onReady(function () { renderModel(config.model); });
if (config.registry) onReady(function () { renderRegistry(config.registry); });
if (config.decision) onReady(function () { renderDecision(config.decision); });
onReady(renderConnectors);
onReady(renderDecisionsRail);
onReady(describeElements);
onReady(renderModeSwitch);
// Archify Sync: one icon button, top right, on every page of an Archify
// file (diagram, model, graph, registry, decision). It opens the Sync menu.
function renderSyncButton() {
if (!(config.source || config.model || config.registry || config.decision || config.graph)) return;
if (document.getElementById('archify-sync-button')) return;
var style = document.createElement('style');
style.textContent = SYNC_BUTTON_STYLE;
document.head.appendChild(style);
var button = document.createElement('button');
button.id = 'archify-sync-button';
button.type = 'button';
button.title = 'Archify Sync: sign in, share this model with others, or join one';
button.addEventListener('click', function (event) { event.stopPropagation(); post({ type: 'syncMenu' }); });
// Last in the row that holds the view switch: Archify's toolbar on a
// diagram (after Export), the Graph page's header actions (after Export,
// built a moment later by graph.js), next to the switch on the other
// pages. It floats only while there is no such row.
document.body.appendChild(button);
function place() {
var modeSwitch = document.getElementById('archify-mode-switch');
var row = document.querySelector('.ag-actions') || (modeSwitch && modeSwitch.parentElement) || document.querySelector('body > .toolbar');
if (!row || row === document.body) return false;
button.classList.add('in-toolbar');
row.classList.add('archify-sync-row');
row.appendChild(button);
return true;
}
if (!place() && window.MutationObserver) {
var watch = new MutationObserver(function () { if (place()) watch.disconnect(); });
watch.observe(document.body, { childList: true, subtree: true });
}
showSyncState(false);
post({ type: 'syncReady' });
}
// Not shared: a cloud. Shared (the model has an .archify-sync file): broadcast waves on green.
var SYNC_ICONS = {
off: '<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M12.5 13H4.25a3.25 3.25 0 0 1-.6-6.44 4.5 4.5 0 0 1 8.7-.81A3.6 3.6 0 0 1 12.5 13Zm-8.25-1h8.25a2.6 2.6 0 0 0 0-5.2h-.5l-.12-.39a3.5 3.5 0 0 0-6.82.66l-.04.4-.4.05A2.25 2.25 0 0 0 4.25 12Z"/></svg>',
on: '<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><circle cx="8" cy="8" r="1.75" fill="currentColor"/><path fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" d="M5.2 5.2a4 4 0 0 0 0 5.6M10.8 5.2a4 4 0 0 1 0 5.6M3.1 3.1a7 7 0 0 0 0 9.8M12.9 3.1a7 7 0 0 1 0 9.8"/></svg>',
};
function showSyncState(shared) {
var button = document.getElementById('archify-sync-button');
if (!button) return;
button.classList.toggle('is-shared', !!shared);
button.innerHTML = shared ? SYNC_ICONS.on : SYNC_ICONS.off;
button.title = shared
? 'Archify Sync: this model is shared. Invite people, publish a version, see versions'
: 'Archify Sync: sign in, share this model with others, or join one';
button.setAttribute('aria-label', shared ? 'Archify Sync (shared)' : 'Archify Sync');
}
window.addEventListener('message', function (event) {
var message = event.data || {};
if (message.type === 'syncState') showSyncState(message.shared);
});
// Every rule is !important: the page's own button styles (Archify's toolbar,
// VS Code's high contrast themes) must not resize or recolour it.
var SYNC_BUTTON_STYLE = '#archify-sync-button { all: unset; position: fixed !important; top: 12px !important; right: 28px !important; z-index: 1001 !important;'
+ ' box-sizing: border-box !important; width: 30px !important; height: 30px !important; min-width: 0 !important; min-height: 0 !important; margin: 0 !important; padding: 0 !important;'
+ ' display: flex !important; align-items: center !important; justify-content: center !important; border-radius: 8px !important; cursor: pointer !important;'
+ ' color: #fff !important; background: var(--vscode-button-background, #0e639c) !important; border: 1px solid var(--vscode-contrastBorder, transparent) !important;'
+ ' box-shadow: 0 1px 4px rgba(0,0,0,.35) !important; }'
+ ' .archify-model-switch-row.archify-sync-row { display: flex !important; align-items: center !important; gap: 0.5rem !important; }'
+ ' #archify-sync-button.in-toolbar { position: relative !important; top: auto !important; right: auto !important; align-self: center !important; flex: none !important; width: 36px !important; height: 36px !important; }'
+ ' .archify-model-switch-row #archify-sync-button.in-toolbar { width: 33px !important; height: 33px !important; }'
+ ' .ag-actions #archify-sync-button.in-toolbar { width: 29px !important; height: 29px !important; }'
+ ' body.vscode-high-contrast #archify-sync-button:not(.is-shared) { background: #0e639c !important; }'
+ ' #archify-sync-button svg { display: block !important; width: 16px !important; height: 16px !important; flex: none !important; }'
+ ' #archify-sync-button:hover { background: var(--vscode-button-hoverBackground, #1177bb) !important; }'
+ ' #archify-sync-button.is-shared { background: #1f8f5f !important; }'
+ ' #archify-sync-button.is-shared:hover { background: #23a36c !important; }'
+ ' #archify-sync-button:focus-visible { outline: 2px solid var(--vscode-focusBorder, #007fd4) !important; outline-offset: 2px !important; }';
onReady(renderSyncButton);
if (config.source) {
// The host answers with the problem count for the Source badge.
post({ type: 'sourceReady' });
if ((vscode.getState() || {}).sourceView) onReady(function () { setSource(true); });
}
if (config.notice) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () { showNotice(config.notice); });
@@ -482,6 +979,8 @@ const MODEL_STYLE = `
.archify-model { --m-text: var(--text, var(--vscode-foreground, CanvasText)); --m-muted: var(--text-muted, var(--vscode-descriptionForeground, GrayText)); --m-panel: var(--panel, var(--vscode-editorWidget-background, Canvas)); --m-border: var(--panel-border, var(--vscode-editorWidget-border, rgba(128,128,128,.35))); --m-accent: var(--frontend-stroke, var(--vscode-textLink-foreground));
max-width: 1400px; margin: 0 auto; padding: 1.25rem 2rem; color: var(--m-text); font-family: var(--vscode-font-family, system-ui, sans-serif); }
.archify-model-head { padding-top: 1.5rem; }
/* Under Archify's fixed toolbar (diagram pages of main.archify), start below it. */
.toolbar ~ .archify-model-head { padding-top: 4.25rem; }
.archify-model-kicker { font-size: 0.6875rem; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; color: var(--m-accent); }
.archify-model-name { margin: 0.25rem 0 0.5rem; font-size: 1.5rem; font-weight: 700; letter-spacing: -0.02em; }
.archify-model-description { margin: 0; max-width: 72ch; font-size: 0.9375rem; line-height: 1.55; color: var(--m-muted); white-space: pre-line; }
@@ -502,6 +1001,10 @@ const MODEL_STYLE = `
.archify-model-folder > .archify-model-summary { padding: 0.55rem 0.75rem; font-size: 0.6875rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--m-muted); font-family: ui-monospace, Menlo, monospace; }
.archify-model-folder > .archify-model-summary:hover { color: var(--m-accent); }
.archify-model-folder > .archify-model-list { margin: 0 0.75rem; }
.archify-model-registry-file > .archify-model-summary { text-transform: none; letter-spacing: 0; font-size: 0.8125rem; }
.archify-model-registry-file > .archify-model-cards { margin: 0.25rem 0.75rem 0; }
.archify-model-open-file { margin-left: 0.5rem; text-transform: none; letter-spacing: 0; font-family: inherit; }
.archify-model-open-file:hover { color: var(--m-accent); }
.archify-model-diagrams > .archify-model-list { margin-top: 0.25rem; }
.archify-model-list { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0.5rem; }
.archify-model-open { display: flex; flex-direction: column; gap: 0.2rem; width: 100%; padding: 0.7rem 0.85rem; text-align: left; cursor: pointer; font: inherit; color: var(--m-text); background: var(--m-panel); border: 1px solid var(--m-border); border-radius: 0.6rem; transition: border-color 0.15s, transform 0.15s; }
@@ -524,6 +1027,44 @@ const MODEL_STYLE = `
.archify-modal-defined { margin: 0.75rem 0 0; font-size: 0.8125rem; color: var(--m-muted); display: flex; flex-wrap: wrap; align-items: center; gap: 0.35rem; }
.archify-modal .archify-model-title { margin: 1.25rem 0 0.6rem; }
.archify-modal .archify-model-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
/* Live: a shared model's state, people and versions. */
.archify-live-status { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; margin: 0 0.9rem; font-size: 0.8125rem; }
.archify-live-dot { width: 0.55rem; height: 0.55rem; border-radius: 50%; background: var(--m-muted); flex: none; }
.archify-model-live.is-online .archify-live-dot { background: var(--vscode-testing-iconPassed, #3fb950); }
.archify-model-live.is-signed-out .archify-live-dot, .archify-model-live.is-forbidden .archify-live-dot, .archify-model-live.is-outdated .archify-live-dot { background: var(--vscode-editorWarning-foreground, #d29922); }
.archify-live-actions { display: inline-flex; flex-wrap: wrap; gap: 0.35rem; margin-left: auto; }
.archify-live .archify-live-action { font-family: var(--vscode-font-family, system-ui, sans-serif); }
.archify-live-people { list-style: none; display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 0.6rem 0.9rem 0; padding: 0; }
.archify-live-person { display: inline-flex; align-items: baseline; gap: 0.4rem; padding: 0.2rem 0.6rem; border: 1px solid var(--m-border); border-radius: 999px; font-size: 0.8125rem; }
.archify-live-person small { color: var(--m-muted); font-family: ui-monospace, Menlo, monospace; font-size: 0.6875rem; }
.archify-live-person.is-me { opacity: 0.75; }
.archify-live-here { font-size: 0.6875rem; color: var(--m-accent); font-weight: 600; }
.archify-live-versions-head { display: flex; align-items: center; gap: 0.5rem; margin: 0.9rem 0.9rem 0.35rem; font-size: 0.8125rem; font-weight: 600; }
.archify-live-note { margin: 0 0.9rem; font-size: 0.8125rem; }
.archify-live-versions { list-style: none; margin: 0 0.9rem; padding: 0; display: grid; gap: 0.3rem; }
.archify-live-version { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; padding: 0.4rem 0.7rem; border: 1px solid var(--m-border); border-radius: 0.5rem; font-size: 0.8125rem; }
.archify-live-version-label { font-family: ui-monospace, Menlo, monospace; }
.archify-live-version.is-publish .archify-live-version-label { color: var(--m-accent); }
.archify-live-version-name { font-weight: 600; }
.archify-live-version-when { color: var(--m-muted); }
/* Decisions: rows, chips and status badges. */
.archify-decision-list { grid-template-columns: 1fr; gap: 0.35rem; }
.archify-decision-open { padding: 0.55rem 0.85rem; }
.archify-decision-line { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.5rem; }
.archify-decision-id { font-family: ui-monospace, Menlo, monospace; font-size: 0.8125rem; color: var(--m-muted); }
.archify-decision-status { font-size: 0.6875rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; padding: 0.05rem 0.45rem; border-radius: 999px; border: 1px solid var(--m-border); color: var(--m-muted); }
.archify-decision-status.is-accepted { color: var(--m-backend); border-color: var(--m-backend); }
.archify-decision-status.is-proposed { color: var(--m-cloud); border-color: var(--m-cloud); }
.archify-decision-status.is-rejected { color: var(--m-security); border-color: var(--m-security); }
.archify-decision-item.is-superseded .archify-model-open, .archify-decision-item.is-rejected .archify-model-open { opacity: 0.6; }
.archify-decision-chip { display: inline-flex; align-items: center; gap: 0.35rem; font-family: inherit; }
.archify-decision-dot { width: 0.4rem; height: 0.4rem; border-radius: 50%; background: var(--m-muted); }
.archify-decision-chip.is-accepted .archify-decision-dot { background: var(--m-backend); }
.archify-decision-chip.is-proposed .archify-decision-dot { background: var(--m-cloud); }
.archify-decision-chip.is-rejected .archify-decision-dot { background: var(--m-security); }
.archify-decision-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 0.6rem; margin: 0.4rem 0 0; }
.archify-decision-section { margin-top: 0.5rem; }
.archify-decision-text { margin: 0; max-width: 72ch; font-size: 0.9375rem; line-height: 1.6; color: var(--m-text); white-space: pre-line; }
/* Registry cards: Archify's own .card look, with fallbacks for the page without a diagram. */
.archify-model { --m-frontend: var(--frontend-stroke, #22d3ee); --m-backend: var(--backend-stroke, #34d399); --m-database: var(--database-stroke, #a78bfa); --m-cloud: var(--cloud-stroke, #fbbf24); --m-security: var(--security-stroke, #fb7185); --m-messagebus: var(--messagebus-stroke, #fb923c); --m-external: var(--external-stroke, #94a3b8); }
.archify-model-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(15rem, 100%), 1fr)); gap: 1rem; margin-top: 0.25rem; }
@@ -542,11 +1083,39 @@ const MODEL_STYLE = `
.archify-model-used-link:hover { border-color: var(--m-accent); }
`;
/* The Model | Graph switch: in Archify's toolbar it is the 2D | 3D switch's twin; on the model page it sits top right. */
const SWITCH_STYLE = `
.archify-mode-switch { display: inline-flex; align-items: center; padding: 0 0.25rem; gap: 0; color: var(--text-muted, var(--vscode-descriptionForeground)); position: relative; }
.toolbar .archify-mode-switch { height: 2.75rem; box-sizing: border-box; }
.toolbar .archify-mode-switch::before { content: ""; position: absolute; inset: 0.25rem 0; border-radius: 0.6875rem; background: color-mix(in srgb, var(--panel) 78%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--panel-border) 85%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); backdrop-filter: blur(12px); }
.toolbar .archify-mode-switch:hover::before { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text) 22%, transparent), 0 1px 2px rgba(15, 23, 42, 0.04); }
/* Anchored on the id: Archify's .toolbar button rules (one of them with :not(#btn-theme)) would win otherwise. */
#archify-mode-switch .archify-mode-seg { position: relative; display: inline-flex; align-items: center; height: 1.75rem; min-height: 0; margin: 0; padding: 0 0.7rem; border: 0; border-radius: 0.5rem; background: transparent; color: inherit; font: inherit; font-weight: 550; font-size: 0.8125rem; cursor: pointer; transition: background 0.15s, color 0.15s; }
/* Archify's toolbar buttons are 2.75rem tall with a painted ::before; the segments are not, like 2D | 3D. */
#archify-mode-switch .archify-mode-seg::before, #archify-mode-switch .archify-mode-seg::after { content: none; }
#archify-mode-switch .archify-mode-seg.on[aria-pressed="true"] { color: var(--bg, var(--vscode-editor-background)); background: var(--text, var(--vscode-foreground)); box-shadow: 0 1px 2px rgba(15, 23, 42, 0.12), 0 6px 16px -8px rgba(15, 23, 42, 0.4); }
#archify-mode-switch .archify-mode-seg:hover:not(.on) { color: var(--text, var(--vscode-foreground)); }
#archify-mode-switch .archify-mode-seg:focus-visible { outline: 2px solid var(--frontend-stroke, var(--vscode-focusBorder)); outline-offset: 1px; }
.archify-source-badge { display: inline-block; min-width: 1rem; margin-left: 0.35rem; padding: 0 0.3rem; border-radius: 999px; background: var(--security-stroke, var(--vscode-editorError-foreground, #f14c4c)); color: var(--bg, #fff); font-size: 0.6875rem; font-weight: 700; line-height: 1rem; text-align: center; }
.archify-source-badge[hidden] { display: none; }
.archify-model-switch-row { float: right; margin: 1.5rem 0 0 1rem; }
body > .archify-model-switch-row { position: relative; z-index: 2; margin: 1rem 1.25rem 0 1rem; }
.archify-model-switch-row .archify-mode-switch { border: 1px solid var(--m-border, var(--vscode-editorWidget-border, rgba(128,128,128,.35))); border-radius: 0.75rem; background: var(--m-panel, var(--vscode-editorWidget-background)); padding: 0.1rem 0.25rem; }
`;
/* Connectors rail panel: highlight of the hovered or selected edge in the SVG. */
const CONNECTOR_STYLE = `
.diagram-container svg [data-edge-key][data-archify-hit] path, .diagram-container svg [data-edge-key][data-archify-selected] path { stroke-width: 3px; filter: drop-shadow(0 0 3px currentColor); }
.diagram-container svg [data-edge-key][data-archify-selected] text { font-weight: 700; }
.archify-connectors .node-outline-item strong { font-weight: 600; }
.diagram-container svg [data-node-id][data-archify-hit] { filter: drop-shadow(0 0 6px var(--frontend-stroke)); }
/* Bottom rail with a Decisions panel: three columns. */
html[data-reader-rail="bottom"] .reader-rail:has(> #archify-decisions) { grid-template-areas: "cards cards cards" "index connectors decisions"; grid-template-columns: repeat(3, minmax(0, 1fr)); }
html[data-reader-rail="bottom"] .reader-rail:has(> #archify-decisions):has(> #node-outline[hidden]) { grid-template-areas: "cards cards" "connectors decisions"; grid-template-columns: repeat(2, minmax(0, 1fr)); }
html[data-reader-rail="bottom"] .reader-rail > #archify-decisions { display: block; grid-area: decisions; padding: 0 1.25rem 0.75rem; border: 1px solid var(--panel-border); border-radius: 0.75rem; background: var(--panel); }
html[data-reader-rail="bottom"] .reader-rail > #archify-decisions .node-outline-head { padding: 1rem 0.25rem 0.375rem; }
html[data-reader-rail="bottom"] .reader-rail > #archify-decisions .node-outline-list { columns: 15rem; column-gap: 1.75rem; padding: 0; overflow: visible; -webkit-mask-image: none; mask-image: none; }
.archify-decision-rail-item.is-superseded, .archify-decision-rail-item.is-rejected { opacity: 0.6; }
/* Bottom rail: Elements and Connectors side by side; Connectors alone when Archify hides its index. */
html[data-reader-rail="bottom"] .reader-rail:has(> .archify-connectors) { grid-template-areas: "cards cards" "index connectors"; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); column-gap: 1rem; }
html[data-reader-rail="bottom"] .reader-rail:has(> .archify-connectors):has(> #node-outline[hidden]) { grid-template-areas: "cards" "connectors"; grid-template-columns: minmax(0, 1fr); }
@@ -576,7 +1145,7 @@ export function prepareDiagramHtml(html: string, options: PageOptions): string {
const head =
`<meta http-equiv="Content-Security-Policy" content="${escapeHtml(contentSecurityPolicy(options.cspSource, options.nonce))}">\n` +
`<script nonce="${options.nonce}">${bridgeScript(options)}</script>\n` +
`<style>${NOTICE_STYLE}${CONNECTOR_STYLE}${options.model ? MODEL_STYLE : ''}</style>\n`;
`<style>${NOTICE_STYLE}${CONNECTOR_STYLE}${SWITCH_STYLE}${options.model ? MODEL_STYLE : ''}</style>\n`;
let page = html
// Archify calls its node rail "Node index"; next to the registry it reads better as Elements.
@@ -603,8 +1172,8 @@ export function prepareDiagramHtml(html: string, options: PageOptions): string {
}
/** The model page for a main.archify without a diagram of its own. */
export function modelPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>, model: ModelPanel): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, model, links: {} });
export function modelPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state' | 'source'>, model: ModelPanel): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, model, links: {}, graphSwitch: { left: 'Model' }, source: options.source });
return `<!DOCTYPE html>
<html lang="en">
<head>
@@ -615,6 +1184,27 @@ export function modelPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'st
<style>
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
${MODEL_STYLE}
${SWITCH_STYLE}
</style>
</head>
<body></body>
</html>`;
}
/** The Graph page of a model: the bundled script builds everything from the host's graph data. */
export function graphPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>, graph: NonNullable<PageOptions['graph']>): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, links: {}, graph });
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="${escapeHtml(contentSecurityPolicy(options.cspSource, options.nonce))}">
<script nonce="${options.nonce}">${bridge}</script>
<script nonce="${options.nonce}" defer src="${escapeHtml(graph.scriptUri)}"></script>
<style>
html, body { margin: 0; height: 100%; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
${NOTICE_STYLE}
</style>
</head>
<body></body>
@@ -622,8 +1212,8 @@ export function modelPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'st
}
/** The registry page for one .archify-registry file. */
export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>, registry: RegistryPanel): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, registry, links: {} });
export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state' | 'source'>, registry: RegistryPanel): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, registry, links: {}, source: options.source });
return `<!DOCTYPE html>
<html lang="en">
<head>
@@ -634,28 +1224,55 @@ export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' |
<style>
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
${MODEL_STYLE}
${SWITCH_STYLE}
${NOTICE_STYLE}
</style>
</head>
<body></body>
</html>`;
}
/** A small VS Code-styled page for loading and error states. */
export function messagePage(
options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>,
title: string,
body: string,
detail?: string,
): string {
/** The decision page for one .archify-decision file. */
export function decisionPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state' | 'source'>, decision: DecisionPanel): string {
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, decision, links: {}, source: options.source });
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="${escapeHtml(contentSecurityPolicy(options.cspSource, options.nonce))}">
<script nonce="${options.nonce}">(function () { var vscode = acquireVsCodeApi(); var state = ${scriptJson(options.state)}; if (state) vscode.setState(state); })();</script>
<script nonce="${options.nonce}">${bridge}</script>
<style>
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
${MODEL_STYLE}
${SWITCH_STYLE}
${NOTICE_STYLE}
</style>
</head>
<body></body>
</html>`;
}
/** A small VS Code-styled page for loading and error states; with `source`, the YAML can be fixed in place. */
export function messagePage(
options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state' | 'source'>,
title: string,
body: string,
detail?: string,
): string {
const script = options.source
? bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, links: {}, source: options.source })
: `(function () { var vscode = acquireVsCodeApi(); var state = ${scriptJson(options.state)}; if (state) vscode.setState(state); })();`;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="${escapeHtml(contentSecurityPolicy(options.cspSource, options.nonce))}">
<script nonce="${options.nonce}">${script}</script>
<style>
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); background: var(--vscode-editor-background); padding: 24px 28px; }
${options.source ? SWITCH_STYLE + NOTICE_STYLE : ''}
h2 { font-weight: 600; font-size: 15px; margin: 0 0 8px; }
p { margin: 0 0 12px; color: var(--vscode-descriptionForeground); }
pre { font-family: var(--vscode-editor-font-family); font-size: 12px; white-space: pre-wrap; word-break: break-word;
+5
View File
@@ -0,0 +1,5 @@
// The package's "./yaml" export needs "bundler" module resolution; this
// repository resolves like Node 10, so point at its types directly.
declare module 'codemirror-json-schema/yaml' {
export * from 'codemirror-json-schema/dist/yaml/index';
}
+258
View File
@@ -0,0 +1,258 @@
import { autocompletion, closeBrackets, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
import { yaml, yamlLanguage } from '@codemirror/lang-yaml';
import { HighlightStyle, bracketMatching, foldGutter, foldKeymap, indentOnInput, indentUnit, syntaxHighlighting } from '@codemirror/language';
import { lintGutter, lintKeymap, nextDiagnostic, setDiagnostics } from '@codemirror/lint';
import { Annotation, EditorState, Range, StateEffect, StateField, Transaction } from '@codemirror/state';
import {
Decoration,
DecorationSet,
EditorView,
WidgetType,
drawSelection,
dropCursor,
highlightActiveLine,
highlightActiveLineGutter,
highlightSpecialChars,
hoverTooltip,
keymap,
lineNumbers,
rectangularSelection,
} from '@codemirror/view';
import { tags as t } from '@lezer/highlight';
import { stateExtensions, updateSchema } from 'codemirror-json-schema';
import { yamlCompletion, yamlSchemaHover } from 'codemirror-json-schema/yaml';
import type { TextChange } from '../../util/textDiff';
/** A problem from the host, as offsets into the "\n" text it checked. */
export interface SourceDiagnostic {
from: number;
to: number;
severity: 'error' | 'warning' | 'info';
message: string;
source?: string;
}
/** A teammate's cursor (Archify Sync), as offsets into the editor's text. */
export interface RemoteCursor {
name: string;
color: string;
anchor: number;
head: number;
}
const setRemoteCursors = StateEffect.define<RemoteCursor[]>();
class RemoteCaret extends WidgetType {
constructor(
readonly name: string,
readonly color: string,
) {
super();
}
eq(other: RemoteCaret): boolean {
return other.name === this.name && other.color === this.color;
}
toDOM(): HTMLElement {
const caret = document.createElement('span');
caret.className = 'cm-remote-caret';
caret.style.borderLeftColor = this.color;
const label = document.createElement('span');
label.className = 'cm-remote-label';
label.textContent = this.name;
label.style.backgroundColor = this.color;
caret.appendChild(label);
return caret;
}
ignoreEvent(): boolean {
return true;
}
}
function remoteDecorations(cursors: RemoteCursor[], length: number): DecorationSet {
const ranges: Range<Decoration>[] = [];
const clamp = (n: number) => Math.max(0, Math.min(n, length));
for (const c of cursors) {
const anchor = clamp(c.anchor);
const head = clamp(c.head);
if (anchor !== head) {
ranges.push(
Decoration.mark({ class: 'cm-remote-selection', attributes: { style: `background-color: color-mix(in srgb, ${c.color} 22%, transparent)` } }).range(Math.min(anchor, head), Math.max(anchor, head)),
);
}
ranges.push(Decoration.widget({ widget: new RemoteCaret(c.name, c.color), side: 1 }).range(head));
}
return Decoration.set(ranges, true);
}
/** Teammates' carets and selections; they move with the text as anyone types. */
const remoteCursors = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(decorations, tr) {
decorations = decorations.map(tr.changes);
for (const effect of tr.effects) if (effect.is(setRemoteCursors)) decorations = remoteDecorations(effect.value, tr.state.doc.length);
return decorations;
},
provide: (field) => EditorView.decorations.from(field),
});
/** Marks transactions that carry text from the host, so they are not sent back. */
const fromHost = Annotation.define<boolean>();
// The page's own variables (Archify's, or ours on model pages), so the
// editor follows the page theme, light or dark.
const theme = EditorView.theme({
'&': { height: '100%', color: 'var(--text, var(--vscode-editor-foreground))', backgroundColor: 'transparent', fontSize: '12.5px' },
'.cm-scroller': { fontFamily: 'var(--vscode-editor-font-family, ui-monospace, Menlo, "SF Mono", monospace)', lineHeight: '1.6' },
'.cm-content': { caretColor: 'var(--frontend-stroke, var(--vscode-editorCursor-foreground))' },
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--frontend-stroke, var(--vscode-editorCursor-foreground))' },
'.cm-gutters': { backgroundColor: 'transparent', color: 'var(--text-muted, var(--vscode-editorLineNumber-foreground))', border: 'none' },
'.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'color-mix(in srgb, var(--text, var(--vscode-editor-foreground)) 5%, transparent)' },
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': {
backgroundColor: 'color-mix(in srgb, var(--frontend-stroke, var(--vscode-editor-selectionBackground)) 28%, transparent) !important',
},
'&.cm-focused': { outline: 'none' },
'.cm-tooltip': {
backgroundColor: 'var(--panel, var(--vscode-editorHoverWidget-background))',
color: 'var(--text, var(--vscode-editorHoverWidget-foreground))',
border: '1px solid var(--panel-border, var(--vscode-editorHoverWidget-border))',
borderRadius: '8px',
maxWidth: '440px',
},
'.cm-tooltip code': { fontFamily: 'var(--vscode-editor-font-family, ui-monospace, Menlo, monospace)', color: 'var(--frontend-stroke, var(--vscode-textPreformat-foreground))' },
'.cm-tooltip-autocomplete ul li[aria-selected]': { backgroundColor: 'var(--frontend-stroke, var(--vscode-list-activeSelectionBackground))', color: 'var(--bg, var(--vscode-list-activeSelectionForeground))' },
'.cm-diagnostic': { padding: '4px 8px' },
'.cm-remote-caret': { position: 'relative', borderLeft: '2px solid', marginLeft: '-1px', marginRight: '-1px', pointerEvents: 'none' },
'.cm-remote-label': {
position: 'absolute',
bottom: '100%',
left: '-2px',
padding: '0 4px',
borderRadius: '3px 3px 3px 0',
color: '#fff',
fontSize: '10px',
lineHeight: '1.5',
fontFamily: 'var(--vscode-font-family, system-ui, sans-serif)',
whiteSpace: 'nowrap',
zIndex: '5',
opacity: '0.9',
},
'.cm-line:first-child .cm-remote-label': { bottom: 'auto', top: '100%', borderRadius: '0 3px 3px 3px' },
'.cm-foldPlaceholder': { backgroundColor: 'transparent', border: '1px solid var(--panel-border, var(--vscode-editorWidget-border))', color: 'inherit' },
});
const highlight = HighlightStyle.define([
{ tag: [t.propertyName, t.definition(t.propertyName)], color: 'var(--frontend-stroke, var(--vscode-symbolIcon-propertyForeground, #22d3ee))' },
{ tag: [t.number, t.bool, t.null, t.atom], color: 'var(--cloud-stroke, var(--vscode-debugTokenExpression-number, #fbbf24))' },
{ tag: [t.comment, t.lineComment], color: 'var(--text-muted, var(--vscode-descriptionForeground))', fontStyle: 'italic' },
{ tag: [t.punctuation, t.separator, t.squareBracket, t.brace], color: 'var(--text-muted, var(--vscode-descriptionForeground))' },
{ tag: [t.keyword, t.typeName, t.labelName, t.meta], color: 'var(--database-stroke, var(--vscode-symbolIcon-keywordForeground, #a78bfa))' },
]);
export class SourceEditor {
readonly view: EditorView;
private schemaKey: string | undefined;
constructor(
parent: HTMLElement,
text: string,
onEdit: (changes: TextChange[], text: string) => void,
/** The main selection moved (or the editor got focus); offsets into the text. */
onSelection: (anchor: number, head: number) => void = () => undefined,
) {
this.view = new EditorView({
parent,
state: EditorState.create({
doc: text,
extensions: [
// Undo and redo are the editor's own: VS Code sends ⌘Z in a focused
// webview to the webview, not to the document. Every step still
// reaches the document as an edit. Save and find stay VS Code's
// (no search panel here).
history(),
lineNumbers(),
highlightActiveLineGutter(),
highlightSpecialChars(),
foldGutter(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
closeBrackets(),
autocompletion(),
rectangularSelection(),
highlightActiveLine(),
keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, ...foldKeymap, ...completionKeymap, ...lintKeymap, indentWithTab]),
EditorState.tabSize.of(2),
indentUnit.of(' '),
yaml(),
theme,
syntaxHighlighting(highlight),
lintGutter(),
stateExtensions(undefined as never),
yamlLanguage.data.of({ autocomplete: yamlCompletion() }),
hoverTooltip(yamlSchemaHover()),
remoteCursors,
EditorView.updateListener.of((update) => {
if (update.selectionSet || update.docChanged || (update.focusChanged && update.view.hasFocus)) {
const main = update.state.selection.main;
onSelection(main.anchor, main.head);
}
if (!update.docChanged || update.transactions.some((tr) => tr.annotation(fromHost))) return;
const changes: TextChange[] = [];
update.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => changes.push({ from: fromA, to: toA, insert: inserted.toString() }));
onEdit(changes, update.state.doc.toString());
}),
],
}),
});
}
get text(): string {
return this.view.state.doc.toString();
}
/** Text from the host (an edit elsewhere, git): one change, cursor kept, not undoable here. */
applyFromHost(change: TextChange): void {
this.view.dispatch({ changes: change, annotations: [fromHost.of(true), Transaction.addToHistory.of(false)] });
}
/** Teammates' cursors, from the host; they replace the ones shown. */
setRemoteCursors(cursors: RemoteCursor[]): void {
this.view.dispatch({ effects: setRemoteCursors.of(cursors) });
}
/** The schema that completion and hover read; `undefined` turns them off. */
setSchema(key: string | undefined, schema: object | undefined): void {
if (key === this.schemaKey) return;
this.schemaKey = key;
updateSchema(this.view, schema as never);
}
/** The host's problems for the text it checked; the editor maps them through later typing. */
setDiagnostics(items: SourceDiagnostic[]): void {
const length = this.view.state.doc.length;
const diagnostics = items
.filter((d) => d.from <= length)
.map((d) => ({ from: d.from, to: Math.min(Math.max(d.to, d.from), length), severity: d.severity, message: d.message, source: d.source }));
this.view.dispatch(setDiagnostics(this.view.state, diagnostics));
}
/** Moves the cursor to the next problem and opens its message. */
nextProblem(): void {
this.view.focus();
nextDiagnostic(this.view);
}
focus(): void {
this.view.focus();
}
requestMeasure(): void {
this.view.requestMeasure();
}
}
+220
View File
@@ -0,0 +1,220 @@
import type { ArchifyHost } from '../host';
import { TextChange, minimalChange } from '../../util/textDiff';
import { RemoteCursor, SourceDiagnostic, SourceEditor } from './editor';
/**
* The Source view of an Archify page: the file's YAML in an editor, in the
* page under its toolbar and heading, in place of the picture. The bridge
* script (page.ts) loads this file the first time Source is chosen and calls
* window.__archifySource.open(); the document itself stays in the host, which
* applies every edit to it and sends back problems and outside changes.
*/
/** Host → page. */
type HostMessage =
| { type: 'sourceText'; text: string; schema?: { key: string; schema: object } | null; checks: string }
| { type: 'sourceDiagnostics'; items: SourceDiagnostic[]; count: number }
| { type: 'sourceSchema'; schema: { key: string; schema: object } | null }
| { type: 'sourceDirty'; dirty: boolean }
| { type: 'sourceCursors'; cursors: RemoteCursor[] };
const STYLE = `
html.archify-source-on .container > :not(.header):not(#archify-source),
html.archify-source-on body > :not(.toolbar):not(.container):not(.archify-model-head):not(.archify-model-switch-row):not(#archify-source):not(#archify-sync-button):not(script):not(style):not(.archify-modal-backdrop),
html.archify-source-on #btn-3d,
html.archify-source-on .archify-vscode-notice { display: none !important; }
html:not(.archify-source-on) #archify-source { display: none !important; }
.archify-source { display: flex; flex-direction: column; box-sizing: border-box; min-height: 260px; margin: 0.75rem 0 1rem; }
body > .archify-source { max-width: 1400px; margin: 0.75rem auto 1rem; padding: 0 2rem; }
.archify-source-editor { flex: 1; min-height: 0; overflow: hidden; border: 1px solid var(--panel-border, var(--vscode-editorWidget-border, rgba(128,128,128,.35))); border-radius: 0.75rem;
background: color-mix(in srgb, var(--panel, var(--vscode-editor-background)) 70%, transparent); }
.archify-source-editor .cm-editor { height: 100%; }
.archify-source-strip { display: flex; flex-wrap: wrap; gap: 0.35rem 1rem; align-items: center; padding: 0.45rem 0.25rem 0; font-size: 0.75rem;
color: var(--text-muted, var(--vscode-descriptionForeground)); font-family: var(--vscode-font-family, system-ui, sans-serif); }
.archify-source-strip .is-ok { color: var(--backend-stroke, var(--vscode-testing-iconPassed, #34d399)); }
.archify-source-strip .is-bad { color: var(--security-stroke, var(--vscode-editorError-foreground, #fb7185)); }
.archify-source-strip button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
.archify-source-strip button:hover { text-decoration: underline; }
.archify-source-strip .archify-source-hint { margin-left: auto; }
.archify-source-strip kbd { font: inherit; font-size: 0.6875rem; padding: 0 0.3rem; border: 1px solid currentColor; border-radius: 0.25rem; opacity: 0.8; }
`;
const MAC = /Mac|iPhone|iPad/.test(navigator.platform);
function isUndoRedo(event: KeyboardEvent): boolean {
const key = event.key.toLowerCase();
return (event.metaKey || event.ctrlKey) && !event.altKey && (key === 'z' || key === 'y');
}
class SourcePane {
private root: HTMLElement | undefined;
private editorHost!: HTMLElement;
private stateEl!: HTMLElement;
private countEl!: HTMLButtonElement;
private checksEl!: HTMLElement;
private editor: SourceEditor | undefined;
/** The text the host last knew the page to have; edits are sent against it. */
private text = '';
private diagnostics: SourceDiagnostic[] = [];
private cursors: RemoteCursor[] = [];
private shown = false;
private selectionTimer: ReturnType<typeof setTimeout> | undefined;
private selection: { anchor: number; head: number } | undefined;
constructor(private readonly host: ArchifyHost) {
window.addEventListener('message', (event) => this.onMessage(event.data as HostMessage));
window.addEventListener('resize', () => this.fit());
}
open(): void {
this.build();
this.shown = true;
document.documentElement.classList.add('archify-source-on');
window.dispatchEvent(new CustomEvent('archify-source', { detail: { on: true } }));
this.fit();
this.host.post({ type: 'sourceOpen' });
this.editor?.focus();
}
close(): void {
this.shown = false;
document.documentElement.classList.remove('archify-source-on');
window.dispatchEvent(new CustomEvent('archify-source', { detail: { on: false } }));
this.host.post({ type: 'sourceClose' });
}
private build(): void {
if (this.root) return;
const style = document.createElement('style');
style.textContent = STYLE;
document.head.appendChild(style);
const root = document.createElement('section');
root.id = 'archify-source';
root.className = 'archify-source';
root.setAttribute('aria-label', 'Source');
this.editorHost = document.createElement('div');
this.editorHost.className = 'archify-source-editor';
const strip = document.createElement('div');
strip.className = 'archify-source-strip';
this.stateEl = document.createElement('span');
this.countEl = document.createElement('button');
this.countEl.type = 'button';
this.countEl.title = 'Go to the next problem';
this.countEl.addEventListener('click', () => this.editor?.nextProblem());
this.checksEl = document.createElement('span');
const hint = document.createElement('span');
hint.className = 'archify-source-hint';
hint.innerHTML = 'Completion as you type, or <kbd>Ctrl</kbd>+<kbd>Space</kbd> · hover a key for its description';
strip.append(this.stateEl, this.countEl, this.checksEl, hint);
root.append(this.editorHost, strip);
this.renderState(false);
this.renderCount();
// Archify's page has single-key shortcuts; typing here must not reach
// them. Keys with ⌘ or Ctrl go on to VS Code (save, find, quick open),
// except undo and redo, which the editor has handled already.
for (const type of ['keydown', 'keypress', 'keyup'] as const) {
root.addEventListener(type, (event) => {
if (!event.metaKey && !event.ctrlKey) event.stopPropagation();
else if (isUndoRedo(event)) event.stopPropagation();
});
}
const header = document.querySelector('.container > .header');
const modelHead = document.querySelector('.archify-model-head');
if (header?.parentElement) header.parentElement.insertBefore(root, header.nextSibling);
else if (modelHead?.parentElement) modelHead.parentElement.insertBefore(root, modelHead.nextSibling);
else document.body.appendChild(root);
this.root = root;
}
/** The editor fills the window below where it starts. */
private fit(): void {
if (!this.root || !this.shown) return;
const top = this.root.getBoundingClientRect().top;
this.root.style.height = `${Math.max(260, window.innerHeight - Math.max(top, 0) - 12)}px`;
this.editor?.requestMeasure();
}
private onMessage(message: HostMessage): void {
if (!message || typeof message !== 'object') return;
switch (message.type) {
case 'sourceText':
this.build();
if (!this.editor) {
this.text = message.text;
this.editor = new SourceEditor(
this.editorHost,
message.text,
(changes, text) => this.onEdit(changes, text),
(anchor, head) => this.onSelection(anchor, head),
);
this.editor.setDiagnostics(this.diagnostics);
this.editor.setRemoteCursors(this.cursors);
this.fit();
if (this.shown) this.editor.focus();
} else {
const change = minimalChange(this.editor.text, message.text);
if (change) this.editor.applyFromHost(change);
this.text = message.text;
}
if (message.schema !== undefined) this.editor.setSchema(message.schema?.key, message.schema?.schema);
this.checksEl.textContent = message.checks;
return;
case 'sourceDiagnostics':
this.diagnostics = message.items;
this.editor?.setDiagnostics(message.items);
this.renderCount();
return;
case 'sourceSchema':
this.editor?.setSchema(message.schema?.key, message.schema?.schema);
return;
case 'sourceDirty':
this.renderState(message.dirty);
return;
case 'sourceCursors':
this.cursors = message.cursors;
this.editor?.setRemoteCursors(message.cursors);
return;
}
}
/** Teammates see where you are; sent at most every 80 ms, after the edit it follows. */
private onSelection(anchor: number, head: number): void {
this.selection = { anchor, head };
if (this.selectionTimer) return;
this.selectionTimer = setTimeout(() => {
this.selectionTimer = undefined;
if (this.selection && this.shown) this.host.post({ type: 'sourceSelection', ...this.selection });
}, 80);
}
private onEdit(changes: TextChange[], text: string): void {
const base = this.text;
this.text = text;
this.host.post({ type: 'sourceEdit', base, text, changes });
}
private renderState(dirty: boolean): void {
if (!this.stateEl) return;
this.stateEl.innerHTML = dirty ? `● Unsaved · <kbd>${MAC ? '⌘' : 'Ctrl+'}S</kbd> saves` : 'Saved';
}
private renderCount(): void {
if (!this.countEl) return;
const problems = this.diagnostics.filter((d) => d.severity !== 'info').length;
this.countEl.className = problems ? 'is-bad' : 'is-ok';
this.countEl.textContent = problems ? `✕ ${problems} problem${problems === 1 ? '' : 's'}` : '✓ No problems';
this.countEl.disabled = !problems;
}
}
declare global {
interface Window {
__archifySource?: { open(): void; close(): void };
}
}
const host = window.__archifyHost;
if (host) window.__archifySource = new SourcePane(host);
+10
View File
@@ -0,0 +1,10 @@
// Stands in for codemirror-json-schema's utils/markdown, which brings
// markdown-it and shiki (about 400 KB) to format schema descriptions. Ours
// only use `code` spans: escape the text and keep those. esbuild.mjs swaps
// this file in.
const escape = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
export function renderMarkdown(markdown: string, inline = true): string {
const html = escape(String(markdown)).replace(/`([^`]+)`/g, '<code>$1</code>');
return inline ? html : `<p>${html.replace(/\n{2,}/g, '</p><p>')}</p>`;
}
+10
View File
@@ -13,3 +13,13 @@ export function viewer3dOption(webview: vscode.Webview, extensionUri: vscode.Uri
defaultView,
};
}
/** The Graph page script (a webview URI). */
export function graphScriptUri(webview: vscode.Webview, extensionUri: vscode.Uri): string {
return webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'dist', 'graph.js')).toString();
}
/** The Source view script (a webview URI), loaded by the page the first time Source is chosen. */
export function sourceScriptUri(webview: vscode.Webview, extensionUri: vscode.Uri): string {
return webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'dist', 'source.js')).toString();
}
+17
View File
@@ -0,0 +1,17 @@
# An architecture decision of this model. The id is unique in the model;
# elements are registry ids, diagrams are paths from the model root.
schema_version: 1
decision:
id: __ID__
title: __TITLE__
status: proposed # proposed | accepted | superseded | rejected
date: __DATE__
elements: []
diagrams: []
supersedes: []
context: >
What was the situation, and what forced a decision.
decision: >
What was decided, in one or two sentences.
consequences: >
What becomes easier, what becomes harder, what must change.
@@ -3,6 +3,7 @@ diagram_type: architecture
meta:
title: Containers
output: containers.html
decisions: [postgres-as-source-of-truth]
components:
- ref: customer
pos: [40, 160]
@@ -22,6 +23,7 @@ components:
- ref: queue
pos: [460, 360]
size: [130, 60]
decisions: [queue-between-api-and-worker]
- ref: worker
pos: [670, 460]
size: [130, 60]
@@ -34,6 +36,6 @@ connections:
- { from: web, to: api, label: JSON }
- { from: api, to: cache, label: read }
- { from: api, to: db, label: SQL }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290] }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290], decisions: [queue-between-api-and-worker] }
- { from: queue, to: worker, label: poll }
- { from: worker, to: db, label: SQL, labelAt: [735, 420] }
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: postgres-as-source-of-truth
title: PostgreSQL as the single source of truth
status: accepted
date: 2026-09-02
elements: [db, api, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Orders, customers and the catalogue were spread over the
shop database and two spreadsheets kept by support.
Refunds were reconciled by hand every Monday.
decision: >
One PostgreSQL database owns orders, customers and the
catalogue. The API is the only writer. Everything else
(cache, search, reports) is derived and may be rebuilt.
consequences: >
Support loses the spreadsheets and gets the admin console.
Any new store must be declared derived or get its own
decision. Backups and migrations are the API team's job.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: queue-between-api-and-worker
title: A queue between the API and the worker
status: accepted
date: 2026-09-16
elements: [api, queue, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Order confirmation emails and invoices were sent inside
the checkout request. A slow mail provider made checkout
slow; a failing one made checkout fail.
decision: >
The API enqueues a job per side effect on SQS. One worker
service consumes the queue and does the slow work.
Checkout returns as soon as the order is stored.
consequences: >
Emails arrive seconds later, not instantly. Jobs must be
idempotent because SQS delivers at least once. The worker
is the second place that writes to the database.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: opensearch-for-product-search
title: OpenSearch for product search
status: proposed
date: 2026-10-19
elements: [api, worker, db]
diagrams: [0200-containers/online-shop.archify]
context: >
Catalogue search runs as SQL LIKE queries on the
database. Typos find nothing and the catalogue page is
the slowest page in the shop.
decision: >
Add a dedicated search service on OpenSearch. The API
queries it; the worker rebuilds the index from the
database after every catalogue change.
consequences: >
The index is derived data under decision 0001 and may be
rebuilt at any time. One more service to run. Search
results can lag the database by the rebuild interval.
@@ -43,4 +43,4 @@ connections:
- { from: router, to: store, label: append }
- { from: router, to: notifier, label: notify }
- { from: router, to: analytics, label: flatten }
- { from: router, to: dlq, label: failed, variant: dashed, labelDy: 24 }
- { from: router, to: dlq, label: failed, variant: dashed, labelDy: 24, decisions: [dead-letter-queue] }
@@ -0,0 +1,18 @@
schema_version: 1
decision:
id: dead-letter-queue
title: Failed events go to a dead-letter queue, never dropped
status: accepted
date: 2026-09-24
elements: [router, dlq, ops]
diagrams: [0200-containers/platform.archify, 0300-components/router.archify]
context: >
Events that failed schema validation were logged and lost.
Nobody noticed until a customer asked where an order went.
decision: >
The router moves every event it cannot process to a
dead-letter queue with the reason. Operations replays
them after the cause is fixed.
consequences: >
Nothing is lost silently. Someone has to watch the queue;
that is an on-call duty for operations.
@@ -32,7 +32,7 @@ boundaries:
connections:
- { from: user, to: spa, label: HTTPS, variant: emphasis }
- { from: spa, to: api, label: JSON }
- { from: api, to: idp, label: verify token, variant: security, labelAt: [531, 110] }
- { from: api, to: idp, label: verify token, variant: security, labelAt: [531, 110], decisions: [external-identity-provider] }
- { from: api, to: cache, label: read }
- { from: api, to: db, label: SQL }
- { from: api, to: storage, label: files }
@@ -0,0 +1,17 @@
schema_version: 1
decision:
id: external-identity-provider
title: Sign in through an identity provider, never store passwords
status: accepted
date: 2026-09-10
elements: [idp, api, spa]
diagrams: [0200-containers/web-app.archify]
context: >
The first version kept password hashes in the database and
had to handle resets, lockouts and two-factor codes itself.
decision: >
Users sign in through an OpenID Connect identity provider.
The single-page app gets a token; the API only verifies it.
consequences: >
No password tables, no reset flows. The identity provider
is a hard dependency: when it is down, nobody can sign in.
+95
View File
@@ -0,0 +1,95 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test } from 'node:test';
import { parse } from 'yaml';
import { effectiveStatus, mergeDecisions, parseDecision, slugify, sortDecisions, validateDecisions } from '../src/model/decisions';
import { mergeRegistries, parseRegistry, resolveRefs, summarizeDiagram } from '../src/model/format';
const model = path.resolve(__dirname, '..', '..', 'test', 'fixtures', 'model');
const read = (rel: string) => fs.readFileSync(path.join(model, rel), 'utf8');
const DECISION_FILES = ['decisions/0001-postgres-as-source-of-truth.archify-decision', 'decisions/0002-queue-between-api-and-worker.archify-decision', 'decisions/0003-opensearch-for-product-search.archify-decision'];
function registryOfModel() {
const files = ['registry/people.archify-registry', 'registry/systems.archify-registry', 'registry/containers.archify-registry'];
return mergeRegistries(files.map((file) => ({ file, ...parseRegistry(read(file), file) })));
}
function decisionsOfModel() {
return mergeDecisions(DECISION_FILES.map((file) => ({ file, ...parseDecision(read(file), file) })));
}
test('decision files parse with lines for every linked id', () => {
const { decision, problems } = parseDecision(read(DECISION_FILES[1]), 'd2');
assert.deepEqual(problems, []);
assert.ok(decision);
assert.equal(decision.id, 'queue-between-api-and-worker');
assert.equal(decision.title, 'A queue between the API and the worker');
assert.equal(decision.status, 'accepted');
assert.deepEqual(decision.elements, ['api', 'queue', 'worker']);
assert.deepEqual(decision.diagrams, ['0200-containers/online-shop.archify']);
assert.equal(decision.lines.elements.length, 3);
assert.ok(decision.context && decision.decision && decision.consequences);
});
test('decision files: broken YAML, missing block, unknown status', () => {
assert.equal(parseDecision('decision: {\n', 'x').problems[0].severity, 'error');
assert.match(parseDecision('context: only text\n', 'x').problems[0].message, /"decision" block/);
const bad = parseDecision('decision:\n id: a\n title: A\n status: maybe\n elements: api\n', 'x');
assert.deepEqual(bad.problems.map((p) => p.message.split(';')[0]), ['Unknown status "maybe"', '"elements" must be a list.']);
assert.equal(bad.problems[0].line, 3);
});
test('decisions merge, validate links, and the superseded rule applies', () => {
const set = decisionsOfModel();
assert.deepEqual(set.problems, []);
assert.equal(set.decisions.size, 3);
const registry = registryOfModel();
const diagrams = new Set(['0100-context/online-shop.archify', '0200-containers/online-shop.archify', '0300-components/api.archify']);
assert.deepEqual(validateDecisions(set, registry, diagrams), []);
// Duplicate id, unknown element, missing diagram, dangling supersedes.
const extra = parseDecision('decision:\n id: queue-between-api-and-worker\n title: Dup\n elements: [ghost]\n diagrams: [0900/x.archify]\n supersedes: [nope]\n', 'dup');
const merged = mergeDecisions([...DECISION_FILES.map((file) => ({ file, ...parseDecision(read(file), file) })), { file: 'dup', ...extra }]);
assert.match(merged.problems[0].message, /defined twice/);
const newer = parseDecision('decision:\n id: one-database\n title: Replace the first\n status: accepted\n supersedes: [postgres-as-source-of-truth]\n', 'd4');
const withNewer = mergeDecisions([...DECISION_FILES.map((file) => ({ file, ...parseDecision(read(file), file) })), { file: 'd4', ...newer }]);
const problems = validateDecisions(mergeDecisions([{ file: 'dup', ...extra }]), registry, diagrams);
assert.deepEqual(problems.map((p) => p.message.split(':')[0]), ['Unknown element "ghost"', 'Diagram "0900/x.archify" does not exist in this model.', 'Decision "nope" (in supersedes) does not exist in this model.']);
assert.deepEqual(effectiveStatus(withNewer.decisions.get('postgres-as-source-of-truth')!, withNewer.decisions), { status: 'superseded', supersededBy: 'one-database' });
assert.deepEqual(effectiveStatus(withNewer.decisions.get('queue-between-api-and-worker')!, withNewer.decisions), { status: 'accepted' });
const order = sortDecisions([...withNewer.decisions.values()], withNewer.decisions).map((d) => d.id);
assert.equal(order[order.length - 1], 'postgres-as-source-of-truth', 'superseded sorts last');
assert.equal(slugify('OpenSearch for product search!'), 'opensearch-for-product-search');
// Numeric ids are a YAML trap and are refused on both sides.
assert.match(parseDecision('decision:\n id: 0001\n title: N\n', 'n').problems[0].message, /is a number to YAML/);
assert.match(parseDecision('decision:\n id: ok\n title: N\n supersedes: [0001]\n', 'n').problems[0].message, /is a number to YAML/);
});
test('diagrams: decisions keys are stripped, collected and checked', () => {
const registry = registryOfModel();
const known = new Set(decisionsOfModel().decisions.keys());
const doc = parse(read('0200-containers/online-shop.archify'));
const r = resolveRefs(doc, { registry, decisions: known, fileName: 'c.archify' });
assert.deepEqual(r.problems, []);
assert.ok(!('decisions' in r.diagram));
const components = r.diagram.components as Record<string, unknown>[];
const connections = r.diagram.connections as Record<string, unknown>[];
assert.ok(components.every((c) => !('decisions' in c)) && connections.every((c) => !('decisions' in c)));
assert.deepEqual(r.decisionRefs.map((d) => [d.id, d.attachedTo.kind, d.pointer]), [
['postgres-as-source-of-truth', 'diagram', '/decisions/0'],
['queue-between-api-and-worker', 'node', '/components/5/decisions/0'],
['queue-between-api-and-worker', 'edge', '/connections/4/decisions/0'],
]);
const numeric = resolveRefs({ decisions: [1], components: [] }, { registry, decisions: known, fileName: 'x.archify' });
assert.match(numeric.problems[0].message, /is a number to YAML/);
const unknown = resolveRefs({ components: [{ id: 'a', type: 'backend', label: 'A', pos: [0, 0], decisions: ['nope'] }] }, { registry, decisions: known, fileName: 'x.archify' });
assert.equal(unknown.problems[0].pointer, '/components/0/decisions/0');
assert.match(unknown.problems[0].message, /Unknown decision "nope"/);
const outside = resolveRefs({ decisions: ['postgres-as-source-of-truth'], components: [] }, { fileName: '/w/loose.archify' });
assert.match(outside.problems[0].message, /not inside a model/);
// Other kinds: nodes and edges carry the key too.
const workflow = resolveRefs({ nodes: [{ id: 'n', type: 'process', label: 'N', decisions: ['postgres-as-source-of-truth'] }], edges: [{ from: 'n', to: 'n', decisions: ['queue-between-api-and-worker'] }] }, { registry, decisions: known, fileName: 'w.archify' });
assert.deepEqual(workflow.decisionRefs.map((d) => d.attachedTo.kind), ['node', 'edge']);
assert.ok(!('decisions' in (workflow.diagram.nodes as Record<string, unknown>[])[0]));
const summary = summarizeDiagram(read('0200-containers/online-shop.archify'), '0200-containers/online-shop.archify');
assert.deepEqual(summary.decisions.map((d) => d.id), ['postgres-as-source-of-truth', 'queue-between-api-and-worker', 'queue-between-api-and-worker']);
});
+53
View File
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import path from 'node:path';
import { test } from 'node:test';
import { EditorSchemas, bundleSchema } from '../src/language/editorSchemas';
import { readSchemas } from '../src/language/schemaCheck';
const schemas = readSchemas(path.resolve(__dirname, '..', '..', 'schemas'));
/** Every "$ref" in a bundled schema must point inside it. */
function resolveAll(schema: object): void {
const visit = (node: unknown): void => {
if (Array.isArray(node)) return node.forEach(visit);
if (!node || typeof node !== 'object') return;
for (const [key, value] of Object.entries(node)) {
if (key === '$ref') {
assert.match(String(value), /^#/, `local ref: ${value}`);
let target: unknown = schema;
for (const part of String(value).slice(1).split('/').filter(Boolean)) {
target = (target as Record<string, unknown>)[part.replace(/~1/g, '/').replace(/~0/g, '~')];
assert.ok(target !== undefined, `${value} resolves`);
}
} else visit(value);
}
};
visit(schema);
}
test('each schema bundles into one self-contained document', () => {
for (const name of Object.keys(schemas)) {
const bundled = bundleSchema(schemas, name);
resolveAll(bundled);
const text = JSON.stringify(bundled);
assert.ok(!text.includes('"prefixItems"'), `${name}: no prefixItems`);
assert.ok(!text.includes('"$schema"'), `${name}: no $schema`);
}
});
test('points become draft-07 tuples', () => {
const architecture = bundleSchema(schemas, 'architecture.schema.json') as { $defs: Record<string, { $defs: Record<string, unknown> }> };
const point = architecture.$defs['file:common.schema.json'].$defs.point as Record<string, unknown>;
assert.deepEqual(point.items, [{ type: 'number' }, { type: 'number' }]);
assert.equal(point.additionalItems, false);
});
test('a diagram gets the schema of its diagram_type, a decision none', () => {
const editor = new EditorSchemas(schemas);
assert.equal(editor.forSource('diagram', 'schema_version: 1\ndiagram_type: sequence\n')?.key, 'sequence.schema.json');
assert.equal(editor.forSource('diagram', 'diagram_type: "workflow"\n')?.key, 'workflow.schema.json');
assert.equal(editor.forSource('diagram', 'meta:\n title: x\n')?.key, 'archify.schema.json');
assert.equal(editor.forSource('diagram', 'diagram_type: poster\n')?.key, 'archify.schema.json');
assert.equal(editor.forSource('registry', '')?.key, 'archify-registry.schema.json');
assert.equal(editor.forSource('decision', ''), undefined);
});
+11 -1
View File
@@ -7,6 +7,7 @@ import { parse } from 'yaml';
import { validate } from '../src/archify/cli';
import { MODEL_EXAMPLES, mainFromExample } from '../src/language/examples';
import { MAIN_FILE, REGISTRY_EXT, hasDiagramBody, mergeRegistries, parseRegistry, readModelMeta, resolveRefs } from '../src/model/format';
import { DECISION_EXT, mergeDecisions, parseDecision, validateDecisions } from '../src/model/decisions';
import { readDiagramSource } from '../src/sources/detect';
const root = path.resolve(__dirname, '..', '..');
@@ -58,6 +59,15 @@ for (const example of MODEL_EXAMPLES) {
if (element.diagram) assert.ok(files.includes(element.diagram), `${element.id} links to missing ${element.diagram}`);
}
// Decisions: at least one, all links resolve.
const decisionFiles = files.filter((f) => f.endsWith(DECISION_EXT));
assert.ok(decisionFiles.length >= 1, 'an example carries at least one decision');
const decisions = mergeDecisions(decisionFiles.map((file) => ({ file, ...parseDecision(read(file), file) })));
assert.deepEqual(decisions.problems, []);
const diagramPaths = new Set(files.filter((f) => f.endsWith('.archify') && f !== MAIN_FILE));
assert.deepEqual(validateDecisions(decisions, registry, diagramPaths), []);
for (const d of decisions.decisions.values()) assert.ok(d.title && d.status && d.context && d.decision && d.consequences, `${d.id} is complete`);
// Diagrams: the three C4 levels, each resolving without problems and valid for Archify.
const diagrams = files.filter((f) => f.endsWith('.archify')).sort();
for (const level of ['0100-context', '0200-containers', '0300-components']) {
@@ -67,7 +77,7 @@ for (const example of MODEL_EXAMPLES) {
for (const file of diagrams) {
const source = readDiagramSource(read(file), file);
assert.ok(source, `${file} is not a diagram`);
const resolved = resolveRefs(source.diagram, { registry, fileName: file });
const resolved = resolveRefs(source.diagram, { registry, decisions: new Set(decisions.decisions.keys()), fileName: file });
assert.deepEqual(resolved.problems, [], file);
for (const link of resolved.links.values()) assert.ok(files.includes(link), `${file} links to missing ${link}`);
for (const id of resolved.used) used.add(id);
+3 -1
View File
@@ -3,6 +3,7 @@ diagram_type: architecture
meta:
title: Containers
output: containers.html
decisions: [postgres-as-source-of-truth]
components:
- ref: customer
pos: [40, 160]
@@ -22,6 +23,7 @@ components:
- ref: queue
pos: [460, 360]
size: [130, 60]
decisions: [queue-between-api-and-worker]
- ref: worker
pos: [670, 460]
size: [130, 60]
@@ -34,6 +36,6 @@ connections:
- { from: web, to: api, label: JSON }
- { from: api, to: cache, label: read }
- { from: api, to: db, label: SQL }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290] }
- { from: api, to: queue, label: enqueue, labelAt: [560, 290], decisions: [queue-between-api-and-worker] }
- { from: queue, to: worker, label: poll }
- { from: worker, to: db, label: SQL, labelAt: [735, 420] }
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: postgres-as-source-of-truth
title: PostgreSQL as the single source of truth
status: accepted
date: 2026-09-02
elements: [db, api, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Orders, customers and the catalogue were spread over the
shop database and two spreadsheets kept by support.
Refunds were reconciled by hand every Monday.
decision: >
One PostgreSQL database owns orders, customers and the
catalogue. The API is the only writer. Everything else
(cache, search, reports) is derived and may be rebuilt.
consequences: >
Support loses the spreadsheets and gets the admin console.
Any new store must be declared derived or get its own
decision. Backups and migrations are the API team's job.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: queue-between-api-and-worker
title: A queue between the API and the worker
status: accepted
date: 2026-09-16
elements: [api, queue, worker]
diagrams: [0200-containers/online-shop.archify]
context: >
Order confirmation emails and invoices were sent inside
the checkout request. A slow mail provider made checkout
slow; a failing one made checkout fail.
decision: >
The API enqueues a job per side effect on SQS. One worker
service consumes the queue and does the slow work.
Checkout returns as soon as the order is stored.
consequences: >
Emails arrive seconds later, not instantly. Jobs must be
idempotent because SQS delivers at least once. The worker
is the second place that writes to the database.
@@ -0,0 +1,20 @@
schema_version: 1
decision:
id: opensearch-for-product-search
title: OpenSearch for product search
status: proposed
date: 2026-10-19
elements: [api, worker, db]
diagrams: [0200-containers/online-shop.archify]
context: >
Catalogue search runs as SQL LIKE queries on the
database. Typos find nothing and the catalogue page is
the slowest page in the shop.
decision: >
Add a dedicated search service on OpenSearch. The API
queries it; the worker rebuilds the index from the
database after every catalogue change.
consequences: >
The index is derived data under decision 0001 and may be
rebuilt at any time. One more service to run. Search
results can lag the database by the rebuild interval.
+162
View File
@@ -0,0 +1,162 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test } from 'node:test';
import { mergeDecisions, parseDecision } from '../src/model/decisions';
import { DecisionAttachment, mergeRegistries, parseRegistry, summarizeDiagram } from '../src/model/format';
import { ModelGraph, buildGraph } from '../src/model/graph';
import { parseQuery, runQuery, shortestPath } from '../src/model/graphQuery';
const model = path.resolve(__dirname, '..', '..', 'test', 'fixtures', 'model');
const read = (rel: string) => fs.readFileSync(path.join(model, rel), 'utf8');
const REGISTRY_FILES = ['registry/people.archify-registry', 'registry/systems.archify-registry', 'registry/containers.archify-registry'];
const DIAGRAM_FILES = ['0100-context/online-shop.archify', '0200-containers/online-shop.archify', '0300-components/api.archify'];
const DECISION_FILES = ['decisions/0001-postgres-as-source-of-truth.archify-decision', 'decisions/0002-queue-between-api-and-worker.archify-decision', 'decisions/0003-opensearch-for-product-search.archify-decision'];
function graphOfModel(): ModelGraph {
const registry = mergeRegistries(REGISTRY_FILES.map((file) => ({ file, ...parseRegistry(read(file), file) })));
const diagrams = DIAGRAM_FILES.map((file) => summarizeDiagram(read(file), file));
const decisions = mergeDecisions(DECISION_FILES.map((file) => ({ file, ...parseDecision(read(file), file) })));
const decisionUsage = new Map<string, { path: string; attachedTo: DecisionAttachment }[]>();
for (const d of diagrams) for (const ref of d.decisions) decisionUsage.set(ref.id, [...(decisionUsage.get(ref.id) ?? []), { path: d.relativePath, attachedTo: ref.attachedTo }]);
return buildGraph({ meta: { id: 'online-shop', name: 'Online Shop' }, registry, diagrams, decisions, decisionUsage });
}
test('diagram summaries carry nodes and edges, shared and inline', () => {
const api = summarizeDiagram(read('0300-components/api.archify'), '0300-components/api.archify');
assert.deepEqual(api.nodes.map((n) => n.id), ['web', 'auth', 'orders', 'catalogue', 'db', 'queue']);
assert.equal(api.nodes[0].ref, 'web');
assert.equal(api.nodes[1].ref, undefined);
assert.equal(api.nodes[1].type, 'security');
assert.equal(api.edges.length, 6);
assert.deepEqual(api.edges[0], { from: 'web', to: 'auth', label: 'sign in' });
const broken = summarizeDiagram('diagram_type: [', 'x.archify');
assert.deepEqual(broken.nodes, []);
assert.deepEqual(broken.edges, []);
});
test('the model graph unites every diagram: elements once, connections once, labels merged', () => {
const graph = graphOfModel();
// 11 registry elements + 3 inline components of the API diagram, plus 3 decision and 3 registry nodes.
assert.equal(graph.nodes.filter((n) => n.kind === 'element').length, 14);
assert.equal(graph.nodes.length, 20);
const db = graph.nodes.find((n) => n.id === 'db')!;
assert.equal(db.shared, true);
assert.equal(db.type, 'database');
assert.deepEqual(db.diagrams, ['0200-containers/online-shop.archify', '0300-components/api.archify']);
assert.equal(db.file, 'registry/containers.archify-registry');
assert.ok(db.description);
const orders = graph.nodes.find((n) => n.id === 'orders')!;
assert.equal(orders.shared, false);
assert.deepEqual(orders.diagrams, ['0300-components/api.archify']);
// api → db is drawn once in the containers diagram; orders → db and catalogue → db are separate connections.
assert.equal(graph.edges.filter((e) => e.kind === 'connection').length, 4 + 7 + 6);
const apiDb = graph.edges.find((e) => e.id === 'api>db')!;
assert.deepEqual(apiDb.labels, ['SQL']);
assert.deepEqual(apiDb.diagrams, ['0200-containers/online-shop.archify']);
assert.deepEqual(graph.diagrams.map((d) => d.path), DIAGRAM_FILES);
});
test('decisions reach the elements they name and the nodes and edges they are attached to', () => {
const graph = graphOfModel();
const queue = graph.nodes.find((n) => n.id === 'queue')!;
assert.deepEqual(queue.decisions, ['queue-between-api-and-worker']);
const api = graph.nodes.find((n) => n.id === 'api')!;
assert.deepEqual([...api.decisions].sort(), ['opensearch-for-product-search', 'postgres-as-source-of-truth', 'queue-between-api-and-worker']);
assert.deepEqual(graph.edges.find((e) => e.id === 'api>queue')!.decisions, ['queue-between-api-and-worker']);
assert.equal(graph.decisions.length, 3);
assert.equal(graph.decisions.find((d) => d.id === 'postgres-as-source-of-truth')!.status, 'accepted');
});
test('decisions and registries are nodes of their own, linked to the elements they are about or define', () => {
const graph = graphOfModel();
const decision = graph.nodes.find((n) => n.id === 'decision:queue-between-api-and-worker')!;
assert.equal(decision.kind, 'decision');
assert.equal(decision.type, 'decision');
assert.equal(decision.status, 'accepted');
assert.equal(decision.sublabel, 'queue-between-api-and-worker');
assert.deepEqual(graph.edges.filter((e) => e.kind === 'decides' && e.from === decision.id).map((e) => e.to).sort(), ['api', 'queue', 'worker']);
const registry = graph.nodes.find((n) => n.id === 'registry:registry/containers.archify-registry')!;
assert.equal(registry.kind, 'registry');
assert.equal(registry.label, 'registry/containers');
assert.deepEqual(registry.elements, ['web', 'api', 'worker', 'queue', 'db', 'cache']);
assert.equal(graph.edges.filter((e) => e.kind === 'defines' && e.from === registry.id).length, 6);
// Walks and paths do not go through them: a registry is not a shortcut between its elements.
assert.deepEqual(shortestPath(graph, 'customer', 'cache')?.nodes, ['customer', 'web', 'api', 'cache']);
const ids = (q: string) => [...runQuery(graph, q).nodes].sort();
assert.ok(!ids('uses:api').some((id) => id.startsWith('registry:') && id !== 'registry:registry/containers.archify-registry'));
// They follow their elements into a result, and a negative term removes them again.
assert.deepEqual(ids('type:database').filter((id) => id.includes(':')), ['decision:opensearch-for-product-search', 'decision:postgres-as-source-of-truth', 'registry:registry/containers.archify-registry']);
assert.deepEqual(ids('type:database -type:decision -type:registry'), ['cache', 'db']);
assert.deepEqual(ids('type:registry'), ['registry:registry/containers.archify-registry', 'registry:registry/people.archify-registry', 'registry:registry/systems.archify-registry']);
assert.ok(ids('decision:queue-between-api-and-worker').includes('decision:queue-between-api-and-worker'));
});
test('an unused registry element is in the graph with no diagrams', () => {
const registry = mergeRegistries([{ file: 'r', ...parseRegistry('elements:\n api: { type: backend, label: API }\n ghost: { type: database, label: Ghost }\n', 'r') }]);
const diagrams = [summarizeDiagram('diagram_type: architecture\ncomponents:\n - ref: api\n', 'a.archify')];
const graph = buildGraph({ meta: {}, registry, diagrams, decisions: mergeDecisions([]), decisionUsage: new Map() });
assert.deepEqual(graph.nodes.filter((n) => n.kind === 'element').map((n) => [n.id, n.diagrams.length]), [['api', 1], ['ghost', 0]]);
assert.deepEqual([...runQuery(graph, 'unused').nodes], ['ghost', 'registry:r']);
});
test('queries parse into terms; unknown keys are plain text', () => {
assert.deepEqual(parseQuery('database type:backend -shared near:api 2 foo:bar unused'), [
{ key: 'text', value: 'database', negate: false },
{ key: 'type', value: 'backend', negate: false },
{ key: 'shared', value: '', negate: true },
{ key: 'near', value: 'api,2', negate: false },
{ key: 'text', value: 'foo:bar', negate: false },
{ key: 'unused', value: '', negate: false },
]);
assert.deepEqual(parseQuery(' '), []);
});
const elementIds = (graph: ModelGraph, q: string) => [...runQuery(graph, q).nodes].filter((id) => !id.includes(':')).sort();
test('queries narrow the graph: text, type, diagram, decision, shared', () => {
const graph = graphOfModel();
const ids = (q: string) => elementIds(graph, q);
assert.equal(runQuery(graph, '').nodes.size, 20);
assert.deepEqual(ids('type:database'), ['cache', 'db']);
assert.deepEqual(ids('type:external'), ['customer', 'email', 'psp', 'support']);
assert.deepEqual(ids('worker'), ['worker']);
assert.deepEqual(ids('diagram:0100-*'), ['customer', 'email', 'psp', 'shop', 'support']);
assert.deepEqual(ids('diagram:0300-components/api'), ['auth', 'catalogue', 'db', 'orders', 'queue', 'web']);
assert.deepEqual(ids('-shared'), ['auth', 'catalogue', 'orders']);
assert.deepEqual(ids('shared type:backend'), ['api', 'worker']);
assert.deepEqual(ids('decision:queue-between-api-and-worker'), ['api', 'queue', 'worker']);
assert.deepEqual(ids('type:backend -worker'), ['api', 'catalogue', 'orders']);
const unknown = runQuery(graph, 'decision:nope');
assert.equal(unknown.nodes.size, 0);
assert.match(unknown.message ?? '', /No decision "nope"/);
});
test('queries walk the graph: uses, near, from/to', () => {
const graph = graphOfModel();
const ids = (q: string) => elementIds(graph, q);
assert.deepEqual(ids('uses:api'), ['api', 'cache', 'db', 'queue', 'web']);
assert.deepEqual(ids('uses:API'), ['api', 'cache', 'db', 'queue', 'web']);
assert.deepEqual(ids('near:worker,2'), ['api', 'catalogue', 'db', 'orders', 'queue', 'worker']);
assert.deepEqual(ids('near:worker 2 type:database'), ['db']);
const result = runQuery(graph, 'from:customer to:db');
assert.deepEqual(result.path, ['customer', 'web', 'api', 'db']);
assert.deepEqual([...result.edges].filter((id) => !id.includes(':')).sort(), ['api>db', 'customer>web', 'web>api']);
// Direction is tried first; against the arrows the search still finds a way.
assert.deepEqual(shortestPath(graph, 'db', 'customer')?.nodes, ['db', 'api', 'web', 'customer']);
assert.equal(shortestPath(graph, 'psp', 'auth')?.nodes.length, 5);
const none = runQuery(graph, 'from:customer to:nowhere');
assert.equal(none.nodes.size, 0);
assert.match(none.message ?? '', /No element "nowhere"/);
const missing = runQuery(graph, 'from:customer');
assert.match(missing.message ?? '', /both from: and to:/);
});
test('connections are shown only when both ends match', () => {
const graph = graphOfModel();
const result = runQuery(graph, 'type:backend');
assert.ok(result.nodes.has('api'));
assert.ok(!result.edges.has('api>db'));
assert.ok(result.edges.has('orders>queue') === false);
assert.ok([...result.edges].every((id) => { const at = id.indexOf('>', id.startsWith('decision:') || id.startsWith('registry:') ? id.indexOf(':') : 0); return result.nodes.has(id.slice(0, at)) && result.nodes.has(id.slice(at + 1)); }));
});
+280 -4
View File
@@ -1,6 +1,10 @@
import assert from 'node:assert/strict';
import path from 'node:path';
import * as vscode from 'vscode';
import * as Y from 'yjs';
import { FileBridge } from '../../src/sync/fileBridge';
import { LiveSpace } from '../../src/sync/liveSpace';
import type { SyncAuth } from '../../src/sync/auth';
const EXTENSION_ID = 'root-at-skic.archify-vscode-ext';
@@ -61,9 +65,18 @@ export async function run(): Promise<void> {
assert.equal(vscode.window.activeTextEditor?.document.uri.toString() === uri.toString(), false, 'no text editor was opened for it');
});
await check('.archify files are YAML and Show Source opens the text beside the diagram', async () => {
await check('Show Source keeps the diagram in its one tab (the page switches to Source)', async () => {
const uri = workspaceFile('web-platform.archify');
await vscode.commands.executeCommand('archify.showSource');
await new Promise((resolve) => setTimeout(resolve, 1000));
assert.equal(vscode.window.visibleTextEditors.some((e) => e.document.uri.toString() === uri.toString()), false, 'no text editor was opened');
const tabs = vscode.window.tabGroups.all.flatMap((g) => g.tabs).filter((t) => t.input instanceof vscode.TabInputCustom && t.input.uri.toString() === uri.toString());
assert.equal(tabs.length, 1);
});
await check('.archify files are YAML and Open in Text Editor opens the text beside the diagram', async () => {
const uri = workspaceFile('web-platform.archify');
await vscode.commands.executeCommand('archify.openInTextEditor');
const editor = await waitFor('source text editor', () =>
vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === uri.toString()),
);
@@ -317,18 +330,78 @@ export async function run(): Promise<void> {
assert.ok(tab);
});
await check('a .archify-registry file opens as the registry view and Show Source opens the YAML', async () => {
await check('Archify | Open Model Graph switches the main.archify editor to the Graph page and back', async () => {
const main = workspaceFile('model/main.archify');
const diagram = workspaceFile('model/0100-context/online-shop.archify');
const commands = vscode.extensions.getExtension(EXTENSION_ID)?.packageJSON.contributes.commands as { command: string; title: string }[];
assert.equal(commands.find((item) => item.command === 'archify.openModelGraph')?.title, 'Archify | Open Model Graph');
await vscode.commands.executeCommand('archify.openModelGraph', diagram);
const tab = await waitFor('model editor active', () =>
vscode.window.tabGroups.all.flatMap((g) => g.tabs).find((t) => t.isActive && t.input instanceof vscode.TabInputCustom && t.input.uri.toString() === main.toString()),
);
assert.ok(tab);
// The choice is remembered per file in the workspace state until the page is switched back.
const ext = vscode.extensions.getExtension(EXTENSION_ID);
assert.ok(ext?.isActive);
await new Promise((resolve) => setTimeout(resolve, 500));
});
await check('a .archify-registry file opens as the registry view and Open in Text Editor opens the YAML', async () => {
const registry = workspaceFile('model/registry/people.archify-registry');
await vscode.commands.executeCommand('vscode.open', registry);
const tab = await waitFor('registry view tab', () =>
vscode.window.tabGroups.all.flatMap((g) => g.tabs).find((t) => t.isActive && t.input instanceof vscode.TabInputCustom && t.input.viewType === 'archify.registry' && t.input.uri.toString() === registry.toString()),
);
assert.ok(tab);
await vscode.commands.executeCommand('archify.showSource');
await vscode.commands.executeCommand('archify.openInTextEditor');
const editor = await waitFor('registry text editor', () => vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === registry.toString()));
assert.equal(editor.document.languageId, 'yaml');
});
await check('a .archify-decision file opens as the decision view; an unknown decision id is a problem in a diagram', async () => {
const decision = workspaceFile('model/decisions/0002-queue-between-api-and-worker.archify-decision');
await vscode.commands.executeCommand('vscode.open', decision);
const tab = await waitFor('decision view tab', () =>
vscode.window.tabGroups.all.flatMap((g) => g.tabs).find((t) => t.isActive && t.input instanceof vscode.TabInputCustom && t.input.viewType === 'archify.decision' && t.input.uri.toString() === decision.toString()),
);
assert.ok(tab);
// A diagram that points at a decision nobody defines.
const bad = workspaceFile('model/0300-components/bad-decision.archify');
await vscode.workspace.fs.writeFile(bad, Buffer.from('schema_version: 1\ndiagram_type: architecture\nmeta:\n title: Bad\n output: bad.html\ndecisions: [nobody-decided]\ncomponents:\n - ref: api\n pos: [40, 60]\n size: [130, 60]\n decisions: [queue-between-api-and-worker]\n', 'utf8'));
const doc = await vscode.workspace.openTextDocument(bad);
await vscode.window.showTextDocument(doc);
const problem = await waitFor('unknown decision problem', () =>
vscode.languages.getDiagnostics(doc.uri).find((d) => d.source === 'archify' && /Unknown decision "nobody-decided"/.test(d.message)),
);
assert.equal(problem.range.start.line, 5);
assert.ok(!vscode.languages.getDiagnostics(doc.uri).some((d) => /queue-between-api-and-worker/.test(d.message)), 'the known decision is not reported');
await vscode.workspace.fs.delete(bad);
});
await check('Archify | New Registry… creates a registry file and opens the registry view; creators are ordered', async () => {
const commands = vscode.extensions.getExtension(EXTENSION_ID)?.packageJSON.contributes as { commands: { command: string }[]; menus: Record<string, { command: string; group: string }[]> };
const creators = commands.menus['explorer/context'].filter((m) => /^archify\.new/.test(m.command));
assert.deepEqual(creators.map((m) => m.command), ['archify.newModel', 'archify.newRegistry', 'archify.newDiagram', 'archify.newDecision']);
assert.deepEqual(creators.map((m) => m.group), ['zzz_archify@1', 'zzz_archify@2', 'zzz_archify@3', 'zzz_archify@4']);
const folder = workspaceFile('model/registry');
const window = vscode.window as unknown as Record<string, unknown>;
const originalInput = window.showInputBox;
window.showInputBox = async () => 'partners';
try {
await vscode.commands.executeCommand('archify.newRegistry', folder);
} finally {
window.showInputBox = originalInput;
}
const file = vscode.Uri.joinPath(folder, 'partners.archify-registry');
const text = new TextDecoder().decode(await vscode.workspace.fs.readFile(file));
assert.match(text, /^elements:/m);
const tab = await waitFor('registry view tab', () =>
vscode.window.tabGroups.all.flatMap((g) => g.tabs).find((t) => t.isActive && t.input instanceof vscode.TabInputCustom && t.input.viewType === 'archify.registry' && t.input.uri.toString() === file.toString()),
);
assert.ok(tab);
await vscode.workspace.fs.delete(file);
});
await check('Archify | New Diagram… → Model creates main.archify from the folder name', async () => {
const folder = workspaceFile('new-shop');
await vscode.workspace.fs.createDirectory(folder);
@@ -385,7 +458,7 @@ export async function run(): Promise<void> {
assert.match(content, /name: Shop two/);
assert.match(content, /title: Shop two — overview/);
const names = (await vscode.workspace.fs.readDirectory(folder)).map(([name]) => name).sort();
assert.deepEqual(names, ['0100-context', '0200-containers', '0300-components', 'main.archify', 'registry']);
assert.deepEqual(names, ['0100-context', '0200-containers', '0300-components', 'decisions', 'main.archify', 'registry']);
const registry = (await vscode.workspace.fs.readDirectory(vscode.Uri.joinPath(folder, 'registry'))).map(([name]) => name).sort();
assert.deepEqual(registry, ['containers.archify-registry', 'people.archify-registry', 'systems.archify-registry']);
const tab = await waitFor('model page tab', () =>
@@ -399,4 +472,207 @@ export async function run(): Promise<void> {
const errors = vscode.languages.getDiagnostics(containers.uri).filter((d) => d.severity === vscode.DiagnosticSeverity.Error);
assert.deepEqual(errors.map((d) => d.message), []);
});
await check('a registry is checked against its schema without a YAML extension', async () => {
const target = workspaceFile('model/registry/typo.archify-registry');
await vscode.workspace.fs.writeFile(target, new TextEncoder().encode('schema_version: 1\nelements:\n billing:\n typ: backend\n label: Billing\n'));
const doc = await vscode.workspace.openTextDocument(target);
await vscode.window.showTextDocument(doc);
const unknown = await waitFor('unknown key diagnostic', () =>
vscode.languages.getDiagnostics(doc.uri).find((d) => d.source === 'archify' && /Unknown key "typ" in elements\.billing/.test(d.message)),
);
assert.equal(doc.getText(unknown.range), 'typ');
assert.ok(vscode.languages.getDiagnostics(doc.uri).some((d) => /"type" is required in elements\.billing/.test(d.message)));
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
await vscode.workspace.fs.delete(target);
});
await check('without a shared model, sync stays unloaded and its commands are there', async () => {
const commands = await vscode.commands.getCommands(true);
for (const id of ['archify.sync.signIn', 'archify.sync.share', 'archify.sync.join', 'archify.sync.menu', 'archify.sync.setServer']) assert.ok(commands.includes(id), `${id} is registered`);
// No server of anyone's built in: empty until the user sets one.
const config = vscode.workspace.getConfiguration('archify.sync');
assert.equal(config.get('server'), '');
// The extension host's module cache: dist/sync.js (Yjs, the WebSocket) is not loaded.
const loaded = Object.keys(require.cache).filter((file) => file.endsWith(`${path.sep}dist${path.sep}sync.js`));
assert.deepEqual(loaded, [], 'the sync bundle is not loaded');
});
await check('sync file bridge: local edits reach the document, teammates\' edits reach files and editors', async () => {
const root = workspaceFile('shared');
const file = (rel: string) => vscode.Uri.joinPath(root, ...rel.split('/'));
const write = (rel: string, text: string) => vscode.workspace.fs.writeFile(file(rel), new TextEncoder().encode(text));
const read = async (rel: string) => new TextDecoder().decode(await vscode.workspace.fs.readFile(file(rel)));
const exists = (rel: string) => Promise.resolve(vscode.workspace.fs.stat(file(rel))).then(() => true, () => false);
await write('main.archify', 'model:\n id: shared\n');
await write('0100-context/a.archify', 'schema_version: 1\r\nmeta:\r\n title: A\r\n');
await write('notes.txt', 'not a model file');
const doc = new Y.Doc();
const teammate = new Y.Doc();
// The server in between: every update reaches the other side.
doc.on('update', (u: Uint8Array, origin: unknown) => origin !== 'remote' && Y.applyUpdate(teammate, u, 'remote'));
teammate.on('update', (u: Uint8Array, origin: unknown) => origin !== 'remote' && Y.applyUpdate(doc, u, 'remote'));
const quiet = { info() {}, warn() {}, error() {}, debug() {}, trace() {} } as unknown as vscode.LogOutputChannel;
const bridge = new FileBridge(root, doc, { origin: 'local' }, quiet);
const theirs = () => teammate.getMap<Y.Text>('files');
try {
await bridge.pushAll(false);
bridge.start(true);
assert.deepEqual([...theirs().keys()].sort(), ['0100-context/a.archify', 'main.archify'], 'only model files are shared');
assert.equal(theirs().get('0100-context/a.archify')!.toString(), 'schema_version: 1\nmeta:\n title: A\n', 'line endings travel as \\n');
// A local edit in an open editor.
const main = await vscode.workspace.openTextDocument(file('main.archify'));
const edit = new vscode.WorkspaceEdit();
edit.insert(main.uri, new vscode.Position(2, 0), ' name: Shared\n');
assert.ok(await vscode.workspace.applyEdit(edit));
await waitFor('local edit at the teammate', () => theirs().get('main.archify')!.toString() === 'model:\n id: shared\n name: Shared\n');
await main.save();
// The teammate types twice in a row into the open file: both land, nothing is undone by an echo.
theirs().get('main.archify')!.insert(0, '# one\n');
theirs().get('main.archify')!.insert(0, '# two\n');
await waitFor('teammate edits in the open editor', () => main.getText() === '# two\n# one\nmodel:\n id: shared\n name: Shared\n');
await waitFor('saved, so git sees it', () => !main.isDirty);
await new Promise((r) => setTimeout(r, 500));
assert.equal(theirs().get('main.archify')!.toString(), main.getText(), 'no echo changed it back');
// The teammate edits a closed file, keeping its CRLF on disk.
const a = theirs().get('0100-context/a.archify')!;
a.insert(a.length, ' output: a.html\n');
const deadline = Date.now() + 10_000;
while ((await read('0100-context/a.archify')) !== 'schema_version: 1\r\nmeta:\r\n title: A\r\n output: a.html\r\n' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 200));
assert.equal(await read('0100-context/a.archify'), 'schema_version: 1\r\nmeta:\r\n title: A\r\n output: a.html\r\n');
// A new file and a deletion from the teammate.
teammate.transact(() => {
const t = new Y.Text();
t.insert(0, 'schema_version: 1\n');
theirs().set('registry/people.archify-registry', t);
theirs().set('../escape.archify', new Y.Text('nope'));
});
const until = async (what: string, probe: () => Promise<boolean>) => {
const end = Date.now() + 10_000;
while (!(await probe())) {
if (Date.now() > end) throw new Error(`Timed out waiting for ${what}`);
await new Promise((r) => setTimeout(r, 200));
}
};
await until('new file on disk', () => exists('registry/people.archify-registry'));
assert.ok(!(await exists('../escape.archify')), 'a path outside the model is never written');
teammate.transact(() => theirs().delete('0100-context/a.archify'));
await until('deleted file gone', async () => !(await exists('0100-context/a.archify')));
// A change on disk by another tool (git, an agent) to a closed file.
await write('registry/people.archify-registry', 'schema_version: 1\nelements: {}\n');
await waitFor('disk change at the teammate', () => theirs().get('registry/people.archify-registry')?.toString() === 'schema_version: 1\nelements: {}\n');
} finally {
bridge.dispose();
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
await vscode.workspace.fs.delete(root, { recursive: true });
}
});
// Opt-in: a running Archify Sync server, a space on it and an access token.
const syncServer = process.env.ARCHIFY_SYNC_TEST_URL;
if (syncServer) await check('two shared copies of a model stay the same through the sync server', async () => {
const space = process.env.ARCHIFY_SYNC_TEST_SPACE!;
const token = process.env.ARCHIFY_SYNC_TEST_TOKEN!;
const storage = workspaceFile('.sync-storage');
const auth = {
session: async () => ({ account: { id: 'it', display_name: 'Integration' } }),
accessToken: async () => token,
} as unknown as SyncAuth;
const quiet = { info() {}, warn() {}, error() {}, debug() {}, trace() {} } as unknown as vscode.LogOutputChannel;
const services = (dir: string) => ({ context: { globalStorageUri: vscode.Uri.joinPath(storage, dir) } as vscode.ExtensionContext, auth, log: quiet, onChange() {} });
const link = { server: syncServer, space, name: 'IT' };
const mine = workspaceFile('live-mine');
const theirs = workspaceFile('live-theirs');
const read = async (root: vscode.Uri, rel: string) => {
try {
return new TextDecoder().decode(await vscode.workspace.fs.readFile(vscode.Uri.joinPath(root, ...rel.split('/'))));
} catch {
return undefined;
}
};
const until = async (what: string, probe: () => Promise<boolean>) => {
const end = Date.now() + 15_000;
while (!(await probe())) {
if (Date.now() > end) throw new Error(`Timed out waiting for ${what}`);
await new Promise((r) => setTimeout(r, 200));
}
};
await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(mine, 'main.archify'), new TextEncoder().encode('model:\n id: it\n'));
await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(mine, 'registry', 'people.archify-registry'), new TextEncoder().encode('schema_version: 1\n'));
await vscode.workspace.fs.createDirectory(theirs);
const a = new LiveSpace(mine, link, 'share', services('a'));
let b: LiveSpace | undefined;
try {
await a.start();
await until('shared copy online', async () => a.state === 'online');
b = new LiveSpace(theirs, link, 'join', services('b'));
await b.start();
await until('joined copy gets the files', async () => (await read(theirs, 'main.archify')) === 'model:\n id: it\n' && (await read(theirs, 'registry/people.archify-registry')) === 'schema_version: 1\n');
// Typing in one copy's editor shows up in the other copy's file.
const doc = await vscode.workspace.openTextDocument(vscode.Uri.joinPath(mine, 'main.archify'));
const edit = new vscode.WorkspaceEdit();
edit.insert(doc.uri, new vscode.Position(2, 0), ' name: Live 🚀\n');
assert.ok(await vscode.workspace.applyEdit(edit));
await until('edit arrives in the other copy', async () => (await read(theirs, 'main.archify')) === 'model:\n id: it\n name: Live 🚀\n');
// A file written by another tool in the other copy comes back.
await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(theirs, '0100-context', 'c.archify'), new TextEncoder().encode('schema_version: 1\n'));
await until('new file arrives back', async () => (await read(mine, '0100-context/c.archify')) === 'schema_version: 1\n');
await until('presence shows one person in both', async () => a.people().length === 1 && b!.people().length === 1);
// A cursor in one copy shows in the other, and stays on its word while text is typed above it.
const at = 'model:\n id: it\n name: '.length;
assert.ok(a.setCursor(vscode.Uri.joinPath(mine, 'main.archify'), { anchor: at, head: at + 4 }));
const theirsMain = vscode.Uri.joinPath(theirs, 'main.archify');
await until('cursor arrives in the other copy', async () => b!.cursors(theirsMain).length === 1);
const cursor = b.cursors(theirsMain)[0];
assert.deepEqual([cursor.name, cursor.anchor, cursor.head], ['Integration', at, at + 4]);
assert.equal(a.cursors(vscode.Uri.joinPath(mine, 'main.archify')).length, 0, 'your own cursor is not drawn for you');
const above = new vscode.WorkspaceEdit();
above.insert(theirsMain, new vscode.Position(0, 0), '# top\n');
assert.ok(await vscode.workspace.applyEdit(above));
await until('cursor moves with the text', async () => b!.cursors(theirsMain)[0]?.anchor === at + '# top\n'.length);
a.setCursor(vscode.Uri.joinPath(mine, 'main.archify'), undefined);
await until('cursor goes away', async () => b!.cursors(theirsMain).length === 0);
} finally {
a.dispose();
b?.dispose();
await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor');
for (const uri of [mine, theirs, storage]) await vscode.workspace.fs.delete(uri, { recursive: true }).then(undefined, () => undefined);
}
});
await check('registry and decision pages own their document: edits make it dirty and VS Code undo reverts them', async () => {
for (const [file, viewType] of [
['model/registry/containers.archify-registry', 'archify.registry'],
['model/decisions/0001-postgres-as-source-of-truth.archify-decision', 'archify.decision'],
] as const) {
const uri = workspaceFile(file);
await vscode.commands.executeCommand('vscode.openWith', uri, viewType);
await waitFor(`${viewType} tab`, () =>
vscode.window.tabGroups.activeTabGroup.activeTab?.input instanceof vscode.TabInputCustom &&
(vscode.window.tabGroups.activeTabGroup.activeTab.input as vscode.TabInputCustom).uri.toString() === uri.toString(),
);
const doc = await vscode.workspace.openTextDocument(uri);
const before = doc.getText();
// What the Source view does with a keystroke: a WorkspaceEdit on the document.
const edit = new vscode.WorkspaceEdit();
edit.insert(uri, new vscode.Position(0, 0), '# edited in Source\n');
assert.ok(await vscode.workspace.applyEdit(edit));
assert.ok(doc.isDirty, `${file} is dirty`);
const tab = vscode.window.tabGroups.activeTabGroup.activeTab;
assert.ok(tab?.isDirty, 'the page tab shows the dirty dot');
// ⌘Z in the page reaches VS Code as the undo command.
await vscode.commands.executeCommand('undo');
await waitFor('undo', () => doc.getText() === before);
await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor');
}
});
}
+12 -17
View File
@@ -3,8 +3,6 @@ import fs from 'node:fs';
import path from 'node:path';
import { test } from 'node:test';
import {
cardsFromElements,
dotForType,
groupOf,
hasDiagramBody,
isMainFile,
@@ -83,22 +81,12 @@ test('resolve: refs become full components, links and usage are collected', () =
assert.deepEqual([...r.used].sort(), ['api', 'cache', 'customer', 'db', 'queue', 'web', 'worker']);
assert.equal(r.refs.get(2)?.id, 'api');
assert.ok(!('model' in r.diagram));
// Cards from the registry descriptions, in drawing order, one per element.
const cards = r.diagram.cards as { dot: string; title: string; items: string[] }[];
assert.equal(cards.length, 7);
assert.deepEqual(cards[0], { dot: 'slate', title: 'Customer', items: ['Buys products; signs in with email or a social account.'] });
assert.equal(cards.find((c) => c.title === 'API')?.dot, 'emerald');
});
test('resolve: own cards win, no cards without refs or descriptions', () => {
const registry = registryOfModel();
// Descriptions travel with the node ids, for the Elements panel; nothing is added to the diagram itself.
assert.ok(!('cards' in r.diagram));
assert.equal(r.descriptions.get('customer'), 'Buys products; signs in with email or a social account.');
assert.equal(r.descriptions.size, 7);
const own = resolveRefs({ components: [{ ref: 'api', pos: [0, 0] }], cards: [{ dot: 'rose', title: 'Mine', items: ['kept'] }] }, { registry, fileName: 'x.archify' });
assert.deepEqual(own.diagram.cards, [{ dot: 'rose', title: 'Mine', items: ['kept'] }]);
const inline = resolveRefs({ components: [{ id: 'a', type: 'backend', label: 'A', pos: [0, 0] }] }, { registry, fileName: 'x.archify' });
assert.ok(!('cards' in inline.diagram));
assert.equal(cardsFromElements([{ id: 'x', type: 'cloud', label: 'X', file: 'r', line: 0 }]).length, 0);
assert.equal(dotForType('messagebus'), 'orange');
assert.equal(dotForType(undefined), 'slate');
assert.deepEqual(own.diagram.cards, [{ dot: 'rose', title: 'Mine', items: ['kept'] }], 'hand-written cards pass through');
});
test('resolve: overrides, second id for the same element, inline elements and links', () => {
@@ -153,3 +141,10 @@ test('summaries and groups: root first, then folders', () => {
assert.deepEqual(groups.map((g) => g.group), ['', '0100-context', '0300-components']);
assert.deepEqual(groups[0].diagrams.map((d) => d.relativePath), ['broken.archify', 'checkout.archify']);
});
test('a registry YAML error is reported at its line, not the first', () => {
const { problems } = parseRegistry('schema_version: 1\nelements:\n api:\n type: backend\n sub\n label: API\n', 'r.archify-registry');
const yaml = problems.find((p) => /not valid YAML/.test(p.message));
assert.ok(yaml, 'a YAML problem');
assert.ok((yaml.line ?? 0) >= 3, `reported on line ${(yaml.line ?? 0) + 1}`);
});
+27 -1
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { prepareDiagramHtml } from '../src/webview/page';
import { decisionPage, messagePage, prepareDiagramHtml, registryPage } from '../src/webview/page';
const page = `<!DOCTYPE html><html><head>
<meta http-equiv="Content-Security-Policy" content="default-src *">
@@ -61,3 +61,29 @@ test('saved view state is merged, not replaced, when the hash changes', () => {
const html = prepareDiagramHtml(page, { cspSource: 'x', nonce: 'n', theme: 'dark', state: { uri: 'file:///a.archify' } });
assert.match(html, /vscode\.setState\(Object\.assign\(\{\}, vscode\.getState\(\) \|\| \{\}, config\.state, \{ hash: location\.hash \}\)\)/);
});
test('a page with Source carries its script and the name of its own view', () => {
const html = prepareDiagramHtml(page, {
cspSource: 'x',
nonce: 'n',
theme: 'dark',
graphSwitch: { left: 'Diagram', query: 'diagram:a.archify' },
source: { scriptUri: 'https://file+.vscode-resource/ext/dist/source.js', left: 'Diagram' },
});
assert.match(html, /"source":\{"scriptUri":"https:\/\/file\+\.vscode-resource\/ext\/dist\/source\.js","left":"Diagram"\}/);
// Loaded on first use, not with the page.
assert.ok(!/<script[^>]+source\.js/.test(html));
assert.match(html, /post\(\{ type: 'sourceReady' \}\)/);
});
test('registry, decision and message pages offer View | Source when given the script', () => {
const source = { scriptUri: 'https://x/dist/source.js', left: 'View' as const };
const registry = registryPage({ cspSource: 'x', nonce: 'n', source }, { file: 'r.archify-registry', inModel: false, problems: [], elements: [] } as never);
const decision = decisionPage({ cspSource: 'x', nonce: 'n', source }, { file: 'd.archify-decision', inModel: false, problems: [], supersededBy: [] } as never);
const message = messagePage({ cspSource: 'x', nonce: 'n', source: { ...source, left: 'Diagram' } }, 'Archify could not render this diagram', 'Fix it');
for (const html of [registry, decision, message]) {
assert.match(html, /"source":\{"scriptUri":"https:\/\/x\/dist\/source\.js"/);
assert.match(html, /\.archify-mode-seg/, 'switch styles');
}
assert.ok(!messagePage({ cspSource: 'x', nonce: 'n' }, 'Rendering…', '').includes('"source"'), 'no Source without the option');
});
+77
View File
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test } from 'node:test';
import { DIAGRAM_SCHEMA, REGISTRY_SCHEMA, SchemaChecker, readSchemas, readablePointer } from '../src/language/schemaCheck';
const root = path.resolve(__dirname, '..', '..');
const checker = new SchemaChecker(readSchemas(path.join(root, 'schemas')));
function walk(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full, out);
else if (/\.archify(-registry)?$/.test(entry.name)) out.push(full);
}
return out;
}
const schemaFor = (file: string) => (file.endsWith('-registry') ? REGISTRY_SCHEMA : DIAGRAM_SCHEMA);
test('every shipped .archify and registry file passes the schema check', () => {
const files = ['examples', 'templates', path.join('test', 'fixtures')].flatMap((dir) => walk(path.join(root, dir)));
assert.ok(files.length > 30, `found ${files.length} files`);
for (const file of files) {
const problems = checker.check(fs.readFileSync(file, 'utf8'), schemaFor(file));
assert.deepEqual(problems.map((p) => p.message), [], path.relative(root, file));
}
});
function problemsAfter(file: string, from: string, to: string) {
const original = fs.readFileSync(path.join(root, file), 'utf8');
assert.ok(original.includes(from), `${file} contains ${from}`);
const text = original.replace(from, to);
return checker.check(text, schemaFor(file)).map((p) => ({ ...p, text: text.slice(p.from, p.to) }));
}
const DIAGRAM = 'templates/models/c4-standard-web-app/0200-containers/web-app.archify';
const REGISTRY = 'templates/models/c4-standard-web-app/registry/containers.archify-registry';
test('an unknown key is placed on the key', () => {
const [problem, ...rest] = problemsAfter(DIAGRAM, 'label: SQL', 'lable: SQL');
assert.equal(rest.length, 0);
assert.equal(problem.text, 'lable');
assert.match(problem.message, /^Unknown key "lable" in connections\[\d+\]\.$/);
});
test('a point with one number is placed on the whole flow list', () => {
const problems = problemsAfter(DIAGRAM, 'pos: [690, 160]', 'pos: [690]');
assert.equal(problems.length, 1);
assert.equal(problems[0].text, '[690]');
assert.match(problems[0].message, /pos needs at least 2 items\.$/);
});
test('registry: a misspelt type key, a bad type, a bad id', () => {
const typo = problemsAfter(REGISTRY, ' type: database', ' typ: database');
assert.deepEqual(typo.map((p) => p.text).sort(), ['db', 'typ']);
assert.ok(typo.some((p) => p.text === 'typ' && /Unknown key "typ"/.test(p.message)));
assert.ok(typo.some((p) => p.text === 'db' && /"type" is required in elements\.db/.test(p.message)));
const bad = problemsAfter(REGISTRY, ' type: cloud', ' type: bucket');
assert.equal(bad.length, 1);
assert.equal(bad[0].text, 'bucket');
assert.match(bad[0].message, /must be one of: frontend, backend, database, cloud, security, messagebus, external\.$/);
});
test('a YAML syntax error is reported once, as YAML', () => {
const problems = problemsAfter(REGISTRY, 'label: API', 'label: [API');
assert.equal(problems.length, 1);
assert.equal(problems[0].kind, 'yaml');
assert.match(problems[0].message, /^YAML: /);
});
test('pointers read like paths', () => {
assert.equal(readablePointer('/connections/4/label'), 'connections[4].label');
assert.equal(readablePointer('/elements/db'), 'elements.db');
assert.equal(readablePointer(''), 'the file');
});
+101
View File
@@ -0,0 +1,101 @@
import assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { test } from 'node:test';
import * as Y from 'yjs';
import { checkServerUrl, parseInviteLink, syncSocketUrl } from '../src/sync/api';
import { OfflineStore } from '../src/sync/offlineStore';
import { formatLink, parseLink } from '../src/sync/protocol';
import { applyToYText, safeChange } from '../src/sync/textSync';
import { applyChanges } from '../src/util/textDiff';
test('safeChange never splits a surrogate pair', () => {
const cases: [string, string][] = [
['x😀y', 'x😃y'],
['😀', '😃'],
['a😀', 'a😀b'],
['😀b', 'a😀b'],
['label: 🚀 API', 'label: 🛰 API'],
['plain', 'plainer'],
];
for (const [before, after] of cases) {
const change = safeChange(before, after)!;
assert.equal(applyChanges(before, [change]), after, `${before} → ${after}`);
for (const at of [change.from, change.to]) {
const code = before.charCodeAt(at);
assert.ok(!(code >= 0xdc00 && code <= 0xdfff), `change edge ${at} lands inside a pair in ${before}`);
}
}
assert.equal(safeChange('same', 'same'), undefined);
});
test('applyToYText reaches the text and syncs between copies', () => {
const a = new Y.Doc();
const b = new Y.Doc();
a.on('update', (u: Uint8Array) => Y.applyUpdate(b, u));
const text = a.getMap<Y.Text>('files');
const t = new Y.Text();
text.set('main.archify', t);
applyToYText(t, 'model:\n id: shop\n');
applyToYText(t, '# 😀\nmodel:\n id: shop\n');
applyToYText(t, '# 😃\nmodel:\n id: shop2\n');
assert.equal(b.getMap<Y.Text>('files').get('main.archify')!.toString(), '# 😃\nmodel:\n id: shop2\n');
assert.equal(applyToYText(t, '# 😃\nmodel:\n id: shop2\n'), false);
});
test('the offline copy keeps every update and survives a torn write', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sync-'));
try {
const doc = new Y.Doc();
const store = new OfflineStore(dir, 'space');
assert.equal(store.exists(), false);
doc.on('update', (u: Uint8Array) => store.append(u));
doc.getText('t').insert(0, 'one ');
doc.getText('t').insert(4, 'two');
assert.equal(store.pending, 2);
// A crash in the middle of the next append.
fs.appendFileSync(path.join(dir, 'space.log'), Buffer.from([200, 0, 0, 0, 1, 2]));
const again = new Y.Doc();
for (const u of new OfflineStore(dir, 'space').load()) Y.applyUpdate(again, u);
assert.equal(again.getText('t').toString(), 'one two');
store.compact(Y.encodeStateAsUpdate(doc));
assert.equal(store.pending, 0);
const compacted = new Y.Doc();
for (const u of new OfflineStore(dir, 'space').load()) Y.applyUpdate(compacted, u);
assert.equal(compacted.getText('t').toString(), 'one two');
store.remove();
assert.equal(store.exists(), false);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('server addresses: https, or http only on this machine', () => {
assert.equal(checkServerUrl('https://archify.example.com/').url, 'https://archify.example.com');
assert.equal(checkServerUrl('http://localhost:8080').url, 'http://localhost:8080');
assert.equal(checkServerUrl('http://127.0.0.1:8080/sync/').url, 'http://127.0.0.1:8080/sync');
assert.ok(checkServerUrl('http://archify.example.com').problem);
assert.ok(checkServerUrl('ftp://x').problem);
assert.ok(checkServerUrl('nonsense').problem);
assert.equal(syncSocketUrl('https://a.example', 'id'), 'wss://a.example/v1/spaces/id/sync?v=1');
});
test('invite links in both forms', () => {
const token = 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-abcde';
assert.deepEqual(parseInviteLink(`https://sync.example/join/${token}`), { server: 'https://sync.example', invite: token });
assert.deepEqual(parseInviteLink(`https://example.com/archify/join/${token}`), { server: 'https://example.com/archify', invite: token });
const ext = `vscode://root-at-skic.archify-vscode-ext/join?server=${encodeURIComponent('https://sync.example/')}&invite=${token}`;
assert.deepEqual(parseInviteLink(ext), { server: 'https://sync.example', invite: token });
assert.equal(parseInviteLink('https://example.com/other'), undefined);
assert.equal(parseInviteLink('not a link'), undefined);
});
test('link files round-trip and refuse junk', () => {
const link = { server: 'https://sync.example', space: '0198f3a2-1b2c-7d3e-8f40-123456789abc', name: 'Shop' };
assert.deepEqual(parseLink(formatLink(link)), link);
assert.equal(parseLink('{"server":"https://x","space":"../../etc"}'), undefined);
assert.equal(parseLink('not json'), undefined);
});
+41
View File
@@ -0,0 +1,41 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { applyChanges, minimalChange, normalizeEol, offsetOf, positionOf } from '../src/util/textDiff';
test('minimalChange keeps the common start and end', () => {
assert.equal(minimalChange('abc', 'abc'), undefined);
assert.deepEqual(minimalChange('label: SQL', 'lable: SQL'), { from: 3, to: 5, insert: 'le' });
assert.deepEqual(minimalChange('a\nb\n', 'a\nx\nb\n'), { from: 2, to: 2, insert: 'x\n' });
assert.deepEqual(minimalChange('aaa', 'aa'), { from: 2, to: 3, insert: '' });
assert.deepEqual(minimalChange('', 'new'), { from: 0, to: 0, insert: 'new' });
});
test('minimalChange round-trips through applyChanges', () => {
const pairs = [['schema_version: 1\nmeta:\n title: A\n', 'schema_version: 1\nmeta:\n title: B\n output: b.html\n'], ['x', ''], ['', 'y'], ['abab', 'ab']];
for (const [before, after] of pairs) {
const change = minimalChange(before, after)!;
assert.equal(applyChanges(before, [change]), after);
}
});
test('applyChanges takes several changes in the coordinates of the original text', () => {
assert.equal(applyChanges('one two three', [{ from: 0, to: 3, insert: '1' }, { from: 8, to: 13, insert: '3' }]), '1 two 3');
});
test('positions and offsets in "\\n" text', () => {
const text = 'ab\ncde\n\nf';
assert.deepEqual(positionOf(text, 0), { line: 0, character: 0 });
assert.deepEqual(positionOf(text, 4), { line: 1, character: 1 });
assert.deepEqual(positionOf(text, 7), { line: 2, character: 0 });
assert.deepEqual(positionOf(text, 99), { line: 3, character: 1 });
for (let offset = 0; offset <= text.length; offset++) {
const { line, character } = positionOf(text, offset);
assert.equal(offsetOf(text, line, character), offset);
}
assert.equal(offsetOf(text, 0, 50), 2, 'clamped to the end of the line');
assert.equal(offsetOf(text, 9, 0), text.length);
});
test('normalizeEol', () => {
assert.equal(normalizeEol('a\r\nb\nc\r\n'), 'a\nb\nc\n');
});