@deviltea/widget-core 0.0.5 → 0.1.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
@@ -3,6 +3,8 @@
3
3
  Cross-cutting Diagnostic/Result/Failure/Error conventions are maintained in
4
4
  [Widget API conventions](https://github.com/DevilTea/widget/blob/main/docs/architecture/widget-api-conventions.md).
5
5
 
6
+ > **Upgrading from 0.0.x?** Follow the [migration guide to 0.1](https://deviltea.github.io/widget/migration/0.1).
7
+
6
8
  > ESM-only package.
7
9
 
8
10
  [![npm version][npm-version-src]][npm-version-href]
@@ -31,6 +33,18 @@ yarn add @deviltea/widget-core
31
33
  pnpm add @deviltea/widget-core
32
34
  ```
33
35
 
36
+ Requires Node.js `>=22.14.0` (or any ES2022 runtime with a global
37
+ `queueMicrotask`; a host with an isolated-error handler can do without it, see
38
+ [Host requirements](#host-requirements)).
39
+
40
+ While the package is `0.x`, a breaking change bumps the **minor** version
41
+ (`0.N.0`), so use a `^0.N.0` range. Core recognizes its own plugins, Blueprints
42
+ and Runtimes by brands private to one loaded copy of the module, so an
43
+ application must load exactly one copy. A library that ships plugins or a
44
+ renderer adapter must declare `@deviltea/widget-core` as a **peer dependency**
45
+ (not a regular dependency) and must not bundle it; `@deviltea/widget-vue` and
46
+ `@deviltea/widget-inspector` do the same.
47
+
34
48
  ## Core model
35
49
 
36
50
  ```text
@@ -55,22 +69,36 @@ contract described below. See
55
69
  [Design constraints](https://deviltea.github.io/widget/packages/widget-core#design-constraints)
56
70
  in the full guide for the exact boundary.
57
71
 
58
- Capability presence (`config`/`slots`/`state`/`properties`/`methods`) is
59
- declaration presence, independent of whether a capability's own domain is
72
+ Capability presence (`config`/`slots`/`state`/`properties`/`methods`/`events`)
73
+ is declaration presence, independent of whether a capability's own domain is
60
74
  empty — a completed plugin exposes these facts at runtime as
61
- `plugin.capabilities: { config, slots, state, properties, methods }`
75
+ `plugin.capabilities: { config, slots, state, properties, methods, events }`
62
76
  (all `boolean`, immutable). See
63
77
  [Reading capability presence at runtime](https://deviltea.github.io/widget/packages/widget-core#reading-capability-presence-at-runtime-plugin-capabilities)
64
78
  in the full guide.
65
79
 
66
- `createWidgetSystem` rejects invalid plugin registration with the coded
67
- `WidgetSystemConfigurationError`: `foreign-plugin` (entry not created by this
68
- loaded module instance; fields `pluginIndex`, `pluginType`, with
69
- `firstPluginIndex` always `null`) and `duplicate-plugin-type` (fields
70
- `pluginIndex`, `pluginType`, `firstPluginIndex`).
80
+ The phase order of `createWidgetPlugin` is
81
+ `description → interfaces → config? → slots? → structure? → state? → properties? → methods? → events? → done`.
82
+ `.structure(validateStructure)` is an optional plugin-level structure validator
83
+ available to every plugin (it is not a capability); `.slots(definitions)` takes
84
+ only the slot definitions. Declarations are validated when the plugin is built,
85
+ so a malformed member throws a `TypeError` naming the plugin, section, member
86
+ and field.
87
+
88
+ `createWidgetSystem` rejects invalid options and plugin registration with the
89
+ coded `WidgetSystemConfigurationError`: `invalid-options` (options not an
90
+ object, `plugins` not an array, or a non-function `validateStructure`),
91
+ `foreign-plugin` (entry not created by this loaded module instance; fields
92
+ `pluginIndex`, `pluginType`, with `firstPluginIndex` always `null`) and
93
+ `duplicate-plugin-type` (fields `pluginIndex`, `pluginType`,
94
+ `firstPluginIndex`). The System exposes `plugins`, `catalog`, `validateStructure`
95
+ and `getPlugin(type)`, which returns `null` for an unregistered type.
71
96
  Inspection entries throw `WidgetInspectionError` (`@deviltea/widget-core/inspection`)
72
97
  and `getWidgetEventEmitter` throws `WidgetIntegrationError`
73
- (`@deviltea/widget-core/integration`, code `foreign-runtime`) for foreign inputs.
98
+ (`@deviltea/widget-core/integration`, code `foreign-runtime`) for foreign inputs;
99
+ `assertCoreRuntime(runtime)` from the same subpath performs only that passive
100
+ provenance check, so a renderer adapter can fail fast at mount when it and the
101
+ application loaded two copies of Core.
74
102
  See
75
103
  [Plugin registration errors](https://deviltea.github.io/widget/packages/widget-core#plugin-registration-errors)
76
104
  in the full guide.
@@ -91,8 +119,12 @@ Runtime state.
91
119
  ## Usage
92
120
 
93
121
  Here is a complete widget: one plugin with `state`, `properties`, and
94
- `methods`, registered into a system, compiled, and run.
122
+ `methods`, registered into a system, compiled, and run. The
123
+ [full guide](https://deviltea.github.io/widget/packages/widget-core#quick-start)
124
+ has a larger end-to-end example with config, slots, an Event, and a container
125
+ that aggregates its children.
95
126
 
127
+ <!-- sample: usage run -->
96
128
  ```typescript
97
129
  import { createWidgetPlugin, createWidgetSystem } from '@deviltea/widget-core'
98
130
 
@@ -183,7 +215,7 @@ const unsubscribe = widget.properties.doubled.subscribe((result) => {
183
215
  console.log('doubled changed ->', result) // { ok: true, value: ... }
184
216
  })
185
217
 
186
- widget.methods.increment(5) // -> { ok: true, value: 5 }
218
+ console.log(widget.methods.increment(5)) // { ok: true, value: 5 }
187
219
  widget.state.count.get() // -> 5
188
220
  widget.properties.doubled.get() // -> { ok: true, value: 10 }
189
221
 
@@ -197,15 +229,32 @@ runtime.dispose()
197
229
  ### Blueprint diagnostics
198
230
 
199
231
  `createBlueprint` accepts `unknown`; malformed input never throws — it always
200
- produces an inspectable Blueprint. Every diagnostic has top-level `code`,
201
- `location`, and `message` fields. Variant-specific facts are direct fields;
202
- structured `path` and `related` fields are not hidden behind a `source` object.
203
- Codes are stable lowercase kebab-case values such as
204
- `invalid-widget-id`, `invalid-widget-config`, `invalid-widget-structure`, and
232
+ produces an inspectable Blueprint. `createBlueprintFromJson(text)` is equivalent
233
+ to `createBlueprint(JSON.parse(text))`, including its diagnostics (an
234
+ overflowing literal such as `1e400` is still diagnosed as
235
+ `json-incompatible-value`); it only replaces the full JSON-domain inspection
236
+ with a cheaper scan, because Core parsed the value itself. Every diagnostic has
237
+ top-level `code`, `location`, and `message` fields. Variant-specific facts are
238
+ direct fields; structured `path` and `related` fields are not hidden behind a
239
+ `source` object. Codes are stable lowercase kebab-case values such as
240
+ `invalid-widget-id`, `duplicate-widget-id`, `unexpected-widget-field`,
241
+ `invalid-widget-config`, `invalid-widget-structure`, and
205
242
  `missing-dependency-target`. Whole-source JSON inspection adds aggregate-only
206
243
  `json-incompatible-value` diagnostics with a source-rooted `path` and closed
207
244
  `reason`, while `source-access-failed` means Core could not safely complete the
208
245
  inspection. These source-level facts do not appear in a node's `.diagnostics`.
246
+ The full code tables are in the
247
+ [guide](https://deviltea.github.io/widget/packages/widget-core#diagnostics).
248
+
249
+ A widget node has exactly the own keys `id`, `type`, `config`, `slots` and
250
+ `meta`. Any other key is reported as `unexpected-widget-field` and makes the
251
+ Blueprint invalid; `meta` is the reserved extension key (any JSON value,
252
+ preserved and never interpreted). An `id` is any string, including `''`.
253
+ Authored source may nest at most `MAX_JSON_DEPTH` (256) containers deep.
254
+ `blueprint.getSourcePath(node)` returns the structured `SourcePath` of a node
255
+ inside `blueprint.source`, usable directly as a `SourcePatch` path — also for the
256
+ node recovery stops at for depth, whose path has at most `MAX_JSON_DEPTH + 2`
257
+ segments, the longest path a `SourcePatch` accepts.
209
258
 
210
259
  Recovery is best-effort: even invalid input still yields a navigable root and
211
260
  node tree via `blueprint.getWidget` / `getParent` / `getChildren` /
@@ -238,22 +287,68 @@ JSON Pointer strings or structured string/number segments, operands are
238
287
  failure is atomic; a successful patch may still commit a semantically invalid
239
288
  Blueprint for inspection.
240
289
 
290
+ <!-- sample: document-patch run -->
241
291
  ```typescript
242
- import { createWidgetDocument } from '@deviltea/widget-core'
292
+ import { createWidgetDocument, createWidgetPlugin, createWidgetSystem } from '@deviltea/widget-core'
293
+
294
+ interface CounterInterfaces {
295
+ config: {
296
+ raw: { step: number }
297
+ resolved: { step: number }
298
+ }
299
+ }
300
+
301
+ const counterPlugin = createWidgetPlugin('counter')
302
+ .description('A counter widget')
303
+ .interfaces<CounterInterfaces>()
304
+ .config({
305
+ description: 'Counter configuration',
306
+ validate: (input): input is { step: number } =>
307
+ typeof input === 'object' && input !== null && typeof (input as { step?: unknown }).step === 'number',
308
+ resolve: rawConfig => ({ step: rawConfig?.step ?? 1 }),
309
+ })
310
+ .done()
311
+
312
+ const system = createWidgetSystem({ plugins: [counterPlugin] })
243
313
 
244
314
  const document = createWidgetDocument({
245
315
  system,
246
- source: { id: 'counter-1', type: 'counter' },
316
+ source: { id: 'counter-1', type: 'counter', config: { step: 1 } },
317
+ })
318
+
319
+ const unsubscribe = document.subscribe((snapshot, { previous, patch }) => {
320
+ console.log(`revision ${previous.revision} -> ${snapshot.revision}`, patch)
247
321
  })
248
322
 
323
+ // Success: `/config/step` exists, so the replace commits revision 1.
249
324
  const result = document.applyPatch([
250
325
  { op: 'replace', path: '/config/step', value: 2 },
251
326
  ], { expectedRevision: 0 })
252
327
 
253
328
  if (result.ok && result.changed)
254
329
  console.log(document.getSnapshot().revision) // 1
330
+
331
+ // Failure: a path that does not exist, a stale revision, and a malformed operation.
332
+ const missing = document.applyPatch([{ op: 'replace', path: '/config/missing', value: 1 }])
333
+ if (!missing.ok)
334
+ console.log(missing.failure.code) // path-not-found
335
+
336
+ const stale = document.applyPatch([{ op: 'replace', path: '/config/step', value: 3 }], { expectedRevision: 0 })
337
+ if (!stale.ok && stale.failure.code === 'document-revision-conflict')
338
+ console.log(stale.failure.expectedRevision, stale.failure.actualRevision) // 0 1
339
+
340
+ const malformed = document.applyPatch([{ op: 'frobnicate', path: '/config' }] as never)
341
+ if (!malformed.ok)
342
+ console.log(malformed.failure.code) // invalid-operation
343
+
344
+ console.log(document.getSnapshot().revision) // 1: a failed patch changes nothing
345
+ unsubscribe()
255
346
  ```
256
347
 
348
+ A patch is an array of `{ op: 'add' | 'replace' | 'test', path, value }`,
349
+ `{ op: 'remove', path }` and `{ op: 'move' | 'copy', from, path }` operations
350
+ (`SourcePatchOperation`).
351
+
257
352
  Authored source is handed to Core **by reference**: `createBlueprint`,
258
353
  `recompile` and `createWidgetDocument` keep `source` as given, so
259
354
  `blueprint.source` is the exact input and Core never clones or freezes it.
@@ -280,21 +375,23 @@ subscribers. `failure.code` is one of:
280
375
  `actualRevision`. Omitting `options` skips this check, and the check runs
281
376
  before any operation is evaluated.
282
377
  - An operation failure `{ code, operationIndex, message }`, where `code` is
283
- `invalid-path`, `path-not-found`, `path-not-traversable`,
284
- `invalid-array-index`, `invalid-move-target`, `test-failed`,
285
- `json-incompatible-value`, or `source-access-failed`, and `operationIndex`
286
- is the failing operation's position in the patch. A failed patch leaves the
287
- committed source and revision unchanged.
378
+ `invalid-operation`, `invalid-path`, `max-depth-exceeded`, `path-not-found`,
379
+ `path-not-traversable`, `invalid-array-index`, `invalid-move-target`,
380
+ `test-failed`, `json-incompatible-value`, or `source-access-failed`, and
381
+ `operationIndex` is the failing operation's position in the patch. A failed
382
+ patch leaves the committed source and revision unchanged.
288
383
 
289
384
  | `code` | Meaning |
290
385
  | --- | --- |
291
- | `invalid-path` | malformed path or operation shape |
386
+ | `invalid-operation` | the patch is not an array, an operation is not an object, or its `op` is unknown |
387
+ | `invalid-path` | a malformed path only |
388
+ | `max-depth-exceeded` | a path longer than `MAX_JSON_DEPTH + 2` segments (the longest source path of a node a Blueprint materializes), or a `copy`/`move` source nested deeper than `MAX_JSON_DEPTH` |
292
389
  | `path-not-found` | the path does not identify an existing location |
293
390
  | `path-not-traversable` | the path passes through a non-traversable value |
294
391
  | `invalid-array-index` | an Array parent was addressed by anything other than an in-bounds canonical index (see below) |
295
392
  | `invalid-move-target` | a `move` into its own descendant |
296
393
  | `test-failed` | a `test` operand did not match the addressed value |
297
- | `json-incompatible-value` | an `add`/`replace`/`test` `value` is outside Core's JSON domain (missing or `undefined`, functions, `bigint`, symbols, `NaN`/`±Infinity`, cycles, non-plain prototypes, sparse or extra-property Arrays, accessors, symbol keys, or reflection that throws); checked after path parsing and before the operation is evaluated |
394
+ | `json-incompatible-value` | an `add`/`replace`/`test` `value` is outside Core's JSON domain (missing or `undefined`, functions, `bigint`, symbols, `NaN`/`±Infinity`, cycles, non-plain prototypes, sparse or extra-property Arrays, accessors, symbol keys, nesting deeper than `MAX_JSON_DEPTH`, or reflection that throws); checked after path parsing and before the operation is evaluated. The failure carries an optional operand-relative `path` and a `reason` |
298
395
  | `source-access-failed` | unsafe access to the *source* material only |
299
396
 
300
397
  Three edge semantics apply to every operation:
@@ -315,12 +412,14 @@ Three edge semantics apply to every operation:
315
412
  `json-incompatible-value`, not `source-access-failed`.
316
413
 
317
414
  `document.subscribe(listener)` registers `listener` and returns an idempotent
318
- unsubscribe function. The listener is not called on subscription; it receives
319
- the new snapshot after each committed (`changed: true`) patch, in subscription
320
- order, over the subscriber list as it stood when notification began. An
415
+ unsubscribe function. The listener is not called on subscription; after each
416
+ committed (`changed: true`) patch it receives `(snapshot, { previous, patch })`,
417
+ in subscription order, over the subscriber list as it stood when notification
418
+ began. No-op detection is JSON-domain equality. An
321
419
  exception thrown by a listener does not fail `applyPatch()` or stop the
322
- remaining listeners, and it is reported outside `applyPatch()`; the reporting
323
- mechanism is not part of the contract.
420
+ remaining listeners, and it is reported separately from the `applyPatch()` result
421
+ (see [Host requirements](#host-requirements)); the reporting mechanism is not
422
+ part of the contract.
324
423
 
325
424
  ### SeparatedWidgetSource tooling
326
425
 
@@ -329,17 +428,28 @@ mechanism is not part of the contract.
329
428
  `widgets` data list; it is useful for authoring tools and normalization, but it
330
429
  is not another `createBlueprint` or `WidgetDocument` input mode.
331
430
 
431
+ <!-- sample: separated-source run -->
332
432
  ```typescript
333
- import {
334
- normalizeSeparatedWidgetSource,
335
- separateWidgetSource,
336
- } from '@deviltea/widget-core'
433
+ import { normalizeSeparatedWidgetSource, separateWidgetSource } from '@deviltea/widget-core'
434
+
435
+ const canonical = {
436
+ id: 'panel-1',
437
+ type: 'panel',
438
+ meta: { note: 'kept' },
439
+ slots: { content: [{ id: 'counter-1', type: 'counter', config: { step: 2 } }] },
440
+ }
337
441
 
338
- const separated = separateWidgetSource(canonicalSource)
339
- const normalized = normalizeSeparatedWidgetSource(separated)
442
+ // `separateWidgetSource(source: unknown)` never throws: it returns `{ separated, diagnostics }`.
443
+ // `separated` is null only when the root cannot be projected; an empty `diagnostics` guarantees
444
+ // a lossless round trip through `normalizeSeparatedWidgetSource`.
445
+ const { separated, diagnostics } = separateWidgetSource(canonical)
446
+ console.log(diagnostics.length) // 0: nothing was lost
340
447
 
341
- normalized.source // best-effort nested source, still unknown for recovery
342
- normalized.diagnostics // representation diagnostics, separate from Blueprint diagnostics
448
+ if (separated !== null) {
449
+ const normalized = normalizeSeparatedWidgetSource(separated)
450
+ console.log(normalized.diagnostics.length) // 0, representation diagnostics (separate from Blueprint diagnostics)
451
+ console.log(JSON.stringify(normalized.source) === JSON.stringify(canonical)) // true: best-effort nested source
452
+ }
343
453
  ```
344
454
 
345
455
  Normalization is deterministic and non-destructive: the first flat data entry
@@ -351,15 +461,46 @@ later occurrence is de-identified with its available subtree preserved.
351
461
 
352
462
  - Declared `events` are public notifications: subscribe through
353
463
  `widget.events[name].subscribe(listener)`. Delivery is synchronous and
354
- depth-first for nested emits; a throwing public listener propagates to the
355
- emit caller and stops the remaining public listeners. Emit authority belongs
356
- to Method `execute` (`emit`) and, for renderers, `@deviltea/widget-core/integration`.
464
+ depth-first for nested emits; a throwing public listener is isolated like every
465
+ other listener (the remaining listeners and the emitting Method still run, and
466
+ the error is reported separately, see [Host requirements](#host-requirements)). A runaway loop (a listener that keeps
467
+ re-invoking the emitting Method) is cut off once one Runtime's emits nest more
468
+ than 128 deep: `WidgetSystemRuntimeReentrancyError` (a `RangeError`, code
469
+ `emit-depth-exceeded`) unwinds to the call that started the loop. Events are
470
+ host-facing and cannot be dependency targets. Emit authority belongs
471
+ to Method `execute` (`emit`, limited to the Events the Method lists in `emits`; a Method that
472
+ emits is not read-only, so no Property may depend on it) and, for renderers, `@deviltea/widget-core/integration`.
357
473
  See [Events](https://deviltea.github.io/widget/packages/widget-core#events).
358
474
  - `widget.state[key].get()` returns `T | null` directly — it is not an
359
475
  `ExecutionResult`.
360
476
  - `widget.properties[name].get()` / `.subscribe(listener)` and
361
- `widget.methods[name](...)` all return an `ExecutionResult<T, Diagnostic>`:
362
- `{ ok: true, value }` or `{ ok: false, failure: { diagnostics: [...] } }`.
477
+ `widget.methods[name](...)` all return an `ExecutionResult<T, D>` (`D` is the member's diagnostic union)
478
+ with `T` exactly as declared (never `T | null`):
479
+ `{ ok: true, value }` or `{ ok: false, failure: { diagnostics: [...] } }`.
480
+ A `void` Method returns `{ ok: true, value: undefined }`.
481
+ - State values are immutable by contract: change detection is identity-based, so
482
+ mutating a value in place and setting the same reference notifies nobody.
483
+ Always `set()` a new value.
484
+ - A throwing Property `compute` never makes a writer (`state.set`, a Method call,
485
+ `resetState()`) throw and never suppresses other subscribers; it is reported
486
+ separately, while `get()` and dependency reads still rethrow. The exception
487
+ stays cached until a dependency changes — except a stack overflow (a first
488
+ read of a chain of on the order of a thousand Properties), which the next read
489
+ evaluates again, so a long chain can be warmed bottom-up.
490
+ - `runtime.snapshotState()` returns the current State as a plain
491
+ `Record<WidgetId, Record<string, unknown>>` (`null` members omitted) that is
492
+ directly usable as `overrideStateDefaults`; `widget.resetState()` resets one
493
+ widget. See
494
+ [Reusing a Runtime](https://deviltea.github.io/widget/packages/widget-core#reusing-a-runtime-resetstate).
495
+ - `deps.*` and `emit` callables are valid only while their own callback is the
496
+ innermost running callback (a Method's `emit` belongs to that Method, not to its widget). A retained callable, a timer or promise
497
+ continuation, a nested callback, or a listener or `validate`-style callback
498
+ running inside the Method gets a `TypeError` (and
499
+ `WidgetSystemRuntimeDisposedError` after dispose, except an `emit` callable for an Event its
500
+ Method did not declare, which is always a `TypeError`). A Property can never write
501
+ State. Core is synchronous by design; see
502
+ [Async work](https://deviltea.github.io/widget/packages/widget-core#async-work)
503
+ for the host recipe.
363
504
  - Properties are lazily evaluated and cached through `alien-signals`; a
364
505
  subscription has no immediate emission and notifies once per actual
365
506
  completed recompute.
@@ -371,6 +512,12 @@ later occurrence is de-identified with its available subtree preserved.
371
512
  active diagnostic collector. Computing a fallback value after the failure
372
513
  does not make the operation succeed: the result is still `ok: false`. See
373
514
  [Dependency failures fail the consumer](https://deviltea.github.io/widget/packages/widget-core#dependency-failures-fail-the-consumer).
515
+ - `runtime.resetState()` restores every State member to its initialization
516
+ outcome (value and diagnostic snapshot) in one batch without re-running
517
+ `validate`, so one Runtime can evaluate many independent inputs. See
518
+ [Reusing a Runtime](https://deviltea.github.io/widget/packages/widget-core#reusing-a-runtime-resetstate).
519
+ - A callback's `addDiagnostic` / `hasAnyDiagnostic` throw a `TypeError` when
520
+ called after that callback returned.
374
521
  - Every state write, property evaluation, and method invocation keeps the
375
522
  **latest completed** diagnostic snapshot only (`getDiagnostics()` /
376
523
  `subscribeDiagnostics()`), never a history.
@@ -378,18 +525,30 @@ later occurrence is de-identified with its available subtree preserved.
378
525
  `subscribeDiagnostics()`: the union of only that widget's own primitive-owned
379
526
  diagnostics (state members -> property members -> method members, declaration
380
527
  order within each capability, each primitive's own local diagnostic order),
381
- never Runtime-level diagnostics even when a diagnostic mentions the same
382
- `widgetId`. `runtime.getDiagnostics()` is the complete aggregate: Runtime-
383
- boundary diagnostics first, followed by each `RuntimeWidget.getDiagnostics()`
384
- in Blueprint semantic widget order; `subscribeDiagnostics()` observes that same
385
- aggregate, and none of these reads/subscriptions activate Property
386
- evaluation.
528
+ never Runtime-level diagnostics even when a diagnostic mentions the same
529
+ `widgetId`. `runtime.getDiagnostics()` is the aggregate over the whole Runtime:
530
+ Runtime-boundary diagnostics first, followed by each
531
+ `RuntimeWidget.getDiagnostics()` in Blueprint semantic widget order;
532
+ `subscribeDiagnostics()` observes that same aggregate, and none of these
533
+ reads/subscriptions activate Property evaluation. Because Properties are lazy,
534
+ the aggregate only contains diagnostics of Properties that have been
535
+ evaluated, and `resetState()` does not clear retained Property or Method
536
+ diagnostics. To validate a Runtime headlessly, read every Property you rely on
537
+ before reading the aggregate (a runnable recipe is in
538
+ [Runtime diagnostics](https://deviltea.github.io/widget/packages/widget-core#runtime-diagnostics)).
387
539
  - `runtime.dispose()` is idempotent. After disposal, `runtime.isDisposed` and
388
540
  `runtime.blueprint` stay readable, but every live query/operation
389
- (including `RuntimeWidget.getDiagnostics()`) and every new subscription
541
+ (including `snapshotState()`, `resetState()` and
542
+ `RuntimeWidget.getDiagnostics()`) and every new subscription
390
543
  (including `RuntimeWidget.subscribeDiagnostics()`) throws
391
544
  `WidgetSystemRuntimeDisposedError`; unsubscribe functions obtained before
392
- disposal remain safe idempotent no-ops.
545
+ disposal remain safe idempotent no-ops. `runtime.subscribeDisposal(listener)`
546
+ is the one disposal signal, for a host that cancels the asynchronous work it
547
+ owns: each listener runs exactly once, synchronously, inside the first
548
+ `dispose()` call with no arguments, after the Runtime is already fully
549
+ disposed (so it cannot read or write the Runtime), in subscription order. A
550
+ throwing listener is isolated and reported like any other;
551
+ subscribing to a disposed Runtime throws `WidgetSystemRuntimeDisposedError`.
393
552
 
394
553
  ### Inspection
395
554
 
@@ -397,10 +556,12 @@ A dedicated, strictly readonly subpath is a supported observation surface for
397
556
  any host (DevTools, prototype players, test harnesses). It exposes
398
557
  compiler/runtime facts, including passive Event occurrence observation through
399
558
  `getEvent(name).subscribe(...)`, and never mutates state, invokes methods, or
400
- forces Property evaluation:
559
+ forces Property evaluation. `inspectPlugin(plugin)` is a superset of the
560
+ plugin's `system.catalog` entry (type, description, capabilities, config
561
+ metadata, slots, and the State/Property/Event member facts):
401
562
 
402
563
  ```typescript
403
- import { inspectBlueprint, inspectRuntime } from '@deviltea/widget-core/inspection'
564
+ import { inspectBlueprint, inspectPlugin, inspectRuntime } from '@deviltea/widget-core/inspection'
404
565
  ```
405
566
 
406
567
  `@deviltea/widget-core`'s root entrypoint does not export this surface. See
@@ -410,17 +571,44 @@ delivery guarantees.
410
571
 
411
572
  ### Host requirements
412
573
 
413
- The current implementation needs an ES2022 engine and a global
414
- `queueMicrotask` whose jobs the host actually runs: a throwing `subscribe` /
415
- `subscribeDiagnostics` listener is isolated and rethrown in a microtask.
416
- Embedded engines such as QuickJS (`rquickjs`) must drain their pending jobs,
417
- or those listener errors never surface. See
418
- [Host requirements](https://deviltea.github.io/widget/packages/widget-core#host-requirements).
574
+ The current implementation needs an ES2022 engine. A throwing State, Property,
575
+ diagnostic, Event, disposal, inspection or `WidgetDocument` listener, and a Property
576
+ `compute` that throws during a subscription's re-evaluation, is isolated: it
577
+ never reaches the call that caused it. By default Core rethrows it in a queued
578
+ microtask, which needs a global `queueMicrotask` whose jobs the host actually
579
+ runs; embedded engines such as QuickJS (`rquickjs`) must drain their pending
580
+ jobs, or those errors never surface. A host can receive them instead:
581
+
582
+ ```typescript
583
+ import { setIsolatedErrorHandler } from '@deviltea/widget-core'
584
+
585
+ setIsolatedErrorHandler(error => console.error('isolated:', error))
586
+ ```
587
+
588
+ The handler is called once per report, after the Runtime call that caused it has
589
+ finished its work and before that call returns (at once when no Runtime call is
590
+ in progress), and it is never re-entered, so it may read and write the Runtime.
591
+ `setIsolatedErrorHandler` returns the handler it replaced, so code that sets one
592
+ for a while can put the previous one back. With a handler set, Core queues a
593
+ microtask only for an exception the handler throws, a report still waiting when
594
+ the handler is removed, and what the handler's handling causes beyond its
595
+ internal bounds; without `queueMicrotask` those reports are dropped and the rest
596
+ of the pass is unaffected, as long as the handler stays set until the Runtime
597
+ call that is running ends: removing it in the middle of a Runtime call returns
598
+ the rest of that call to the default mode, whose `queueMicrotask` call is not
599
+ guarded, so an exception isolated in the rest of that call throws at the point
600
+ of the failure (a `ReferenceError` when the global is missing). A host whose
601
+ handler stays set, catches its own exceptions and does not keep causing what it
602
+ handles needs neither `queueMicrotask` nor a
603
+ drained job queue. See
604
+ [Receiving isolated errors](https://deviltea.github.io/widget/packages/widget-core#receiving-isolated-errors)
605
+ and [Host requirements](https://deviltea.github.io/widget/packages/widget-core#host-requirements).
419
606
 
420
607
  The full guide at
421
608
  [docs/site/packages/widget-core.md](https://deviltea.github.io/widget/packages/widget-core)
422
- covers the dependency grammar, the compile pipeline, and every Runtime
423
- primitive in detail.
609
+ covers the dependency grammar, the compile pipeline, every Runtime primitive,
610
+ the complete diagnostic and error tables, and guides for async work, persisted
611
+ documents, generic plugin factories and renderer adapters.
424
612
 
425
613
  ## License
426
614
 
@@ -434,5 +622,5 @@ primitive in detail.
434
622
  [npm-downloads-href]: https://npmjs.com/package/@deviltea/widget-core
435
623
  [bundle-src]: https://img.shields.io/bundlephobia/minzip/@deviltea/widget-core?style=flat&colorA=080f12&colorB=1fa669&label=minzip
436
624
  [bundle-href]: https://bundlephobia.com/result?p=@deviltea/widget-core
437
- [license-src]: https://img.shields.io/github/license/DevilTea/deviltea-labs.svg?style=flat&colorA=080f12&colorB=1fa669
625
+ [license-src]: https://img.shields.io/github/license/DevilTea/widget.svg?style=flat&colorA=080f12&colorB=1fa669
438
626
  [license-href]: https://github.com/DevilTea/widget/blob/main/LICENSE