@nesso-how/plugin 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  Build Nesso plugins with TypeScript: **actions** read and edit graphs, **vocabularies** define relation types, and **themes** customize appearance.
4
4
 
5
+ ## Install
6
+
7
+ With Node.js and npm installed, add the SDK to your TypeScript project:
8
+
9
+ ```sh
10
+ npm install --save-dev @nesso-how/plugin
11
+ ```
12
+
13
+ This installs the development SDK, not a plugin in Nesso. If you are starting a new plugin, use the example below for TypeScript and bundler configuration, including React UI support. To install and try your built plugin in the desktop app, follow the [local testing instructions](example/README.md#test-an-unpublished-build).
14
+
5
15
  ## Create a plugin
6
16
 
7
17
  Copy the [standalone action example](example/) into a separate project. It includes the SDK, TypeScript configuration, and bundler setup:
@@ -15,20 +25,21 @@ Choose your own package name and action ID, then edit `src/index.ts`:
15
25
 
16
26
  ```ts
17
27
  import type { ActionContribution, NessoOperation } from '@nesso-how/plugin'
18
- import source from '../package.json' with { type: 'json' }
19
28
 
20
29
  export const create = (): readonly ActionContribution[] => {
21
30
  const action: ActionContribution = {
22
31
  id: 'uppercase-labels',
23
- label: source.i18n.metadata.name,
32
+ label: { en: 'Uppercase labels' },
24
33
  run: async ({ document }) => {
25
34
  const state = document.getState()
26
35
 
27
- const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({
28
- kind: 'concept.label',
29
- id,
30
- value: label.toUpperCase(),
31
- }))
36
+ const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(
37
+ ({ id, label }) => ({
38
+ kind: 'concept.label',
39
+ id,
40
+ value: label.toUpperCase(),
41
+ }),
42
+ )
32
43
 
33
44
  await document.applyOperations(operations)
34
45
  },
@@ -64,7 +75,7 @@ Keep the example's build configuration and set these fields in `package.json`:
64
75
  },
65
76
  "i18n": {
66
77
  "metadata": {
67
- "name": { "en": "Uppercase labels" },
78
+ "name": { "en": "Label tools" },
68
79
  "description": { "en": "Uppercase concept labels in a view." },
69
80
  "documentation": { "en": "Updates labels in one undoable batch." }
70
81
  }
@@ -72,24 +83,76 @@ Keep the example's build configuration and set these fields in `package.json`:
72
83
  }
73
84
  ```
74
85
 
75
- Declare the operations your action uses in `writes`. The optional permissions listed in `capabilities` are `files`, `notifications`, and `storage`; each authorizes all methods of that API. All fields shown under `nesso` and `i18n.metadata` are required. Add the `nesso-plugin` keyword for discovery in Settings → Plugins.
86
+ Declare the operations your action uses in `writes`. The optional permissions listed in `capabilities` are `files`, `notifications`, `storage`, and `ui`. The first three authorize their APIs; `ui` authorizes interactive UI contributions. All fields shown under `nesso` and `i18n.metadata` are required. Add the `nesso-plugin` keyword for discovery in Settings → Plugins.
76
87
 
77
- Labels and metadata use `{ en: string, it?: string, 'zh-CN'?: string }`, with English required as the fallback.
88
+ `i18n.metadata.name` names the plugin in Settings. Each action defines its own `label` for menus, independently of the plugin name. Labels and metadata use `{ en: string, it?: string, 'zh-CN'?: string }`, with English required as the fallback.
78
89
 
79
90
  ### Build and test
80
91
 
81
92
  Run `npm run build`, then follow the example's [local testing instructions](example/README.md#test-an-unpublished-build).
82
93
 
83
- Actions must ship one self-contained browser ES module with dependencies bundled; the example's build handles this. Test and install external plugins in the desktop app.
94
+ Actions ship one browser ES module with dependencies bundled except React and React DOM, which Nesso supplies inside the sandbox. Keep `react`, `react/*`, `react-dom`, and `react-dom/*` external in your bundler; the example's build handles this. The runtime supports React 19. Test and install external plugins in the desktop app.
84
95
 
85
96
  ## Action API
86
97
 
87
98
  Nesso passes `{ document, storage, files, notifications, signal, viewId }` to `run` as `ActionContext`. `document` exposes the shared graph, view membership, and transient selection; `storage` holds the plugin's private data for that document.
88
99
 
89
- `create()` receives no arguments and returns an array of actions with unique lowercase kebab-case IDs, localized labels, optional icons, and `run(context)` handlers. Use `ActionIconName` for supported icons.
100
+ `create()` receives no arguments and returns an array of actions with unique lowercase kebab-case IDs, localized labels, optional icons, and either a `run(context)` handler or a React component in `ui`. The two forms are mutually exclusive. Use `ActionIconName` for supported icons.
90
101
 
91
102
  Keep graph reads and effects inside `run`. **Await every write, file dialog, and notification** before returning; the action ends when `run` finishes. Use `signal` to detect cancellation.
92
103
 
104
+ ### Action UI
105
+
106
+ Declare the `ui` capability and set the action's `ui` property to a React component instead of a `run` handler. Nesso mounts it in an isolated central panel and unmounts it when the session ends.
107
+
108
+ ```tsx
109
+ import { useSyncExternalStore } from 'react'
110
+ import type { ActionContext, ActionContribution } from '@nesso-how/plugin'
111
+
112
+ function Browse({ document }: ActionContext) {
113
+ const state = useSyncExternalStore(document.subscribe, document.getState)
114
+ return (
115
+ <ul>
116
+ {state.viewGraph.concepts.map(({ id, label }) => (
117
+ <li key={id}>{label}</li>
118
+ ))}
119
+ </ul>
120
+ )
121
+ }
122
+
123
+ export const create = (): readonly ActionContribution[] => [
124
+ { id: 'browse', label: { en: 'Browse concepts' }, ui: Browse },
125
+ ]
126
+ ```
127
+
128
+ #### Context
129
+
130
+ Components receive `ActionContext` directly as props, with the same APIs and permissions as `run`. `viewId` and the supplied `viewGraph` refer to the invoked view. Subscribe with `useSyncExternalStore` when rendering snapshot data. Discovery runs `create()` in a Worker, so keep DOM access and effects inside components or `run`, not at module scope or in `create()`. The panel can access its own DOM, but not the host DOM, native bridge, network, or direct persistent storage; use the injected APIs for files and storage.
131
+
132
+ #### Styling
133
+
134
+ Nesso supplies React, the `@nesso-how/ui` component stylesheet, and theme CSS variables such as `var(--background)` and `var(--foreground)`. Import your own CSS normally; the [standalone example](example/) bundles and injects it. Bundle dependencies other than React/React DOM and inline assets; remote or separate assets are not supported. The host does not compile plugin Tailwind classes. Read `locale` from `document.getState()` for translated content. Label inputs and preserve Tab/Shift+Tab navigation.
135
+
136
+ #### Lifecycle
137
+
138
+ Use React effects to clean up subscriptions and resources. Panels have no action execution timeout, but initialization and API requests have deadlines. Uncaught errors or rejected promises fail the session; handle expected errors in your UI. Nesso provides the title, close control, and loading/failure screens. Changing the active view revokes the current panel instance and mounts the same action in a new instance for the selected view, including All. Closing or replacing a panel discards its React state: save progress through `storage` during use, not during cleanup, which is best effort.
139
+
140
+ ### Action badges
141
+
142
+ Add optional `badge(input)` to a `run` or `ui` action. It may return synchronously or asynchronously:
143
+
144
+ ```ts
145
+ badge: ({ viewGraph }) => ({
146
+ value: viewGraph.concepts.length,
147
+ })
148
+ ```
149
+
150
+ - `input`: readonly `viewId` (`null` for All), target `viewGraph`, private document storage `records` (requires `storage`; otherwise empty), and `now` in Unix milliseconds.
151
+ - Return `{ value: number | null, refreshAt?: number }`. `value` is an integer from 0 to 999,999; zero and `null` hide the badge.
152
+ - For time-dependent counts, calculate from `now` and return `refreshAt` as an absolute Unix-millisecond timestamp. Omit it otherwise. Timed refreshes run no more often than every 15 seconds.
153
+
154
+ Runs in an isolated Worker with no action APIs and a 2-second calculation limit. Nesso calculates only visible badges and refreshes them after graph, saved-view, or plugin storage changes. Results are not persisted; failures hide the badge.
155
+
93
156
  ### Read the invoked view
94
157
 
95
158
  - `document.getState()` returns the latest readonly local snapshot synchronously and makes it the basis for subsequent writes.
@@ -100,7 +163,7 @@ The graph snapshot provides:
100
163
 
101
164
  - `viewGraph`: `{ concepts, relations, relationTypes }` for the invoked view.
102
165
  - `selected`: the invoked view's selection.
103
- - `targetViewId`: the invoked view's ID, or `null` for All; navigation does not change the target.
166
+ - `targetViewId`: the invoked view's ID, or `null` for All; fixed for each invocation. Headless actions keep their target during navigation; panels restart with a new invocation when the active view changes.
104
167
  - `activeVocab`: the current vocabulary, or `null`.
105
168
 
106
169
  Concept and relation-type IDs are absolute IRIs. Relations are `{ source, predicate, target }` triples; use `JSON.stringify([source, predicate, target])` as their selection/write ID.
@@ -109,24 +172,24 @@ Concept and relation-type IDs are absolute IRIs. Relations are `{ source, predic
109
172
 
110
173
  Call helpers on `document` and declare their operation kinds in `nesso.writes`:
111
174
 
112
- | Helper | Required `writes` entry |
113
- | --- | --- |
114
- | `setConceptLabel(id, value)` | `concept.label` |
115
- | `setConceptDescription(id, value)` | `concept.description` |
116
- | `setConceptColor(id, value)` | `concept.color` |
117
- | `setConceptBold(id, value)` | `concept.bold` |
118
- | `setConceptItalic(id, value)` | `concept.italic` |
119
- | `setConceptPosition(id, { x, y })` | `concept.position` |
120
- | `setConceptPositions([{ id, position: { x, y } }])` | `concept.positions` |
121
- | `addConcept(position?)` | `concept.add` |
122
- | `removeConcept(id)` | `concept.remove` |
123
- | `connect(source, target)` | `relation.connect` |
124
- | `reconnectRelation(id, source, target)` | `relation.reconnect` |
125
- | `setRelationType(id, typeId)` | `relation.type` |
126
- | `createRelationType(id, label)` | `relation.type.create` |
127
- | `removeRelation(id)` | `relation.remove` |
128
- | `setSelection([{ kind, id }])` | `selection.set` |
129
- | `setViewMembership(viewId, conceptId, included)` | `view.membership` |
175
+ | Helper | Required `writes` entry |
176
+ | --------------------------------------------------- | ----------------------- |
177
+ | `setConceptLabel(id, value)` | `concept.label` |
178
+ | `setConceptNotes(id, value)` | `concept.notes` |
179
+ | `setConceptColor(id, value)` | `concept.color` |
180
+ | `setConceptBold(id, value)` | `concept.bold` |
181
+ | `setConceptItalic(id, value)` | `concept.italic` |
182
+ | `setConceptPosition(id, { x, y })` | `concept.position` |
183
+ | `setConceptPositions([{ id, position: { x, y } }])` | `concept.positions` |
184
+ | `addConcept(position?)` | `concept.add` |
185
+ | `removeConcept(id)` | `concept.remove` |
186
+ | `connect(source, target)` | `relation.connect` |
187
+ | `reconnectRelation(id, source, target)` | `relation.reconnect` |
188
+ | `setRelationType(id, typeId)` | `relation.type` |
189
+ | `createRelationType(id, label)` | `relation.type.create` |
190
+ | `removeRelation(id)` | `relation.remove` |
191
+ | `setSelection([{ kind, id }])` | `selection.set` |
192
+ | `setViewMembership(viewId, conceptId, included)` | `view.membership` |
130
193
 
131
194
  `addConcept` returns the new IRI. New concepts join the active saved view and link to the single selected concept, if any. These links and `connect` use the vocabulary's default relation type. `createRelationType` creates and assigns a type to the given relation.
132
195
 
@@ -138,11 +201,11 @@ The invoked view is **not a write sandbox**: permitted writes can affect the who
138
201
 
139
202
  ### Files, notifications, and failures
140
203
 
141
- | API | Required capability | Result |
142
- | --- | --- | --- |
143
- | `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
144
- | `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
145
- | `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
204
+ | API | Required capability | Result |
205
+ | ------------------------------------------------------------------------------------------------------ | ------------------- | -------------------------------------------------------------------------------- |
206
+ | `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
207
+ | `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
208
+ | `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
146
209
 
147
210
  Files use UTF-8 text and host-managed dialogs or browser downloads; `files` grants no unrestricted filesystem access. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
148
211
 
@@ -177,24 +240,23 @@ Await all storage calls before the action returns. Success means the validated c
177
240
 
178
241
  - A document has a persistent identity outside graph JSON-LD. Resetting it creates a new identity and empty plugin storage; a mismatched saved identity is reported and protected, never silently attached to another document.
179
242
  - Removing a view or changing membership does not delete concept data.
180
- - Deleting a concept retains its records during the current app session so document Undo/Redo can recover it. Private storage changes themselves do not enter graph history.
181
- - On startup, after the document and plugin storage restore successfully, Nesso removes records whose explicit `conceptId` is absent from the graph. Graph history does not survive restart. Cleanup is skipped after failed restoration and does not execute plugin code.
182
- - Put data that should be cleaned with a concept, including its logs, inside concept-associated records. IDs embedded in arbitrary payloads are opaque and cannot be cleaned by the host.
183
- - Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data. Startup reference cleanup still applies even when the plugin is absent.
243
+ - Deleting a concept retains its records, including across restart and backup restoration. Document Undo/Redo can recover the concept during the current app session; private storage changes themselves do not enter graph history.
244
+ - Use concept-associated records to identify a concept's data, including its logs. Plugins may explicitly delete records no longer needed; IDs embedded in arbitrary payloads remain opaque to the host.
245
+ - Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data.
184
246
 
185
247
  #### Limits
186
248
 
187
249
  Storage accepts finite JSON primitives, dense arrays, and plain objects, including `null`; not `undefined`, dates, maps, functions, cyclic data, or custom prototypes. Returned snapshots and stored payloads are independent copies.
188
250
 
189
- | Budget | Limit |
190
- | --- | --- |
191
- | Record, encoded as UTF-8 JSON | 256 KiB |
192
- | Namespace snapshot | 8 MiB |
193
- | Total plugin storage per document | 64 MiB |
194
- | Records per plugin | 10,000 |
195
- | Plugin namespaces per document | 128 |
196
- | Record nesting | 24 levels |
197
- | Record key | 1–128 characters |
251
+ | Budget | Limit |
252
+ | --------------------------------- | ---------------- |
253
+ | Record, encoded as UTF-8 JSON | 256 KiB |
254
+ | Namespace snapshot | 8 MiB |
255
+ | Total plugin storage per document | 64 MiB |
256
+ | Records per plugin | 10,000 |
257
+ | Plugin namespaces per document | 128 |
258
+ | Record nesting | 24 levels |
259
+ | Record key | 1–128 characters |
198
260
 
199
261
  Concept IDs must be absolute IRIs and refer to an existing document concept when writing. Deletes may remove retained orphan records. Keys are logical identifiers, not paths. Normal action channel request, deadline, rate, and cancellation limits also apply.
200
262
 
@@ -206,7 +268,11 @@ Set `nesso.kind` to `"vocab"`, `entry` to a package-local JSON file such as `"di
206
268
  {
207
269
  "id": "my-vocab",
208
270
  "relationTypes": [
209
- { "id": "urn:my-vocab:depends-on", "label": "depends on" }
271
+ {
272
+ "id": "urn:my-vocab:depends-on",
273
+ "label": "depends on",
274
+ "translations": { "en": "depends on", "it": "dipende da", "zh-CN": "依赖于" }
275
+ }
210
276
  ],
211
277
  "defaultTypeId": "urn:my-vocab:depends-on"
212
278
  }
@@ -214,6 +280,8 @@ Set `nesso.kind` to `"vocab"`, `entry` to a package-local JSON file such as `"di
214
280
 
215
281
  Use stable absolute IRIs for relation types and choose a default from your own list. See [Base Vocab](../../plugins/base-vocab/) for a larger example.
216
282
 
283
+ `label` is the canonical label saved in the graph. Optional `translations` provides display labels for `en`, `it`, and `zh-CN`, each nonempty and at most 30 characters. The app resolves the current locale, then English, then `label`, without changing document data. Translations apply only when the type's IRI and canonical label match an installed vocabulary; custom labels remain unchanged. Missing or disabled vocabularies fall back to the stored label.
284
+
217
285
  ## Themes
218
286
 
219
287
  Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use empty `writes` and `capabilities`. A `ThemeDefinition` contains:
@@ -225,4 +293,6 @@ Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use em
225
293
 
226
294
  Only light themes are supported. Use readable text contrast; arbitrary CSS and remote fonts are unsupported.
227
295
 
228
- For the full API and validation rules, see [action types](src/runtime.ts), [graph operations](src/types.ts), and [theme/vocabulary schemas](src/definitions.ts).
296
+ The SDK exposes shared graph and operation types from the internal [`@nesso-how/core`](../core/) package. Trusted renderers use its synchronous store contract; plugins use only the permission-limited asynchronous `ActionContext` above. The published SDK bundles these shared contracts and helpers, so plugin projects need no separate core dependency.
297
+
298
+ For the full API and validation rules, see [action types](src/runtime.ts), [graph operations](../core/src/types.ts), and [theme/vocabulary schemas](src/definitions.ts).
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as createWriteCommands, B as NotificationAction, F as GraphSnapshot, G as SectionId, H as PanelSizes, I as NessoOperation, J as VocabDefinition, K as Selection, L as NessoState, N as LocalizedText, R as NessoStore, U as Preferences, V as Notifications, W as SavedView, Y as WorkspaceState, Z as ThemeDefinition, a as ActionState, b as PluginStorageRecord, c as actionIconNames, i as ActionIconName, j as PluginError, n as ActionContribution, o as PluginI18n, q as Viewport, r as ActionDescriptor, s as PluginManifest, t as ActionContext, v as PluginStorage, y as PluginStorageKey, z as Notification } from "./runtime-BrWPGuBB.js";
2
- export { type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type LocalizedText, type NessoOperation, type NessoState, type NessoStore, type Notification, type NotificationAction, type Notifications, type PanelSizes, PluginError, type PluginI18n, type PluginManifest, type PluginStorage, type PluginStorageKey, type PluginStorageRecord, type Preferences, type SavedView, type SectionId, type Selection, type ThemeDefinition, type Viewport, type VocabDefinition, type WorkspaceState, actionIconNames, createWriteCommands };
1
+ import { B as ThemeDefinition, C as PluginStorage, F as PluginError, G as SavedView, K as Selection, L as LocalizedText, T as PluginStorageRecord, U as GraphSnapshot, W as NessoOperation, a as ActionDescriptor, c as PluginI18n, i as ActionContribution, l as PluginManifest, n as ActionBadgeResult, o as ActionIconName, q as VocabDefinition, r as ActionContext, s as ActionState, t as ActionBadgeInput, u as actionIconNames, w as PluginStorageKey } from "./runtime-BxtTAcko.js";
2
+ export { type ActionBadgeInput, type ActionBadgeResult, type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type LocalizedText, type NessoOperation, PluginError, type PluginI18n, type PluginManifest, type PluginStorage, type PluginStorageKey, type PluginStorageRecord, type SavedView, type Selection, type ThemeDefinition, type VocabDefinition, actionIconNames };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { x as PluginError, t as actionIconNames, b as createWriteCommands } from "./runtime-C-k6OiHL.js";
1
+ export { C as PluginError, t as actionIconNames } from "./runtime-BM45o1qi.js";
@@ -0,0 +1 @@
1
+ export declare function checkMessageSize(value: unknown, limit: number, maximumDepth?: number): void;
@@ -0,0 +1,28 @@
1
+ import { PluginError } from './errors.js';
2
+ export function checkMessageSize(value, limit, maximumDepth = 32) {
3
+ const visit = (value, depth) => {
4
+ if (depth > maximumDepth)
5
+ throw new PluginError('invalid-input', [
6
+ { path: 'message', message: 'Nesting limit exceeded' },
7
+ ]);
8
+ if (value === null)
9
+ return;
10
+ if (typeof value === 'object') {
11
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype)
12
+ throw new PluginError('invalid-input', [
13
+ { path: 'message', message: 'Expected plain data' },
14
+ ]);
15
+ for (const item of Object.values(value))
16
+ visit(item, depth + 1);
17
+ }
18
+ else if (!['string', 'number', 'boolean', 'undefined'].includes(typeof value) ||
19
+ (typeof value === 'number' && !Number.isFinite(value))) {
20
+ throw new PluginError('invalid-input', [
21
+ { path: 'message', message: 'Expected serializable data' },
22
+ ]);
23
+ }
24
+ };
25
+ visit(value, 0);
26
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit)
27
+ throw new PluginError('invalid-input', [{ path: 'message', message: 'Message limit exceeded' }]);
28
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ import type { DeepReadonly, VocabDefinition } from '@nesso-how/core';
3
+ export declare const themeColors: readonly ['background', 'foreground', 'canvas', 'sidebar', 'primary', 'primary-hover', 'primary-foreground', 'muted', 'muted-foreground', 'hover', 'pressed', 'border', 'ring', 'selection-halo', 'node-border', 'edge', 'handle'];
4
+ declare const themeDefinition: z.ZodObject<{
5
+ id: z.ZodString;
6
+ colors: z.ZodObject<{
7
+ background: z.ZodString;
8
+ border: z.ZodString;
9
+ canvas: z.ZodString;
10
+ edge: z.ZodString;
11
+ foreground: z.ZodString;
12
+ handle: z.ZodString;
13
+ hover: z.ZodString;
14
+ muted: z.ZodString;
15
+ "muted-foreground": z.ZodString;
16
+ "node-border": z.ZodString;
17
+ pressed: z.ZodString;
18
+ primary: z.ZodString;
19
+ "primary-foreground": z.ZodString;
20
+ "primary-hover": z.ZodString;
21
+ ring: z.ZodString;
22
+ "selection-halo": z.ZodString;
23
+ sidebar: z.ZodString;
24
+ }, z.core.$strict>;
25
+ metrics: z.ZodObject<{
26
+ 'radius-control': z.ZodNumber;
27
+ 'radius-object': z.ZodNumber;
28
+ 'duration-state': z.ZodNumber;
29
+ }, z.core.$strict>;
30
+ fonts: z.ZodObject<{
31
+ sans: z.ZodObject<{
32
+ faces: z.ZodArray<z.ZodObject<{
33
+ path: z.ZodString;
34
+ weight: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>;
35
+ style: z.ZodEnum<{
36
+ italic: "italic";
37
+ normal: "normal";
38
+ }>;
39
+ unicodeRange: z.ZodOptional<z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>>;
40
+ }, z.core.$strict>>;
41
+ }, z.core.$strict>;
42
+ mono: z.ZodObject<{
43
+ faces: z.ZodArray<z.ZodObject<{
44
+ path: z.ZodString;
45
+ weight: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>;
46
+ style: z.ZodEnum<{
47
+ italic: "italic";
48
+ normal: "normal";
49
+ }>;
50
+ unicodeRange: z.ZodOptional<z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>>;
51
+ }, z.core.$strict>>;
52
+ }, z.core.$strict>;
53
+ }, z.core.$strict>;
54
+ }, z.core.$strict>;
55
+ export declare const vocabRelationType: z.ZodObject<{
56
+ id: z.ZodString;
57
+ label: z.ZodString;
58
+ translations: z.ZodOptional<z.ZodObject<{
59
+ en: z.ZodOptional<z.ZodString>;
60
+ it: z.ZodOptional<z.ZodString>;
61
+ 'zh-CN': z.ZodOptional<z.ZodString>;
62
+ }, z.core.$strict>>;
63
+ }, z.core.$strict>;
64
+ export type ThemeDefinition = DeepReadonly<z.infer<typeof themeDefinition>>;
65
+ export type Definition = ThemeDefinition | VocabDefinition;
66
+ export declare function parseDefinition(kind: 'theme', value: unknown): ThemeDefinition;
67
+ export declare function parseDefinition(kind: 'vocab', value: unknown): VocabDefinition;
68
+ export declare function parseDefinition(kind: 'theme' | 'vocab', value: unknown): Definition;
69
+ export {};
@@ -0,0 +1,124 @@
1
+ import { z } from 'zod';
2
+ import { validateGraph } from '@nesso-how/schema';
3
+ import { parseOrThrow } from './errors.js';
4
+ export const themeColors = [
5
+ 'background',
6
+ 'foreground',
7
+ 'canvas',
8
+ 'sidebar',
9
+ 'primary',
10
+ 'primary-hover',
11
+ 'primary-foreground',
12
+ 'muted',
13
+ 'muted-foreground',
14
+ 'hover',
15
+ 'pressed',
16
+ 'border',
17
+ 'ring',
18
+ 'selection-halo',
19
+ 'node-border',
20
+ 'edge',
21
+ 'handle',
22
+ ];
23
+ const contributionId = z
24
+ .string()
25
+ .max(64)
26
+ .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
27
+ const color = z.string().regex(/^#[\da-fA-F]{6}([\da-fA-F]{2})?$/);
28
+ const fontFace = z.strictObject({
29
+ path: z
30
+ .string()
31
+ .max(240)
32
+ .regex(/^(?:[\w-]+\/)*[\w-]+\.woff2$/),
33
+ weight: z
34
+ .tuple([z.number().int().min(1).max(1000), z.number().int().min(1).max(1000)])
35
+ .refine(([min, max]) => min <= max),
36
+ style: z.enum(['normal', 'italic']),
37
+ unicodeRange: z
38
+ .array(z
39
+ .tuple([z.number().int().min(0).max(0x10ffff), z.number().int().min(0).max(0x10ffff)])
40
+ .refine(([min, max]) => min <= max))
41
+ .min(1)
42
+ .max(64)
43
+ .optional(),
44
+ });
45
+ const font = z.strictObject({ faces: z.array(fontFace).max(32) });
46
+ const luminance = (value) => {
47
+ const channels = [1, 3, 5].map((offset) => parseInt(value.slice(offset, offset + 2), 16) / 255);
48
+ const linear = channels.map((value) => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
49
+ return linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;
50
+ };
51
+ const opaque = (value) => value.length === 7 || value.slice(7).toLowerCase() === 'ff';
52
+ const contrast = (left, right) => (Math.max(luminance(left), luminance(right)) + 0.05) /
53
+ (Math.min(luminance(left), luminance(right)) + 0.05);
54
+ const themeDefinition = z
55
+ .strictObject({
56
+ id: contributionId,
57
+ colors: z.strictObject(Object.fromEntries(themeColors.map((key) => [key, color]))),
58
+ metrics: z.strictObject({
59
+ 'radius-control': z.number().min(0).max(16),
60
+ 'radius-object': z.number().min(0).max(16),
61
+ 'duration-state': z.number().int().min(0).max(300),
62
+ }),
63
+ fonts: z.strictObject({ sans: font, mono: font }),
64
+ })
65
+ .superRefine(({ colors, fonts }, context) => {
66
+ for (const key of ['background', 'canvas', 'sidebar']) {
67
+ if (!opaque(colors[key]) || luminance(colors[key]) < 0.8)
68
+ context.addIssue({
69
+ code: 'custom',
70
+ path: ['colors', key],
71
+ message: 'Expected an opaque light surface',
72
+ });
73
+ if (!opaque(colors.foreground) || contrast(colors.foreground, colors[key]) < 4.5)
74
+ context.addIssue({
75
+ code: 'custom',
76
+ path: ['colors', 'foreground'],
77
+ message: 'Insufficient foreground contrast',
78
+ });
79
+ }
80
+ if (!opaque(colors.primary) ||
81
+ !opaque(colors['primary-foreground']) ||
82
+ contrast(colors.primary, colors['primary-foreground']) < 4.5)
83
+ context.addIssue({
84
+ code: 'custom',
85
+ path: ['colors', 'primary-foreground'],
86
+ message: 'Insufficient primary contrast',
87
+ });
88
+ if (fonts.sans.faces.length + fonts.mono.faces.length > 32)
89
+ context.addIssue({ code: 'custom', path: ['fonts'], message: 'Font face limit exceeded' });
90
+ });
91
+ export const vocabRelationType = z.strictObject({
92
+ id: z.string().min(1).max(2048),
93
+ label: z.string().max(30),
94
+ translations: z
95
+ .strictObject({
96
+ en: z.string().trim().min(1).max(30).optional(),
97
+ it: z.string().trim().min(1).max(30).optional(),
98
+ 'zh-CN': z.string().trim().min(1).max(30).optional(),
99
+ })
100
+ .optional(),
101
+ });
102
+ const vocabDefinition = z
103
+ .strictObject({
104
+ id: contributionId,
105
+ relationTypes: z.array(vocabRelationType).min(1),
106
+ defaultTypeId: z.string().min(1).max(2048),
107
+ })
108
+ .superRefine(({ relationTypes, defaultTypeId }, context) => {
109
+ for (const issue of validateGraph({
110
+ concepts: [],
111
+ relations: [],
112
+ relationTypes: relationTypes.map(({ id, label }) => ({ id, label })),
113
+ }))
114
+ context.addIssue({ code: 'custom', path: ['relationTypes'], message: issue.message });
115
+ if (!relationTypes.some(({ id }) => id === defaultTypeId))
116
+ context.addIssue({
117
+ code: 'custom',
118
+ path: ['defaultTypeId'],
119
+ message: 'Default type must be offered by the vocabulary',
120
+ });
121
+ });
122
+ export function parseDefinition(kind, value) {
123
+ return parseOrThrow(kind === 'theme' ? themeDefinition : vocabDefinition, value);
124
+ }
@@ -0,0 +1,10 @@
1
+ import { NessoError, type ErrorIssue } from '@nesso-how/errors';
2
+ import type { ZodType } from 'zod';
3
+ import type { LocalizedText } from './i18n.ts';
4
+ export declare class PluginError extends NessoError {
5
+ name: string;
6
+ readonly code: string;
7
+ readonly displayMessage?: LocalizedText;
8
+ constructor(code: string, issues: ErrorIssue[], displayMessage?: LocalizedText);
9
+ }
10
+ export declare function parseOrThrow(schema: ZodType, value: unknown, prefix?: string): any;
@@ -0,0 +1,45 @@
1
+ import { NessoError } from '@nesso-how/errors';
2
+ const boundText = (text, limit) => {
3
+ let result = '';
4
+ let bytes = 0;
5
+ const encoder = new TextEncoder();
6
+ for (const character of text) {
7
+ bytes += encoder.encode(character).byteLength;
8
+ if (bytes > limit)
9
+ break;
10
+ result += character;
11
+ }
12
+ return result;
13
+ };
14
+ export class PluginError extends NessoError {
15
+ name = 'PluginError';
16
+ code;
17
+ displayMessage;
18
+ constructor(code, issues, displayMessage) {
19
+ const bounded = issues.slice(0, 32).map(({ path, message }) => ({
20
+ path: boundText(path, 256),
21
+ message: boundText(message, 2048),
22
+ }));
23
+ if (!bounded.length)
24
+ bounded.push({ path: 'plugin', message: 'Plugin request failed' });
25
+ super(bounded);
26
+ this.code = code;
27
+ if (displayMessage)
28
+ this.displayMessage = {
29
+ en: boundText(displayMessage.en, 2048),
30
+ ...(displayMessage.it !== undefined ? { it: boundText(displayMessage.it, 2048) } : {}),
31
+ ...(displayMessage['zh-CN'] !== undefined
32
+ ? { 'zh-CN': boundText(displayMessage['zh-CN'], 2048) }
33
+ : {}),
34
+ };
35
+ }
36
+ }
37
+ export function parseOrThrow(schema, value, prefix = '') {
38
+ const parsed = schema.safeParse(value);
39
+ if (!parsed.success)
40
+ throw new PluginError('invalid-input', parsed.error.issues.map((issue) => ({
41
+ path: `${prefix}${issue.path.join('.')}`,
42
+ message: issue.message,
43
+ })));
44
+ return parsed.data;
45
+ }
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+ export declare const fileTextLimit: number;
3
+ export declare const fileOpenOptions: z.ZodObject<{
4
+ extensions: z.ZodArray<z.ZodString>;
5
+ mimeTypes: z.ZodArray<z.ZodString>;
6
+ }, z.core.$strict>;
7
+ export declare const fileSaveOptions: z.ZodObject<{
8
+ name: z.ZodString;
9
+ mediaType: z.ZodString;
10
+ text: z.ZodString;
11
+ }, z.core.$strict>;
12
+ export declare const fileOpenResult: z.ZodNullable<z.ZodObject<{
13
+ name: z.ZodString;
14
+ mediaType: z.ZodString;
15
+ text: z.ZodString;
16
+ }, z.core.$strict>>;
17
+ export type FileOpenOptions = z.infer<typeof fileOpenOptions>;
18
+ export type FileSaveOptions = z.infer<typeof fileSaveOptions>;
19
+ export type FileOpenResult = z.infer<typeof fileOpenResult>;
20
+ export declare function parseFileOptions<K extends 'open' | 'save'>(kind: K, value: unknown): K extends 'open' ? FileOpenOptions : FileSaveOptions;
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { parseOrThrow } from './errors.js';
3
+ export const fileTextLimit = 16 * 1024 * 1024;
4
+ const mediaType = z
5
+ .string()
6
+ .max(128)
7
+ .regex(/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/);
8
+ export const fileOpenOptions = z.strictObject({
9
+ extensions: z
10
+ .array(z.string().regex(/^[a-zA-Z0-9]{1,16}$/))
11
+ .min(1)
12
+ .max(16),
13
+ mimeTypes: z.array(mediaType).max(16),
14
+ });
15
+ export const fileSaveOptions = z.strictObject({
16
+ name: z
17
+ .string()
18
+ .trim()
19
+ .min(1)
20
+ .max(240)
21
+ .regex(/^[^/\\]+$/)
22
+ .refine((value) => value !== '.' &&
23
+ value !== '..' &&
24
+ [...value].every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)),
25
+ mediaType,
26
+ text: z
27
+ .string()
28
+ .max(fileTextLimit)
29
+ .refine((value) => new TextEncoder().encode(value).byteLength <= fileTextLimit, 'File text byte limit exceeded'),
30
+ });
31
+ export const fileOpenResult = z
32
+ .strictObject({ name: z.string().min(1).max(240), mediaType, text: fileSaveOptions.shape.text })
33
+ .nullable();
34
+ export function parseFileOptions(kind, value) {
35
+ return parseOrThrow(kind === 'open' ? fileOpenOptions : fileSaveOptions, value);
36
+ }
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+ import type { Locale } from '@nesso-how/i18n';
3
+ export type LocalizedText = Readonly<{
4
+ en: string;
5
+ } & Partial<Record<Locale, string>>>;
6
+ export declare const text: (limit: number) => z.ZodString;
7
+ export declare const localizedText: (limit: number) => z.ZodObject<{
8
+ en: z.ZodString;
9
+ it: z.ZodOptional<z.ZodString>;
10
+ 'zh-CN': z.ZodOptional<z.ZodString>;
11
+ }, z.core.$strict>;
12
+ export declare const resolvePluginText: (value: LocalizedText, locale: Locale) => string;