@nesso-how/plugin 0.5.0 → 0.7.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 +102 -58
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node/data.d.ts +1 -0
- package/dist/node/data.js +39 -0
- package/dist/node/definitions.d.ts +69 -0
- package/dist/node/definitions.js +124 -0
- package/dist/node/errors.d.ts +12 -0
- package/dist/node/errors.js +60 -0
- package/dist/node/files.d.ts +25 -0
- package/dist/node/files.js +53 -0
- package/dist/node/i18n.d.ts +12 -0
- package/dist/node/i18n.js +11 -0
- package/dist/node/images.d.ts +11 -0
- package/dist/node/images.js +10 -0
- package/dist/node/index.d.ts +7 -0
- package/dist/node/index.js +2 -0
- package/dist/node/package.d.ts +34 -0
- package/dist/node/package.js +224 -0
- package/dist/node/runtime.d.ts +586 -0
- package/dist/node/runtime.js +511 -0
- package/dist/node/storage.d.ts +72 -0
- package/dist/node/storage.js +71 -0
- package/dist/node/theme-fonts.d.ts +2 -0
- package/dist/node/theme-fonts.js +11 -0
- package/dist/package.d.ts +1 -1
- package/dist/package.js +1 -1
- package/dist/{runtime-CJPU4o4h.js → runtime-D6GosMdU.js} +375 -252
- package/dist/{runtime-D4jO7tbm.d.ts → runtime-DGDBGkWs.d.ts} +228 -133
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +1 -1
- package/example/README.md +5 -2
- package/example/package.json +37 -19
- package/example/src/Quiz.css +50 -8
- package/example/src/Quiz.tsx +29 -8
- package/example/src/index.ts +7 -5
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -33,11 +33,13 @@ export const create = (): readonly ActionContribution[] => {
|
|
|
33
33
|
run: async ({ document }) => {
|
|
34
34
|
const state = document.getState()
|
|
35
35
|
|
|
36
|
-
const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
36
|
+
const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(
|
|
37
|
+
({ id, label }) => ({
|
|
38
|
+
kind: 'concept.label',
|
|
39
|
+
id,
|
|
40
|
+
value: label.toUpperCase(),
|
|
41
|
+
}),
|
|
42
|
+
)
|
|
41
43
|
|
|
42
44
|
await document.applyOperations(operations)
|
|
43
45
|
},
|
|
@@ -65,7 +67,7 @@ Keep the example's build configuration and set these fields in `package.json`:
|
|
|
65
67
|
"version": "1.0.0",
|
|
66
68
|
"keywords": ["nesso-plugin"],
|
|
67
69
|
"nesso": {
|
|
68
|
-
"apiVersion":
|
|
70
|
+
"apiVersion": 2,
|
|
69
71
|
"kind": "actions",
|
|
70
72
|
"entry": "dist/index.js",
|
|
71
73
|
"writes": ["concept.label"],
|
|
@@ -83,6 +85,8 @@ Keep the example's build configuration and set these fields in `package.json`:
|
|
|
83
85
|
|
|
84
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.
|
|
85
87
|
|
|
88
|
+
API version, npm SDK version, host storage envelope version, and private payload versions remain independent: bump only what your change affects.
|
|
89
|
+
|
|
86
90
|
`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.
|
|
87
91
|
|
|
88
92
|
### Build and test
|
|
@@ -109,7 +113,13 @@ import type { ActionContext, ActionContribution } from '@nesso-how/plugin'
|
|
|
109
113
|
|
|
110
114
|
function Browse({ document }: ActionContext) {
|
|
111
115
|
const state = useSyncExternalStore(document.subscribe, document.getState)
|
|
112
|
-
return
|
|
116
|
+
return (
|
|
117
|
+
<ul>
|
|
118
|
+
{state.viewGraph.concepts.map(({ id, label }) => (
|
|
119
|
+
<li key={id}>{label}</li>
|
|
120
|
+
))}
|
|
121
|
+
</ul>
|
|
122
|
+
)
|
|
113
123
|
}
|
|
114
124
|
|
|
115
125
|
export const create = (): readonly ActionContribution[] => [
|
|
@@ -127,7 +137,23 @@ Nesso supplies React, the `@nesso-how/ui` component stylesheet, and theme CSS va
|
|
|
127
137
|
|
|
128
138
|
#### Lifecycle
|
|
129
139
|
|
|
130
|
-
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. Closing or replacing a panel discards its React state: save progress through `storage` during use, not during cleanup, which is best effort.
|
|
140
|
+
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 channel and context and mounts a fresh React instance for the selected view, including All, while reusing the sandbox and loaded modules. Closing or replacing a panel discards its React state: save progress through `storage` during use, not during cleanup, which is best effort.
|
|
141
|
+
|
|
142
|
+
### Action badges
|
|
143
|
+
|
|
144
|
+
Add optional `badge(input)` to a `run` or `ui` action. It may return synchronously or asynchronously:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
badge: ({ viewGraph }) => ({
|
|
148
|
+
value: viewGraph.concepts.length,
|
|
149
|
+
})
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
- `input`: readonly `viewId` (`null` for All), target `viewGraph`, private document storage `records` (requires `storage`; otherwise empty), and `now` in Unix milliseconds.
|
|
153
|
+
- Return `{ value: number | null, refreshAt?: number }`. `value` is an integer from 0 to 999,999; zero and `null` hide the badge.
|
|
154
|
+
- 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.
|
|
155
|
+
|
|
156
|
+
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.
|
|
131
157
|
|
|
132
158
|
### Read the invoked view
|
|
133
159
|
|
|
@@ -139,7 +165,7 @@ The graph snapshot provides:
|
|
|
139
165
|
|
|
140
166
|
- `viewGraph`: `{ concepts, relations, relationTypes }` for the invoked view.
|
|
141
167
|
- `selected`: the invoked view's selection.
|
|
142
|
-
- `targetViewId`: the invoked view's ID, or `null` for All; navigation
|
|
168
|
+
- `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.
|
|
143
169
|
- `activeVocab`: the current vocabulary, or `null`.
|
|
144
170
|
|
|
145
171
|
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.
|
|
@@ -148,42 +174,46 @@ Concept and relation-type IDs are absolute IRIs. Relations are `{ source, predic
|
|
|
148
174
|
|
|
149
175
|
Call helpers on `document` and declare their operation kinds in `nesso.writes`:
|
|
150
176
|
|
|
151
|
-
| Helper
|
|
152
|
-
|
|
|
153
|
-
| `setConceptLabel(id, value)`
|
|
154
|
-
| `
|
|
155
|
-
| `setConceptColor(id, value)`
|
|
156
|
-
| `setConceptBold(id, value)`
|
|
157
|
-
| `setConceptItalic(id, value)`
|
|
158
|
-
| `setConceptPosition(id, { x, y })`
|
|
159
|
-
| `setConceptPositions([{ id, position: { x, y } }])` | `concept.positions`
|
|
160
|
-
| `addConcept(position?)`
|
|
161
|
-
| `removeConcept(id)`
|
|
162
|
-
| `connect(source, target)`
|
|
163
|
-
| `reconnectRelation(id, source, target)`
|
|
164
|
-
| `setRelationType(id, typeId)`
|
|
165
|
-
| `createRelationType(id, label)`
|
|
166
|
-
| `removeRelation(id)`
|
|
167
|
-
| `setSelection([{ kind, id }])`
|
|
168
|
-
| `setViewMembership(viewId, conceptId, included)`
|
|
177
|
+
| Helper | Required `writes` entry |
|
|
178
|
+
| --------------------------------------------------- | ----------------------- |
|
|
179
|
+
| `setConceptLabel(id, value)` | `concept.label` |
|
|
180
|
+
| `setConceptNotes(id, value)` | `concept.notes` |
|
|
181
|
+
| `setConceptColor(id, value)` | `concept.color` |
|
|
182
|
+
| `setConceptBold(id, value)` | `concept.bold` |
|
|
183
|
+
| `setConceptItalic(id, value)` | `concept.italic` |
|
|
184
|
+
| `setConceptPosition(id, { x, y })` | `concept.position` |
|
|
185
|
+
| `setConceptPositions([{ id, position: { x, y } }])` | `concept.positions` |
|
|
186
|
+
| `addConcept(position?)` | `concept.add` |
|
|
187
|
+
| `removeConcept(id)` | `concept.remove` |
|
|
188
|
+
| `connect(source, target)` | `relation.connect` |
|
|
189
|
+
| `reconnectRelation(id, source, target)` | `relation.reconnect` |
|
|
190
|
+
| `setRelationType(id, typeId)` | `relation.type` |
|
|
191
|
+
| `createRelationType(id, label)` | `relation.type.create` |
|
|
192
|
+
| `removeRelation(id)` | `relation.remove` |
|
|
193
|
+
| `setSelection([{ kind, id }])` | `selection.set` |
|
|
194
|
+
| `setViewMembership(viewId, conceptId, included)` | `view.membership` |
|
|
169
195
|
|
|
170
196
|
`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.
|
|
171
197
|
|
|
172
|
-
For related edits, use `document.applyOperations(operations)` as in the quickstart. The entire batch succeeds or changes nothing. Separate calls are separate transactions. Raw `concept.add` operations require an explicit new absolute IRI.
|
|
198
|
+
For related edits, use `document.applyOperations(operations)` as in the quickstart. The entire batch succeeds or changes nothing. Editing, reconnecting, retyping, or removing an unknown concept or relation rejects the batch, as does reconnecting or retyping onto an existing relation; removing an item already removed earlier in the same batch, such as a relation of a removed concept, is allowed. Separate calls are separate transactions. Raw `concept.add` operations require an explicit new absolute IRI.
|
|
173
199
|
|
|
174
200
|
Every write checks against the last snapshot you read, or the initial snapshot if you haven't read one. Successful writes advance that baseline, so awaited sequential writes work normally. Incoming updates alone do not advance it. A conflict rejects with `stale-state`; let the failure propagate so Nesso can ask the user to run the action again. Never retry mutations automatically or read a new snapshot just to submit edits calculated from old data.
|
|
175
201
|
|
|
176
202
|
The invoked view is **not a write sandbox**: permitted writes can affect the whole document. Only the operations listed above are available to plugins.
|
|
177
203
|
|
|
178
|
-
### Files, notifications, and failures
|
|
204
|
+
### Files, images, notifications, and failures
|
|
205
|
+
|
|
206
|
+
| API | Required capability | Result |
|
|
207
|
+
| ------------------------------------------------------------------------------------------------------ | ------------------- | -------------------------------------------------------------------------------- |
|
|
208
|
+
| `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
|
|
209
|
+
| `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
|
|
210
|
+
| `files.save({ name: 'graph.png', mediaType: 'image/png', base64 })` | `files` | `{ saved: boolean }`; the host decodes canonical base64 before saving. |
|
|
211
|
+
| `images.renderView({ format: 'png', scale: 2 })` | `images` | `{ mediaType: 'image/png', base64 }` for the invoked view. |
|
|
212
|
+
| `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
|
|
179
213
|
|
|
180
|
-
|
|
181
|
-
| --- | --- | --- |
|
|
182
|
-
| `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
|
|
183
|
-
| `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
|
|
184
|
-
| `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
|
|
214
|
+
File saves accept exactly one of UTF-8 `text` or canonical `base64` (without a data URL prefix), with a 16 MiB decoded byte limit. File opening remains UTF-8 text only. Host-managed dialogs or browser downloads grant no unrestricted filesystem access. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
|
|
185
215
|
|
|
186
|
-
|
|
216
|
+
`images.renderView` captures the invoked view with the current theme and fonts, without selection or canvas controls. Scale defaults to `2`, or accepts `4`. Empty or oversized images fail rather than silently downscaling (8192 pixels per side, 16,777,216 pixels total, 16 MiB PNG). Save the result separately with `files.save({ name: 'view.png', ...image })`; this also requires `files`.
|
|
187
217
|
|
|
188
218
|
Failures throw `PluginError` with `code` and `{ path, message }[]` issues. Let them propagate instead of reporting success. Files and notifications cannot be rolled back with graph edits.
|
|
189
219
|
|
|
@@ -194,19 +224,26 @@ Declare `storage` to read, write, or delete your plugin's private data. Nesso de
|
|
|
194
224
|
```ts
|
|
195
225
|
const records = await storage.list()
|
|
196
226
|
|
|
197
|
-
await storage.set(
|
|
227
|
+
await storage.set(
|
|
228
|
+
'progress',
|
|
229
|
+
{ attempts: 1, answers: ['good'] },
|
|
230
|
+
{ kind: 'concept', id: concept.id },
|
|
231
|
+
)
|
|
198
232
|
await storage.set('settings', { enabled: true })
|
|
199
|
-
|
|
233
|
+
if (viewId !== null)
|
|
234
|
+
await storage.set('notes', { text: 'Project ideas' }, { kind: 'view', id: viewId })
|
|
235
|
+
await storage.delete('progress', { kind: 'concept', id: concept.id })
|
|
200
236
|
```
|
|
201
237
|
|
|
202
|
-
`storage.list()` returns all records as an array. Each record has a `key`, a JSON `value`, and
|
|
238
|
+
`storage.list()` returns all records as an array, including records associated with deleted concepts or views. Each record has a `key`, a JSON `value`, and an optional `scope`:
|
|
203
239
|
|
|
204
|
-
- Without `
|
|
205
|
-
- With `
|
|
206
|
-
-
|
|
240
|
+
- Without `scope`, the record belongs to the document, for example plugin configuration or notes for Overview (`viewId === null`).
|
|
241
|
+
- With `{ kind: 'concept', id }`, it belongs to that concept. Its data is shared across all views containing the concept.
|
|
242
|
+
- With `{ kind: 'view', id }`, it belongs to that saved view, independently of its name or membership. Use a non-null `viewId`.
|
|
243
|
+
- Scopes identify records within the same plugin/document namespace; they do not create separate namespaces or revision baselines. The same key can be used at document scope and for different concepts and views, including a concept and view with the same ID.
|
|
207
244
|
- Payloads belong to the plugin: the host does not interpret their fields or implement domain logic.
|
|
208
245
|
|
|
209
|
-
`storage.set(key, value,
|
|
246
|
+
`storage.set(key, value, scope?)` saves one record and `storage.delete(key, scope?)` removes one. Set requires the referenced concept or saved view to exist. Concept IDs must be absolute IRIs; view IDs are opaque identifiers. Delete also accepts references to deleted entities so plugins can explicitly remove orphan records. Each call is a single transaction returning `true` when storage changed and `false` for valid net-no-op writes, such as saving an identical value or deleting a missing record. Failed writes throw instead of returning `false`.
|
|
210
247
|
|
|
211
248
|
The SDK tracks storage revisions internally. Every mutation checks against the last listed snapshot or the preceding successful mutation. If you haven't listed storage, the first mutation reads its baseline automatically. Concurrent changes reject stale writes with `stale-state`, without refreshing the baseline or retrying automatically. List storage again before recomputing edits; never refresh just to resubmit edits calculated from old data. Document reads do not refresh the storage baseline, and storage writes do not invalidate the document snapshot. Document edits and private storage calls are separate transactions.
|
|
212
249
|
|
|
@@ -215,25 +252,24 @@ Await all storage calls before the action returns. Success means the validated c
|
|
|
215
252
|
#### Data lifecycle
|
|
216
253
|
|
|
217
254
|
- 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.
|
|
218
|
-
-
|
|
219
|
-
- Deleting a concept retains its records
|
|
220
|
-
-
|
|
221
|
-
-
|
|
222
|
-
- Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data. Startup reference cleanup still applies even when the plugin is absent.
|
|
255
|
+
- Renaming a view or changing membership does not affect scoped records. Removing a view does not delete concept data.
|
|
256
|
+
- Deleting a concept or saved view retains its records, including across restart and backup restoration. Document Undo/Redo can recover the entity during the current app session, reconnecting its records by the same ID; private storage changes themselves do not enter graph history. Creating a different entity with the same name does not reconnect old records.
|
|
257
|
+
- Use explicit scopes to identify concept or view data, including logs. Plugins own payload schemas and any explicit cleanup; the host does not automatically purge orphan records. IDs embedded in arbitrary keys or payloads remain opaque to the host.
|
|
258
|
+
- Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data.
|
|
223
259
|
|
|
224
260
|
#### Limits
|
|
225
261
|
|
|
226
262
|
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.
|
|
227
263
|
|
|
228
|
-
| Budget
|
|
229
|
-
|
|
|
230
|
-
| Record, encoded as UTF-8 JSON
|
|
231
|
-
| Namespace snapshot
|
|
232
|
-
| Total plugin storage per document | 64 MiB
|
|
233
|
-
| Records per plugin
|
|
234
|
-
| Plugin namespaces per document
|
|
235
|
-
| Record nesting
|
|
236
|
-
| Record key
|
|
264
|
+
| Budget | Limit |
|
|
265
|
+
| --------------------------------- | ---------------- |
|
|
266
|
+
| Record, encoded as UTF-8 JSON | 256 KiB |
|
|
267
|
+
| Namespace snapshot | 8 MiB |
|
|
268
|
+
| Total plugin storage per document | 64 MiB |
|
|
269
|
+
| Records per plugin | 10,000 |
|
|
270
|
+
| Plugin namespaces per document | 128 |
|
|
271
|
+
| Record nesting | 24 levels |
|
|
272
|
+
| Record key | 1–128 characters |
|
|
237
273
|
|
|
238
274
|
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.
|
|
239
275
|
|
|
@@ -245,7 +281,11 @@ Set `nesso.kind` to `"vocab"`, `entry` to a package-local JSON file such as `"di
|
|
|
245
281
|
{
|
|
246
282
|
"id": "my-vocab",
|
|
247
283
|
"relationTypes": [
|
|
248
|
-
{
|
|
284
|
+
{
|
|
285
|
+
"id": "urn:my-vocab:depends-on",
|
|
286
|
+
"label": "depends on",
|
|
287
|
+
"translations": { "en": "depends on", "it": "dipende da", "zh-CN": "依赖于" }
|
|
288
|
+
}
|
|
249
289
|
],
|
|
250
290
|
"defaultTypeId": "urn:my-vocab:depends-on"
|
|
251
291
|
}
|
|
@@ -253,6 +293,8 @@ Set `nesso.kind` to `"vocab"`, `entry` to a package-local JSON file such as `"di
|
|
|
253
293
|
|
|
254
294
|
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.
|
|
255
295
|
|
|
296
|
+
`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.
|
|
297
|
+
|
|
256
298
|
## Themes
|
|
257
299
|
|
|
258
300
|
Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use empty `writes` and `capabilities`. A `ThemeDefinition` contains:
|
|
@@ -264,4 +306,6 @@ Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use em
|
|
|
264
306
|
|
|
265
307
|
Only light themes are supported. Use readable text contrast; arbitrary CSS and remote fonts are unsupported.
|
|
266
308
|
|
|
267
|
-
|
|
309
|
+
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.
|
|
310
|
+
|
|
311
|
+
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 {
|
|
2
|
-
export { type
|
|
1
|
+
import { B as LocalizedText, C as PluginStorage, E as PluginStorageScope, I as ImageRenderOptions, J as SavedView, K as GraphSnapshot, L as RenderedImage, R as PluginError, T as PluginStorageRecord, U as ThemeDefinition, X as VocabDefinition, Y as Selection, a as ActionDescriptor, c as PluginI18n, i as ActionContribution, l as PluginManifest, n as ActionBadgeResult, o as ActionIconName, q as NessoOperation, r as ActionContext, s as ActionState, t as ActionBadgeInput, u as actionIconNames, w as PluginStorageKey } from "./runtime-DGDBGkWs.js";
|
|
2
|
+
export { type ActionBadgeInput, type ActionBadgeResult, type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type ImageRenderOptions, type LocalizedText, type NessoOperation, PluginError, type PluginI18n, type PluginManifest, type PluginStorage, type PluginStorageKey, type PluginStorageRecord, type PluginStorageScope, type RenderedImage, type SavedView, type Selection, type ThemeDefinition, type VocabDefinition, actionIconNames };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { C as PluginError, t as actionIconNames } from "./runtime-D6GosMdU.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function checkMessageSize(value: unknown, limit: number, maximumDepth?: number): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { PluginError } from './errors.js';
|
|
2
|
+
export function checkMessageSize(value, limit, maximumDepth = 32) {
|
|
3
|
+
const exceeded = () => new PluginError('invalid-input', [{ path: 'message', message: 'Message limit exceeded' }]);
|
|
4
|
+
let size = 0;
|
|
5
|
+
const visit = (value, depth) => {
|
|
6
|
+
if (depth > maximumDepth)
|
|
7
|
+
throw new PluginError('invalid-input', [
|
|
8
|
+
{ path: 'message', message: 'Nesting limit exceeded' },
|
|
9
|
+
]);
|
|
10
|
+
if (value === undefined)
|
|
11
|
+
return;
|
|
12
|
+
size += typeof value === 'string' ? value.length + 1 : 1;
|
|
13
|
+
if (size > limit)
|
|
14
|
+
throw exceeded();
|
|
15
|
+
if (value === null)
|
|
16
|
+
return;
|
|
17
|
+
if (typeof value === 'object') {
|
|
18
|
+
const array = Array.isArray(value);
|
|
19
|
+
if (!array && Object.getPrototypeOf(value) !== Object.prototype)
|
|
20
|
+
throw new PluginError('invalid-input', [
|
|
21
|
+
{ path: 'message', message: 'Expected plain data' },
|
|
22
|
+
]);
|
|
23
|
+
for (const [key, item] of Object.entries(value)) {
|
|
24
|
+
if (!array && item !== undefined)
|
|
25
|
+
size += key.length;
|
|
26
|
+
visit(item, depth + 1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
else if (!['string', 'number', 'boolean'].includes(typeof value) ||
|
|
30
|
+
(typeof value === 'number' && !Number.isFinite(value))) {
|
|
31
|
+
throw new PluginError('invalid-input', [
|
|
32
|
+
{ path: 'message', message: 'Expected serializable data' },
|
|
33
|
+
]);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
visit(value, 0);
|
|
37
|
+
if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit)
|
|
38
|
+
throw exceeded();
|
|
39
|
+
}
|
|
@@ -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,12 @@
|
|
|
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 const pluginErrorCodes: readonly ['invalid-input', 'denied', 'stale-state', 'stale-context', 'unavailable', 'cancelled', 'timeout', 'closed', 'failed'];
|
|
5
|
+
export declare function pluginErrorCode(error: unknown): "cancelled" | "closed" | "denied" | "failed" | "invalid-input" | "stale-context" | "stale-state" | "timeout" | "unavailable";
|
|
6
|
+
export declare class PluginError extends NessoError {
|
|
7
|
+
name: string;
|
|
8
|
+
readonly code: string;
|
|
9
|
+
readonly displayMessage?: LocalizedText;
|
|
10
|
+
constructor(code: string, issues: ErrorIssue[], displayMessage?: LocalizedText);
|
|
11
|
+
}
|
|
12
|
+
export declare function parseOrThrow(schema: ZodType, value: unknown, prefix?: string): any;
|
|
@@ -0,0 +1,60 @@
|
|
|
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 const pluginErrorCodes = [
|
|
15
|
+
'invalid-input',
|
|
16
|
+
'denied',
|
|
17
|
+
'stale-state',
|
|
18
|
+
'stale-context',
|
|
19
|
+
'unavailable',
|
|
20
|
+
'cancelled',
|
|
21
|
+
'timeout',
|
|
22
|
+
'closed',
|
|
23
|
+
'failed',
|
|
24
|
+
];
|
|
25
|
+
export function pluginErrorCode(error) {
|
|
26
|
+
const code = error instanceof Error && 'code' in error ? error.code : undefined;
|
|
27
|
+
return pluginErrorCodes.find((known) => known === code) ?? 'failed';
|
|
28
|
+
}
|
|
29
|
+
export class PluginError extends NessoError {
|
|
30
|
+
name = 'PluginError';
|
|
31
|
+
code;
|
|
32
|
+
displayMessage;
|
|
33
|
+
constructor(code, issues, displayMessage) {
|
|
34
|
+
const bounded = issues.slice(0, 32).map(({ path, message }) => ({
|
|
35
|
+
path: boundText(path, 256),
|
|
36
|
+
message: boundText(message, 2048),
|
|
37
|
+
}));
|
|
38
|
+
if (!bounded.length)
|
|
39
|
+
bounded.push({ path: 'plugin', message: 'Plugin request failed' });
|
|
40
|
+
super(bounded);
|
|
41
|
+
this.code = code;
|
|
42
|
+
if (displayMessage)
|
|
43
|
+
this.displayMessage = {
|
|
44
|
+
en: boundText(displayMessage.en, 2048),
|
|
45
|
+
...(displayMessage.it !== undefined ? { it: boundText(displayMessage.it, 2048) } : {}),
|
|
46
|
+
...(displayMessage['zh-CN'] !== undefined
|
|
47
|
+
? { 'zh-CN': boundText(displayMessage['zh-CN'], 2048) }
|
|
48
|
+
: {}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function parseOrThrow(schema, value, prefix = '') {
|
|
53
|
+
const parsed = schema.safeParse(value);
|
|
54
|
+
if (!parsed.success)
|
|
55
|
+
throw new PluginError('invalid-input', parsed.error.issues.map((issue) => ({
|
|
56
|
+
path: `${prefix}${issue.path.join('.')}`,
|
|
57
|
+
message: issue.message,
|
|
58
|
+
})));
|
|
59
|
+
return parsed.data;
|
|
60
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
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 fileBase64: z.ZodString;
|
|
8
|
+
export declare const fileSaveOptions: z.ZodUnion<readonly [z.ZodObject<{
|
|
9
|
+
name: z.ZodString;
|
|
10
|
+
mediaType: z.ZodString;
|
|
11
|
+
text: z.ZodString;
|
|
12
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
13
|
+
name: z.ZodString;
|
|
14
|
+
mediaType: z.ZodString;
|
|
15
|
+
base64: z.ZodString;
|
|
16
|
+
}, z.core.$strict>]>;
|
|
17
|
+
export declare const fileOpenResult: z.ZodNullable<z.ZodObject<{
|
|
18
|
+
name: z.ZodString;
|
|
19
|
+
mediaType: z.ZodString;
|
|
20
|
+
text: z.ZodString;
|
|
21
|
+
}, z.core.$strict>>;
|
|
22
|
+
export type FileOpenOptions = z.infer<typeof fileOpenOptions>;
|
|
23
|
+
export type FileSaveOptions = z.infer<typeof fileSaveOptions>;
|
|
24
|
+
export type FileOpenResult = z.infer<typeof fileOpenResult>;
|
|
25
|
+
export declare function parseFileOptions<K extends 'open' | 'save'>(kind: K, value: unknown): K extends 'open' ? FileOpenOptions : FileSaveOptions;
|