@deviltea/widget-core 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DevilTea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,327 @@
1
+ # @deviltea/widget-core
2
+
3
+ Cross-cutting Diagnostic/Result/Failure/Error conventions are maintained in
4
+ [Widget API conventions](../../../docs/architecture/widget-api-conventions.md).
5
+
6
+ > ESM-only package.
7
+
8
+ [![npm version][npm-version-src]][npm-version-href]
9
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
10
+ [![bundle][bundle-src]][bundle-href]
11
+ [![License][license-src]][license-href]
12
+
13
+ A renderer-agnostic widget composition core: declare `WidgetPlugin`s with a
14
+ capability-phase builder, register them into a `WidgetSystem`, compile an
15
+ unknown/raw widget tree into a diagnosable `WidgetSystemBlueprint`, and run a
16
+ valid Blueprint as an `alien-signals`-backed `WidgetSystemRuntime`.
17
+
18
+ ## Installation
19
+
20
+ To install the package, use either `npm`, `yarn`, or `pnpm`:
21
+
22
+ ```bash
23
+ npm install @deviltea/widget-core
24
+ ```
25
+
26
+ ```bash
27
+ yarn add @deviltea/widget-core
28
+ ```
29
+
30
+ ```bash
31
+ pnpm add @deviltea/widget-core
32
+ ```
33
+
34
+ ## Core model
35
+
36
+ ```text
37
+ WidgetPlugin plugin semantic contract, built with createWidgetPlugin()
38
+ WidgetSystem immutable registered plugin universe
39
+ WidgetSystemBlueprint immutable compiled semantic snapshot of one source tree, valid | invalid
40
+ WidgetDocument revisioned source + Blueprint coordinator with atomic SourcePatch commits
41
+ WidgetSystemRuntime executable instance of a valid Blueprint
42
+ ```
43
+
44
+ ```text
45
+ createWidgetPlugin(type) -> builder -> WidgetPlugin
46
+ createWidgetSystem({ plugins }) -> WidgetSystem
47
+ system.createBlueprint(source: unknown) -> WidgetSystemBlueprint
48
+ blueprint.createRuntime() -> WidgetSystemRuntime // only when blueprint.status === 'valid'
49
+ ```
50
+
51
+ A renderer/integration layer consumes the Runtime; the core itself knows
52
+ nothing about rendering, persistence versioning, or metadata. Source editing
53
+ is limited to the revisioned `WidgetDocument` and JSON-domain `SourcePatch`
54
+ contract described below. See
55
+ [Design constraints](https://deviltea.github.io/deviltea-labs/packages/widget-core#design-constraints)
56
+ in the full guide for the exact boundary.
57
+
58
+ Capability presence (`config`/`slots`/`state`/`properties`/`methods`) is
59
+ declaration presence, independent of whether a capability's own domain is
60
+ empty — a completed plugin exposes these facts at runtime as
61
+ `plugin.capabilities: { config, slots, state, properties, methods }`
62
+ (all `boolean`, immutable). See
63
+ [Reading capability presence at runtime](https://deviltea.github.io/deviltea-labs/packages/widget-core#reading-capability-presence-at-runtime-plugin-capabilities)
64
+ in the full guide.
65
+
66
+ Plugin, config, and slot descriptions are required intrinsic metadata. The
67
+ immutable `system.catalog` is a passive projection of registered widget types,
68
+ descriptions, and capability descriptions; it does not contain Blueprint or
69
+ Runtime state.
70
+
71
+ ## Usage
72
+
73
+ Here is a complete widget: one plugin with `state`, `properties`, and
74
+ `methods`, registered into a system, compiled, and run.
75
+
76
+ ```typescript
77
+ import { createWidgetPlugin, createWidgetSystem } from '@deviltea/widget-core'
78
+
79
+ // 1. Declare the plugin's capabilities.
80
+ interface CounterInterfaces {
81
+ state: {
82
+ count: number
83
+ }
84
+ properties: {
85
+ doubled: number
86
+ }
87
+ methods: {
88
+ increment: (step: number) => number
89
+ reset: () => void
90
+ }
91
+ }
92
+
93
+ // 2. Build the plugin through the capability-phase builder.
94
+ const counterPlugin = createWidgetPlugin('counter')
95
+ .description('A counter widget')
96
+ .interfaces<CounterInterfaces>()
97
+ .state(state =>
98
+ state.count({
99
+ validate: (input): input is number => typeof input === 'number',
100
+ default: () => 0,
101
+ }),
102
+ )
103
+ .properties(properties =>
104
+ properties.doubled({
105
+ registerDeps: ({ dep }) => ({
106
+ count: dep.self.state.get('count'),
107
+ }),
108
+ compute: ({ deps }) => {
109
+ const count = deps.count()
110
+ return (count.ok ? count.value ?? 0 : 0) * 2
111
+ },
112
+ }),
113
+ )
114
+ .methods(methods =>
115
+ methods
116
+ .increment({
117
+ validateArgs: (args): args is [number] => args.length === 1 && typeof args[0] === 'number',
118
+ registerDeps: ({ dep }) => ({
119
+ count: dep.self.state.get('count'),
120
+ setCount: dep.self.state.set('count'),
121
+ }),
122
+ execute: ({ args: [step], deps }) => {
123
+ const current = deps.count()
124
+ const value = (current.ok ? current.value ?? 0 : 0) + step
125
+ deps.setCount(value)
126
+ return value
127
+ },
128
+ })
129
+ .reset({
130
+ validateArgs: (args): args is [] => args.length === 0,
131
+ registerDeps: ({ dep }) => ({
132
+ setCount: dep.self.state.set('count'),
133
+ }),
134
+ execute: ({ deps }) => {
135
+ deps.setCount(0)
136
+ },
137
+ }),
138
+ )
139
+ .done()
140
+
141
+ // 3. Register plugins into an immutable system.
142
+ const system = createWidgetSystem({
143
+ plugins: [counterPlugin],
144
+ })
145
+
146
+ // 4. Compile an unknown/raw widget tree into a Blueprint.
147
+ const blueprint = system.createBlueprint({
148
+ id: 'counter-1',
149
+ type: 'counter',
150
+ })
151
+
152
+ // 5. Only a `valid` Blueprint can create a Runtime.
153
+ if (blueprint.status !== 'valid')
154
+ throw new Error('invalid widget definition')
155
+
156
+ const runtime = blueprint.createRuntime()
157
+ const widget = runtime.getWidget('counter-1')
158
+ if (widget === null)
159
+ throw new Error('widget not found')
160
+
161
+ // 6. Operate/subscribe through the Runtime primitives.
162
+ const unsubscribe = widget.properties.doubled.subscribe((result) => {
163
+ console.log('doubled changed ->', result) // { ok: true, value: ... }
164
+ })
165
+
166
+ widget.methods.increment(5) // -> { ok: true, value: 5 }
167
+ widget.state.count.get() // -> 5
168
+ widget.properties.doubled.get() // -> { ok: true, value: 10 }
169
+
170
+ widget.methods.reset()
171
+ widget.state.count.get() // -> 0
172
+
173
+ unsubscribe()
174
+ runtime.dispose()
175
+ ```
176
+
177
+ ### Blueprint diagnostics
178
+
179
+ `createBlueprint` accepts `unknown`; malformed input never throws — it always
180
+ produces an inspectable Blueprint. Every diagnostic has top-level `code`,
181
+ `location`, and `message` fields. Variant-specific facts are direct fields;
182
+ structured `path` and `related` fields are not hidden behind a `source` object.
183
+ Codes are stable lowercase kebab-case values such as
184
+ `invalid-widget-id`, `invalid-widget-config`, `invalid-widget-structure`, and
185
+ `missing-dependency-target`. Whole-source JSON inspection adds aggregate-only
186
+ `json-incompatible-value` diagnostics with a source-rooted `path` and closed
187
+ `reason`, while `source-access-failed` means Core could not safely complete the
188
+ inspection. These source-level facts do not appear in a node's `.diagnostics`.
189
+
190
+ Recovery is best-effort: even invalid input still yields a navigable root and
191
+ node tree via `blueprint.getWidget` / `getParent` / `getChildren` /
192
+ `.diagnostics`. Editing means recompiling a new source, not mutating
193
+ the Blueprint:
194
+
195
+ ```typescript
196
+ const nextBlueprint = blueprint.recompile(nextSource)
197
+ ```
198
+
199
+ Only `blueprint.status === 'valid'` narrows to a Blueprint exposing
200
+ `createRuntime`; an `'invalid'` Blueprint remains inspectable but cannot
201
+ create a Runtime.
202
+
203
+ `sourceJsonCompatible` is the proof for the authored JSON domain. When it is
204
+ `true`, `blueprint.source` and source fragments on recovered navigation nodes
205
+ are `JsonValue`; when it is `false`, the source remains `unknown`. The false
206
+ branch covers either confirmed JSON-domain incompatibility or an unproven safe
207
+ inspection; `blueprint.diagnostics` distinguishes those causes. A valid
208
+ Blueprint requires both semantic validity and this proof, so Runtime creation
209
+ never promotes non-JSON authored material.
210
+
211
+ ### WidgetDocument and SourcePatch
212
+
213
+ `createWidgetDocument({ system, source })` keeps the current source and its
214
+ compiled Blueprint together behind a monotonically increasing revision. A
215
+ `SourcePatch` is one JSON-domain RFC6901/RFC6902 patch language: paths may be
216
+ JSON Pointer strings or structured string/number segments, operands are
217
+ `JsonValue`, and successful patches are applied copy-on-write. Mechanical
218
+ failure is atomic; a successful patch may still commit a semantically invalid
219
+ Blueprint for inspection.
220
+
221
+ ```typescript
222
+ import { createWidgetDocument } from '@deviltea/widget-core'
223
+
224
+ const document = createWidgetDocument({
225
+ system,
226
+ source: { id: 'counter-1', type: 'counter' },
227
+ })
228
+
229
+ const result = document.applyPatch([
230
+ { op: 'replace', path: '/config/step', value: 2 },
231
+ ], { expectedRevision: 0 })
232
+
233
+ if (result.ok && result.changed)
234
+ console.log(document.getSnapshot().revision) // 1
235
+ ```
236
+
237
+ ### SeparatedWidgetSource tooling
238
+
239
+ `WidgetSource` is the only canonical nested authored representation. The explicit
240
+ `SeparatedWidgetSource` projection contains a nested structural tree and a flat
241
+ `widgets` data list; it is useful for authoring tools and normalization, but it
242
+ is not another `createBlueprint` or `WidgetDocument` input mode.
243
+
244
+ ```typescript
245
+ import {
246
+ normalizeSeparatedWidgetSource,
247
+ separateWidgetSource,
248
+ } from '@deviltea/widget-core'
249
+
250
+ const separated = separateWidgetSource(canonicalSource)
251
+ const normalized = normalizeSeparatedWidgetSource(separated)
252
+
253
+ normalized.source // best-effort nested source, still unknown for recovery
254
+ normalized.diagnostics // representation diagnostics, separate from Blueprint diagnostics
255
+ ```
256
+
257
+ Normalization is deterministic and non-destructive: the first flat data entry
258
+ for an ID wins, missing data produces a partial nested node, unused data is not
259
+ guessed into the tree, and repeated structural IDs are diagnosed while the
260
+ later occurrence is de-identified with its available subtree preserved.
261
+
262
+ ### Runtime semantics
263
+
264
+ - `widget.state[key].get()` returns `T | null` directly — it is not an
265
+ `ExecutionResult`.
266
+ - `widget.properties[name].get()` / `.subscribe(listener)` and
267
+ `widget.methods[name](...)` all return an `ExecutionResult<T, Diagnostic>`:
268
+ `{ ok: true, value }` or `{ ok: false, failure: { diagnostics: [...] } }`.
269
+ - Properties are lazily evaluated and cached through `alien-signals`; a
270
+ subscription has no immediate emission and notifies once per actual
271
+ completed recompute.
272
+ - Every `RuntimeMethod` invocation batches its dependency/state writes; the
273
+ batch flushes once the method returns, so partial writes from nested method
274
+ calls are not observed mid-flight by outside subscribers.
275
+ - Every state write, property evaluation, and method invocation keeps the
276
+ **latest completed** diagnostic snapshot only (`getDiagnostics()` /
277
+ `subscribeDiagnostics()`), never a history.
278
+ - Every `RuntimeWidget` also exposes an aggregate `getDiagnostics()` /
279
+ `subscribeDiagnostics()`: the union of only that widget's own primitive-owned
280
+ diagnostics (state members -> property members -> method members, declaration
281
+ order within each capability, each primitive's own local diagnostic order),
282
+ never Runtime-level diagnostics even when a diagnostic mentions the same
283
+ `widgetId`. `runtime.getDiagnostics()` is the complete aggregate: Runtime-
284
+ boundary diagnostics first, followed by each `RuntimeWidget.getDiagnostics()`
285
+ in Blueprint semantic widget order; `subscribeDiagnostics()` observes that same
286
+ aggregate, and none of these reads/subscriptions activate Property
287
+ evaluation.
288
+ - `runtime.dispose()` is idempotent. After disposal, `runtime.isDisposed` and
289
+ `runtime.blueprint` stay readable, but every live query/operation
290
+ (including `RuntimeWidget.getDiagnostics()`) and every new subscription
291
+ (including `RuntimeWidget.subscribeDiagnostics()`) throws
292
+ `WidgetSystemRuntimeDisposedError`; unsubscribe functions obtained before
293
+ disposal remain safe idempotent no-ops.
294
+
295
+ ### Inspection (DevTools)
296
+
297
+ A dedicated, strictly readonly subpath exposes compiler/runtime facts for
298
+ building inspectors — it never mutates state, invokes methods, or forces
299
+ Property evaluation:
300
+
301
+ ```typescript
302
+ import { inspectBlueprint, inspectRuntime } from '@deviltea/widget-core/inspection'
303
+ ```
304
+
305
+ `@deviltea/widget-core`'s root entrypoint does not export this surface. See
306
+ [Inspection](https://deviltea.github.io/deviltea-labs/packages/widget-core#inspection-devtools)
307
+ in the full guide for the exact contract.
308
+
309
+ The full guide at
310
+ [docs/site/packages/widget-core.md](https://deviltea.github.io/deviltea-labs/packages/widget-core)
311
+ covers the dependency grammar, the compile pipeline, and every Runtime
312
+ primitive in detail.
313
+
314
+ ## License
315
+
316
+ [MIT](https://github.com/DevilTea/deviltea-labs/blob/main/LICENSE) License © 2023-PRESENT [DevilTea](https://github.com/DevilTea)
317
+
318
+ <!-- Badges -->
319
+
320
+ [npm-version-src]: https://img.shields.io/npm/v/@deviltea/widget-core?style=flat&colorA=080f12&colorB=1fa669
321
+ [npm-version-href]: https://npmjs.com/package/@deviltea/widget-core
322
+ [npm-downloads-src]: https://img.shields.io/npm/dm/@deviltea/widget-core?style=flat&colorA=080f12&colorB=1fa669
323
+ [npm-downloads-href]: https://npmjs.com/package/@deviltea/widget-core
324
+ [bundle-src]: https://img.shields.io/bundlephobia/minzip/@deviltea/widget-core?style=flat&colorA=080f12&colorB=1fa669&label=minzip
325
+ [bundle-href]: https://bundlephobia.com/result?p=@deviltea/widget-core
326
+ [license-src]: https://img.shields.io/github/license/DevilTea/deviltea-labs.svg?style=flat&colorA=080f12&colorB=1fa669
327
+ [license-href]: https://github.com/DevilTea/deviltea-labs/blob/main/LICENSE