Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ab4287f02 | ||
|
|
0745de822a | ||
|
|
f4df6a0834 | ||
|
|
4b36136432 | ||
|
|
7dde9ffffe | ||
|
|
f6f59fae67 | ||
|
|
0752128789 | ||
|
|
517697197e | ||
|
|
c71296b01a | ||
|
|
86a8adf03b | ||
|
|
6153c7f145 | ||
|
|
885977c4aa | ||
|
|
95c6e60199 | ||
|
|
b54304fef8 | ||
|
|
8407c9a956 | ||
|
|
c2d33780f9 | ||
|
|
90c7be06de | ||
|
|
7d2d55543e | ||
|
|
c262bb06a7 | ||
|
|
63f0633daa | ||
|
|
ef272e4d96 | ||
|
|
f6097b1d00 | ||
|
|
9ccd67b2dd | ||
|
|
d02c331155 | ||
|
|
c99f3e5fe8 | ||
|
|
a9021312b0 | ||
|
|
2726a66113 | ||
|
|
a5a9f92e75 | ||
|
|
268c75cfae | ||
|
|
27d4794ff8 | ||
|
|
5bcd34b839 | ||
|
|
69b87833b7 | ||
|
|
058c0d17a8 |
No files matched your search
@@ -1,5 +1,77 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 0.11.0 — 2026-11-08
|
||||||
|
|
||||||
|
- **arc42 and ArchiMate examples.** *Archify | New Model…* now offers nine examples, three per framework. **arc42** (Cinema Tickets, IoT Telemetry, Team Wiki): the overview is the business context with quality goals, constraints, quality scenarios, risks and a glossary as cards; then `0300-context`, `0500-building-blocks` (levels 1 and 2), `0600-runtime` (sequence diagrams), `0700-deployment`, and the decisions as section 9. **ArchiMate** (Insurance Claims, HR Onboarding, Logistics Tracking): the overview is a layered view of the business, application and technology layers; then `0100-business` (with the business process as a workflow), `0200-application` and `0300-technology`, one registry file per layer, each element's ArchiMate type under its name.
|
||||||
|
- **`ref:` in every diagram kind.** Workflow and dataflow nodes, sequence participants and lifecycle states can use registry elements, as architecture components do; the Source view's schema check accepts them too. Sequence participants take no `tag`.
|
||||||
|
|
||||||
|
## 0.10.10 — 2026-11-08
|
||||||
|
|
||||||
|
- README: the Buy me a coffee button at the top.
|
||||||
|
|
||||||
|
## 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
|
## 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.
|
- **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.
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
# Archify Diagram Viewer
|
# Archify Diagram Viewer
|
||||||
|
|
||||||
|
[](https://buymeacoffee.com/root.at.skic)
|
||||||
|
|
||||||
Create and view [Archify](https://github.com/tt-a1i/archify) diagrams inside VS Code. You write a diagram as a **`.archify` file in YAML**; clicking it opens the interactive diagram, and the diagram follows your edits as you type.
|
Create and view [Archify](https://github.com/tt-a1i/archify) diagrams inside VS Code. You write a diagram as a **`.archify` file in YAML**; clicking it opens the interactive diagram, and the diagram follows your edits as you type.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
This is an unofficial extension. It bundles the Archify renderer (MIT, © tt-a1i) and runs it on VS Code's own Node runtime, so nothing else needs to be installed.
|
This is an unofficial extension. It bundles the Archify renderer (MIT, © tt-a1i) and runs it on VS Code's own Node runtime, so nothing else needs to be installed.
|
||||||
|
|
||||||
Free and open source. If it saves you time, you can [buy me a coffee](https://buymeacoffee.com/root.at.skic) ☕
|
|
||||||
|
|
||||||
## Supported files
|
## Supported files
|
||||||
|
|
||||||
| File | Format | What the extension does |
|
| 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. |
|
| `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. |
|
| Rendered Archify `.html` | HTML | Read-only viewer instead of a browser. |
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ New diagrams should be `.archify` files; everything below describes them unless
|
|||||||
|
|
||||||
The fastest start: right-click a folder in the Explorer and choose **Archify | New Diagram…** (also in *File → New File…* and the Command Palette). Pick a kind of diagram (Architecture, Workflow, Sequence, Data Flow, Lifecycle or Everyday Plan), give it a name, and a small working `.archify` file is created and opened. Change its YAML to fit your case.
|
The fastest start: right-click a folder in the Explorer and choose **Archify | New Diagram…** (also in *File → New File…* and the Command Palette). Pick a kind of diagram (Architecture, Workflow, Sequence, Data Flow, Lifecycle or Everyday Plan), give it a name, and a small working `.archify` file is created and opened. Change its YAML to fit your case.
|
||||||
|
|
||||||
For a whole set of diagrams, choose **Archify | New Model…** instead and pick one of the examples (C4 - Standard Web App, C4 - E-Shop, C4 - Event-Based Integration). A model folder with context, container and component diagrams and a shared registry is created and its model page opens. See [Models](#models).
|
For a whole set of diagrams, choose **Archify | New Model…** instead and pick one of the examples: three in C4, three in arc42 and three in ArchiMate. A model folder with its diagrams, a shared registry and decisions is created and its model page opens. See [Models](#models).
|
||||||
|
|
||||||
To write one by hand:
|
To write one by hand:
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ To write one by hand:
|
|||||||
```
|
```
|
||||||
|
|
||||||
2. Click it in the Explorer: the diagram opens.
|
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).
|
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`.
|
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.
|
- **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.
|
`.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.
|
||||||
|
|
||||||
@@ -64,21 +64,21 @@ The Archify CLI and the AI agents that use it write diagrams as JSON, named `nam
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **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 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).
|
- **New model from an example**: *Archify | New Model…* creates a complete model folder from an example: C4, arc42 or ArchiMate, three of each.
|
||||||
- **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).
|
- **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. **Show Source** opens the YAML beside it, and edits re-render live.
|
- **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=…`).
|
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **Export**: the diagram's own Export menu (PNG, SVG, share card, …) saves through a VS Code save dialog.
|
||||||
- **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*.
|
- **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
|
## 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.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -124,16 +124,34 @@ online-shop/
|
|||||||
- **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.
|
- **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.
|
||||||
- **Descriptions.** Under a model diagram, hovering a row of the **Elements** panel shows the registry description of that element.
|
- **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.
|
- **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. **Show Source** opens the YAML beside it.
|
- **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.
|
- **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`.
|
- **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 with context, container and component diagrams. **arc42 - Cinema Tickets**, **arc42 - IoT Telemetry** and **arc42 - Team Wiki** follow arc42's sections: the overview is the business context with goals, constraints, quality scenarios, risks and a glossary as cards, then `0300-context`, `0500-building-blocks`, `0600-runtime` (sequence diagrams) and `0700-deployment`, with section 9 as decisions. **ArchiMate - Insurance Claims**, **ArchiMate - HR Onboarding** and **ArchiMate - Logistics Tracking** are layered: the overview is a layered view, then `0100-business`, `0200-application` and `0300-technology`, one registry file per layer, each element's ArchiMate type as its tag. Every example has a registry and decisions. For an empty model, *Archify | New Diagram… → Model* creates just a `main.archify`.
|
||||||
- **The graph.** The **Model | Graph** 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** and opens the graph already narrowed to that diagram. *Archify | Open Model Graph* does the same from the Command Palette or Explorer.
|
- **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.
|
- **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**.
|
- **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.
|
- **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).
|
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
|
## 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.
|
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.
|
||||||
@@ -156,7 +174,7 @@ When verification fails, the default (`archify.sourceEvidence: "fallback"`) stil
|
|||||||
|
|
||||||
## Security
|
## 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
|
## Development
|
||||||
|
|
||||||
|
|||||||
+29
@@ -18,6 +18,17 @@ const common = {
|
|||||||
mainFields: ['module', 'main'],
|
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) {
|
if (tests) {
|
||||||
// Unit tests cover the modules that do not import 'vscode'; the
|
// Unit tests cover the modules that do not import 'vscode'; the
|
||||||
// integration suite runs inside VS Code, which provides it.
|
// integration suite runs inside VS Code, which provides it.
|
||||||
@@ -40,6 +51,14 @@ if (tests) {
|
|||||||
outfile: 'dist/extension.js',
|
outfile: 'dist/extension.js',
|
||||||
external: ['vscode'],
|
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.
|
// Runs inside the Archify page in the webview; three.js is bundled in.
|
||||||
esbuild.context({
|
esbuild.context({
|
||||||
...common,
|
...common,
|
||||||
@@ -58,6 +77,16 @@ if (tests) {
|
|||||||
entryPoints: ['src/graph/index.ts'],
|
entryPoints: ['src/graph/index.ts'],
|
||||||
outfile: 'dist/graph.js',
|
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) {
|
if (watch) {
|
||||||
await Promise.all(contexts.map((ctx) => ctx.watch()));
|
await Promise.all(contexts.map((ctx) => ctx.watch()));
|
||||||
|
|||||||
Generated
+1082
-23
File diff suppressed because it is too large.
Load diff
+114
-8
@@ -2,7 +2,7 @@
|
|||||||
"name": "archify-vscode-ext",
|
"name": "archify-vscode-ext",
|
||||||
"displayName": "Archify Diagram Viewer",
|
"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.",
|
"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.9.0",
|
"version": "0.11.0",
|
||||||
"publisher": "root-at-skic",
|
"publisher": "root-at-skic",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"sponsor": {
|
"sponsor": {
|
||||||
@@ -45,7 +45,8 @@
|
|||||||
"workspaceContains:**/*.{archify,architecture.json,workflow.json,sequence.json,dataflow.json,lifecycle.json}",
|
"workspaceContains:**/*.{archify,architecture.json,workflow.json,sequence.json,dataflow.json,lifecycle.json}",
|
||||||
"onWebviewPanel:archify.preview",
|
"onWebviewPanel:archify.preview",
|
||||||
"workspaceContains:**/*.archify-registry",
|
"workspaceContains:**/*.archify-registry",
|
||||||
"workspaceContains:**/*.archify-decision"
|
"workspaceContains:**/*.archify-decision",
|
||||||
|
"onUri"
|
||||||
],
|
],
|
||||||
"contributes": {
|
"contributes": {
|
||||||
"commands": [
|
"commands": [
|
||||||
@@ -102,6 +103,11 @@
|
|||||||
{
|
{
|
||||||
"command": "archify.showSource",
|
"command": "archify.showSource",
|
||||||
"title": "Archify | Show Source",
|
"title": "Archify | Show Source",
|
||||||
|
"icon": "$(code)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "archify.openInTextEditor",
|
||||||
|
"title": "Archify | Open in Text Editor",
|
||||||
"icon": "$(go-to-file)"
|
"icon": "$(go-to-file)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -113,6 +119,56 @@
|
|||||||
"command": "archify.openModelGraph",
|
"command": "archify.openModelGraph",
|
||||||
"title": "Archify | Open Model Graph",
|
"title": "Archify | Open Model Graph",
|
||||||
"icon": "$(type-hierarchy)"
|
"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": {
|
"menus": {
|
||||||
@@ -145,6 +201,10 @@
|
|||||||
"command": "archify.showSource",
|
"command": "archify.showSource",
|
||||||
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
|
"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",
|
"command": "archify.openModel",
|
||||||
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
|
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
|
||||||
@@ -152,6 +212,22 @@
|
|||||||
{
|
{
|
||||||
"command": "archify.openModelGraph",
|
"command": "archify.openModelGraph",
|
||||||
"when": "archify.isDiagramSource || archifyPreviewFocus || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'"
|
"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": [
|
"editor/title": [
|
||||||
@@ -171,7 +247,7 @@
|
|||||||
"group": "navigation"
|
"group": "navigation"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"command": "archify.showSource",
|
"command": "archify.openInTextEditor",
|
||||||
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'",
|
"when": "archifyPreviewFocus || activeCustomEditorId == 'archify.htmlViewer' || activeCustomEditorId == 'archify.diagram' || activeCustomEditorId == 'archify.registry' || activeCustomEditorId == 'archify.decision'",
|
||||||
"group": "navigation"
|
"group": "navigation"
|
||||||
},
|
},
|
||||||
@@ -241,6 +317,11 @@
|
|||||||
"command": "archify.openModelGraph",
|
"command": "archify.openModelGraph",
|
||||||
"when": "resourceFilename =~ /\\.archify(-registry|-decision)?$/",
|
"when": "resourceFilename =~ /\\.archify(-registry|-decision)?$/",
|
||||||
"group": "zzz_archify@9"
|
"group": "zzz_archify@9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "archify.sync.share",
|
||||||
|
"when": "resourceFilename == main.archify",
|
||||||
|
"group": "archify@9"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"editor/title/context": [
|
"editor/title/context": [
|
||||||
@@ -433,6 +514,14 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "Node.js executable (18 or newer) used to run the renderer. Empty means the runtime bundled with VS Code."
|
"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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -454,10 +543,12 @@
|
|||||||
{
|
{
|
||||||
"fileMatch": "*.archify-registry",
|
"fileMatch": "*.archify-registry",
|
||||||
"url": "./schemas/archify-registry.schema.json"
|
"url": "./schemas/archify-registry.schema.json"
|
||||||
},
|
}
|
||||||
|
],
|
||||||
|
"authentication": [
|
||||||
{
|
{
|
||||||
"fileMatch": "*.archify-decision",
|
"id": "archify-sync",
|
||||||
"url": "./schemas/archify-decision.schema.json"
|
"label": "Archify Sync"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -477,9 +568,9 @@
|
|||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
"@types/three": "^0.186.0",
|
"@types/three": "^0.186.0",
|
||||||
"@types/vscode": "~1.100.0",
|
"@types/vscode": "~1.100.0",
|
||||||
|
"@types/ws": "^8.18.2",
|
||||||
"@vscode/test-electron": "^3.1.0",
|
"@vscode/test-electron": "^3.1.0",
|
||||||
"@vscode/vsce": "^3.0.0",
|
"@vscode/vsce": "^3.0.0",
|
||||||
"ajv": "^8.20.0",
|
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"jsonc-parser": "^3.3.1",
|
"jsonc-parser": "^3.3.1",
|
||||||
"typescript": "^5.8.0"
|
"typescript": "^5.8.0"
|
||||||
@@ -489,9 +580,24 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext#readme",
|
"homepage": "https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext#readme",
|
||||||
"dependencies": {
|
"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": "^3.34.4",
|
||||||
"cytoscape-fcose": "^2.2.0",
|
"cytoscape-fcose": "^2.2.0",
|
||||||
|
"lib0": "^0.2.119",
|
||||||
"three": "^0.186.1",
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,7 +214,7 @@
|
|||||||
"ref": {
|
"ref": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$",
|
"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."
|
"description": "A shared element from the model’s registry (*.archify-registry). Its type, label, sublabel, brand and sources come from there; the diagram adds its own placement and may override label, sublabel and tag."
|
||||||
},
|
},
|
||||||
"diagram": {
|
"diagram": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
|
|||||||
@@ -129,13 +129,6 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"required": [
|
|
||||||
"id",
|
|
||||||
"type",
|
|
||||||
"label",
|
|
||||||
"stage",
|
|
||||||
"row"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
"$ref": "common.schema.json#/$defs/id"
|
"$ref": "common.schema.json#/$defs/id"
|
||||||
@@ -188,8 +181,35 @@
|
|||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
||||||
|
},
|
||||||
|
"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 its own placement and may override label, sublabel and tag."
|
||||||
|
},
|
||||||
|
"diagram": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"ref",
|
||||||
|
"stage",
|
||||||
|
"row"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"type",
|
||||||
|
"label",
|
||||||
|
"stage",
|
||||||
|
"row"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"flows": {
|
"flows": {
|
||||||
|
|||||||
@@ -145,13 +145,6 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"required": [
|
|
||||||
"id",
|
|
||||||
"type",
|
|
||||||
"label",
|
|
||||||
"lane",
|
|
||||||
"col"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
"$ref": "common.schema.json#/$defs/id"
|
"$ref": "common.schema.json#/$defs/id"
|
||||||
@@ -216,8 +209,35 @@
|
|||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
||||||
|
},
|
||||||
|
"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 its own placement and may override label, sublabel and tag."
|
||||||
|
},
|
||||||
|
"diagram": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"ref",
|
||||||
|
"lane",
|
||||||
|
"col"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"type",
|
||||||
|
"label",
|
||||||
|
"lane",
|
||||||
|
"col"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"transitions": {
|
"transitions": {
|
||||||
|
|||||||
@@ -117,11 +117,6 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"required": [
|
|
||||||
"id",
|
|
||||||
"type",
|
|
||||||
"label"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
"$ref": "common.schema.json#/$defs/id"
|
"$ref": "common.schema.json#/$defs/id"
|
||||||
@@ -152,8 +147,31 @@
|
|||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
||||||
|
},
|
||||||
|
"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 its own placement and may override label, sublabel and tag."
|
||||||
|
},
|
||||||
|
"diagram": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"ref"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"type",
|
||||||
|
"label"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"segments": {
|
"segments": {
|
||||||
|
|||||||
@@ -280,13 +280,6 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
"required": [
|
|
||||||
"id",
|
|
||||||
"lane",
|
|
||||||
"col",
|
|
||||||
"type",
|
|
||||||
"label"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": {
|
"id": {
|
||||||
"$ref": "common.schema.json#/$defs/id"
|
"$ref": "common.schema.json#/$defs/id"
|
||||||
@@ -339,8 +332,35 @@
|
|||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
"description": "Ids of architecture decisions (*.archify-decision files of the model) this is about. Shown in the Decisions panel under the diagram."
|
||||||
|
},
|
||||||
|
"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 its own placement and may override label, sublabel and tag."
|
||||||
|
},
|
||||||
|
"diagram": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Diagram that explains this element, relative to the model root (main.archify). Double-click the node to open it."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"ref",
|
||||||
|
"lane",
|
||||||
|
"col"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"lane",
|
||||||
|
"col",
|
||||||
|
"type",
|
||||||
|
"label"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"edges": {
|
"edges": {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// Adds the model keys to the editor schemas in schemas/ (the CLI keeps the
|
// Adds the model keys to the editor schemas in schemas/ (the CLI keeps the
|
||||||
// strict originals): `model` on main.archify, `ref` and `diagram` on
|
// strict originals): `model` on main.archify, `ref` and `diagram` on each
|
||||||
// architecture components, and a schema for *.archify-registry files.
|
// kind's nodes, and a schema for *.archify-registry files.
|
||||||
// Run after sync-archify.mjs, or on its own after editing this file.
|
// Run after sync-archify.mjs, or on its own after editing this file.
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
@@ -28,6 +28,7 @@ const DIAGRAM_LINK = { type: 'string', description: 'Diagram that explains this
|
|||||||
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 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 NODE_COLLECTIONS = ['components', 'nodes', 'participants', 'states'];
|
||||||
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'];
|
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'];
|
||||||
|
const NODE_COLLECTION_OF = { architecture: 'components', workflow: 'nodes', dataflow: 'nodes', sequence: 'participants', lifecycle: 'states' };
|
||||||
|
|
||||||
for (const file of fs.readdirSync(schemas)) {
|
for (const file of fs.readdirSync(schemas)) {
|
||||||
if (!/^(architecture|workflow|sequence|dataflow|lifecycle)\.schema\.json$/.test(file)) continue;
|
if (!/^(architecture|workflow|sequence|dataflow|lifecycle)\.schema\.json$/.test(file)) continue;
|
||||||
@@ -38,14 +39,21 @@ for (const file of fs.readdirSync(schemas)) {
|
|||||||
const items = schema.properties[key]?.items;
|
const items = schema.properties[key]?.items;
|
||||||
if (items?.properties) items.properties.decisions = DECISIONS;
|
if (items?.properties) items.properties.decisions = DECISIONS;
|
||||||
}
|
}
|
||||||
if (file === 'architecture.schema.json') {
|
// The list where each kind keeps its nodes takes `ref` (as the extension's resolver does).
|
||||||
const item = schema.properties.components.items;
|
const nodes = NODE_COLLECTION_OF[file.replace('.schema.json', '')];
|
||||||
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.' };
|
const item = schema.properties[nodes]?.items;
|
||||||
|
if (item?.properties) {
|
||||||
|
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 its own placement and may override label, sublabel and tag.' };
|
||||||
item.properties.diagram = DIAGRAM_LINK;
|
item.properties.diagram = DIAGRAM_LINK;
|
||||||
// A ref brings type and label with it; an inline component must state them.
|
// A ref brings type and label with it; an inline node must state them. Re-runs keep the original list.
|
||||||
item.anyOf = [{ required: ['ref'] }, { required: ['id', 'type', 'label'] }];
|
const required = item.required ?? item.anyOf?.[1]?.required;
|
||||||
|
if (required) {
|
||||||
|
// Placement (lane/col, stage/row) stays the diagram's own; only id, type and label may come from the ref.
|
||||||
|
const placement = required.filter((key) => !['id', 'type', 'label'].includes(key));
|
||||||
|
item.anyOf = [{ required: ['ref', ...placement] }, { required }];
|
||||||
delete item.required;
|
delete item.required;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
write(file, schema);
|
write(file, schema);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,17 @@ export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
|
|||||||
|
|
||||||
vscode.commands.registerCommand('archify.refreshPreview', () => ctx.views.activePreview?.update(true)),
|
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 () => {
|
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;
|
const preview = ctx.views.activePreview;
|
||||||
if (preview?.isEditor) {
|
if (preview?.isEditor) {
|
||||||
// The diagram is the editor; open the YAML text beside it.
|
// The diagram is the editor; open the YAML text beside it.
|
||||||
|
|||||||
+4
-2
@@ -15,6 +15,7 @@ import { DiagramViewManager } from './views/diagramView';
|
|||||||
import { RegistryViewProvider } from './views/registryView';
|
import { RegistryViewProvider } from './views/registryView';
|
||||||
import { DecisionViewProvider } from './views/decisionView';
|
import { DecisionViewProvider } from './views/decisionView';
|
||||||
import { DECISION_SELECTOR, DecisionLanguage } from './language/decisionLanguage';
|
import { DECISION_SELECTOR, DecisionLanguage } from './language/decisionLanguage';
|
||||||
|
import { registerSync } from './sync/loader';
|
||||||
|
|
||||||
export function activate(context: vscode.ExtensionContext): void {
|
export function activate(context: vscode.ExtensionContext): void {
|
||||||
const models = new ModelService();
|
const models = new ModelService();
|
||||||
@@ -22,8 +23,8 @@ export function activate(context: vscode.ExtensionContext): void {
|
|||||||
extension: context,
|
extension: context,
|
||||||
views: new DiagramViewManager(context, models),
|
views: new DiagramViewManager(context, models),
|
||||||
htmlViewer: new HtmlViewerProvider(context.extensionUri),
|
htmlViewer: new HtmlViewerProvider(context.extensionUri),
|
||||||
registry: new RegistryViewProvider(models),
|
registry: new RegistryViewProvider(context, models),
|
||||||
decision: new DecisionViewProvider(models),
|
decision: new DecisionViewProvider(context, models),
|
||||||
models,
|
models,
|
||||||
};
|
};
|
||||||
const refs = new RefLanguage(models);
|
const refs = new RefLanguage(models);
|
||||||
@@ -47,6 +48,7 @@ export function activate(context: vscode.ExtensionContext): void {
|
|||||||
...newDiagramCommands(ctx),
|
...newDiagramCommands(ctx),
|
||||||
...renderCommands(ctx),
|
...renderCommands(ctx),
|
||||||
...modelCommands(ctx),
|
...modelCommands(ctx),
|
||||||
|
...registerSync(context, models),
|
||||||
);
|
);
|
||||||
registerContextKeys(context, models);
|
registerContextKeys(context, models);
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-6
@@ -226,12 +226,27 @@ class GraphPage {
|
|||||||
this.nameEl.textContent = this.graph.meta.name || this.graph.meta.id || 'Untitled model';
|
this.nameEl.textContent = this.graph.meta.name || this.graph.meta.id || 'Untitled model';
|
||||||
titles.append(this.kickerEl, this.nameEl);
|
titles.append(this.kickerEl, this.nameEl);
|
||||||
const actions = el('div', 'ag-actions');
|
const actions = el('div', 'ag-actions');
|
||||||
const sw = el('button', 'ag-switch');
|
// Model | Graph | Source, as on the model page. Source goes back to the
|
||||||
sw.type = 'button';
|
// model page and opens it in Source (the page reads sourceView on load).
|
||||||
sw.title = 'Back to the model page';
|
const sw = el('div', 'ag-switch');
|
||||||
sw.setAttribute('aria-label', 'Graph view on; switch to the model page');
|
sw.setAttribute('role', 'group');
|
||||||
sw.append(el('span', 'ag-seg', 'Model'), el('span', 'ag-seg on', 'Graph'));
|
sw.setAttribute('aria-label', 'View');
|
||||||
sw.addEventListener('click', () => this.host.post({ type: 'showModel' }));
|
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');
|
const exportButton = el('button', 'ag-button ag-primary', 'Export PNG');
|
||||||
exportButton.type = 'button';
|
exportButton.type = 'button';
|
||||||
exportButton.title = 'Save the graph as it is on screen, as a PNG';
|
exportButton.title = 'Save the graph as it is on screen, as a PNG';
|
||||||
|
|||||||
+5
-4
@@ -20,13 +20,14 @@ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--ag-bg)
|
|||||||
.ag-actions { margin-left: auto; display: flex; align-items: center; gap: 0.5rem; }
|
.ag-actions { margin-left: auto; display: flex; align-items: center; gap: 0.5rem; }
|
||||||
.ag-bar .ag-button { min-height: 2rem; }
|
.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. */
|
/* 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; cursor: pointer; }
|
.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::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-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-switch:focus-visible { outline: 2px solid var(--ag-accent); outline-offset: -4px; }
|
.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 { display: inline-flex; align-items: center; height: 1.75rem; margin: 0.25rem 0; padding: 0 0.7rem; border-radius: 0.5rem; font-weight: 550; font-size: 0.8125rem; 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.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-switch:hover .ag-seg:not(.on) { color: var(--ag-fg); }
|
.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 { 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::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 { color: var(--ag-fg); }
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { isArchifyFile } from '../sources/detect';
|
|||||||
import { log } from '../util/log';
|
import { log } from '../util/log';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { diagnosticPointer, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from './jsonPointer';
|
import { diagnosticPointer, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from './jsonPointer';
|
||||||
|
import { DIAGRAM_SCHEMA, REGISTRY_SCHEMA, SchemaChecker, SchemaProblem, readSchemas } from './schemaCheck';
|
||||||
|
|
||||||
const JSON_LANGUAGES = new Set(['json', 'jsonc']);
|
const JSON_LANGUAGES = new Set(['json', 'jsonc']);
|
||||||
|
|
||||||
@@ -33,6 +34,7 @@ export class DiagnosticsController implements vscode.Disposable {
|
|||||||
private readonly timers = new Map<string, NodeJS.Timeout>();
|
private readonly timers = new Map<string, NodeJS.Timeout>();
|
||||||
private readonly sequence = new Map<string, number>();
|
private readonly sequence = new Map<string, number>();
|
||||||
private readonly disposables: vscode.Disposable[];
|
private readonly disposables: vscode.Disposable[];
|
||||||
|
private checker: SchemaChecker | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly context: vscode.ExtensionContext,
|
private readonly context: vscode.ExtensionContext,
|
||||||
@@ -54,6 +56,22 @@ export class DiagnosticsController implements vscode.Disposable {
|
|||||||
this.revalidateAll();
|
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 {
|
private enabled(uri: vscode.Uri): boolean {
|
||||||
return vscode.workspace.getConfiguration('archify', uri).get<boolean>('validation.enabled', true);
|
return vscode.workspace.getConfiguration('archify', uri).get<boolean>('validation.enabled', true);
|
||||||
}
|
}
|
||||||
@@ -136,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 {
|
try {
|
||||||
const runtime = await runtimeFor(this.context, doc.uri);
|
const runtime = await runtimeFor(this.context, doc.uri);
|
||||||
const result = await validate(runtime, source.type, source.json);
|
const result = await validate(runtime, source.type, source.json);
|
||||||
@@ -210,6 +239,10 @@ export class DiagnosticsController implements vscode.Disposable {
|
|||||||
const root = await this.models.rootOf(doc.uri);
|
const root = await this.models.rootOf(doc.uri);
|
||||||
const rel = root ? path.relative(root.fsPath, doc.uri.fsPath) : path.basename(doc.uri.fsPath);
|
const rel = root ? path.relative(root.fsPath, doc.uri.fsPath) : path.basename(doc.uri.fsPath);
|
||||||
const problems: ModelProblem[] = [...parseRegistry(text, rel).problems];
|
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) {
|
if (root) {
|
||||||
try {
|
try {
|
||||||
const index = await this.models.index(root);
|
const index = await this.models.index(root);
|
||||||
@@ -223,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 });
|
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;
|
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 {
|
dispose(): void {
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -4,7 +4,8 @@ import { modelIdFromName, titleFromName } from './templates';
|
|||||||
/**
|
/**
|
||||||
* Example models shipped with the extension (templates/models/<folder>).
|
* Example models shipped with the extension (templates/models/<folder>).
|
||||||
* "Archify | New Model…" offers them; each is a complete model folder:
|
* "Archify | New Model…" offers them; each is a complete model folder:
|
||||||
* main.archify, registry/*.archify-registry and diagrams by level.
|
* main.archify, registry/*.archify-registry, decisions and diagrams in the
|
||||||
|
* framework's folders: C4 levels, arc42 sections or ArchiMate layers.
|
||||||
*/
|
*/
|
||||||
export interface ModelExample {
|
export interface ModelExample {
|
||||||
/** Folder under templates/models and the default name of the new model folder. */
|
/** Folder under templates/models and the default name of the new model folder. */
|
||||||
@@ -17,8 +18,17 @@ export const MODEL_EXAMPLES: readonly ModelExample[] = [
|
|||||||
{ folder: 'c4-standard-web-app', label: 'C4 - Standard Web App', description: 'Single-page app, API, database, cache, file storage, identity provider' },
|
{ folder: 'c4-standard-web-app', label: 'C4 - Standard Web App', description: 'Single-page app, API, database, cache, file storage, identity provider' },
|
||||||
{ folder: 'c4-e-shop', label: 'C4 - E-Shop', description: 'Web shop, API, worker, queue, payment and email providers' },
|
{ folder: 'c4-e-shop', label: 'C4 - E-Shop', description: 'Web shop, API, worker, queue, payment and email providers' },
|
||||||
{ folder: 'c4-event-based-integration', label: 'C4 - Event-Based Integration', description: 'Event bus, router, dead-letter queue, event store, consumers' },
|
{ folder: 'c4-event-based-integration', label: 'C4 - Event-Based Integration', description: 'Event bus, router, dead-letter queue, event store, consumers' },
|
||||||
|
{ folder: 'arc42-cinema-tickets', label: 'arc42 - Cinema Tickets', description: 'Context, building blocks, runtime and deployment views; seat booking with payment' },
|
||||||
|
{ folder: 'arc42-iot-telemetry', label: 'arc42 - IoT Telemetry', description: 'Devices over MQTT, ingest, time-series store, alerting, dashboards' },
|
||||||
|
{ folder: 'arc42-team-wiki', label: 'arc42 - Team Wiki', description: 'A small self-hosted wiki: the arc42 sections at their smallest' },
|
||||||
|
{ folder: 'archimate-insurance-claims', label: 'ArchiMate - Insurance Claims', description: 'Business, application and technology layers of claim handling' },
|
||||||
|
{ folder: 'archimate-hr-onboarding', label: 'ArchiMate - HR Onboarding', description: 'Onboarding a new employee across HR, identity and IT services' },
|
||||||
|
{ folder: 'archimate-logistics-tracking', label: 'ArchiMate - Logistics Tracking', description: 'Shipment tracking from pick-up to proof of delivery, layer by layer' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** The framework prefix of an example folder; the model id is the folder without it. */
|
||||||
|
export const EXAMPLE_PREFIX = /^(c4|arc42|archimate)-/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The example's main.archify for a new model folder. When the folder keeps
|
* The example's main.archify for a new model folder. When the folder keeps
|
||||||
* the example's name the file is used as written; otherwise id, name and the
|
* the example's name the file is used as written; otherwise id, name and the
|
||||||
|
|||||||
@@ -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)];
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { isMap, isScalar, isSeq, parseDocument } from 'yaml';
|
import { LineCounter, isMap, isScalar, isSeq, parseDocument } from 'yaml';
|
||||||
import { ModelProblem, Registry } from './format';
|
import { ModelProblem, Registry } from './format';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,9 +46,11 @@ export function slugify(title: string): string {
|
|||||||
/** Parses one decision file. Problems carry 0-based lines. */
|
/** Parses one decision file. Problems carry 0-based lines. */
|
||||||
export function parseDecision(text: string, file: string): { decision?: Decision; problems: ModelProblem[] } {
|
export function parseDecision(text: string, file: string): { decision?: Decision; problems: ModelProblem[] } {
|
||||||
const problems: ModelProblem[] = [];
|
const problems: ModelProblem[] = [];
|
||||||
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) {
|
for (const error of doc.errors) {
|
||||||
problems.push({ message: `Decision 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: `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 };
|
if (doc.errors.length) return { problems };
|
||||||
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
|
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
|
||||||
|
|||||||
+28
-14
@@ -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`
|
* The model file formats (see docs/model.md): `main.archify` with a `model`
|
||||||
@@ -83,9 +83,11 @@ export function hasDiagramBody(doc: unknown): boolean {
|
|||||||
export function parseRegistry(text: string, file: string): { elements: RegistryElement[]; problems: ModelProblem[] } {
|
export function parseRegistry(text: string, file: string): { elements: RegistryElement[]; problems: ModelProblem[] } {
|
||||||
const problems: ModelProblem[] = [];
|
const problems: ModelProblem[] = [];
|
||||||
const elements: RegistryElement[] = [];
|
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) {
|
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 };
|
if (doc.errors.length) return { elements, problems };
|
||||||
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
|
const lineOf = (offset: number | undefined) => (offset === undefined ? 0 : text.slice(0, offset).split('\n').length - 1);
|
||||||
@@ -161,13 +163,21 @@ export interface DecisionRef {
|
|||||||
|
|
||||||
/** Collections whose items may carry `decisions` (and `diagram` links), per diagram kind. */
|
/** Collections whose items may carry `decisions` (and `diagram` links), per diagram kind. */
|
||||||
const NODE_COLLECTIONS = ['components', 'nodes', 'participants', 'states'] as const;
|
const NODE_COLLECTIONS = ['components', 'nodes', 'participants', 'states'] as const;
|
||||||
|
/** The list that holds a diagram kind's nodes, where `ref` is resolved. */
|
||||||
|
const NODE_COLLECTION_OF: Record<string, (typeof NODE_COLLECTIONS)[number]> = {
|
||||||
|
architecture: 'components',
|
||||||
|
workflow: 'nodes',
|
||||||
|
dataflow: 'nodes',
|
||||||
|
sequence: 'participants',
|
||||||
|
lifecycle: 'states',
|
||||||
|
};
|
||||||
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'] as const;
|
const EDGE_COLLECTIONS = ['connections', 'edges', 'flows', 'transitions', 'messages'] as const;
|
||||||
|
|
||||||
export interface ResolvedDiagram {
|
export interface ResolvedDiagram {
|
||||||
/** The diagram as Archify expects it: refs expanded, model block and links removed. */
|
/** The diagram as Archify expects it: refs expanded, model block and links removed. */
|
||||||
diagram: Obj;
|
diagram: Obj;
|
||||||
problems: ModelProblem[];
|
problems: ModelProblem[];
|
||||||
/** Component index → the registry element it came from. */
|
/** Node index (in the kind's node list) → the registry element it came from. */
|
||||||
refs: Map<number, RegistryElement>;
|
refs: Map<number, RegistryElement>;
|
||||||
/** Node id → diagram path (relative to the model root) it links to. */
|
/** Node id → diagram path (relative to the model root) it links to. */
|
||||||
links: Map<string, string>;
|
links: Map<string, string>;
|
||||||
@@ -251,10 +261,14 @@ export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiag
|
|||||||
delete diagram.model;
|
delete diagram.model;
|
||||||
const decisionRefs = takeDecisionRefs(diagram, options, problems);
|
const decisionRefs = takeDecisionRefs(diagram, options, problems);
|
||||||
const { registry } = options;
|
const { registry } = options;
|
||||||
const components = Array.isArray(diagram.components) ? diagram.components : undefined;
|
// Each kind keeps its nodes in its own list; sequence participants have no tag.
|
||||||
if (!components) return { diagram, problems, refs, links, used, descriptions, decisionRefs };
|
const kind = str(diagram.diagram_type);
|
||||||
|
const collection = (kind && NODE_COLLECTION_OF[kind]) ?? NODE_COLLECTIONS.find((key) => Array.isArray(diagram[key]));
|
||||||
|
const nodes = collection && Array.isArray(diagram[collection]) ? (diagram[collection] as unknown[]) : undefined;
|
||||||
|
if (!collection || !nodes) return { diagram, problems, refs, links, used, descriptions, decisionRefs };
|
||||||
|
const copied: readonly string[] = kind === 'sequence' ? COPIED_FIELDS.filter((key) => key !== 'tag') : COPIED_FIELDS;
|
||||||
|
|
||||||
diagram.components = components.map((raw, index) => {
|
diagram[collection] = nodes.map((raw, index) => {
|
||||||
if (!isObj(raw)) return raw;
|
if (!isObj(raw)) return raw;
|
||||||
const ref = str(raw.ref);
|
const ref = str(raw.ref);
|
||||||
const linkFromComponent = str(raw.diagram);
|
const linkFromComponent = str(raw.diagram);
|
||||||
@@ -273,7 +287,7 @@ export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiag
|
|||||||
? `Unknown element "${ref}": no registry of this model defines it.`
|
? `Unknown element "${ref}": no registry of this model defines it.`
|
||||||
: `"${ref}" cannot be resolved: ${options.fileName.split(/[\\/]/).pop()} is not inside a model (no ${MAIN_FILE} above it).`,
|
: `"${ref}" cannot be resolved: ${options.fileName.split(/[\\/]/).pop()} is not inside a model (no ${MAIN_FILE} above it).`,
|
||||||
severity: 'error',
|
severity: 'error',
|
||||||
pointer: `/components/${index}/ref`,
|
pointer: `/${collection}/${index}/ref`,
|
||||||
});
|
});
|
||||||
return { type: 'external', label: ref, ...own, id };
|
return { type: 'external', label: ref, ...own, id };
|
||||||
}
|
}
|
||||||
@@ -281,19 +295,19 @@ export function resolveRefs(doc: unknown, options: ResolveOptions): ResolvedDiag
|
|||||||
refs.set(index, element);
|
refs.set(index, element);
|
||||||
if (element.description) descriptions.set(id, element.description.trim());
|
if (element.description) descriptions.set(id, element.description.trim());
|
||||||
for (const key of Object.keys(own)) {
|
for (const key of Object.keys(own)) {
|
||||||
if ((COPIED_FIELDS as readonly string[]).includes(key) && !(OVERRIDABLE_FIELDS as readonly string[]).includes(key)) {
|
if (copied.includes(key) && !(OVERRIDABLE_FIELDS as readonly string[]).includes(key)) {
|
||||||
problems.push({
|
problems.push({
|
||||||
message: `"${key}" comes from the registry element "${ref}" and cannot be changed in a diagram.`,
|
message: `"${key}" comes from the registry element "${ref}" and cannot be changed in a diagram.`,
|
||||||
severity: 'error',
|
severity: 'error',
|
||||||
pointer: `/components/${index}/${key}`,
|
pointer: `/${collection}/${index}/${key}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const merged: Obj = { id };
|
const merged: Obj = { id };
|
||||||
for (const key of COPIED_FIELDS) if (element[key] !== undefined) merged[key] = element[key];
|
for (const key of copied) if (element[key as (typeof COPIED_FIELDS)[number]] !== undefined) merged[key] = element[key as (typeof COPIED_FIELDS)[number]];
|
||||||
for (const [key, value] of Object.entries(own)) {
|
for (const [key, value] of Object.entries(own)) {
|
||||||
if (key === 'id') continue;
|
if (key === 'id') continue;
|
||||||
if (!(COPIED_FIELDS as readonly string[]).includes(key) || (OVERRIDABLE_FIELDS as readonly string[]).includes(key)) merged[key] = value;
|
if (!copied.includes(key) || (OVERRIDABLE_FIELDS as readonly string[]).includes(key)) merged[key] = value;
|
||||||
}
|
}
|
||||||
const link = linkFromComponent ?? element.diagram;
|
const link = linkFromComponent ?? element.diagram;
|
||||||
if (link) links.set(id, link);
|
if (link) links.set(id, link);
|
||||||
@@ -351,8 +365,8 @@ export function summarizeDiagram(text: string, relativePath: string): DiagramSum
|
|||||||
}
|
}
|
||||||
const obj = isObj(doc) ? doc : {};
|
const obj = isObj(doc) ? doc : {};
|
||||||
const meta = isObj(obj.meta) ? obj.meta : {};
|
const meta = isObj(obj.meta) ? obj.meta : {};
|
||||||
const components = Array.isArray(obj.components) ? obj.components : [];
|
const items = NODE_COLLECTIONS.flatMap((key) => (Array.isArray(obj[key]) ? (obj[key] as unknown[]) : []));
|
||||||
const used = [...new Set(components.map((c) => (isObj(c) ? str(c.ref) : undefined)).filter((r): r is string => !!r))];
|
const used = [...new Set(items.map((c) => (isObj(c) ? str(c.ref) : undefined)).filter((r): r is string => !!r))];
|
||||||
const decisions = takeDecisionRefs({ ...obj }, { registry: { elements: new Map(), files: [], problems: [] }, fileName: relativePath }, []);
|
const decisions = takeDecisionRefs({ ...obj }, { registry: { elements: new Map(), files: [], problems: [] }, fileName: relativePath }, []);
|
||||||
const nodes: DiagramNode[] = [];
|
const nodes: DiagramNode[] = [];
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
|
|||||||
+102
@@ -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`);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
@@ -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 };
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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) }),
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}`;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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)`);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
+11
-4
@@ -58,13 +58,20 @@ class Viewer3D {
|
|||||||
this.interceptViewerControls();
|
this.interceptViewerControls();
|
||||||
if (this.saved.active ?? host.defaultView === '3d') this.setActive(true);
|
if (this.saved.active ?? host.defaultView === '3d') this.setActive(true);
|
||||||
else this.syncButtons();
|
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
|
// -------------------------------------------------------------- chrome
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The 2D | 3D switch: Export's twin in the toolbar. Both states are always
|
* The 2D | 3D switch in the toolbar, left of Diagram | Graph | Source (it
|
||||||
* visible, the filled half is the current one, a click flips 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 {
|
private buildSwitch(): HTMLButtonElement {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
@@ -79,8 +86,8 @@ class Viewer3D {
|
|||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
this.setActive(!this.active);
|
this.setActive(!this.active);
|
||||||
});
|
});
|
||||||
const exportWrap = document.querySelector('.toolbar .export-wrap');
|
const anchor = document.querySelector('.toolbar #archify-mode-switch') ?? document.querySelector('.toolbar .export-wrap');
|
||||||
if (exportWrap?.parentElement) exportWrap.parentElement.insertBefore(button, exportWrap);
|
if (anchor?.parentElement) anchor.parentElement.insertBefore(button, anchor);
|
||||||
else document.querySelector('.toolbar')?.appendChild(button);
|
else document.querySelector('.toolbar')?.appendChild(button);
|
||||||
return button;
|
return button;
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-13
@@ -6,31 +6,41 @@ import { DecisionPanel, decisionPanelFromIndex, decisionPanelStandalone } from '
|
|||||||
import { ModelService } from '../model/service';
|
import { ModelService } from '../model/service';
|
||||||
import { readText } from '../util/files';
|
import { readText } from '../util/files';
|
||||||
import { log } from '../util/log';
|
import { log } from '../util/log';
|
||||||
|
import { sourceScriptUri } from '../webview/viewer3d';
|
||||||
|
import { SourceSession } from './sourceSession';
|
||||||
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
||||||
import { decisionPage, makeNonce } from '../webview/page';
|
import { decisionPage, makeNonce } from '../webview/page';
|
||||||
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
||||||
|
|
||||||
export { DECISION_VIEW_TYPE };
|
export { DECISION_VIEW_TYPE };
|
||||||
|
|
||||||
class DecisionDocument implements vscode.CustomDocument {
|
|
||||||
constructor(readonly uri: vscode.Uri) {}
|
|
||||||
dispose(): void {}
|
|
||||||
}
|
|
||||||
|
|
||||||
class DecisionView implements vscode.Disposable {
|
class DecisionView implements vscode.Disposable {
|
||||||
private seq = 0;
|
private seq = 0;
|
||||||
private timer: NodeJS.Timeout | undefined;
|
private timer: NodeJS.Timeout | undefined;
|
||||||
private last: string | undefined;
|
private last: string | undefined;
|
||||||
root: vscode.Uri | undefined;
|
root: vscode.Uri | undefined;
|
||||||
private readonly disposables: vscode.Disposable[] = [];
|
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(
|
constructor(
|
||||||
|
private readonly context: vscode.ExtensionContext,
|
||||||
private readonly models: ModelService,
|
private readonly models: ModelService,
|
||||||
readonly panel: vscode.WebviewPanel,
|
readonly panel: vscode.WebviewPanel,
|
||||||
readonly uri: vscode.Uri,
|
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.disposables.push(
|
||||||
|
this.source,
|
||||||
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
|
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 === '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 === 'openRegistry') return void this.openRegistryLine(message.file, message.line);
|
||||||
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
|
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
|
||||||
@@ -86,7 +96,12 @@ class DecisionView implements vscode.Disposable {
|
|||||||
const fingerprint = JSON.stringify(decision);
|
const fingerprint = JSON.stringify(decision);
|
||||||
if (fingerprint === this.last) return;
|
if (fingerprint === this.last) return;
|
||||||
this.last = fingerprint;
|
this.last = fingerprint;
|
||||||
this.panel.webview.html = decisionPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce() }, decision);
|
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 {
|
dispose(): void {
|
||||||
@@ -95,13 +110,16 @@ class DecisionView implements vscode.Disposable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Read-only custom editor for .archify-decision files: the decision as a page, with its elements and diagrams. */
|
/** Custom editor for .archify-decision files: the decision as a page, with its elements and diagrams. */
|
||||||
export class DecisionViewProvider implements vscode.CustomReadonlyEditorProvider<DecisionDocument>, vscode.Disposable {
|
export class DecisionViewProvider implements vscode.CustomTextEditorProvider, vscode.Disposable {
|
||||||
private readonly views = new Set<DecisionView>();
|
private readonly views = new Set<DecisionView>();
|
||||||
private active: DecisionView | undefined;
|
private active: DecisionView | undefined;
|
||||||
private readonly disposables: vscode.Disposable[];
|
private readonly disposables: vscode.Disposable[];
|
||||||
|
|
||||||
constructor(private readonly models: ModelService) {
|
constructor(
|
||||||
|
private readonly context: vscode.ExtensionContext,
|
||||||
|
private readonly models: ModelService,
|
||||||
|
) {
|
||||||
this.disposables = [
|
this.disposables = [
|
||||||
vscode.window.registerCustomEditorProvider(DECISION_VIEW_TYPE, this, {
|
vscode.window.registerCustomEditorProvider(DECISION_VIEW_TYPE, this, {
|
||||||
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
|
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
|
||||||
@@ -122,13 +140,16 @@ export class DecisionViewProvider implements vscode.CustomReadonlyEditorProvider
|
|||||||
return this.active?.uri;
|
return this.active?.uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
openCustomDocument(uri: vscode.Uri): DecisionDocument {
|
/** The view of the focused page, if any. */
|
||||||
return new DecisionDocument(uri);
|
get activeView(): { source: SourceSession } | undefined {
|
||||||
|
return this.active;
|
||||||
}
|
}
|
||||||
|
|
||||||
async resolveCustomEditor(document: DecisionDocument, 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 };
|
panel.webview.options = { enableScripts: true };
|
||||||
const view = new DecisionView(this.models, panel, document.uri);
|
const view = new DecisionView(this.context, this.models, panel, document.uri);
|
||||||
this.views.add(view);
|
this.views.add(view);
|
||||||
const onViewState = () => {
|
const onViewState = () => {
|
||||||
if (panel.active) this.active = view;
|
if (panel.active) this.active = view;
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ import { log } from '../util/log';
|
|||||||
import { viewerTheme } from '../util/settings';
|
import { viewerTheme } from '../util/settings';
|
||||||
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
||||||
import { graphPage, makeNonce, messagePage, modelPage, prepareDiagramHtml } from '../webview/page';
|
import { graphPage, makeNonce, messagePage, modelPage, prepareDiagramHtml } from '../webview/page';
|
||||||
import { graphScriptUri, viewer3dOption, viewerRoots } from '../webview/viewer3d';
|
import { graphScriptUri, sourceScriptUri, viewer3dOption, viewerRoots } from '../webview/viewer3d';
|
||||||
|
import { liveBridge } from '../sync/liveBridge';
|
||||||
|
import { SourceSession } from './sourceSession';
|
||||||
|
|
||||||
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, PREVIEW_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, PREVIEW_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
||||||
|
|
||||||
@@ -50,6 +52,12 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
private graphQuery: string | undefined;
|
private graphQuery: string | undefined;
|
||||||
/** True while the webview shows the Graph page, which takes model updates as messages. */
|
/** True while the webview shows the Graph page, which takes model updates as messages. */
|
||||||
private graphShown = false;
|
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(
|
constructor(
|
||||||
private readonly context: vscode.ExtensionContext,
|
private readonly context: vscode.ExtensionContext,
|
||||||
@@ -69,9 +77,23 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
panel.title = `Preview ${path.basename(uri.path)}`;
|
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(
|
this.disposables.push(
|
||||||
panel.onDidDispose(() => this.dispose()),
|
panel.onDidDispose(() => this.dispose()),
|
||||||
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
|
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
|
||||||
|
if (this.source?.handle(message)) return;
|
||||||
if (message.type === 'hash') {
|
if (message.type === 'hash') {
|
||||||
this.hash = message.hash;
|
this.hash = message.hash;
|
||||||
return;
|
return;
|
||||||
@@ -97,10 +119,25 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
this.setGraph(false);
|
this.setGraph(false);
|
||||||
return;
|
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);
|
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') {
|
if (uri.scheme === 'file') {
|
||||||
const watcher = vscode.workspace.createFileSystemWatcher(
|
const watcher = vscode.workspace.createFileSystemWatcher(
|
||||||
new vscode.RelativePattern(vscode.Uri.file(path.dirname(uri.fsPath)), path.basename(uri.fsPath)),
|
new vscode.RelativePattern(vscode.Uri.file(path.dirname(uri.fsPath)), path.basename(uri.fsPath)),
|
||||||
@@ -116,11 +153,35 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
void this.update();
|
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. */
|
/** Posts to the webview; a panel closed mid-update is not an error. */
|
||||||
private post(message: unknown): void {
|
private post(message: unknown): void {
|
||||||
Promise.resolve(this.panel.webview.postMessage(message)).catch(() => undefined);
|
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 {
|
private state(): PreviewState {
|
||||||
return { uri: this.uri.toString(), hash: this.hash, graph: this.graph };
|
return { uri: this.uri.toString(), hash: this.hash, graph: this.graph };
|
||||||
}
|
}
|
||||||
@@ -131,6 +192,10 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
|
|
||||||
/** Switches a main.archify editor between its model page and the Graph page. */
|
/** Switches a main.archify editor between its model page and the Graph page. */
|
||||||
setGraph(on: boolean, query?: string): void {
|
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.graph = on;
|
||||||
this.graphQuery = query;
|
this.graphQuery = query;
|
||||||
const modes = this.graphModes();
|
const modes = this.graphModes();
|
||||||
@@ -156,21 +221,21 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.graphShown = true;
|
this.graphShown = true;
|
||||||
this.panel.webview.html = graphPage(
|
this.setHtml(graphPage(
|
||||||
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() },
|
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() },
|
||||||
{ graph, query: this.graphQuery, scriptUri: graphScriptUri(this.panel.webview, this.context.extensionUri) },
|
{ graph, query: this.graphQuery, scriptUri: graphScriptUri(this.panel.webview, this.context.extensionUri) },
|
||||||
);
|
));
|
||||||
this.graphQuery = undefined;
|
this.graphQuery = undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
private showMessage(title: string, body: string, detail?: string): void {
|
private showMessage(title: string, body: string, detail?: string): void {
|
||||||
this.lastHtml = undefined;
|
this.lastHtml = undefined;
|
||||||
this.panel.webview.html = messagePage(
|
this.setHtml(messagePage(
|
||||||
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() },
|
{ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state(), source: this.sourceOption('Diagram') },
|
||||||
title,
|
title,
|
||||||
body,
|
body,
|
||||||
detail,
|
detail,
|
||||||
);
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opens a diagram of the model, given its path relative to the model root. */
|
/** Opens a diagram of the model, given its path relative to the model root. */
|
||||||
@@ -192,7 +257,7 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
this.lastHtml = fingerprint;
|
this.lastHtml = fingerprint;
|
||||||
this.rendered = false;
|
this.rendered = false;
|
||||||
this.graphShown = false;
|
this.graphShown = false;
|
||||||
this.panel.webview.html = modelPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state() }, model);
|
this.setHtml(modelPage({ cspSource: this.panel.webview.cspSource, nonce: makeNonce(), state: this.state(), source: this.sourceOption('Model') }, model));
|
||||||
}
|
}
|
||||||
|
|
||||||
scheduleUpdate(): void {
|
scheduleUpdate(): void {
|
||||||
@@ -203,6 +268,7 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
|
|
||||||
async update(force = false): Promise<void> {
|
async update(force = false): Promise<void> {
|
||||||
clearTimeout(this.timer);
|
clearTimeout(this.timer);
|
||||||
|
if (this.disposed) return;
|
||||||
const seq = ++this.seq;
|
const seq = ++this.seq;
|
||||||
let text: string;
|
let text: string;
|
||||||
try {
|
try {
|
||||||
@@ -285,6 +351,7 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
decisions: prepared.decisions,
|
decisions: prepared.decisions,
|
||||||
model,
|
model,
|
||||||
graphSwitch: main ? { left: 'Model' } : prepared.root ? { left: 'Diagram', query: `diagram:${path.relative(prepared.root.fsPath, this.uri.fsPath).split(path.sep).join('/')}` } : undefined,
|
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.
|
// Nonces differ per render, so compare the renderer output instead.
|
||||||
const fingerprint = `${viewerTheme()}\u0000${result.evidenceNotice ?? ''}\u0000${JSON.stringify([model ?? null, [...prepared.links], [...prepared.descriptions], prepared.decisions])}\u0000${result.html}`;
|
const fingerprint = `${viewerTheme()}\u0000${result.evidenceNotice ?? ''}\u0000${JSON.stringify([model ?? null, [...prepared.links], [...prepared.descriptions], prepared.decisions])}\u0000${result.html}`;
|
||||||
@@ -294,10 +361,14 @@ class DiagramPreview implements vscode.Disposable {
|
|||||||
}
|
}
|
||||||
this.lastHtml = fingerprint;
|
this.lastHtml = fingerprint;
|
||||||
this.rendered = true;
|
this.rendered = true;
|
||||||
this.panel.webview.html = html;
|
this.setHtml(html);
|
||||||
}
|
}
|
||||||
|
|
||||||
dispose(): void {
|
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);
|
clearTimeout(this.timer);
|
||||||
this.onDisposeEmitter.fire();
|
this.onDisposeEmitter.fire();
|
||||||
this.onDisposeEmitter.dispose();
|
this.onDisposeEmitter.dispose();
|
||||||
|
|||||||
+33
-12
@@ -5,31 +5,41 @@ import { RegistryPanel, registryPanelFromIndex, registryPanelStandalone } from '
|
|||||||
import { ModelService } from '../model/service';
|
import { ModelService } from '../model/service';
|
||||||
import { readText } from '../util/files';
|
import { readText } from '../util/files';
|
||||||
import { log } from '../util/log';
|
import { log } from '../util/log';
|
||||||
|
import { sourceScriptUri } from '../webview/viewer3d';
|
||||||
|
import { SourceSession } from './sourceSession';
|
||||||
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
|
||||||
import { makeNonce, registryPage } from '../webview/page';
|
import { makeNonce, registryPage } from '../webview/page';
|
||||||
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
import { DECISION_VIEW_TYPE, DIAGRAM_EDITOR_VIEW_TYPE, REGISTRY_VIEW_TYPE } from './viewTypes';
|
||||||
|
|
||||||
export { REGISTRY_VIEW_TYPE };
|
export { REGISTRY_VIEW_TYPE };
|
||||||
|
|
||||||
class RegistryDocument implements vscode.CustomDocument {
|
|
||||||
constructor(readonly uri: vscode.Uri) {}
|
|
||||||
dispose(): void {}
|
|
||||||
}
|
|
||||||
|
|
||||||
class RegistryView implements vscode.Disposable {
|
class RegistryView implements vscode.Disposable {
|
||||||
private seq = 0;
|
private seq = 0;
|
||||||
private timer: NodeJS.Timeout | undefined;
|
private timer: NodeJS.Timeout | undefined;
|
||||||
private last: string | undefined;
|
private last: string | undefined;
|
||||||
root: vscode.Uri | undefined;
|
root: vscode.Uri | undefined;
|
||||||
private readonly disposables: vscode.Disposable[] = [];
|
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(
|
constructor(
|
||||||
|
private readonly context: vscode.ExtensionContext,
|
||||||
private readonly models: ModelService,
|
private readonly models: ModelService,
|
||||||
readonly panel: vscode.WebviewPanel,
|
readonly panel: vscode.WebviewPanel,
|
||||||
readonly uri: vscode.Uri,
|
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.disposables.push(
|
||||||
|
this.source,
|
||||||
panel.webview.onDidReceiveMessage((message: WebviewMessage) => {
|
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 === '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 === 'openRegistry') return void this.openRegistryLine(message.file, message.line);
|
||||||
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
|
if (message.type === 'openDecision') return void this.openInModel(message.file, DECISION_VIEW_TYPE);
|
||||||
@@ -84,7 +94,12 @@ class RegistryView implements vscode.Disposable {
|
|||||||
const fingerprint = JSON.stringify(registry);
|
const fingerprint = JSON.stringify(registry);
|
||||||
if (fingerprint === this.last) return;
|
if (fingerprint === this.last) return;
|
||||||
this.last = fingerprint;
|
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 {
|
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 readonly views = new Set<RegistryView>();
|
||||||
private active: RegistryView | undefined;
|
private active: RegistryView | undefined;
|
||||||
private readonly disposables: vscode.Disposable[];
|
private readonly disposables: vscode.Disposable[];
|
||||||
|
|
||||||
constructor(private readonly models: ModelService) {
|
constructor(
|
||||||
|
private readonly context: vscode.ExtensionContext,
|
||||||
|
private readonly models: ModelService,
|
||||||
|
) {
|
||||||
this.disposables = [
|
this.disposables = [
|
||||||
vscode.window.registerCustomEditorProvider(REGISTRY_VIEW_TYPE, this, {
|
vscode.window.registerCustomEditorProvider(REGISTRY_VIEW_TYPE, this, {
|
||||||
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
|
webviewOptions: { retainContextWhenHidden: true, enableFindWidget: true },
|
||||||
@@ -121,13 +139,16 @@ export class RegistryViewProvider implements vscode.CustomReadonlyEditorProvider
|
|||||||
return this.active?.uri;
|
return this.active?.uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
openCustomDocument(uri: vscode.Uri): RegistryDocument {
|
/** The view of the focused page, if any. */
|
||||||
return new RegistryDocument(uri);
|
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 };
|
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);
|
this.views.add(view);
|
||||||
const onViewState = () => {
|
const onViewState = () => {
|
||||||
if (panel.active) this.active = view;
|
if (panel.active) this.active = view;
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import path from 'node:path';
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import { repoRootFor } from '../archify/runtime';
|
import { repoRootFor } from '../archify/runtime';
|
||||||
import { log } from '../util/log';
|
import { log } from '../util/log';
|
||||||
|
import type { LiveAction } from '../sync/liveBridge';
|
||||||
|
|
||||||
export type WebviewMessage =
|
export type WebviewMessage =
|
||||||
| { type: 'hash'; hash: string }
|
| { type: 'hash'; hash: string }
|
||||||
@@ -14,6 +15,10 @@ export type WebviewMessage =
|
|||||||
| { type: 'openDecision'; file: string }
|
| { type: 'openDecision'; file: string }
|
||||||
| { type: 'showGraph'; query?: string }
|
| { type: 'showGraph'; query?: string }
|
||||||
| { type: 'showModel' }
|
| { type: 'showModel' }
|
||||||
|
| { type: 'liveReady' }
|
||||||
|
| { type: 'liveAction'; action: LiveAction }
|
||||||
|
| { type: 'syncMenu' }
|
||||||
|
| { type: 'syncReady' }
|
||||||
| { type: 'error'; message: string };
|
| { type: 'error'; message: string };
|
||||||
|
|
||||||
/** Column for opening files next to a webview without covering it. */
|
/** Column for opening files next to a webview without covering it. */
|
||||||
@@ -63,6 +68,28 @@ async function openSource(
|
|||||||
vscode.window.showWarningMessage(`Archify: source file "${message.path}" was not found in the workspace.`);
|
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(
|
export async function handleWebviewMessage(
|
||||||
message: WebviewMessage,
|
message: WebviewMessage,
|
||||||
context: vscode.Uri,
|
context: vscode.Uri,
|
||||||
@@ -96,10 +123,20 @@ export async function handleWebviewMessage(
|
|||||||
case 'error':
|
case 'error':
|
||||||
vscode.window.showErrorMessage(`Archify: ${message.message}`);
|
vscode.window.showErrorMessage(`Archify: ${message.message}`);
|
||||||
break;
|
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 'hash':
|
||||||
case 'openDiagram':
|
case 'openDiagram':
|
||||||
case 'showGraph':
|
case 'showGraph':
|
||||||
case 'showModel':
|
case 'showModel':
|
||||||
|
case 'liveReady':
|
||||||
|
case 'liveAction':
|
||||||
// Handled by the view, which knows the model root.
|
// Handled by the view, which knows the model root.
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
+319
-34
@@ -28,6 +28,8 @@ export interface PageOptions {
|
|||||||
decisions?: DiagramDecision[];
|
decisions?: DiagramDecision[];
|
||||||
/** Pages inside a model get a switch to the model's Graph page; `left` names the page they are on. */
|
/** 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 };
|
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. */
|
/** 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 };
|
graph?: { graph: ModelGraph; query?: string; scriptUri: string };
|
||||||
}
|
}
|
||||||
@@ -93,6 +95,7 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
decisions: options.decisions || [],
|
decisions: options.decisions || [],
|
||||||
descriptions: options.descriptions || {},
|
descriptions: options.descriptions || {},
|
||||||
graphSwitch: options.graphSwitch,
|
graphSwitch: options.graphSwitch,
|
||||||
|
source: options.source,
|
||||||
graph: options.graph ? { graph: options.graph.graph, query: options.graph.query } : undefined,
|
graph: options.graph ? { graph: options.graph.graph, query: options.graph.query } : undefined,
|
||||||
};
|
};
|
||||||
return `(function () {
|
return `(function () {
|
||||||
@@ -205,6 +208,7 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
}, true);
|
}, true);
|
||||||
|
|
||||||
// Collapsible panels of the model page; open/closed is kept in the webview state.
|
// 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 panelStates() { return (vscode.getState() || {}).modelPanels || {}; }
|
||||||
function panel(key, className, title, count, defaultOpen) {
|
function panel(key, className, title, count, defaultOpen) {
|
||||||
// count: a number or a short text such as "3 files".
|
// count: a number or a short text such as "3 files".
|
||||||
@@ -615,8 +619,13 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(head, anchor); else document.body.appendChild(head);
|
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(head, anchor); else document.body.appendChild(head);
|
||||||
|
|
||||||
var body = el('section', 'archify-model archify-model-body');
|
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 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);
|
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.'));
|
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) {
|
model.groups.forEach(function (group) {
|
||||||
@@ -632,6 +641,7 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
var button = el('button', 'archify-model-open');
|
var button = el('button', 'archify-model-open');
|
||||||
button.type = 'button';
|
button.type = 'button';
|
||||||
button.title = diagram.path;
|
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-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.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 }); });
|
button.addEventListener('click', function () { post({ type: 'openDiagram', path: diagram.path }); });
|
||||||
@@ -649,7 +659,7 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
byFile[element.file].push(element);
|
byFile[element.file].push(element);
|
||||||
});
|
});
|
||||||
files.sort();
|
files.sort();
|
||||||
var registryPanel = panel('registry', 'archify-model-registry', 'Registries', files.length + (files.length === 1 ? ' file' : ' files'), true);
|
var registryPanel = panel('registry', 'archify-model-registry', 'Registries', files.length + (files.length === 1 ? ' file' : ' files'), false);
|
||||||
body.appendChild(registryPanel);
|
body.appendChild(registryPanel);
|
||||||
files.forEach(function (file) {
|
files.forEach(function (file) {
|
||||||
var elements = byFile[file].slice().sort(function (a, b) { return a.line - b.line; });
|
var elements = byFile[file].slice().sort(function (a, b) { return a.line - b.line; });
|
||||||
@@ -667,44 +677,205 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
}
|
}
|
||||||
// Decisions: one list, live ones first, superseded and rejected dimmed and last.
|
// Decisions: one list, live ones first, superseded and rejected dimmed and last.
|
||||||
if (model.decisions && model.decisions.length) {
|
if (model.decisions && model.decisions.length) {
|
||||||
var decisionsPanel = panel('decisions', 'archify-model-decisions', 'Decisions', model.decisions.length, true);
|
var decisionsPanel = panel('decisions', 'archify-model-decisions', 'Decisions', model.decisions.length, false);
|
||||||
body.appendChild(decisionsPanel);
|
body.appendChild(decisionsPanel);
|
||||||
var decisionList = el('ul', 'archify-model-list archify-decision-list');
|
var decisionList = el('ul', 'archify-model-list archify-decision-list');
|
||||||
model.decisions.forEach(function (row) { decisionList.appendChild(decisionRowItem(row)); });
|
model.decisions.forEach(function (row) { decisionList.appendChild(decisionRowItem(row)); });
|
||||||
decisionsPanel.appendChild(decisionList);
|
decisionsPanel.appendChild(decisionList);
|
||||||
}
|
}
|
||||||
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(body, anchor.nextSibling); else document.body.appendChild(body);
|
if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(body, anchor.nextSibling); else document.body.appendChild(body);
|
||||||
|
post({ type: 'liveReady' });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Model | Graph (or Diagram | Graph): Export's twin in Archify's toolbar,
|
var LIVE_STATE = {
|
||||||
// or at the top of the model page. Graph opens the model's Graph page.
|
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() {
|
function renderModeSwitch() {
|
||||||
var sw = config.graphSwitch;
|
var sw = config.graphSwitch;
|
||||||
if (!sw || document.getElementById('archify-mode-switch')) return;
|
var src = config.source;
|
||||||
var button = el('button', 'archify-mode-switch');
|
if ((!sw && !src) || document.getElementById('archify-mode-switch')) return;
|
||||||
button.id = 'archify-mode-switch';
|
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.type = 'button';
|
||||||
button.title = 'Open the model as one graph, with a query box';
|
button.title = title;
|
||||||
button.setAttribute('aria-label', sw.left + ' view; switch to the model graph');
|
button.addEventListener('click', function (event) { event.stopPropagation(); action(); });
|
||||||
button.appendChild(el('span', 'archify-mode-seg on', sw.left));
|
group.appendChild(button);
|
||||||
button.appendChild(el('span', 'archify-mode-seg', 'Graph'));
|
return button;
|
||||||
button.addEventListener('click', function (event) {
|
}
|
||||||
event.stopPropagation();
|
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 });
|
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 exportWrap = document.querySelector('.toolbar .export-wrap');
|
||||||
var head = document.querySelector('.archify-model-head');
|
var head = document.querySelector('.archify-model-head');
|
||||||
if (exportWrap && exportWrap.parentNode) exportWrap.parentNode.insertBefore(button, exportWrap);
|
if (exportWrap && exportWrap.parentNode) exportWrap.parentNode.insertBefore(group, exportWrap);
|
||||||
else if (head) {
|
else {
|
||||||
var row = el('div', 'archify-model-switch-row');
|
var row = el('div', 'archify-model-switch-row');
|
||||||
row.appendChild(button);
|
row.appendChild(group);
|
||||||
head.insertBefore(row, head.firstChild);
|
if (head) head.insertBefore(row, head.firstChild);
|
||||||
} else document.body.appendChild(button);
|
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) {
|
window.addEventListener('message', function (event) {
|
||||||
var message = event.data || {};
|
var message = event.data || {};
|
||||||
if (message.type === 'notice') showNotice(message.notice);
|
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) {
|
function onReady(fn) {
|
||||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
|
||||||
@@ -717,6 +888,83 @@ function bridgeScript(options: PageOptions): string {
|
|||||||
onReady(renderDecisionsRail);
|
onReady(renderDecisionsRail);
|
||||||
onReady(describeElements);
|
onReady(describeElements);
|
||||||
onReady(renderModeSwitch);
|
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 (config.notice) {
|
||||||
if (document.readyState === 'loading') {
|
if (document.readyState === 'loading') {
|
||||||
document.addEventListener('DOMContentLoaded', function () { showNotice(config.notice); });
|
document.addEventListener('DOMContentLoaded', function () { showNotice(config.notice); });
|
||||||
@@ -731,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));
|
.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); }
|
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; }
|
.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-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-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; }
|
.archify-model-description { margin: 0; max-width: 72ch; font-size: 0.9375rem; line-height: 1.55; color: var(--m-muted); white-space: pre-line; }
|
||||||
@@ -777,6 +1027,26 @@ 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-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-title { margin: 1.25rem 0 0.6rem; }
|
||||||
.archify-modal .archify-model-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
|
.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. */
|
/* Decisions: rows, chips and status badges. */
|
||||||
.archify-decision-list { grid-template-columns: 1fr; gap: 0.35rem; }
|
.archify-decision-list { grid-template-columns: 1fr; gap: 0.35rem; }
|
||||||
.archify-decision-open { padding: 0.55rem 0.85rem; }
|
.archify-decision-open { padding: 0.55rem 0.85rem; }
|
||||||
@@ -815,15 +1085,22 @@ const MODEL_STYLE = `
|
|||||||
|
|
||||||
/* The Model | Graph switch: in Archify's toolbar it is the 2D | 3D switch's twin; on the model page it sits top right. */
|
/* 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 = `
|
const SWITCH_STYLE = `
|
||||||
.archify-mode-switch { display: inline-flex; align-items: center; padding: 0 0.25rem; gap: 0; border: 0; background: transparent; color: var(--text-muted, var(--vscode-descriptionForeground)); font: inherit; cursor: pointer; position: relative; }
|
.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::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); }
|
.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); }
|
||||||
.archify-mode-seg { position: relative; display: inline-flex; align-items: center; height: 1.75rem; padding: 0 0.7rem; border-radius: 0.5rem; font-weight: 550; font-size: 0.8125rem; transition: background 0.15s, color 0.15s; }
|
/* Anchored on the id: Archify's .toolbar button rules (one of them with :not(#btn-theme)) would win otherwise. */
|
||||||
.archify-mode-seg.on { 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 { 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-mode-switch:hover .archify-mode-seg:not(.on) { color: var(--text, var(--vscode-foreground)); }
|
/* Archify's toolbar buttons are 2.75rem tall with a painted ::before; the segments are not, like 2D | 3D. */
|
||||||
.archify-mode-switch:focus-visible { outline: 2px solid var(--frontend-stroke, var(--vscode-focusBorder)); outline-offset: 2px; border-radius: 0.75rem; }
|
#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; }
|
.archify-model-switch-row { float: right; margin: 1.5rem 0 0 1rem; }
|
||||||
.archify-model-switch-row .archify-mode-switch { border: 1px solid var(--m-border); border-radius: 0.75rem; background: var(--m-panel); padding: 0.1rem 0.25rem; }
|
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. */
|
/* Connectors rail panel: highlight of the hovered or selected edge in the SVG. */
|
||||||
@@ -895,8 +1172,8 @@ export function prepareDiagramHtml(html: string, options: PageOptions): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The model page for a main.archify without a diagram of its own. */
|
/** 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 {
|
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' } });
|
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>
|
return `<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -935,8 +1212,8 @@ export function graphPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'st
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The registry page for one .archify-registry file. */
|
/** The registry page for one .archify-registry file. */
|
||||||
export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>, registry: RegistryPanel): string {
|
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: {} });
|
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, registry, links: {}, source: options.source });
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -947,6 +1224,8 @@ export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' |
|
|||||||
<style>
|
<style>
|
||||||
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
|
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
|
||||||
${MODEL_STYLE}
|
${MODEL_STYLE}
|
||||||
|
${SWITCH_STYLE}
|
||||||
|
${NOTICE_STYLE}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body></body>
|
<body></body>
|
||||||
@@ -954,8 +1233,8 @@ export function registryPage(options: Pick<PageOptions, 'cspSource' | 'nonce' |
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The decision page for one .archify-decision file. */
|
/** The decision page for one .archify-decision file. */
|
||||||
export function decisionPage(options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>, decision: DecisionPanel): string {
|
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: {} });
|
const bridge = bridgeScript({ cspSource: options.cspSource, nonce: options.nonce, theme: undefined, state: options.state, decision, links: {}, source: options.source });
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -966,28 +1245,34 @@ export function decisionPage(options: Pick<PageOptions, 'cspSource' | 'nonce' |
|
|||||||
<style>
|
<style>
|
||||||
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
|
body { margin: 0; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
|
||||||
${MODEL_STYLE}
|
${MODEL_STYLE}
|
||||||
|
${SWITCH_STYLE}
|
||||||
|
${NOTICE_STYLE}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body></body>
|
<body></body>
|
||||||
</html>`;
|
</html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A small VS Code-styled page for loading and error states. */
|
/** A small VS Code-styled page for loading and error states; with `source`, the YAML can be fixed in place. */
|
||||||
export function messagePage(
|
export function messagePage(
|
||||||
options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state'>,
|
options: Pick<PageOptions, 'cspSource' | 'nonce' | 'state' | 'source'>,
|
||||||
title: string,
|
title: string,
|
||||||
body: string,
|
body: string,
|
||||||
detail?: string,
|
detail?: string,
|
||||||
): 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>
|
return `<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<meta http-equiv="Content-Security-Policy" content="${escapeHtml(contentSecurityPolicy(options.cspSource, options.nonce))}">
|
<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}">${script}</script>
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); background: var(--vscode-editor-background); padding: 24px 28px; }
|
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; }
|
h2 { font-weight: 600; font-size: 15px; margin: 0 0 8px; }
|
||||||
p { margin: 0 0 12px; color: var(--vscode-descriptionForeground); }
|
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;
|
pre { font-family: var(--vscode-editor-font-family); font-size: 12px; white-space: pre-wrap; word-break: break-word;
|
||||||
|
|||||||
@@ -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';
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[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>`;
|
||||||
|
}
|
||||||
@@ -18,3 +18,8 @@ export function viewer3dOption(webview: vscode.Webview, extensionUri: vscode.Uri
|
|||||||
export function graphScriptUri(webview: vscode.Webview, extensionUri: vscode.Uri): string {
|
export function graphScriptUri(webview: vscode.Webview, extensionUri: vscode.Uri): string {
|
||||||
return webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'dist', 'graph.js')).toString();
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Technical context
|
||||||
|
output: technical-context.html
|
||||||
|
components:
|
||||||
|
- ref: customer
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: usher
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: tickets
|
||||||
|
pos: [290, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: psp
|
||||||
|
pos: [560, 60]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: mail
|
||||||
|
pos: [560, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: pos
|
||||||
|
pos: [560, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
connections:
|
||||||
|
- { from: customer, to: tickets, label: HTTPS JSON, variant: emphasis }
|
||||||
|
- { from: usher, to: tickets, label: HTTPS app }
|
||||||
|
- { from: tickets, to: psp, label: REST webhook, variant: security }
|
||||||
|
- { from: tickets, to: mail, label: SMTP TLS }
|
||||||
|
- { from: tickets, to: pos, label: REST VPN }
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Booking API - level 2
|
||||||
|
output: booking.html
|
||||||
|
decisions: [seat-holds-with-ttl]
|
||||||
|
components:
|
||||||
|
- ref: web
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: programme
|
||||||
|
type: backend
|
||||||
|
label: Programme
|
||||||
|
sublabel: shows, halls
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: seats
|
||||||
|
type: backend
|
||||||
|
label: Seat Holds
|
||||||
|
sublabel: lock, release
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: checkout
|
||||||
|
type: backend
|
||||||
|
label: Checkout
|
||||||
|
sublabel: orders, webhook
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: seatlock
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [seat-holds-with-ttl]
|
||||||
|
- ref: db
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: psp
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [150, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Booking API
|
||||||
|
wraps: [programme, seats, checkout]
|
||||||
|
connections:
|
||||||
|
- { from: web, to: programme, label: browse }
|
||||||
|
- { from: web, to: seats, label: hold, variant: emphasis }
|
||||||
|
- { from: web, to: checkout, label: pay }
|
||||||
|
- { from: programme, to: db, label: SQL }
|
||||||
|
- { from: seats, to: seatlock, label: SET NX, decisions: [seat-holds-with-ttl] }
|
||||||
|
- { from: checkout, to: psp, label: session, variant: security }
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Building blocks - level 1
|
||||||
|
output: level-1.html
|
||||||
|
decisions: [booking-owns-seat-inventory]
|
||||||
|
components:
|
||||||
|
- ref: web
|
||||||
|
pos: [40, 110]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mobile
|
||||||
|
pos: [40, 210]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: scanner
|
||||||
|
pos: [40, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: booking
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: seatlock
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db
|
||||||
|
pos: [460, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ticketing
|
||||||
|
pos: [250, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: possync
|
||||||
|
pos: [670, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: psp
|
||||||
|
pos: [900, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: pos
|
||||||
|
pos: [900, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: mail
|
||||||
|
pos: [900, 460]
|
||||||
|
size: [150, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Cinema Tickets
|
||||||
|
wraps: [web, mobile, scanner, booking, seatlock, db, ticketing, possync]
|
||||||
|
connections:
|
||||||
|
- { from: web, to: booking, label: JSON, variant: emphasis }
|
||||||
|
- { from: mobile, to: booking, label: JSON }
|
||||||
|
- { from: booking, to: seatlock, label: hold }
|
||||||
|
- { from: booking, to: db, label: SQL }
|
||||||
|
- { from: booking, to: psp, label: checkout, variant: security }
|
||||||
|
- { from: booking, to: ticketing, label: issue, labelAt: [315, 234] }
|
||||||
|
- { from: scanner, to: ticketing, label: check-in }
|
||||||
|
- { from: ticketing, to: db, label: SQL }
|
||||||
|
- { from: ticketing, to: mail, label: QR mail }
|
||||||
|
- { from: possync, to: db, label: SQL }
|
||||||
|
- { from: possync, to: pos, label: sales, decisions: [booking-owns-seat-inventory] }
|
||||||
|
cards:
|
||||||
|
- dot: amber
|
||||||
|
title: 8 Crosscutting concepts
|
||||||
|
items:
|
||||||
|
- "Times in UTC; shown in cinema local time"
|
||||||
|
- "Every write carries an idempotency key"
|
||||||
|
- "QR payload signed with an Ed25519 key"
|
||||||
|
- "Structured logs with order id as trace key"
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Runtime - book seats
|
||||||
|
output: book-seats.html
|
||||||
|
viewBox: [1060, 680]
|
||||||
|
column_fit: spread
|
||||||
|
decisions: [seat-holds-with-ttl]
|
||||||
|
participants:
|
||||||
|
- { ref: customer }
|
||||||
|
- { ref: web }
|
||||||
|
- { ref: booking }
|
||||||
|
- { ref: seatlock }
|
||||||
|
- { ref: psp }
|
||||||
|
- { ref: ticketing }
|
||||||
|
- { ref: mail }
|
||||||
|
messages:
|
||||||
|
- { from: customer, to: web, y: 170, label: pick seats, variant: emphasis }
|
||||||
|
- { from: web, to: booking, y: 214, label: POST /holds }
|
||||||
|
- { from: booking, to: seatlock, y: 258, label: SET NX TTL 8m, decisions: [seat-holds-with-ttl] }
|
||||||
|
- { from: seatlock, to: booking, y: 302, label: OK, variant: return }
|
||||||
|
- { from: booking, to: web, y: 346, label: hold id, variant: return }
|
||||||
|
- { from: web, to: psp, y: 390, label: hosted checkout, variant: security }
|
||||||
|
- { from: psp, to: booking, y: 434, label: webhook paid, variant: security }
|
||||||
|
- { from: booking, to: ticketing, y: 478, label: issue tickets }
|
||||||
|
- { from: ticketing, to: mail, y: 522, label: QR e-mail }
|
||||||
|
- { from: mail, to: customer, y: 566, label: tickets, variant: return }
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Runtime - check-in at the door
|
||||||
|
output: check-in.html
|
||||||
|
viewBox: [900, 480]
|
||||||
|
column_fit: spread
|
||||||
|
decisions: [signed-qr-codes]
|
||||||
|
participants:
|
||||||
|
- { ref: usher }
|
||||||
|
- { ref: scanner }
|
||||||
|
- { ref: ticketing }
|
||||||
|
- { ref: db }
|
||||||
|
messages:
|
||||||
|
- { from: usher, to: scanner, y: 180, label: scan QR, variant: emphasis, note: signature checked offline, decisions: [signed-qr-codes] }
|
||||||
|
- { from: scanner, to: ticketing, y: 230, label: POST /checkins }
|
||||||
|
- { from: ticketing, to: db, y: 280, label: first scan wins }
|
||||||
|
- { from: ticketing, to: scanner, y: 330, label: valid seat 7F, variant: return }
|
||||||
|
- { from: scanner, to: usher, y: 380, label: green light, variant: return }
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Deployment - production
|
||||||
|
output: production.html
|
||||||
|
components:
|
||||||
|
- ref: customer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: ingress
|
||||||
|
type: security
|
||||||
|
label: Ingress
|
||||||
|
sublabel: TLS, WAF
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: web
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: booking
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ticketing
|
||||||
|
pos: [460, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: possync
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: seatlock
|
||||||
|
pos: [710, 110]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db
|
||||||
|
pos: [710, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: pos
|
||||||
|
pos: [250, 460]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: scanner
|
||||||
|
pos: [40, 460]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: EU cloud - k8s cluster
|
||||||
|
wraps: [ingress, web, booking, ticketing, possync]
|
||||||
|
- kind: security-group
|
||||||
|
label: Managed data zone
|
||||||
|
wraps: [seatlock, db]
|
||||||
|
- kind: region
|
||||||
|
label: Cinema site
|
||||||
|
wraps: [pos, scanner]
|
||||||
|
connections:
|
||||||
|
- { from: customer, to: ingress, label: HTTPS, variant: emphasis }
|
||||||
|
- { from: ingress, to: web, label: route }
|
||||||
|
- { from: ingress, to: booking, label: route }
|
||||||
|
- { from: booking, to: seatlock, label: TLS }
|
||||||
|
- { from: booking, to: db, label: TLS }
|
||||||
|
- { from: ticketing, to: db, label: TLS }
|
||||||
|
- { from: possync, to: pos, label: VPN, variant: security }
|
||||||
|
- { from: scanner, to: ingress, label: HTTPS }
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: seat-holds-with-ttl
|
||||||
|
title: Seat holds as Redis keys with a TTL
|
||||||
|
status: accepted
|
||||||
|
date: 2026-09-08
|
||||||
|
elements: [booking, seatlock]
|
||||||
|
diagrams: [0500-building-blocks/booking.archify, 0600-runtime/book-seats.archify]
|
||||||
|
context: >
|
||||||
|
A customer may spend minutes at the payment page. Holding seats
|
||||||
|
as rows in the database left orphans when a browser closed, and
|
||||||
|
a nightly job freed them far too late for Friday shows.
|
||||||
|
decision: >
|
||||||
|
A hold is one Redis key per seat, set with SET NX and an
|
||||||
|
8-minute TTL. The payment webhook turns holds into an order in
|
||||||
|
PostgreSQL; an expired key frees the seat without any job.
|
||||||
|
consequences: >
|
||||||
|
Holds survive no Redis restart; at worst a customer re-picks
|
||||||
|
seats. The webhook must check the hold still exists before it
|
||||||
|
confirms the order, otherwise it refunds.
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: booking-owns-seat-inventory
|
||||||
|
title: The Booking API owns the seat inventory
|
||||||
|
status: accepted
|
||||||
|
date: 2026-09-22
|
||||||
|
elements: [booking, db, possync, pos]
|
||||||
|
diagrams: [0500-building-blocks/level-1.archify]
|
||||||
|
context: >
|
||||||
|
The box-office POS and the web shop both sold seats from their
|
||||||
|
own copy of the seat map. Twice a month a seat was sold at the
|
||||||
|
counter and online.
|
||||||
|
decision: >
|
||||||
|
The Tickets DB is the only seat inventory. The POS asks POS Sync
|
||||||
|
for a seat before it prints a ticket; POS Sync writes the sale
|
||||||
|
through the same rules as online orders.
|
||||||
|
consequences: >
|
||||||
|
The counter needs the network to sell; a fallback block of
|
||||||
|
reserved seats per show covers outages. The POS vendor adapter
|
||||||
|
is ours to maintain.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: signed-qr-codes
|
||||||
|
title: Signed QR codes checked offline at the door
|
||||||
|
status: accepted
|
||||||
|
date: 2026-10-06
|
||||||
|
elements: [ticketing, scanner]
|
||||||
|
diagrams: [0600-runtime/check-in.archify]
|
||||||
|
context: >
|
||||||
|
Cinema Wi-Fi drops when a full hall arrives. A scanner that
|
||||||
|
needs the server for every ticket stops the queue.
|
||||||
|
decision: >
|
||||||
|
The Ticket Service signs each QR payload (ticket id, show,
|
||||||
|
seat) with a private key. The scanner app verifies it with the
|
||||||
|
public key and queues check-ins until it is online again.
|
||||||
|
consequences: >
|
||||||
|
A forwarded ticket scans twice while offline; the second scan
|
||||||
|
is flagged when the queue syncs. Key rotation needs an app
|
||||||
|
update window.
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
schema_version: 1
|
||||||
|
model:
|
||||||
|
id: cinema-tickets
|
||||||
|
name: Cinema Tickets
|
||||||
|
description: >
|
||||||
|
An arc42 example: online and mobile seat booking for a small
|
||||||
|
cinema chain. This overview is section 3 (business context) with
|
||||||
|
cards for sections 1, 2, 10, 11 and 12. 0300-context holds the
|
||||||
|
technical context (3), 0500-building-blocks the building block
|
||||||
|
view (5), 0600-runtime the runtime view (6), 0700-deployment the
|
||||||
|
deployment view (7), decisions/ the architecture decisions (9).
|
||||||
|
Crosscutting concepts (8) are a card on the level-1 diagram.
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Cinema Tickets - business context
|
||||||
|
output: main.html
|
||||||
|
components:
|
||||||
|
- ref: customer
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: usher
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: tickets
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: psp
|
||||||
|
pos: [540, 60]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: mail
|
||||||
|
pos: [540, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: pos
|
||||||
|
pos: [540, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
connections:
|
||||||
|
- { from: customer, to: tickets, label: books seats, variant: emphasis }
|
||||||
|
- { from: usher, to: tickets, label: checks in }
|
||||||
|
- { from: tickets, to: psp, label: payments, variant: security }
|
||||||
|
- { from: tickets, to: mail, label: tickets }
|
||||||
|
- { from: tickets, to: pos, label: seat sales }
|
||||||
|
cards:
|
||||||
|
- dot: cyan
|
||||||
|
title: 1 Quality goals
|
||||||
|
items:
|
||||||
|
- "No seat is ever sold twice"
|
||||||
|
- "Checkout under 2 s at Friday peak"
|
||||||
|
- "Door check-in works offline"
|
||||||
|
- dot: slate
|
||||||
|
title: 2 Constraints
|
||||||
|
items:
|
||||||
|
- "Existing box-office POS stays"
|
||||||
|
- "Card data only at the provider"
|
||||||
|
- "Team of four; hosted in the EU"
|
||||||
|
- dot: emerald
|
||||||
|
title: 10 Quality scenarios
|
||||||
|
items:
|
||||||
|
- "500 holds on one show in 1 min: no double sale"
|
||||||
|
- "Wi-Fi down at the door: scans go on, sync later"
|
||||||
|
- "Payment fails: seats free again within 8 min"
|
||||||
|
- dot: rose
|
||||||
|
title: 11 Risks
|
||||||
|
items:
|
||||||
|
- "POS vendor API is slow and undocumented"
|
||||||
|
- "Forwarded QR e-mails: first scan wins"
|
||||||
|
- dot: violet
|
||||||
|
title: 12 Glossary
|
||||||
|
items:
|
||||||
|
- "Show: one screening of a film in a hall"
|
||||||
|
- "Hold: a seat locked for one customer"
|
||||||
|
- "Check-in: first valid scan of a ticket"
|
||||||
|
- "POS: point-of-sale till at the box office"
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
web:
|
||||||
|
type: frontend
|
||||||
|
label: Web Shop
|
||||||
|
sublabel: React
|
||||||
|
brand: react
|
||||||
|
description: >
|
||||||
|
Programme, seat map and checkout in the browser.
|
||||||
|
mobile:
|
||||||
|
type: frontend
|
||||||
|
label: Mobile App
|
||||||
|
sublabel: iOS and Android
|
||||||
|
description: >
|
||||||
|
The same booking flow as the web shop, plus a ticket wallet.
|
||||||
|
scanner:
|
||||||
|
type: frontend
|
||||||
|
label: Scanner App
|
||||||
|
sublabel: door phones
|
||||||
|
description: >
|
||||||
|
Reads QR codes at the door; checks signatures offline.
|
||||||
|
booking:
|
||||||
|
type: backend
|
||||||
|
label: Booking API
|
||||||
|
sublabel: Node.js
|
||||||
|
brand: node-js
|
||||||
|
description: >
|
||||||
|
Shows, seat maps, seat holds and orders; the only writer of
|
||||||
|
the seat inventory.
|
||||||
|
diagram: 0500-building-blocks/booking.archify
|
||||||
|
ticketing:
|
||||||
|
type: backend
|
||||||
|
label: Ticket Service
|
||||||
|
sublabel: QR, check-in
|
||||||
|
description: >
|
||||||
|
Issues signed QR tickets, sends them by e-mail and records
|
||||||
|
check-ins at the door.
|
||||||
|
possync:
|
||||||
|
type: backend
|
||||||
|
label: POS Sync
|
||||||
|
sublabel: adapter
|
||||||
|
description: >
|
||||||
|
Exchanges seat sales with the box-office POS in both directions.
|
||||||
|
seatlock:
|
||||||
|
type: database
|
||||||
|
label: Seat Locks
|
||||||
|
sublabel: Redis
|
||||||
|
brand: redis
|
||||||
|
description: >
|
||||||
|
Short-lived seat holds with a TTL while the customer pays.
|
||||||
|
db:
|
||||||
|
type: database
|
||||||
|
label: Tickets DB
|
||||||
|
sublabel: PostgreSQL
|
||||||
|
brand: postgresql
|
||||||
|
description: >
|
||||||
|
Shows, seats, orders and tickets; the source of truth.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
customer:
|
||||||
|
type: external
|
||||||
|
label: Moviegoer
|
||||||
|
sublabel: web and mobile
|
||||||
|
description: >
|
||||||
|
Picks a show, holds seats and pays; gets the tickets by e-mail.
|
||||||
|
usher:
|
||||||
|
type: external
|
||||||
|
label: Usher
|
||||||
|
sublabel: door staff
|
||||||
|
description: >
|
||||||
|
Scans tickets at the auditorium door with the scanner app.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
tickets:
|
||||||
|
type: cloud
|
||||||
|
label: Cinema Tickets
|
||||||
|
sublabel: the system
|
||||||
|
description: >
|
||||||
|
Online booking, seat holds, e-mail tickets and door check-in
|
||||||
|
for the five cinemas of the fictional Lantern Cinemas chain.
|
||||||
|
diagram: 0500-building-blocks/level-1.archify
|
||||||
|
psp:
|
||||||
|
type: external
|
||||||
|
label: Payment provider
|
||||||
|
sublabel: hosted checkout
|
||||||
|
description: >
|
||||||
|
Takes card and wallet payments on its own page; we never see
|
||||||
|
card numbers.
|
||||||
|
pos:
|
||||||
|
type: external
|
||||||
|
label: Box-office POS
|
||||||
|
sublabel: in each cinema
|
||||||
|
description: >
|
||||||
|
Till system at the counter; sells walk-in seats from the same
|
||||||
|
seat map.
|
||||||
|
mail:
|
||||||
|
type: external
|
||||||
|
label: E-mail service
|
||||||
|
sublabel: transactional
|
||||||
|
description: >
|
||||||
|
Delivers ticket e-mails with QR codes and receipts.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Technical context
|
||||||
|
output: technical-context.html
|
||||||
|
decisions: [mqtt-with-mutual-tls]
|
||||||
|
components:
|
||||||
|
- ref: homeowner
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ops-engineer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: installer
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: telemetry-platform
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: heat-pump
|
||||||
|
pos: [540, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: push-service
|
||||||
|
pos: [540, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: service-desk
|
||||||
|
pos: [540, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: homeowner, to: telemetry-platform, label: HTTPS }
|
||||||
|
- { from: ops-engineer, to: telemetry-platform, label: HTTPS, variant: security }
|
||||||
|
- { from: installer, to: telemetry-platform, label: HTTPS }
|
||||||
|
- { from: heat-pump, to: telemetry-platform, label: MQTT 8883, variant: emphasis, decisions: [mqtt-with-mutual-tls] }
|
||||||
|
- { from: telemetry-platform, to: push-service, label: HTTP/2 }
|
||||||
|
- { from: telemetry-platform, to: service-desk, label: webhook }
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Ingest, level 2
|
||||||
|
output: ingest.html
|
||||||
|
components:
|
||||||
|
- ref: mqtt-broker
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: decoder
|
||||||
|
type: backend
|
||||||
|
label: Decoder
|
||||||
|
sublabel: payload v1, v2
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: validator
|
||||||
|
type: backend
|
||||||
|
label: Validator
|
||||||
|
sublabel: ranges, clock
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: writer
|
||||||
|
type: backend
|
||||||
|
label: Batch writer
|
||||||
|
sublabel: 500 rows
|
||||||
|
pos: [670, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: dead-letter
|
||||||
|
type: database
|
||||||
|
label: Dead letters
|
||||||
|
sublabel: rejected readings
|
||||||
|
pos: [460, 310]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: tsdb
|
||||||
|
pos: [880, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: rules
|
||||||
|
pos: [670, 310]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Ingest
|
||||||
|
wraps: [decoder, validator, writer, dead-letter]
|
||||||
|
connections:
|
||||||
|
- { from: mqtt-broker, to: decoder, label: messages, variant: emphasis }
|
||||||
|
- { from: decoder, to: validator, label: readings, variant: emphasis }
|
||||||
|
- { from: validator, to: writer, label: valid, variant: emphasis }
|
||||||
|
- { from: validator, to: dead-letter, label: invalid, variant: dashed, labelAt: [525, 234] }
|
||||||
|
- { from: writer, to: tsdb, label: COPY, variant: emphasis }
|
||||||
|
- { from: writer, to: rules, label: stream, labelAt: [735, 234] }
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Building blocks, level 1
|
||||||
|
output: level-1.html
|
||||||
|
decisions: [timescaledb-for-telemetry]
|
||||||
|
components:
|
||||||
|
- ref: heat-pump
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: installer
|
||||||
|
pos: [40, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mqtt-broker
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [mqtt-with-mutual-tls]
|
||||||
|
- ref: provisioning
|
||||||
|
pos: [250, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: rules
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ingest
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: device-registry
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: tsdb
|
||||||
|
pos: [670, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: device-api
|
||||||
|
pos: [670, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ops-dashboard
|
||||||
|
pos: [880, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: customer-app
|
||||||
|
pos: [880, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: push-service
|
||||||
|
pos: [1090, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ops-engineer
|
||||||
|
pos: [1090, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: homeowner
|
||||||
|
pos: [1090, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: IoT Telemetry
|
||||||
|
wraps: [mqtt-broker, provisioning, rules, ingest, device-registry, tsdb, device-api, ops-dashboard, customer-app]
|
||||||
|
connections:
|
||||||
|
- { from: heat-pump, to: mqtt-broker, label: publish, variant: emphasis, decisions: [mqtt-with-mutual-tls] }
|
||||||
|
- { from: mqtt-broker, to: ingest, label: subscribe, variant: emphasis }
|
||||||
|
- { from: ingest, to: tsdb, label: write, variant: emphasis }
|
||||||
|
- { from: ingest, to: rules, label: stream }
|
||||||
|
- { from: ingest, to: device-registry, label: lookup, labelAt: [525, 234] }
|
||||||
|
- { from: rules, to: push-service, label: alert }
|
||||||
|
- { from: installer, to: provisioning, label: register }
|
||||||
|
- { from: provisioning, to: mqtt-broker, label: certs, variant: security }
|
||||||
|
- { from: provisioning, to: device-registry, label: store }
|
||||||
|
- { from: device-api, to: tsdb, label: read }
|
||||||
|
- { from: device-api, to: device-registry, label: read }
|
||||||
|
- { from: tsdb, to: ops-dashboard, label: query }
|
||||||
|
- { from: customer-app, to: device-api, label: REST }
|
||||||
|
- { from: ops-engineer, to: ops-dashboard, label: views }
|
||||||
|
- { from: homeowner, to: customer-app, label: uses }
|
||||||
|
cards:
|
||||||
|
- dot: amber
|
||||||
|
title: 8 Crosscutting concepts
|
||||||
|
items:
|
||||||
|
- Device identity, one X.509 certificate per device
|
||||||
|
- Idempotent writes, keyed by device id and timestamp
|
||||||
|
- Observability, metrics and traces on every service
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Device provisioning
|
||||||
|
output: device-provisioning.html
|
||||||
|
decisions: [mqtt-with-mutual-tls]
|
||||||
|
participants:
|
||||||
|
- { ref: installer }
|
||||||
|
- { ref: provisioning }
|
||||||
|
- { ref: device-registry, label: Devices }
|
||||||
|
- { ref: heat-pump }
|
||||||
|
- { ref: mqtt-broker }
|
||||||
|
messages:
|
||||||
|
- { from: installer, to: provisioning, y: 160, label: register serial, variant: emphasis }
|
||||||
|
- { from: provisioning, to: device-registry, y: 210, label: store device }
|
||||||
|
- { from: provisioning, to: installer, y: 260, label: certificate, variant: return }
|
||||||
|
- { from: installer, to: heat-pump, y: 310, label: load certificate }
|
||||||
|
- { from: heat-pump, to: mqtt-broker, y: 360, label: connect mTLS, variant: emphasis }
|
||||||
|
- { from: mqtt-broker, to: provisioning, y: 410, label: check revocation }
|
||||||
|
- { from: mqtt-broker, to: heat-pump, y: 460, label: CONNACK, variant: return }
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Fault reading to alert
|
||||||
|
output: telemetry-to-alert.html
|
||||||
|
participants:
|
||||||
|
- { ref: heat-pump }
|
||||||
|
- { ref: mqtt-broker }
|
||||||
|
- { ref: ingest }
|
||||||
|
- { ref: tsdb, label: TSDB }
|
||||||
|
- { ref: rules }
|
||||||
|
- { ref: push-service }
|
||||||
|
messages:
|
||||||
|
- { from: heat-pump, to: mqtt-broker, y: 160, label: publish fault, variant: emphasis }
|
||||||
|
- { from: mqtt-broker, to: ingest, y: 210, label: deliver QoS 1 }
|
||||||
|
- { from: ingest, to: tsdb, y: 260, label: write batch }
|
||||||
|
- { from: tsdb, to: ingest, y: 310, label: committed, variant: return }
|
||||||
|
- { from: ingest, to: mqtt-broker, y: 360, label: ack, variant: return }
|
||||||
|
- { from: ingest, to: rules, y: 410, label: reading }
|
||||||
|
- { from: rules, to: push-service, y: 460, label: send alert, variant: emphasis }
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Deployment, production
|
||||||
|
output: production.html
|
||||||
|
decisions: [timescaledb-for-telemetry]
|
||||||
|
components:
|
||||||
|
- ref: heat-pump
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mqtt-broker
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ingest
|
||||||
|
pos: [490, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: rules
|
||||||
|
pos: [490, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: provisioning
|
||||||
|
pos: [280, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: device-api
|
||||||
|
pos: [490, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: tsdb
|
||||||
|
pos: [760, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: device-registry
|
||||||
|
pos: [760, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Kubernetes cluster, eu-central
|
||||||
|
wraps: [mqtt-broker, ingest, rules, provisioning, device-api]
|
||||||
|
- kind: security-group
|
||||||
|
label: Managed DB zone
|
||||||
|
wraps: [tsdb, device-registry]
|
||||||
|
connections:
|
||||||
|
- { from: heat-pump, to: mqtt-broker, label: "8883", variant: emphasis }
|
||||||
|
- { from: mqtt-broker, to: ingest, label: in-cluster }
|
||||||
|
- { from: ingest, to: tsdb, label: "5432", variant: emphasis }
|
||||||
|
- { from: ingest, to: rules, label: gRPC }
|
||||||
|
- { from: device-api, to: device-registry, label: "5432" }
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: mqtt-with-mutual-tls
|
||||||
|
title: MQTT with mutual TLS for device traffic
|
||||||
|
status: accepted
|
||||||
|
date: 2026-08-12
|
||||||
|
elements: [heat-pump, mqtt-broker, provisioning]
|
||||||
|
diagrams: [0300-context/technical-context.archify, 0500-building-blocks/level-1.archify]
|
||||||
|
context: >
|
||||||
|
Heat pumps sit behind home routers on slow and flaky links.
|
||||||
|
The first prototype polled an HTTPS endpoint and drained
|
||||||
|
mobile data plans; shared API keys leaked from one device.
|
||||||
|
decision: >
|
||||||
|
Devices publish over MQTT 3.1.1 on port 8883. Each device
|
||||||
|
has its own client certificate issued by Provisioning;
|
||||||
|
the broker rejects any connection without one.
|
||||||
|
consequences: >
|
||||||
|
Small messages and one long-lived connection per device.
|
||||||
|
Certificates must be rotated and revoked, so Provisioning
|
||||||
|
is a critical building block. Installers need a step to
|
||||||
|
register the device before it can connect.
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: timescaledb-for-telemetry
|
||||||
|
title: TimescaleDB for telemetry
|
||||||
|
status: accepted
|
||||||
|
date: 2026-09-03
|
||||||
|
elements: [tsdb, ingest, ops-dashboard]
|
||||||
|
diagrams: [0500-building-blocks/level-1.archify, 0700-deployment/production.archify]
|
||||||
|
context: >
|
||||||
|
The fleet sends about 4,000 readings a second. A plain
|
||||||
|
PostgreSQL table grew too fast and dashboards slowed down
|
||||||
|
after a few weeks of data.
|
||||||
|
decision: >
|
||||||
|
Store telemetry in TimescaleDB hypertables with hourly
|
||||||
|
continuous aggregates. Raw data is kept 90 days, rollups
|
||||||
|
10 years. The team already runs PostgreSQL.
|
||||||
|
consequences: >
|
||||||
|
SQL stays the query language for the API and the
|
||||||
|
dashboard. Retention jobs must be monitored. Very high
|
||||||
|
device counts may need sharding later (see risk R1).
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
schema_version: 1
|
||||||
|
model:
|
||||||
|
id: iot-telemetry
|
||||||
|
name: IoT Telemetry
|
||||||
|
description: >
|
||||||
|
An arc42 example: a fictional heat pump maker collects device telemetry
|
||||||
|
over MQTT, stores it, raises alerts and shows it to operations and customers.
|
||||||
|
main.archify holds section 3 business context with cards for sections
|
||||||
|
1 goals, 2 constraints, 10 quality, 11 risks and 12 glossary;
|
||||||
|
0300-context the technical context; 0500-building-blocks section 5;
|
||||||
|
0600-runtime section 6; 0700-deployment section 7; decisions/ section 9;
|
||||||
|
the crosscutting concepts of section 8 are a card on level-1.
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Business context
|
||||||
|
output: main.html
|
||||||
|
components:
|
||||||
|
- ref: homeowner
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: ops-engineer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: installer
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: telemetry-platform
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: heat-pump
|
||||||
|
pos: [540, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: push-service
|
||||||
|
pos: [540, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: service-desk
|
||||||
|
pos: [540, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: homeowner, to: telemetry-platform, label: checks }
|
||||||
|
- { from: ops-engineer, to: telemetry-platform, label: monitors }
|
||||||
|
- { from: installer, to: telemetry-platform, label: registers }
|
||||||
|
- { from: heat-pump, to: telemetry-platform, label: telemetry, variant: emphasis }
|
||||||
|
- { from: telemetry-platform, to: push-service, label: alerts }
|
||||||
|
- { from: telemetry-platform, to: service-desk, label: tickets }
|
||||||
|
cards:
|
||||||
|
- dot: cyan
|
||||||
|
title: 1 Quality goals
|
||||||
|
items:
|
||||||
|
- Reliability, no telemetry lost once accepted
|
||||||
|
- Timeliness, alert within 60 s of a fault
|
||||||
|
- Security, every device authenticated
|
||||||
|
- dot: slate
|
||||||
|
title: 2 Constraints
|
||||||
|
items:
|
||||||
|
- Devices speak MQTT only; firmware by a partner
|
||||||
|
- Data stays in one EU region
|
||||||
|
- Team of six; PostgreSQL skills in house
|
||||||
|
- dot: emerald
|
||||||
|
title: 10 Quality scenarios
|
||||||
|
items:
|
||||||
|
- A fault code reaches the homeowner within 60 s
|
||||||
|
- Broker restart, devices reconnect, no data lost
|
||||||
|
- A stolen certificate is revoked within 15 min
|
||||||
|
- dot: rose
|
||||||
|
title: 11 Risks
|
||||||
|
items:
|
||||||
|
- R1 fleet growth beyond one TSDB node
|
||||||
|
- R2 partner firmware delays certificate rotation
|
||||||
|
- dot: violet
|
||||||
|
title: 12 Glossary
|
||||||
|
items:
|
||||||
|
- Telemetry, readings a device sends
|
||||||
|
- Rollup, hourly aggregate of telemetry
|
||||||
|
- Provisioning, giving a device its identity
|
||||||
|
- Fault code, error number from the device
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
mqtt-broker:
|
||||||
|
type: messagebus
|
||||||
|
label: MQTT broker
|
||||||
|
sublabel: mutual TLS
|
||||||
|
description: >
|
||||||
|
Terminates device connections; one topic per device.
|
||||||
|
ingest:
|
||||||
|
type: backend
|
||||||
|
label: Ingest
|
||||||
|
sublabel: Go
|
||||||
|
brand: go
|
||||||
|
description: >
|
||||||
|
Decodes, validates and stores telemetry; forwards it to the rules.
|
||||||
|
diagram: 0500-building-blocks/ingest.archify
|
||||||
|
tsdb:
|
||||||
|
type: database
|
||||||
|
label: Time series DB
|
||||||
|
sublabel: TimescaleDB
|
||||||
|
brand: postgresql
|
||||||
|
description: >
|
||||||
|
Raw telemetry for 90 days and hourly rollups for 10 years.
|
||||||
|
rules:
|
||||||
|
type: backend
|
||||||
|
label: Rules engine
|
||||||
|
sublabel: alerting
|
||||||
|
description: >
|
||||||
|
Evaluates thresholds and fault codes; raises alerts.
|
||||||
|
provisioning:
|
||||||
|
type: security
|
||||||
|
label: Provisioning
|
||||||
|
sublabel: device certs
|
||||||
|
description: >
|
||||||
|
Registers devices and issues their client certificates.
|
||||||
|
device-registry:
|
||||||
|
type: database
|
||||||
|
label: Device registry
|
||||||
|
sublabel: PostgreSQL
|
||||||
|
brand: postgresql
|
||||||
|
description: >
|
||||||
|
Devices, owners, firmware versions and certificate state.
|
||||||
|
device-api:
|
||||||
|
type: backend
|
||||||
|
label: Device API
|
||||||
|
sublabel: REST
|
||||||
|
description: >
|
||||||
|
Serves telemetry and device data to the customer app.
|
||||||
|
ops-dashboard:
|
||||||
|
type: frontend
|
||||||
|
label: Ops dashboard
|
||||||
|
sublabel: Grafana
|
||||||
|
brand: grafana
|
||||||
|
description: >
|
||||||
|
Fleet view for the operations team, read only on the TSDB.
|
||||||
|
customer-app:
|
||||||
|
type: frontend
|
||||||
|
label: Customer app
|
||||||
|
sublabel: mobile
|
||||||
|
description: >
|
||||||
|
Shows the homeowner their heat pump and its alerts.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
homeowner:
|
||||||
|
type: external
|
||||||
|
label: Homeowner
|
||||||
|
sublabel: customer app
|
||||||
|
description: >
|
||||||
|
Owns a heat pump; checks temperatures and gets fault alerts.
|
||||||
|
ops-engineer:
|
||||||
|
type: external
|
||||||
|
label: Ops engineer
|
||||||
|
sublabel: operations team
|
||||||
|
description: >
|
||||||
|
Watches the fleet, handles alerts and plans service visits.
|
||||||
|
installer:
|
||||||
|
type: external
|
||||||
|
label: Installer
|
||||||
|
sublabel: field service
|
||||||
|
description: >
|
||||||
|
Mounts heat pumps on site and registers them with the platform.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
telemetry-platform:
|
||||||
|
type: cloud
|
||||||
|
label: IoT Telemetry
|
||||||
|
sublabel: the system
|
||||||
|
description: >
|
||||||
|
Everything we build and run; broker, ingest, stores, rules and apps.
|
||||||
|
diagram: 0500-building-blocks/level-1.archify
|
||||||
|
heat-pump:
|
||||||
|
type: external
|
||||||
|
label: Heat pump
|
||||||
|
sublabel: field device
|
||||||
|
description: >
|
||||||
|
Sends telemetry every 30 seconds over MQTT; built by a partner.
|
||||||
|
push-service:
|
||||||
|
type: external
|
||||||
|
label: Push service
|
||||||
|
sublabel: mobile push
|
||||||
|
description: >
|
||||||
|
Delivers push notifications to the customer app.
|
||||||
|
service-desk:
|
||||||
|
type: external
|
||||||
|
label: Service desk
|
||||||
|
sublabel: ticketing
|
||||||
|
description: >
|
||||||
|
Opens service tickets for faults that need a visit.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Technical context
|
||||||
|
output: technical-context.html
|
||||||
|
components:
|
||||||
|
- ref: engineer
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: wiki-admin
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: wiki
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: idp
|
||||||
|
pos: [520, 60]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: object-store
|
||||||
|
pos: [520, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
connections:
|
||||||
|
- { from: engineer, to: wiki, label: HTTPS, variant: emphasis }
|
||||||
|
- { from: wiki-admin, to: wiki, label: kubectl }
|
||||||
|
- { from: wiki, to: idp, label: OIDC, variant: security }
|
||||||
|
- { from: wiki, to: object-store, label: S3 API }
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Building blocks - level 1
|
||||||
|
output: level-1.html
|
||||||
|
decisions: [postgres-full-text-search]
|
||||||
|
components:
|
||||||
|
- ref: engineer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: web
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: api
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: backup-job
|
||||||
|
pos: [670, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: idp
|
||||||
|
pos: [670, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: object-store
|
||||||
|
pos: [880, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Team Wiki
|
||||||
|
wraps: [web, api, db, backup-job]
|
||||||
|
connections:
|
||||||
|
- { from: engineer, to: web, label: HTTPS, variant: emphasis }
|
||||||
|
- { from: web, to: api, label: JSON, variant: emphasis }
|
||||||
|
- { from: api, to: db, label: SQL, labelAt: [525, 234], decisions: [postgres-full-text-search] }
|
||||||
|
- { from: api, to: idp, label: OIDC, variant: security }
|
||||||
|
- { from: api, to: object-store, label: files }
|
||||||
|
- { from: backup-job, to: db, label: dump }
|
||||||
|
- { from: backup-job, to: object-store, label: upload }
|
||||||
|
cards:
|
||||||
|
- dot: amber
|
||||||
|
title: 8 Crosscutting concepts
|
||||||
|
items:
|
||||||
|
- Access - every request checked against space groups
|
||||||
|
- Logs - JSON to stdout, collected by the cluster
|
||||||
|
- Config - environment variables, secrets from the vault
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Building blocks - level 2, Wiki API
|
||||||
|
output: wiki-api.html
|
||||||
|
components:
|
||||||
|
- ref: web
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: auth
|
||||||
|
type: security
|
||||||
|
label: Auth
|
||||||
|
sublabel: OIDC session
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: pages
|
||||||
|
type: backend
|
||||||
|
label: Pages
|
||||||
|
sublabel: revisions
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: search
|
||||||
|
type: backend
|
||||||
|
label: Search
|
||||||
|
sublabel: full-text
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [postgres-full-text-search]
|
||||||
|
- id: attachments
|
||||||
|
type: backend
|
||||||
|
label: Attachments
|
||||||
|
pos: [250, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: idp
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db
|
||||||
|
pos: [460, 210]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: object-store
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Wiki API
|
||||||
|
wraps: [auth, pages, search, attachments]
|
||||||
|
connections:
|
||||||
|
- { from: web, to: auth, label: sign in, variant: security }
|
||||||
|
- { from: web, to: pages, label: edit, labelAt: [222, 182] }
|
||||||
|
- { from: web, to: search, label: query }
|
||||||
|
- { from: web, to: attachments, label: upload }
|
||||||
|
- { from: auth, to: idp, label: OIDC, variant: security }
|
||||||
|
- { from: pages, to: db, label: SQL }
|
||||||
|
- { from: search, to: db, label: SQL }
|
||||||
|
- { from: attachments, to: object-store, label: S3 }
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Runtime - search and open a page
|
||||||
|
output: search-page.html
|
||||||
|
participants:
|
||||||
|
- ref: engineer
|
||||||
|
- ref: web
|
||||||
|
- ref: api
|
||||||
|
- { ref: db, label: DB }
|
||||||
|
- { ref: object-store, label: Object store }
|
||||||
|
messages:
|
||||||
|
- { from: engineer, to: web, y: 160, label: type query, variant: emphasis }
|
||||||
|
- { from: web, to: api, y: 210, label: GET /search }
|
||||||
|
- { from: api, to: db, y: 260, label: full-text query }
|
||||||
|
- { from: db, to: api, y: 310, label: ranked pages, variant: return }
|
||||||
|
- { from: api, to: web, y: 360, label: results, variant: return }
|
||||||
|
- { from: web, to: api, y: 410, label: GET /pages/id }
|
||||||
|
- { from: api, to: object-store, y: 460, label: signed URL }
|
||||||
|
- { from: api, to: web, y: 510, label: page, variant: return }
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: sequence
|
||||||
|
meta:
|
||||||
|
title: Runtime - sign in
|
||||||
|
output: sign-in.html
|
||||||
|
decisions: [sso-only-via-company-idp]
|
||||||
|
participants:
|
||||||
|
- ref: engineer
|
||||||
|
- ref: web
|
||||||
|
- ref: api
|
||||||
|
- { ref: idp, label: Company IdP }
|
||||||
|
messages:
|
||||||
|
- { from: engineer, to: web, y: 160, label: open wiki, variant: emphasis }
|
||||||
|
- { from: web, to: api, y: 210, label: GET /session }
|
||||||
|
- { from: api, to: web, y: 260, label: redirect, variant: return }
|
||||||
|
- { from: web, to: idp, y: 310, label: OIDC login, variant: security }
|
||||||
|
- { from: idp, to: api, y: 360, label: code, variant: return }
|
||||||
|
- { from: api, to: idp, y: 410, label: token exchange, variant: security }
|
||||||
|
- { from: api, to: web, y: 460, label: session cookie, variant: return }
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Deployment - production
|
||||||
|
output: production.html
|
||||||
|
components:
|
||||||
|
- ref: engineer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- id: ingress
|
||||||
|
type: security
|
||||||
|
label: Ingress
|
||||||
|
sublabel: TLS
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: web
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: api
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db
|
||||||
|
pos: [670, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: backup-job
|
||||||
|
pos: [670, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: idp
|
||||||
|
pos: [460, 460]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: object-store
|
||||||
|
pos: [880, 460]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Company cluster
|
||||||
|
wraps: [ingress, web, api, db, backup-job]
|
||||||
|
- kind: security-group
|
||||||
|
label: Namespace team-wiki
|
||||||
|
wraps: [web, api, db, backup-job]
|
||||||
|
connections:
|
||||||
|
- { from: engineer, to: ingress, label: HTTPS, variant: emphasis }
|
||||||
|
- { from: ingress, to: web, label: static }
|
||||||
|
- { from: ingress, to: api, label: /api, variant: emphasis }
|
||||||
|
- { from: api, to: db, label: SQL }
|
||||||
|
- { from: api, to: idp, label: OIDC, variant: security, labelAt: [525, 234] }
|
||||||
|
- { from: backup-job, to: db, label: dump }
|
||||||
|
- { from: backup-job, to: object-store, label: S3 }
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: postgres-full-text-search
|
||||||
|
title: PostgreSQL full-text search, no search engine
|
||||||
|
status: accepted
|
||||||
|
date: 2026-10-05
|
||||||
|
elements: [api, db]
|
||||||
|
diagrams: [0500-building-blocks/level-1.archify, 0500-building-blocks/wiki-api.archify]
|
||||||
|
context: >
|
||||||
|
The wiki holds a few thousand pages for one team. A
|
||||||
|
separate search engine would be one more service to run,
|
||||||
|
back up and keep in sync.
|
||||||
|
decision: >
|
||||||
|
Search uses PostgreSQL full-text search on a generated
|
||||||
|
column of each page. The API queries it in the same
|
||||||
|
transaction as the page data.
|
||||||
|
consequences: >
|
||||||
|
Results are never stale and backups cover search too.
|
||||||
|
Ranking is simpler than a search engine. Revisit when
|
||||||
|
the wiki grows past 100000 pages.
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: sso-only-via-company-idp
|
||||||
|
title: Sign-in only through the company identity provider
|
||||||
|
status: accepted
|
||||||
|
date: 2026-10-12
|
||||||
|
elements: [idp, api, web]
|
||||||
|
diagrams: [0300-context/technical-context.archify, 0600-runtime/sign-in.archify]
|
||||||
|
context: >
|
||||||
|
Leavers kept access to the old wiki because it had its
|
||||||
|
own passwords. Nobody owned the user list.
|
||||||
|
decision: >
|
||||||
|
The wiki has no local accounts. Users sign in with OIDC
|
||||||
|
at the company identity provider; team groups map to
|
||||||
|
wiki spaces.
|
||||||
|
consequences: >
|
||||||
|
Offboarding removes wiki access at once. The wiki cannot
|
||||||
|
be used when the identity provider is down. The admin
|
||||||
|
needs a break-glass account kept in the vault.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
schema_version: 1
|
||||||
|
model:
|
||||||
|
id: team-wiki
|
||||||
|
name: Team Wiki
|
||||||
|
description: >
|
||||||
|
An arc42 example: a small self-hosted wiki for an engineering
|
||||||
|
team. Sections 1 goals, 2 constraints, 3 business context,
|
||||||
|
10 quality, 11 risks and 12 glossary are on this overview;
|
||||||
|
0300-context holds 3 technical context, 0500-building-blocks
|
||||||
|
5 building blocks, 0600-runtime 6 runtime, 0700-deployment
|
||||||
|
7 deployment and decisions 9 architecture decisions.
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Team Wiki - business context
|
||||||
|
output: main.html
|
||||||
|
decisions: [sso-only-via-company-idp]
|
||||||
|
components:
|
||||||
|
- ref: engineer
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: wiki-admin
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: wiki
|
||||||
|
pos: [280, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: idp
|
||||||
|
pos: [520, 60]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: object-store
|
||||||
|
pos: [520, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
connections:
|
||||||
|
- { from: engineer, to: wiki, label: reads, variant: emphasis }
|
||||||
|
- { from: wiki-admin, to: wiki, label: runs }
|
||||||
|
- { from: wiki, to: idp, label: sign-in, variant: security }
|
||||||
|
- { from: wiki, to: object-store, label: files }
|
||||||
|
cards:
|
||||||
|
- dot: cyan
|
||||||
|
title: 1 Quality goals
|
||||||
|
items:
|
||||||
|
- Findability - any page found in two searches
|
||||||
|
- Security - only current staff can read
|
||||||
|
- Operability - one person runs it in an hour a week
|
||||||
|
- dot: slate
|
||||||
|
title: 2 Constraints
|
||||||
|
items:
|
||||||
|
- Runs on the company Kubernetes cluster
|
||||||
|
- Sign-in only via the company identity provider
|
||||||
|
- dot: emerald
|
||||||
|
title: 10 Quality scenarios
|
||||||
|
items:
|
||||||
|
- A search over 5000 pages answers in under 1 s
|
||||||
|
- A leaver loses access within 5 minutes
|
||||||
|
- The admin restores last night's state in 30 minutes
|
||||||
|
- dot: rose
|
||||||
|
title: 11 Risks
|
||||||
|
items:
|
||||||
|
- Identity provider outage blocks all sign-ins
|
||||||
|
- Backups untested until a restore drill is run
|
||||||
|
- dot: violet
|
||||||
|
title: 12 Glossary
|
||||||
|
items:
|
||||||
|
- Space - pages of one team, mapped to a group
|
||||||
|
- Revision - one saved version of a page
|
||||||
|
- Attachment - a file stored beside a page
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
web:
|
||||||
|
type: frontend
|
||||||
|
label: Web App
|
||||||
|
sublabel: React
|
||||||
|
brand: react
|
||||||
|
description: >
|
||||||
|
Page editor, viewer and search box in the browser; talks
|
||||||
|
only to the API.
|
||||||
|
api:
|
||||||
|
type: backend
|
||||||
|
label: Wiki API
|
||||||
|
sublabel: REST
|
||||||
|
description: >
|
||||||
|
Pages, search, attachments and access checks; the only
|
||||||
|
writer of the database.
|
||||||
|
diagram: 0500-building-blocks/wiki-api.archify
|
||||||
|
db:
|
||||||
|
type: database
|
||||||
|
label: Database
|
||||||
|
sublabel: PostgreSQL
|
||||||
|
brand: postgresql
|
||||||
|
description: >
|
||||||
|
Pages, revisions, users and the full-text index; the
|
||||||
|
source of truth.
|
||||||
|
backup-job:
|
||||||
|
type: backend
|
||||||
|
label: Backup job
|
||||||
|
sublabel: nightly
|
||||||
|
description: >
|
||||||
|
Dumps the database at 02:00 and writes it to the backup
|
||||||
|
bucket; keeps 30 days.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
engineer:
|
||||||
|
type: external
|
||||||
|
label: Engineer
|
||||||
|
sublabel: team member
|
||||||
|
description: >
|
||||||
|
Reads and edits pages, searches, attaches files; signs in
|
||||||
|
with the company account.
|
||||||
|
wiki-admin:
|
||||||
|
type: external
|
||||||
|
label: Wiki admin
|
||||||
|
sublabel: platform team
|
||||||
|
description: >
|
||||||
|
Runs the wiki, restores backups and manages spaces.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
wiki:
|
||||||
|
type: cloud
|
||||||
|
label: Team Wiki
|
||||||
|
sublabel: the system
|
||||||
|
description: >
|
||||||
|
Everything we build and run; web app, API, database and
|
||||||
|
the backup job.
|
||||||
|
diagram: 0500-building-blocks/level-1.archify
|
||||||
|
idp:
|
||||||
|
type: security
|
||||||
|
label: Identity provider
|
||||||
|
sublabel: company SSO
|
||||||
|
description: >
|
||||||
|
The company identity provider; signs users in over OIDC
|
||||||
|
and owns team membership.
|
||||||
|
object-store:
|
||||||
|
type: external
|
||||||
|
label: Object storage
|
||||||
|
sublabel: S3-compatible
|
||||||
|
description: >
|
||||||
|
Company object storage; holds attachments and nightly
|
||||||
|
backups in separate buckets.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Business actors and services
|
||||||
|
output: business-services.html
|
||||||
|
components:
|
||||||
|
- ref: hr
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: manager
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: service-desk
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: onboard
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
diagram: 0100-business/onboard-employee.archify
|
||||||
|
- ref: onboarding-svc
|
||||||
|
pos: [480, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: workplace-svc
|
||||||
|
pos: [480, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: new-hire
|
||||||
|
pos: [690, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: hr, to: onboard, label: assigned }
|
||||||
|
- { from: manager, to: onboard, label: assigned }
|
||||||
|
- { from: service-desk, to: onboard, label: assigned }
|
||||||
|
- { from: onboard, to: onboarding-svc, label: realizes }
|
||||||
|
- { from: onboard, to: workplace-svc, label: realizes }
|
||||||
|
- { from: onboarding-svc, to: new-hire, label: serves, variant: emphasis }
|
||||||
|
- { from: workplace-svc, to: new-hire, label: serves }
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
schema_version: 2
|
||||||
|
diagram_type: workflow
|
||||||
|
meta:
|
||||||
|
title: Onboard Employee
|
||||||
|
output: onboard-employee.html
|
||||||
|
viewBox: [1040, 660]
|
||||||
|
lanes:
|
||||||
|
- { id: hr-lane, label: HR }
|
||||||
|
- { id: manager-lane, label: Hiring manager }
|
||||||
|
- { id: desk-lane, label: IT service desk }
|
||||||
|
- { id: hire-lane, label: New hire }
|
||||||
|
mainPath: [contract-signed, record, request, create-accounts, issue-laptop, first-day]
|
||||||
|
nodes:
|
||||||
|
- { ref: contract-signed, lane: hr-lane, col: 0, width: 120 }
|
||||||
|
- { id: record, lane: hr-lane, col: 1, type: backend, label: Create record, tag: Business Process }
|
||||||
|
- { id: request, lane: manager-lane, col: 2, type: frontend, label: Request access, tag: Business Process }
|
||||||
|
- { ref: create-accounts, lane: desk-lane, col: 3, width: 120, decisions: [hr-system-drives-identity] }
|
||||||
|
- { ref: issue-laptop, lane: desk-lane, col: 4, decisions: [zero-touch-laptops] }
|
||||||
|
- { ref: first-day, lane: hire-lane, col: 5 }
|
||||||
|
edges:
|
||||||
|
- { from: contract-signed, to: record, label: triggers }
|
||||||
|
- { from: record, to: request, label: notifies }
|
||||||
|
- { from: request, to: create-accounts, label: ticket }
|
||||||
|
- { from: create-accounts, to: issue-laptop, label: then }
|
||||||
|
- { from: issue-laptop, to: first-day, label: hand over }
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Application components, services and data
|
||||||
|
output: application-components.html
|
||||||
|
components:
|
||||||
|
- ref: provisioning-svc
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: portal
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: device-svc
|
||||||
|
pos: [670, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: hr-system
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: iam
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: itsm
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mdm-app
|
||||||
|
pos: [670, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: employee-record
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: account
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: asset
|
||||||
|
pos: [460, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: iam, to: provisioning-svc, label: realizes }
|
||||||
|
- { from: itsm, to: portal, label: realizes }
|
||||||
|
- { from: mdm-app, to: device-svc, label: realizes }
|
||||||
|
- { from: hr-system, to: employee-record, label: writes, labelAt: [105, 234] }
|
||||||
|
- { from: iam, to: account, label: writes, labelAt: [315, 234] }
|
||||||
|
- { from: itsm, to: asset, label: writes, labelAt: [525, 234] }
|
||||||
|
- { from: mdm-app, to: asset, label: reads }
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Application cooperation
|
||||||
|
output: application-cooperation.html
|
||||||
|
decisions: [hr-system-drives-identity]
|
||||||
|
components:
|
||||||
|
- ref: hr-system
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: iam
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
diagram: 0200-application/application-components.archify
|
||||||
|
- ref: itsm
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: collab
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mdm-app
|
||||||
|
pos: [460, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: hr-system, to: iam, label: joiner event, variant: emphasis, decisions: [hr-system-drives-identity] }
|
||||||
|
- { from: hr-system, to: itsm, label: laptop request }
|
||||||
|
- { from: iam, to: collab, label: provisions }
|
||||||
|
- { from: iam, to: mdm-app, label: users }
|
||||||
|
- { from: itsm, to: mdm-app, label: assigns }
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Technology layer
|
||||||
|
output: infrastructure.html
|
||||||
|
decisions: [zero-touch-laptops]
|
||||||
|
components:
|
||||||
|
- ref: hr-saas
|
||||||
|
pos: [40, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: sso
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: directory
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: itsm-saas
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mdm-saas
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: laptop
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: office-net
|
||||||
|
pos: [250, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: SaaS tenants
|
||||||
|
wraps: [hr-saas, sso, directory, itsm-saas, mdm-saas]
|
||||||
|
- kind: security-group
|
||||||
|
label: Office
|
||||||
|
wraps: [laptop, office-net]
|
||||||
|
connections:
|
||||||
|
- { from: directory, to: sso, label: realizes }
|
||||||
|
- { from: sso, to: hr-saas, label: serves }
|
||||||
|
- { from: sso, to: itsm-saas, label: serves }
|
||||||
|
- { from: directory, to: mdm-saas, label: devices, labelAt: [525, 134] }
|
||||||
|
- { from: mdm-saas, to: laptop, label: manages, labelAt: [525, 234], variant: security, decisions: [zero-touch-laptops] }
|
||||||
|
- { from: laptop, to: office-net, label: connects }
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: hr-system-drives-identity
|
||||||
|
title: The HR system drives identity
|
||||||
|
status: accepted
|
||||||
|
date: 2026-09-08
|
||||||
|
elements: [hr-system, iam, account, employee-record]
|
||||||
|
diagrams: [0200-application/application-cooperation.archify, 0100-business/onboard-employee.archify]
|
||||||
|
context: >
|
||||||
|
Accounts were created by hand from emails sent by HR.
|
||||||
|
New hires waited days for access, and leavers kept
|
||||||
|
accounts for weeks after their last day.
|
||||||
|
decision: >
|
||||||
|
The HR system is the source of truth for joiners and
|
||||||
|
leavers. Identity management reads its events and
|
||||||
|
creates, changes and disables accounts automatically.
|
||||||
|
consequences: >
|
||||||
|
No account without an employee record. HR data quality
|
||||||
|
now decides access, so start dates must be right. The
|
||||||
|
service desk only handles exceptions.
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
schema_version: 1
|
||||||
|
decision:
|
||||||
|
id: zero-touch-laptops
|
||||||
|
title: Zero-touch enrollment for laptops
|
||||||
|
status: accepted
|
||||||
|
date: 2026-10-05
|
||||||
|
elements: [mdm-app, mdm-saas, laptop, device-svc, asset]
|
||||||
|
diagrams: [0300-technology/infrastructure.archify, 0100-business/onboard-employee.archify]
|
||||||
|
context: >
|
||||||
|
Every laptop was imaged by hand at the service desk,
|
||||||
|
which took half a day per device and left settings that
|
||||||
|
differed from one laptop to the next.
|
||||||
|
decision: >
|
||||||
|
Laptops are registered in device management at purchase.
|
||||||
|
They configure themselves at first sign-in over any
|
||||||
|
internet connection; the office network needs no VPN.
|
||||||
|
consequences: >
|
||||||
|
Laptops can be shipped straight to the new hire. A lost
|
||||||
|
laptop is wiped remotely. Setup depends on the MDM
|
||||||
|
tenant being reachable on the first day.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
schema_version: 1
|
||||||
|
model:
|
||||||
|
id: hr-onboarding
|
||||||
|
name: HR Onboarding
|
||||||
|
description: >
|
||||||
|
An ArchiMate example: how a new employee is onboarded, from signed
|
||||||
|
contract to first day. Business, application and technology layers
|
||||||
|
map to folders; each element's ArchiMate type is shown as its tag.
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: HR Onboarding - layered view
|
||||||
|
output: main.html
|
||||||
|
components:
|
||||||
|
- ref: new-hire
|
||||||
|
pos: [40, 70]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: onboarding-svc
|
||||||
|
pos: [270, 70]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: onboard
|
||||||
|
pos: [500, 70]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: portal
|
||||||
|
pos: [40, 270]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: iam
|
||||||
|
pos: [270, 270]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: provisioning-svc
|
||||||
|
pos: [500, 270]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: office-net
|
||||||
|
pos: [40, 470]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: sso
|
||||||
|
pos: [270, 470]
|
||||||
|
size: [170, 60]
|
||||||
|
- ref: directory
|
||||||
|
pos: [500, 470]
|
||||||
|
size: [170, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Business layer
|
||||||
|
wraps: [new-hire, onboarding-svc, onboard]
|
||||||
|
- kind: region
|
||||||
|
label: Application layer
|
||||||
|
wraps: [portal, iam, provisioning-svc]
|
||||||
|
- kind: region
|
||||||
|
label: Technology layer
|
||||||
|
wraps: [office-net, sso, directory]
|
||||||
|
connections:
|
||||||
|
- { from: onboarding-svc, to: new-hire, label: serves, variant: emphasis }
|
||||||
|
- { from: onboard, to: onboarding-svc, label: realizes }
|
||||||
|
- { from: portal, to: new-hire, label: serves }
|
||||||
|
- { from: provisioning-svc, to: onboard, label: serves }
|
||||||
|
- { from: iam, to: provisioning-svc, label: realizes }
|
||||||
|
- { from: office-net, to: portal, label: serves }
|
||||||
|
- { from: sso, to: iam, label: serves }
|
||||||
|
- { from: directory, to: sso, label: realizes }
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
hr-system:
|
||||||
|
type: backend
|
||||||
|
label: HR system
|
||||||
|
sublabel: App Component
|
||||||
|
tag: App Component
|
||||||
|
description: >
|
||||||
|
Holds employee records and contracts; the source of truth for joiners.
|
||||||
|
diagram: 0200-application/application-cooperation.archify
|
||||||
|
iam:
|
||||||
|
type: security
|
||||||
|
label: Identity mgmt
|
||||||
|
sublabel: App Component
|
||||||
|
tag: App Component
|
||||||
|
description: >
|
||||||
|
Creates and removes accounts from HR events; single sign-on for all apps.
|
||||||
|
diagram: 0200-application/application-components.archify
|
||||||
|
itsm:
|
||||||
|
type: backend
|
||||||
|
label: IT service mgmt
|
||||||
|
sublabel: App Component
|
||||||
|
tag: App Component
|
||||||
|
description: >
|
||||||
|
Tickets, requests and the asset inventory of the IT service desk.
|
||||||
|
mdm-app:
|
||||||
|
type: backend
|
||||||
|
label: Device mgmt
|
||||||
|
sublabel: App Component
|
||||||
|
tag: App Component
|
||||||
|
description: >
|
||||||
|
Enrolls laptops, pushes policies and apps, wipes lost devices.
|
||||||
|
collab:
|
||||||
|
type: backend
|
||||||
|
label: Mail and chat
|
||||||
|
sublabel: App Component
|
||||||
|
tag: App Component
|
||||||
|
description: >
|
||||||
|
Mailbox, calendar and chat; accounts provisioned by identity management.
|
||||||
|
provisioning-svc:
|
||||||
|
type: cloud
|
||||||
|
label: Provisioning
|
||||||
|
sublabel: App Service
|
||||||
|
tag: App Service
|
||||||
|
description: >
|
||||||
|
Account create, change and disable, triggered by the HR system.
|
||||||
|
device-svc:
|
||||||
|
type: cloud
|
||||||
|
label: Enrollment
|
||||||
|
sublabel: App Service
|
||||||
|
tag: App Service
|
||||||
|
description: >
|
||||||
|
Zero-touch enrollment; the laptop configures itself at first sign-in.
|
||||||
|
portal:
|
||||||
|
type: frontend
|
||||||
|
label: Service portal
|
||||||
|
sublabel: App Interface
|
||||||
|
tag: App Interface
|
||||||
|
description: >
|
||||||
|
Where managers request equipment and access for a new hire.
|
||||||
|
employee-record:
|
||||||
|
type: database
|
||||||
|
label: Employee record
|
||||||
|
sublabel: Data Object
|
||||||
|
tag: Data Object
|
||||||
|
description: >
|
||||||
|
Name, role, department, manager and start date of an employee.
|
||||||
|
account:
|
||||||
|
type: database
|
||||||
|
label: Account
|
||||||
|
sublabel: Data Object
|
||||||
|
tag: Data Object
|
||||||
|
description: >
|
||||||
|
User id, groups and licences of one person.
|
||||||
|
asset:
|
||||||
|
type: database
|
||||||
|
label: Asset
|
||||||
|
sublabel: Data Object
|
||||||
|
tag: Data Object
|
||||||
|
description: >
|
||||||
|
A laptop with serial number, owner and enrollment state.
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
new-hire:
|
||||||
|
type: external
|
||||||
|
label: New hire
|
||||||
|
sublabel: Business Actor
|
||||||
|
tag: Business Actor
|
||||||
|
description: >
|
||||||
|
The person joining the company; signs the contract and starts on day one.
|
||||||
|
hr:
|
||||||
|
type: external
|
||||||
|
label: HR officer
|
||||||
|
sublabel: Business Role
|
||||||
|
tag: Business Role
|
||||||
|
description: >
|
||||||
|
Prepares the contract and the employee record; owns the onboarding process.
|
||||||
|
manager:
|
||||||
|
type: external
|
||||||
|
label: Hiring manager
|
||||||
|
sublabel: Business Role
|
||||||
|
tag: Business Role
|
||||||
|
description: >
|
||||||
|
Requests access and equipment for the new hire and plans the first day.
|
||||||
|
service-desk:
|
||||||
|
type: external
|
||||||
|
label: IT service desk
|
||||||
|
sublabel: Business Role
|
||||||
|
tag: Business Role
|
||||||
|
description: >
|
||||||
|
Creates accounts, prepares the laptop and hands it over.
|
||||||
|
onboard:
|
||||||
|
type: backend
|
||||||
|
label: Onboard Employee
|
||||||
|
sublabel: Business Process
|
||||||
|
tag: Business Process
|
||||||
|
description: >
|
||||||
|
From signed contract to a productive first day.
|
||||||
|
diagram: 0100-business/onboard-employee.archify
|
||||||
|
onboarding-svc:
|
||||||
|
type: cloud
|
||||||
|
label: Onboarding
|
||||||
|
sublabel: Business Service
|
||||||
|
tag: Business Service
|
||||||
|
description: >
|
||||||
|
What the new hire gets from HR; contract, record, welcome and first day plan.
|
||||||
|
diagram: 0100-business/business-services.archify
|
||||||
|
workplace-svc:
|
||||||
|
type: cloud
|
||||||
|
label: Workplace setup
|
||||||
|
sublabel: Business Service
|
||||||
|
tag: Business Service
|
||||||
|
description: >
|
||||||
|
Accounts and a ready laptop, delivered by the IT service desk.
|
||||||
|
contract-signed:
|
||||||
|
type: messagebus
|
||||||
|
label: Contract signed
|
||||||
|
sublabel: Business Event
|
||||||
|
tag: Business Event
|
||||||
|
description: >
|
||||||
|
Starts the process; HR records the start date.
|
||||||
|
create-accounts:
|
||||||
|
type: backend
|
||||||
|
label: Create accounts
|
||||||
|
sublabel: Business Process
|
||||||
|
tag: Business Process
|
||||||
|
description: >
|
||||||
|
Service desk confirms the accounts the identity system provisioned.
|
||||||
|
issue-laptop:
|
||||||
|
type: backend
|
||||||
|
label: Issue laptop
|
||||||
|
sublabel: Business Process
|
||||||
|
tag: Business Process
|
||||||
|
description: >
|
||||||
|
An enrolled laptop is assigned and handed over.
|
||||||
|
first-day:
|
||||||
|
type: messagebus
|
||||||
|
label: First day
|
||||||
|
sublabel: Business Event
|
||||||
|
tag: Business Event
|
||||||
|
description: >
|
||||||
|
The new hire signs in for the first time; the process ends.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
schema_version: 1
|
||||||
|
elements:
|
||||||
|
hr-saas:
|
||||||
|
type: cloud
|
||||||
|
label: HR tenant
|
||||||
|
sublabel: Node
|
||||||
|
tag: Node
|
||||||
|
description: >
|
||||||
|
The SaaS tenant that runs the HR system.
|
||||||
|
diagram: 0300-technology/infrastructure.archify
|
||||||
|
itsm-saas:
|
||||||
|
type: cloud
|
||||||
|
label: ITSM tenant
|
||||||
|
sublabel: Node
|
||||||
|
tag: Node
|
||||||
|
description: >
|
||||||
|
The SaaS tenant that runs IT service management.
|
||||||
|
mdm-saas:
|
||||||
|
type: cloud
|
||||||
|
label: MDM tenant
|
||||||
|
sublabel: Node
|
||||||
|
tag: Node
|
||||||
|
description: >
|
||||||
|
The SaaS tenant that runs device management.
|
||||||
|
directory:
|
||||||
|
type: backend
|
||||||
|
label: Directory
|
||||||
|
sublabel: System Software
|
||||||
|
tag: System Software
|
||||||
|
description: >
|
||||||
|
Cloud directory service; users, groups and devices.
|
||||||
|
diagram: 0300-technology/infrastructure.archify
|
||||||
|
sso:
|
||||||
|
type: security
|
||||||
|
label: Single sign-on
|
||||||
|
sublabel: Tech Service
|
||||||
|
tag: Tech Service
|
||||||
|
description: >
|
||||||
|
SAML and OIDC sign-in for every SaaS tenant, backed by the directory.
|
||||||
|
laptop:
|
||||||
|
type: frontend
|
||||||
|
label: Laptop
|
||||||
|
sublabel: Device
|
||||||
|
tag: Device
|
||||||
|
description: >
|
||||||
|
Company laptop, enrolled before it is handed over.
|
||||||
|
office-net:
|
||||||
|
type: messagebus
|
||||||
|
label: Office network
|
||||||
|
sublabel: Network
|
||||||
|
tag: Network
|
||||||
|
description: >
|
||||||
|
Wired and wireless network of the office; internet only, no VPN.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Business layer
|
||||||
|
output: business-layer.html
|
||||||
|
components:
|
||||||
|
- ref: customer
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: insurant
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: claim-registration
|
||||||
|
pos: [460, 60]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: claim-payment
|
||||||
|
pos: [460, 260]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: handle-claim
|
||||||
|
pos: [690, 160]
|
||||||
|
size: [150, 60]
|
||||||
|
- ref: claims-handler
|
||||||
|
pos: [920, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: customer, to: insurant, label: assigned to }
|
||||||
|
- { from: claim-registration, to: insurant, label: serves, variant: emphasis }
|
||||||
|
- { from: claim-payment, to: insurant, label: serves }
|
||||||
|
- { from: handle-claim, to: claim-registration, label: realizes }
|
||||||
|
- { from: handle-claim, to: claim-payment, label: realizes }
|
||||||
|
- { from: claims-handler, to: handle-claim, label: assigned to }
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
schema_version: 2
|
||||||
|
diagram_type: workflow
|
||||||
|
meta:
|
||||||
|
title: Handle Claim
|
||||||
|
output: handle-claim.html
|
||||||
|
viewBox: [840, 534]
|
||||||
|
lanes:
|
||||||
|
- { id: insurant-lane, label: Insurant }
|
||||||
|
- { id: handler-lane, label: Claims handler }
|
||||||
|
- { id: systems-lane, label: Applications }
|
||||||
|
mainPath: [damage, register, accept, valuate, pay]
|
||||||
|
nodes:
|
||||||
|
- { id: damage, lane: insurant-lane, col: 0, type: external, label: Damage occurs, tag: Business Event }
|
||||||
|
- { ref: insurant, lane: insurant-lane, col: 5 }
|
||||||
|
- { id: register, lane: handler-lane, col: 1, type: backend, label: Register, tag: Business Process }
|
||||||
|
- { id: accept, lane: handler-lane, col: 2, type: security, label: Accept, sublabel: check coverage, tag: Business Process }
|
||||||
|
- { id: valuate, lane: handler-lane, col: 3, type: backend, label: Valuate, tag: Business Process }
|
||||||
|
- { id: pay, lane: handler-lane, col: 4, type: backend, label: Pay, tag: Business Process }
|
||||||
|
- { ref: claims-app, lane: systems-lane, col: 2 }
|
||||||
|
- { ref: payment, lane: systems-lane, col: 4 }
|
||||||
|
edges:
|
||||||
|
- { from: damage, to: register, label: report }
|
||||||
|
- { from: register, to: accept }
|
||||||
|
- { from: accept, to: valuate, label: covered }
|
||||||
|
- { from: valuate, to: pay, label: approved }
|
||||||
|
- { from: pay, to: insurant, label: paid }
|
||||||
|
- { from: accept, to: insurant, label: rejected, role: branch, variant: dashed }
|
||||||
|
- { from: claims-app, to: accept, label: serves, role: async }
|
||||||
|
- { from: payment, to: pay, label: serves, role: async }
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Application cooperation
|
||||||
|
output: application-cooperation.html
|
||||||
|
components:
|
||||||
|
- ref: portal
|
||||||
|
pos: [40, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: claims-app
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: crm
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: policy-admin
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [policies-stay-on-mainframe]
|
||||||
|
- ref: doc-mgmt
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [documents-in-object-storage]
|
||||||
|
- ref: payment
|
||||||
|
pos: [250, 460]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: portal, to: claims-app, label: claims, variant: emphasis }
|
||||||
|
- { from: crm, to: claims-app, label: customer, labelAt: [315, 134] }
|
||||||
|
- { from: policy-admin, to: claims-app, label: coverage, decisions: [policies-stay-on-mainframe] }
|
||||||
|
- { from: claims-app, to: doc-mgmt, label: documents }
|
||||||
|
- { from: claims-app, to: payment, label: payments, labelAt: [315, 334] }
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Application structure
|
||||||
|
output: application-structure.html
|
||||||
|
components:
|
||||||
|
- ref: portal
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: claims-admin
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: claims-app
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: claim
|
||||||
|
pos: [460, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: crm
|
||||||
|
pos: [670, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: customer-file
|
||||||
|
pos: [880, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: policy-admin
|
||||||
|
pos: [670, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: policy
|
||||||
|
pos: [880, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
connections:
|
||||||
|
- { from: claims-admin, to: portal, label: serves, variant: emphasis }
|
||||||
|
- { from: claims-app, to: claims-admin, label: realizes }
|
||||||
|
- { from: claims-app, to: claim, label: accesses, labelAt: [525, 234] }
|
||||||
|
- { from: crm, to: customer-file, label: accesses }
|
||||||
|
- { from: policy-admin, to: policy, label: accesses }
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
schema_version: 1
|
||||||
|
diagram_type: architecture
|
||||||
|
meta:
|
||||||
|
title: Technology layer
|
||||||
|
output: infrastructure.html
|
||||||
|
components:
|
||||||
|
- ref: dmz
|
||||||
|
pos: [40, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: doc-store
|
||||||
|
pos: [250, 60]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [documents-in-object-storage]
|
||||||
|
- ref: app-servers
|
||||||
|
pos: [250, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db-service
|
||||||
|
pos: [250, 260]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: db-cluster
|
||||||
|
pos: [250, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mq
|
||||||
|
pos: [460, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
- ref: mainframe
|
||||||
|
pos: [670, 160]
|
||||||
|
size: [130, 60]
|
||||||
|
decisions: [policies-stay-on-mainframe]
|
||||||
|
- ref: dc-lan
|
||||||
|
pos: [670, 360]
|
||||||
|
size: [130, 60]
|
||||||
|
boundaries:
|
||||||
|
- kind: region
|
||||||
|
label: Data centre
|
||||||
|
wraps: [doc-store, app-servers, db-service, db-cluster, mq, mainframe, dc-lan]
|
||||||
|
connections:
|
||||||
|
- { from: dmz, to: app-servers, label: HTTPS, variant: security }
|
||||||
|
- { from: app-servers, to: doc-store, label: S3 API }
|
||||||
|
- { from: db-service, to: app-servers, label: serves }
|
||||||
|
- { from: db-cluster, to: db-service, label: realizes }
|
||||||
|
- { from: app-servers, to: mq, label: MQ }
|
||||||
|
- { from: mq, to: mainframe, label: bridge }
|
||||||
|
- { from: db-cluster, to: dc-lan, label: LAN }
|
||||||
|
- { from: mainframe, to: dc-lan, label: LAN, labelAt: [735, 234] }
|
||||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user