@opetope/react 0.14.0 → 0.16.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/README.md +67 -48
  3. package/dist/act-delivery.d.ts +20 -0
  4. package/dist/command-hook-controller.d.ts +13 -3
  5. package/dist/command-hook.d.ts +8 -8
  6. package/dist/contribution-frame-DL0dyVP4.js +2 -0
  7. package/dist/contribution-frame-DL0dyVP4.js.map +1 -0
  8. package/dist/{contribution-isolation-Bzfbt4iM.js → contribution-isolation-Ig70xFiC.js} +2 -2
  9. package/dist/contribution-isolation-Ig70xFiC.js.map +1 -0
  10. package/dist/contribution-isolation.d.ts +3 -3
  11. package/dist/errors.d.ts +4 -3
  12. package/dist/index.d.ts +2 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.js.map +1 -1
  15. package/dist/integration.d.ts +0 -4
  16. package/dist/integration.js +1 -1
  17. package/dist/integration.js.map +1 -1
  18. package/dist/model-hook.d.ts +5 -4
  19. package/dist/model-selection-snapshot.d.ts +6 -7
  20. package/dist/readable-hooks.d.ts +5 -8
  21. package/dist/requires-models.d.ts +4 -7
  22. package/dist/resource-command.d.ts +25 -26
  23. package/dist/resource-hook.d.ts +3 -7
  24. package/dist/resource-verb-hook.d.ts +28 -0
  25. package/dist/scenario-diagnostics.d.ts +3 -1
  26. package/dist/scenario-mount.d.ts +2 -1
  27. package/dist/scenario-slot.d.ts +6 -15
  28. package/dist/scenario-types.d.ts +68 -11
  29. package/dist/scenario-wait.d.ts +8 -1
  30. package/dist/scenario.d.ts +5 -3
  31. package/dist/selection-hooks.d.ts +6 -4
  32. package/dist/selector-sources.d.ts +64 -0
  33. package/dist/slot.d.ts +9 -7
  34. package/dist/testing.d.ts +2 -8
  35. package/dist/testing.js +3 -3
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -5
  38. package/dist/contribution-frame-Bh104T5Z.js +0 -2
  39. package/dist/contribution-frame-Bh104T5Z.js.map +0 -1
  40. package/dist/contribution-isolation-Bzfbt4iM.js.map +0 -1
  41. package/dist/feature-boundary.d.ts +0 -29
  42. package/dist/feature-demand.d.ts +0 -21
package/CHANGELOG.md CHANGED
@@ -1,5 +1,123 @@
1
1
  # @opetope/react
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f66744b: `CommandHook.dismiss()` clears the outcome a consumer shows until its next run settles; it belongs to that outcome, so a timer of an old outcome never clears a new one, and a `CommandHook` built by hand in a test now needs it (D543). Kit `failureOf(status)` reads a domain refusal returned as a `Result` and a thrown `failed` outcome for one place in the UI, `null` while a run is in flight (D543).
8
+ `opetope/no-command-in-deps` offers `hook.dismiss` as the dependency of a callback that reads it (D543).
9
+
10
+ ### Patch Changes
11
+
12
+ - f3e4e4a: Make npm READMEs self-contained, pin installation examples to the documented version and link to the same release's
13
+ public documentation. Clarify timer cancellation and physical cleanup, switch-navigation persistence and screen
14
+ matching, and correct timer examples so cancellation can finish their owned bodies.
15
+ - b8d122e: Testing gains `testResourceState` constructors and `testResourceView(readable)` (D502), and `testClock()` for `ctx.timers`, installed with `configureTesting({ clock })`; `createScenario` accepts the renderer's `act` (D541).
16
+ - Updated dependencies [f3e4e4a]
17
+ - Updated dependencies [03c3229]
18
+ - Updated dependencies [1f50be7]
19
+ - Updated dependencies [0693357]
20
+ - Updated dependencies [c88bc3d]
21
+ - Updated dependencies [9a758fb]
22
+ - Updated dependencies [b8d122e]
23
+ - @opetope/core@0.16.0
24
+ - @opetope/runtime@0.16.0
25
+
26
+ ## 0.15.0
27
+
28
+ ### Minor Changes
29
+
30
+ - fe97978: `onSuccess` and `onFailure` of a `CommandHook` run may return anything: the answer is not awaited and never becomes the outcome, so `onSuccess: () => close.run()` compiles, and a throw or a rejected answer of either callback is reported apart from the run (D474). The verbs of a `ResourceHook` — `refresh`, `reset` and `retry` — take no options any more and answer the Resource operation outcome itself: read `await refresh.run()` or `refresh.outcome` instead of `outcome.value`, and write the callback as code after `await refresh.run()` (D520).
31
+
32
+ Behavior change: a `refresh`, `reset` or `retry` of a `ResourceHook` still in flight when its component unmounted, or its Resource was replaced, answered the outcome of the operation; now that consumer's wait answers `{ kind: 'cancelled' }`, while the Resource's work goes on and the hook keeps its last settled outcome. Notice it where code after `await refresh.run()` expects `ready` for a component that is gone (D520).
33
+
34
+ - 544bdd9: Feature `own` keeps composition and host lifetimes only — `imports`, `requires`, `model`, `select`, `attach` and `command` — and a feature command takes `parallel`, `queue` or `{ pending: 'latest' }`. `own.effect`, `own.event`, `own.resource`, `own.scope` and `own.lane` are removed: declare them in a model's `ModelContext` and compose the model through `own.model` (D501). `FeatureInstance.instance` is no longer public: pass the feature handle to `settled(instance)` or use its `ready` and `close` (D517). Runtime no longer re-exports Core's Resource declaration and state types and `skipChange` — import them from `@opetope/core`; `ResourceView` stays a shared boundary type. React removes `useSelector` and, from `@opetope/react/integration`, the `FeatureBoundary` demand family with `useFeature` and `useFeatureRetry`: select model data with `read(source, project)` in `useModel`, or create a stable `derive(source, project, { equals })` for a standalone projection and pass it to `useReadable` (D500). `opetope/no-retired-vocabulary` reports the removed words with the instruction and moves the Resource type imports with `--fix`.
35
+
36
+ Behavior change: an event of feature `own` whose subscription failed asynchronously, or a scope of feature `own` whose first child failed to open, rejected the feature's `ready`; moved into a model, the failure goes to the reporter — a scope's as `ModelScopeOpenError` — and `ready` can resolve. A synchronous throw in an event `subscribe` still rejects opening, as `preparation failed` instead of `attachment <key> failed to open`. Notice it where a test or a host waits for `ready` to reject, or matches that text rather than `name` and `code` (D501).
37
+
38
+ Behavior change: after close, a Resource declared in feature `own` and exported answered `idle('unleased')`; moved into a model the feature owns, it answers `idle('retired')`, and `settled(instance)` waits for that model's effect and event runs, so one still running ends the wait with `WaitTimeoutError`. Notice it where a test asserts the state of a closed feature's Resource or settles an instance while a run is in flight (D501).
39
+
40
+ - dac0543: `openApplication` and `createScenario` check `imports` by type, as they already check `conditions`: an application whose enabled features import a host contract that `imports` does not bind no longer compiles, and the error names the import and its feature, ``the host contract imported as `api` by `shop.browse` requires a binding``. Pass `bind(contract, value)` for every hard and `onDemand` import; an `optional` one may stay unbound, and a binding that no enabled feature imports is refused too. A binding written by hand as `{ contract, value }`, a list annotated `ApplicationImportBinding[]` and an options record annotated `OpenApplicationOptions<Features>` or `ScenarioOptions<Features, Mount>` are refused: let the call infer the list. `ApplicationImportBinding<Value>` and `HostContract<Value>` are invariant now, so a binding of any contract is written `ApplicationImportBinding`, without an argument. Types only (D478).
41
+ - b6471b3: Pagination is applied to a built Resource instead of written in its declaration: `ctx.resource.load({ …, pagination: { load, merge, nextCursor } })` becomes `ctx.resource.paginate(ctx.resource.load({ … }), { cursor, load, merge })` in the model that declares it, and answers the same handle with `pagination` on it; a feature Resource has no pagination, so declare it in a model the feature owns. `ConsumerResource<Data, Key, Cursor>` loses its third parameter: a paginated `consumers` field is `PaginatedResource<Data, Key, Cursor, 'consumers'>`. In React `pagination.loadNext` is a plain function answering `Promise<PaginationOutcome>`, so `loadNext.run()`, `.inFlight` and `.outcome` are gone and the status is read from `pagination.state`. `loadNext({ retry: false })` starts nothing over a failed cursor, and `testPagination` from `@opetope/runtime/testing` stands in for the capability. `opetope/no-retired-vocabulary` and the compiler name the replacement of `pagination` in the record of `ctx.resource.load` or `ctx.resource.live` and of `nextCursor` in the record of `ctx.resource.paginate` (D486, D487, D488).
42
+
43
+ Behavior change: a `merge` that threw, or answered `skipChange` or a thenable, left `loadNext()` pending forever with nothing reported; now the reporter hears it once and every caller of that `loadNext()` is rejected with it. Notice it where a caller waited for a page that never came (D486, D487).
44
+
45
+ Behavior change: `pagination.state` was a new record on every write of the data, a tuple cursor a new array each time; now it keeps its record while its kind, its cursor and its error stand. Notice it where an effect or a memo keyed on it ran on every data write and now runs when the page moves (D487).
46
+
47
+ Behavior change: a page that answered but left its cursor where it was, or whose `merge` was refused, kept the state `failed` with the error of the page before; now the answer takes that failure away and the state is `ready`, and an operation that ended where it started publishes the record it left through `loading` again. Notice it where a view shows the error of a page (D487).
48
+
49
+ Behavior change: a page whose operation was superseded — by a `refresh()` or `reset()`, from inside its own `merge` included — was still written and published; now it does not land, the data stay as they were and `loadNext()` answers `superseded`. Notice it where a page was expected after a refresh started (D489).
50
+
51
+ - 3e0dc0b: `useReadable` reads a `ResourceView` too, with its demand held by committed mounts only, as `read` of a model selection holds it; the demand is committed in a layout effect, so when releasing one view synchronously changes another, the hook reads the new snapshot before paint. Its explicit type argument names the source now, not its value: `useReadable<number>(count)` is refused, so write `useReadable<Readable<number>>(count)` or let the call infer (D469).
52
+ - 54397dd: `lifetime: 'owner'` is now `lifetime: 'model'`, a model context's `acquire(resource)` is `hold(resource)`, a Resource view's `initial` is `fallback` and `identity.scope` is `identity.partition`; `opetope/no-retired-vocabulary` fixes each where it proves the context — the factories of `model`, `openModel` and a slot contribution's `model` included — and names the rest. Every Resource and its pagination, `model` and `consumers` alike, exposes a passive `observe()`, and `acquire()` answers `{ state, release }` instead of a disposer: call `lease.release()` (D514).
53
+
54
+ A Resource verb called inside a captured update supersedes the update, keeping the verb's work and leaving no loading state stuck. Each grace window of a `consumers` Resource compares its inputs with the request its last lease selected: returning to the parked identity reveals its latest state without restarting it, work already admitted goes on until its normal release, and when the window ends the data a lease read are released instead of staying cached until the next lease (D516).
55
+
56
+ Behavior change: a `reset`, `refresh` or `retry` that a confirmed write's reducer calls used to let that write land; now the write answers `superseded` and the verb's work goes on. Notice it where a confirmed write reports `superseded` although no key or request moved.
57
+
58
+ Behavior change: inside the grace window of a `consumers` Resource, a request whose key or partition differs from the parked one used to keep showing the old data; now the Resource shows `idle('unleased')` and its pagination `unavailable`, and `refresh`, `retry` and `reset` answer `skipped: unleased` only while the record is hidden — a visible parked record is served. Notice it where a passive reader or a projection expects data after the last lease.
59
+
60
+ Behavior change: a confirmed commit that superseded the load in flight of a one-shot Resource left `pending: 'refresh'` on its state for good; now nothing is pending after the commit, which answered the epoch that load was fetching. Notice it where a spinner reads `state.pending` (D489).
61
+
62
+ Behavior change: runtime activity inspection published `opetope.runtime-activity/5`; now it publishes `/6`, because the Resource lifetime literal changed, while graph and frame stay `/5` and model state `/1`. Notice it where a custom inspection adapter or a recorded fixture checks the revision (D514).
63
+
64
+ - 86c7d69: Testing fixtures have one non-React entry, `@opetope/runtime/testing`: Core no longer exports `/testing`, and React `/testing` keeps only scenarios and Slot rendering. `command` becomes `testCommand`, Navigation's `fakeLinkSource` and `fakeLinkCodec` become `testLinkSource` and `testLinkCodec`, Kit `ExternalSource.publish` becomes `set`, and the public Core `State` becomes `TestReadable` beside `testReadable`. `CommandInputArgs` is no longer exported: a wrapper forwards `RunCommandArgs` or `Parameters<CommandHook<Input, Output>['run']>`. `Scenario.waitFor` answers the accepted value, with type-guard narrowing. `opetope/no-retired-vocabulary` moves the imports with aliases that keep local and public names, and rewrites a Kit receiver only where its origin is proved (D502, D517).
65
+
66
+ Behavior change: `scenario.waitFor(read)` finished when `read` answered any truthy value; like Runtime `waitFor`, it now waits only while `read` answers `false`, `null` or `undefined`, so `0` and `''` finish at once, and it resolves with the value. Notice it where a test waits on a count or a text from JavaScript — pass an `accept` predicate for the condition it meant (D502).
67
+
68
+ - 5e7c654: A `useModel` selector reads a source only through `read`, from its second argument, now exported as `SelectionContext`: `model.count.getSnapshot()`, which read once and never updated the component, no longer compiles, and neither do `subscribe`, `acquire` or a write to a `State` (D476, D518). The types no longer check what a selector returns, so a hook generic in its model or in its value compiles without an annotation and a selector costs about half as much to check; the result is checked at run time instead (D525). The `read` of a `SelectionContext` called after the selector returned throws `TypeError: A selector's read was called after the selector returned: read inside the selector.` `opetope/no-snapshot-read-in-render`, `error` in `recommended` and in the shipped `oxlintrc.json`, now reads the inline selector as render code, so it reports more after the upgrade: a `getSnapshot()` in the selector or in a projection handed to `read(source, project)`, on any receiver, and a selector that answers the whole model, `model => model`; select the fields the component uses (D476).
69
+
70
+ Behavior change: a selector that left a `Readable` or a `ResourceView` in a field of its result used to hand the component the source object; now the selection throws `TypeError: A selector returned a Readable in field "x": read(source) inside the selector.` (or its `ResourceView` form) in development and in production. A Resource or a Command field still becomes its hook, and a source one level down passes. A result that is an array, a tuple, a promise or another container throws `Model selection requires a record of named fields, not an array, a promise or another container.` Notice it where a component throws while rendering after the upgrade.
71
+
72
+ Behavior change: a `useModel` selector that writes a `State` it closed over used to write; now it throws `TypeError: a selector reads; write in a command` before the write. Notice it where a component throws while rendering after the upgrade.
73
+
74
+ ### Patch Changes
75
+
76
+ - 5e7c654: Type diagnostics name a concrete remedy for invalid model, Resource, React selector, host binding and Navigation calls, and valid calls infer as strictly as before. A host contract union cannot bind a value of only one of its declarations: narrow to one host contract or condition. An untyped `derive` source no longer picks a diagnostic overload silently; a Resource data or key mismatch names the key at the declaration without an absolute import path, and a mismatched data, key or lifetime is an ordinary TS2322 without the exact-optional advice. The instruction a command body reads when it uses an input nothing named names the inline form first, `(ctx): ModelOf<typeof M> => ...`, and the refusal of `grace` on a model Resource says that only `consumers` has a grace window.
77
+ - 5e7c654: The hover of every public declaration gives a self-contained description of what it does and how its ownership works.
78
+ - 5e7c654: Documentation only. Migration guides are removed; the changelog lists behavior changes: `@opetope/runtime/docs` no longer ships `migrations/` or the `wave-migration.md` and `resource-migration.md` link pages. A change that neither the compiler nor the lint reports is a `Behavior change` line of the changelog, a mechanical rename is fixed by `opetope/no-retired-vocabulary`, and the compiler names the replacement of any other removed form.
79
+
80
+ `@opetope/runtime/docs` no longer ships the decision archive or the maintainer pages: a shipped document keeps the text of a link into the repository and drops its destination, and cites a decision by its number alone; the unpacked package is about 2.3 MB smaller (D492). The shipped reference pages follow one template — how to do it with a compiled example, the signature from the built declarations, the laws, and why. The README and the guides explain React 19 notification timing and inline model authoring, and declare a component as a top-level function wrapped after, `const CounterButton = requiresModels([CounterModel])(CounterButtonView)`, which React Compiler and the compiler rules of oxlint can see. The references say that every caller of a Command whose owner is fenced while its body runs is answered at the fence, not when the body returns, and call the `consumers` lifetime by that name instead of `lease`.
81
+
82
+ The guides are recipes: the task, a compiled example, why it holds and the reference pages that own its laws; the longest ones split into focused pages such as choosing a node, a source adapter, delivering live changes, showing screens on a surface and handling deep links. The link pages `spec.md`, `primitives.md`, `cookbook.md`, `how-it-works.md`, `agent-guide.md`, `devtools.md` and `releases.md` are removed; `reference/index.md` is the entry point.
83
+
84
+ - f9f6459: New: `ctx.resource.list` declares a feed of keyed items with the record of `ctx.resource.load` and `items`, `key`, `next`, and optionally `order`, `refresh` and `resolve`. One loader reads every page, the library keeps the cursor beside the data, pages fold by the key of their items, `refresh: 'head'` sews a fresh first page onto the scrolled tail, and the pages follow the law of `paginate`. `capture(list)` answers `upsert(items)` and `remove(keys)` beside `update`; `upsert` folds the repeats of a key in its batch through `resolve(earlier, later)`, or keeps the later item, where the key first came, while a page or an answer of `update` that repeats a key is refused. `ListCommit`, `OwnedListResource` and `ListLoadContext` are public Core types, so exported list helpers and hoisted loaders emit portable declarations. `testResource` from `@opetope/runtime/testing` is a Resource a test sets by hand, paginated or not (D489, D490).
85
+ - 0f102d6: Behavior change: `reset()` of a live Resource, and `retry()` of one that was `failed` or `loading` without data, answered `ready` as soon as the new connection was healthy, while the Resource was still `loading`; now they answer on the first data of the epoch, and `failed` when a `load` of that epoch fails before any data. Notice it on a quiet stream: `await reset()` waits for its first message, and a React `reset` stays `inFlight` until then (D355).
86
+ - c153f4f: A `ModelStateWriter`, also a helper parameter typed with it, reads with the same passive `read(source)` as every execution, so a hand-written writer now needs `read` beside `update` (D526). `@opetope/runtime/testing` exports `read(source)` for fixtures; Runtime `waitFor` and React `Scenario.waitFor` take a readable source directly, with an optional `accept`, and answer the accepted value, while the callback form of Runtime `waitFor` now also refuses a callback that answers a promise on some calls only, and `settled` and `waitFor` refuse a spread copy of a handle. The new `prefer-read` rule warns in the recommended config on a passive `getSnapshot()` inside an execution and fixes only the forms it proves equivalent, so a project whose lint admits no warning sees it at once.
87
+ - 1aa622e: A flush that changes nothing no longer allocates: a `derive` or `computed` that reads the same sources in the same order as last time — a source read again after another one, as in `read(a) + read(b) + read(a)` or `derive([a, b, a], …)`, included — reuses what it recorded then, and the values a flush changed are published without building a table. Every derived value and state cell retains less memory, most of all one that nobody or a single listener observes; what listeners and reactions hear, and in which order, is unchanged. `useModel` no longer repeats its commit effect when a render selects the same result.
88
+ - 86c7d69: New in `@opetope/runtime/testing`: `configureTesting({ timeoutMs })` supplies a process-wide default deadline for Runtime waits and React scenarios, which explicit options override, and its restore cancels only its own setting, in any order. `openModel` and `createScenario` with `reporter: 'collect'` collect reports in a readonly `reported`, and `expectNoReports` asserts on that list; a constructor that fails synchronously returns no handle, so inspect its rollback reports with a callback reporter. `preloadAll(application)` warms every lazy feature body without opening an instance, waits for every load and then rejects with the first observed failure, `undefined` included (D503).
89
+ - Updated dependencies [5e7c654]
90
+ - Updated dependencies [ac23b91]
91
+ - Updated dependencies [0f102d6]
92
+ - Updated dependencies [1f600e2]
93
+ - Updated dependencies [5e7c654]
94
+ - Updated dependencies [5e7c654]
95
+ - Updated dependencies [bd6ec20]
96
+ - Updated dependencies [5e7c654]
97
+ - Updated dependencies [0f102d6]
98
+ - Updated dependencies [544bdd9]
99
+ - Updated dependencies [0286832]
100
+ - Updated dependencies [b6a6564]
101
+ - Updated dependencies [dac0543]
102
+ - Updated dependencies [5e7c654]
103
+ - Updated dependencies [f9f6459]
104
+ - Updated dependencies [0f102d6]
105
+ - Updated dependencies [0f102d6]
106
+ - Updated dependencies [b6471b3]
107
+ - Updated dependencies [c153f4f]
108
+ - Updated dependencies [54397dd]
109
+ - Updated dependencies [dfc7ced]
110
+ - Updated dependencies [0286832]
111
+ - Updated dependencies [5e7c654]
112
+ - Updated dependencies [3e0dc0b]
113
+ - Updated dependencies [1aa622e]
114
+ - Updated dependencies [5e7c654]
115
+ - Updated dependencies [86c7d69]
116
+ - Updated dependencies [86c7d69]
117
+ - Updated dependencies [4df6a8b]
118
+ - @opetope/core@0.15.0
119
+ - @opetope/runtime@0.15.0
120
+
3
121
  ## 0.14.0
4
122
 
5
123
  ### Minor Changes
package/README.md CHANGED
@@ -1,93 +1,112 @@
1
1
  # `@opetope/react`
2
2
 
3
- React hooks and slots for Opetope models. A contribution grants the models its UI may read; hooks subscribe to selected data and expose commands with local status.
3
+ React 19 bindings for Opetope models and UI contributions. A `Slot` renders the contributions published into a
4
+ named extension point and grants each mount its feature models. Hooks subscribe to selected values and expose
5
+ commands as consumers with `run`, `inFlight` and `outcome`.
4
6
 
5
7
  ## Installation
6
8
 
7
9
  ```sh
8
- npm install --save-exact @opetope/core @opetope/runtime @opetope/react 'react@^19' 'react-dom@^19'
10
+ npm install --save-exact @opetope/core@0.16.0 @opetope/runtime@0.16.0 @opetope/react@0.16.0 'react@^19' 'react-dom@^19'
11
+ npm install --save-dev typescript '@types/react@^19' '@types/react-dom@^19'
9
12
  ```
10
13
 
11
- Use matching exact Opetope versions; for release candidates, install every Opetope package from `@next`.
12
- Packages are ESM-only and support Node 20.19+. React integrations support React and React DOM 19.
14
+ The API is experimental. Keep all Opetope packages at the same exact version. The commands pin the API shown
15
+ here; for prereleases, select `@next` on every Opetope package. Packages are ESM-only and support Node 20.19+.
16
+ React and React DOM must be version 19. Use a client-side TypeScript application with `strict`,
17
+ `exactOptionalPropertyTypes`, the DOM library and `jsx: "react-jsx"`. SSR and hydration are outside the current contract.
13
18
 
14
19
  ## Example
15
20
 
16
- This focused example shows the package boundary. [Start](../runtime/docs/start.md) includes a complete
17
- feature, host, React entry and cleanup in one visible module.
21
+ This module declares a counter, contributes its button and exports a mounting function. Call `mountCounter(element)`
22
+ with an HTML element; keep its returned cleanup function and await it when the host closes the screen.
18
23
 
19
24
  <!--example id="doc-readme-react-0"
20
- /* … */
21
25
  -->
22
26
 
23
27
  ```tsx
24
28
  import { defineModel } from '@opetope/core';
25
- import type { Command, Readable } from '@opetope/core';
26
- import { defineSlot, requiresModels, Slot, useModel } from '@opetope/react';
29
+ import type { Command, ModelOf, Readable } from '@opetope/core';
30
+ import { defineSlot, Slot, useModel } from '@opetope/react';
31
+ import { defineFeature, openFeature } from '@opetope/runtime';
32
+ import { createRoot } from 'react-dom/client';
27
33
 
28
- const CounterModel = defineModel<{
34
+ const Counter = defineModel<{
29
35
  readonly count: Readable<number>;
30
36
  readonly increment: Command<void, void>;
31
- }>('example.counter.model');
32
- const CounterSlot = defineSlot<{ readonly label: string }>('example.counter.slot');
33
-
34
- const CounterButton = requiresModels([CounterModel])(({ label }: { readonly label: string }) => {
35
- const {
36
- count,
37
- increment: { run, inFlight, outcome },
38
- } = useModel(CounterModel, (model, { read }) => ({
37
+ }>('example.counter');
38
+ const content = defineSlot('example.counter.content');
39
+
40
+ function CounterButton() {
41
+ const { count, increment } = useModel(Counter, (model, { read }) => ({
39
42
  count: read(model.count),
40
43
  increment: model.increment,
41
44
  }));
42
-
43
45
  return (
44
- <button disabled={inFlight} onClick={() => void run()}>
45
- {outcome?.kind === 'failed' ? 'Retry' : `${label}: ${count}`}
46
+ <button disabled={increment.inFlight} onClick={() => void increment.run()} type="button">
47
+ Count: {count}
46
48
  </button>
47
49
  );
50
+ }
51
+
52
+ const counterFeature = defineFeature('example.counter', {
53
+ own: ({ model }) => ({
54
+ counter: model(Counter, (ctx): ModelOf<typeof Counter> => {
55
+ const count = ctx.state(0);
56
+ return {
57
+ count,
58
+ increment: ctx.command(({ update }) => update(count, previous => previous + 1)),
59
+ };
60
+ }),
61
+ }),
62
+ provides: ({ slot }) => ({ content: slot(content, { Component: CounterButton }) }),
48
63
  });
49
64
 
50
- function CounterArea() {
51
- return <Slot props={{ label: 'Count' }} target={CounterSlot} />;
65
+ export async function mountCounter(element: HTMLElement) {
66
+ const instance = openFeature(counterFeature, { reporter: console.error });
67
+ try {
68
+ await instance.ready;
69
+ } catch (error) {
70
+ await instance.close();
71
+ throw error;
72
+ }
73
+ const root = createRoot(element);
74
+ root.render(<Slot target={content} />);
75
+ return async () => {
76
+ root.unmount();
77
+ await instance.close();
78
+ };
52
79
  }
53
80
  ```
54
81
 
82
+ `read` subscribes to the count; selecting the command exposes `increment.run()`. The feature owns the model and
83
+ `Slot` grants it to the button. A plain component rendered outside a contribution has no model grant. The
84
+ [Start tutorial](https://unpkg.com/@opetope/runtime@0.16.0/docs/start.md) adds the HTML entry and a visible close button.
85
+
86
+ ## Entries
87
+
88
+ | Import | Purpose |
89
+ | ---------------------------- | ---------------------------------------------------- |
90
+ | `@opetope/react` | Slots, hooks and model requirements. |
91
+ | `@opetope/react/integration` | A contribution error boundary for a host. |
92
+ | `@opetope/react/testing` | React scenarios and contribution rendering in tests. |
93
+
55
94
  ## Documentation
56
95
 
57
- The [reference](../runtime/docs/reference/react.md) owns the detailed contract, options and failure semantics.
58
- [Guides](../runtime/docs/guides/index.md) show individual tasks. Documentation is shipped with
59
- `@opetope/runtime` in `docs/`, so an installed application can read it without access to this repository.
96
+ - [Start: build, mount and close one feature](https://unpkg.com/@opetope/runtime@0.16.0/docs/start.md).
97
+ - [Guides: recipes for individual tasks](https://unpkg.com/@opetope/runtime@0.16.0/docs/guides/index.md).
98
+ - [API reference](https://unpkg.com/@opetope/runtime@0.16.0/docs/reference/react.md): signatures, options and lifecycle guarantees.
60
99
 
61
- For a contributor checkout, use `npm run ci:type --workspace @opetope/react` and
62
- `npm run ci:test --workspace @opetope/react` where provided. The root `npm run check` performs full acceptance;
63
- [contributor commands](../runtime/docs/maintainers/contributing.md) describe the build and package checks.
100
+ The links open the Markdown files from this release. The full documentation also ships in `@opetope/runtime/docs`;
101
+ with Runtime installed, start at `node_modules/@opetope/runtime/docs/start.md`.
64
102
 
65
103
  <a id="hello-ui"></a>
66
- [See Hello UI](../runtime/docs/reference/react.md#react-hello-ui).
67
-
68
104
  <a id="selecting-data-and-commands"></a>
69
- [See Selecting data and commands](../runtime/docs/reference/react.md).
70
-
71
105
  <a id="application-host"></a>
72
- [See Application host](../runtime/docs/reference/react.md).
73
-
74
106
  <a id="feature-demand-boundary"></a>
75
- [See Feature demand boundary](../runtime/docs/reference/react.md).
76
-
77
107
  <a id="contributions"></a>
78
- [See Contributions](../runtime/docs/reference/react.md).
79
-
80
108
  <a id="scenario-tests-and-physical-activity"></a>
81
- [See Scenario tests and physical activity](../runtime/docs/reference/react.md).
82
-
83
109
  <a id="testing"></a>
84
- [See Testing](../runtime/docs/reference/react.md).
85
-
86
110
  <a id="word-map-and-entries"></a>
87
- [See Word map and entries](../runtime/docs/reference/react.md).
88
-
89
111
  <a id="laws"></a>
90
- [See Laws](../runtime/docs/reference/react.md).
91
-
92
112
  <a id="compatibility-contract"></a>
93
- [See Compatibility contract](../runtime/docs/reference/react.md).
@@ -0,0 +1,20 @@
1
+ type ActFunction = (callback: () => unknown) => PromiseLike<unknown>;
2
+ /** Installs `act` for the deliveries made while it is installed; the answer removes this install, once. */
3
+ declare function installAct(act: ActFunction): () => void;
4
+ /**
5
+ * The delivery React is handed: itself with no `act` installed, and otherwise the same call inside `act`. Deliveries
6
+ * take at most two arguments — a listener none, a status `inFlight` and `outcome` — which are passed on as written.
7
+ */
8
+ declare function inAct<Deliver extends (first: never, second: never) => void>(deliver: Deliver): Deliver;
9
+ /**
10
+ * React work of this package — an effect of a hook, or the cleanup it answers — runs between `enterCommit` and
11
+ * `leaveCommit`. A delivery it causes runs directly, inside the commit React is already running, whichever `act` that
12
+ * commit belongs to. With no `act` installed the pair touches nothing, and it allocates nothing either way, so an
13
+ * effect that runs on every commit can take it: `leaveCommit` is handed what `enterCommit` answered.
14
+ */
15
+ declare function enterCommit(): boolean;
16
+ declare function leaveCommit(entered: boolean): void;
17
+ /** A step inside `act`: React flushes a synchronous scope, and pops it, before `act` returns. */
18
+ declare function actNow<Value>(act: ActFunction, run: () => Value): Value;
19
+ export { actNow, enterCommit, inAct, installAct, leaveCommit };
20
+ export type { ActFunction };
@@ -1,13 +1,23 @@
1
1
  import type { CommandInputArgs, CallRunOptions } from '@opetope/core/internal';
2
2
  import type { CommandOutcome } from './command.js';
3
+ /**
4
+ * D474: a callback's answer is not awaited and changes nothing — the run has already settled — so any value is
5
+ * accepted, and a rejected promise among them is reported like a throw, detached from the outcome it watched.
6
+ */
3
7
  type CommandRunOptions<Output> = Readonly<{
4
- onFailure?: (error: unknown) => PromiseLike<void> | void;
5
- onSuccess?: (value: Output) => PromiseLike<void> | void;
8
+ /** Called with a failure that is not a cancellation; its answer is not awaited, and a throw or rejection is reported. */
9
+ onFailure?: (error: unknown) => unknown;
10
+ /** Called with the body's value; its answer is not awaited and changes no outcome, and a throw or rejection is reported. */
11
+ onSuccess?: (value: Output) => unknown;
12
+ /** Cancels this run's wait: the run answers `cancelled`, and an already-aborted signal never reaches the command. */
6
13
  signal?: AbortSignal;
7
14
  }>;
15
+ /**
16
+ * The options element of the spread form is `CommandRunOptions<Output> | undefined`.
17
+ */
8
18
  type CommandRun<Input, Output> = {
9
19
  (input: Input, options?: CommandRunOptions<Output>): Promise<CommandOutcome<Output>>;
10
- (...args: [...CommandInputArgs<Input>, options?: CommandRunOptions<Output>]): Promise<CommandOutcome<Output>>;
20
+ (...args: [...CommandInputArgs<Input>, options?: CommandRunOptions<Output> | undefined]): Promise<CommandOutcome<Output>>;
11
21
  };
12
22
  type CommandInvoker = Readonly<{
13
23
  run: (input: never, options?: CallRunOptions<unknown>) => Promise<unknown>;
@@ -1,24 +1,24 @@
1
1
  import type { Command } from '@opetope/core';
2
2
  import type { CommandOutcome } from './command.js';
3
- import { CommandHookController } from './command-hook-controller.js';
4
3
  import type { CommandRun } from './command-hook-controller.js';
5
4
  /** D292: a cancellation is not an answer of the product, so it never settles into the outcome this hook shows. */
6
5
  type SettledOutcome<Output> = Exclude<CommandOutcome<Output>, {
7
6
  readonly kind: 'cancelled';
8
7
  }>;
8
+ /** D543: the dismissal of a snapshot without an outcome; one function, so its identity says «nothing to clear». */
9
+ declare const noOutcome: () => void;
9
10
  interface CommandHookStatus<Output> {
11
+ /**
12
+ * Clears the outcome this snapshot shows, so `outcome` answers `undefined` until the next run settles. A later
13
+ * outcome and the runs in flight stay; call it from an effect or an event handler, not during render.
14
+ */
15
+ readonly dismiss: () => void;
10
16
  readonly inFlight: boolean;
11
17
  readonly outcome: SettledOutcome<Output> | undefined;
12
18
  }
13
19
  type CommandHook<Input, Output> = CommandHookStatus<Output> & {
14
20
  readonly run: CommandRun<Input, Output>;
15
21
  };
16
- /**
17
- * The status half of a consumer, apart from what it is a consumer of. D321 gives a resource the same two verbs a
18
- * command has, so the same three React hooks answer for them: the state of this consumer, the attachment that moves
19
- * it, and the synchronisation of a slot that was already busy when this mount arrived.
20
- */
21
- declare function useCommandStatus<Input, Output>(currentSlot: CommandHookController<Input, Output>): CommandHook<Input, Output>;
22
22
  declare function useCommand<Input, Output>(command: Command<Input, Output>): CommandHook<Input, Output>;
23
- export { useCommand, useCommandStatus };
23
+ export { noOutcome, useCommand };
24
24
  export type { CommandHook };
@@ -0,0 +1,2 @@
1
+ import{jsx as p}from"react/jsx-runtime";import{useContext as G,createContext as H,useRef as F,useCallback as M,useSyncExternalStore as j,useLayoutEffect as g,useInsertionEffect as z,memo as J,useMemo as y,useState as Q}from"react";import{createAggregateError as x,isResourceView as S,resourceViewDemands as X,isCallTarget as Y,isModel as Z,isReadable as I,createLifetimeController as _,createCallController as ee,reportDetachedError as R,getContributionOwner as te,setStateFromOwner as ne,createState as se,closeStateFromOwner as E}from"@opetope/core/internal";import{isResourceValue as ie,reportRuntimeFailure as re,requireContributionModelPlans as oe,openContributionModels as ae}from"@opetope/runtime/internal";import{a as d,u as ce,b as de}from"./contribution-isolation-Ig70xFiC.js";const w=[];let v,b=0;function ue(n){const e={act:n};return w.push(e),v=n,()=>{var s;const t=w.indexOf(e);t<0||(w.splice(t,1),v=(s=w[w.length-1])==null?void 0:s.act)}}function C(n){const e=v;if(e===void 0)return n;const t=n;return(i,r)=>{if(b>0){t(i,r);return}b+=1;try{e(()=>t(i,r))}finally{b-=1}}}function h(){return v===void 0?!1:(b+=1,!0)}function m(n){n&&(b-=1)}function le(n,e){let t;b+=1;try{n(()=>{t=e()})}finally{b-=1}return t}const $=H(void 0);function fe(){const n=G($);if(n===void 0)throw new d("missing","Opetope hook was called outside a contribution mount.");return n}function A(n){return ie(n)}function B(n){const e=n.pagination;if(!(typeof e!="object"||e===null))return e}function T(n){return{loadNext:e=>B(n).loadNext(e),refresh:()=>n.refresh(),reset:()=>n.reset(),retry:()=>n.retry()}}function he(n,e){const t=e.get(n);if(t!==void 0)return t;const s=T(n);return e.set(n,s),s}const O=new Set;function q(n,e=[]){for(const t of n){const s=t.dispose;t.dispose=void 0;try{s==null||s()}catch(i){e.push(i)}}if(e.length===1)throw e[0];if(e.length>1)throw x(e,"Model selection sources failed to release.")}class L{enabled=!1;leases=new Map;listeners=new Set;retained=O;sources=new Set;subscriptions=new Map;close(){this.enabled=!1,this.sources=new Set,this.retained=O,this.releaseAll()}commit(e,t=O){this.sources=e,this.retained=t,this.enabled=!0;try{this.synchronize()}catch(s){this.enabled=!1,this.releaseAll([s])}}subscribe=e=>{const t={notify:C(e)};this.listeners.add(t);try{this.subscribeSources()}catch(s){this.listeners.delete(t),this.releaseAll([s])}return()=>{this.listeners.delete(t),this.listeners.size===0&&this.releaseAll()}};add(e){const t={dispose:void 0};this.subscriptions.set(e,t);const s=e.subscribe(this.notify);if(typeof s!="function")throw new TypeError("Model selection source must return a disposer.");this.subscriptions.get(e)===t?t.dispose=s:s()}notify=()=>{for(const e of[...this.listeners])this.listeners.has(e)&&e.notify()};releaseAll(e){const t=[...this.subscriptions.values(),...this.leases.values()];this.subscriptions.clear(),this.leases.clear(),q(t,e)}removeUnselected(){const e=[];for(const[t,s]of this.subscriptions)this.sources.has(t)||(this.subscriptions.delete(t),e.push(s));for(const[t,s]of this.leases)this.retained.has(t)||(this.leases.delete(t),e.push(s));q(e)}retain(e){const t={dispose:void 0};this.leases.set(e,t);const s=e.acquire();if(typeof s!="function")throw new TypeError("Model selection resource must answer a release disposer.");this.leases.get(e)===t?t.dispose=s:s()}ready(){return this.enabled&&this.listeners.size>0}retainSelected(){for(const e of this.retained){if(!this.enabled)return;this.retained.has(e)&&!this.leases.has(e)&&this.retain(e)}}subscribeSources(){for(const e of this.sources){if(!this.ready())return;this.sources.has(e)&&!this.subscriptions.has(e)&&this.add(e)}}synchronize(){this.removeUnselected(),this.subscribeSources(),this.retainSelected()}}class me{store=new L;observations=new WeakMap;observe(e){let t=this.observations.get(e);return t===void 0&&(t=e.observe(),this.observations.set(e,t)),t}commit(e){const t=this.observations.get(e);t===void 0?this.store.close():this.store.commit(new Set([t]),new Set(X(e)))}}function be(n){const e=F(void 0);let t=e.current;t===void 0&&(t={views:void 0},e.current=t);let s,i;if(S(n)){const a=t.views??(t.views=new me);s=a.observe(n),i=a.store}else s=n,i=s;const r=M(a=>i.subscribe(C(a)),[i]),c=M(()=>s.getSnapshot(),[s]),o=j(r,c,c);return g(()=>{var u;const a=h();try{(u=t.views)==null||u.commit(n)}finally{m(a)}},[t,n]),o}function V(n){return be(n)}const k=new WeakMap;function pe(n){if(arguments.length>1)throw new d("binding-invalid","Command follows the target it binds; binding options are forbidden.");if(!Y(n))throw new d("binding-invalid","Command target is not authentic.");return k.set(n,{target:n}),n}function ge(n){const e=k.get(n);if(e===void 0)throw new d("binding-invalid","Command binding is not authentic.");return e}function D(n){return typeof n=="object"&&n!==null&&k.has(n)}const we=Symbol("opetope.model-binding"),ye=Symbol("opetope.model-binding-identity"),ve=Object.freeze({}),N=new WeakMap;function Ce(n,e,t){if(typeof t!="string")throw new d("binding-invalid",`Model ${n.id} accepts only string fields.`);const s=Object.getOwnPropertyDescriptor(e,t);if((s==null?void 0:s.enumerable)!==!0||!("value"in s))throw new d("binding-invalid",`Model ${n.id}.${t} requires an enumerable data binding.`);return s.value}function Me(n){return I(n)||A(n)||S(n)||typeof n=="function"}function Se(n,e){const t=[],s=Reflect.ownKeys(e);if(s.length===0)throw new d("binding-invalid",`Model ${n.id} requires at least one field.`);for(const i of s){const r=Ce(n,e,i);if(!Me(r)){if(!D(r))throw new d("binding-invalid",`Model ${n.id}.${String(i)} requires a Readable, a Resource, a ResourceView or a bound command.`);t.push(r)}}return Object.freeze(t)}function P(n,e){if(!Z(n))throw new d("binding-invalid","Model declaration is not authentic.");if(typeof e!="object"||e===null)throw new d("binding-invalid",`Model ${n.id} requires a record binding.`);const t=Se(n,e),s=Object.freeze({[we]:ve,[ye]:!0});return N.set(s,{commands:t,declaration:n,model:e}),s}function Re(n){const e=N.get(n);if(e===void 0)throw new d("binding-invalid","Model binding is not authentic.");return e}let Ae=0;function Oe(n){const e=new Map,t=[],s=new Set;for(const i of n){const r=Re(i);if(e.has(r.declaration))throw new d("duplicate",`Model ${r.declaration.id} is bound twice in one mount.`);e.set(r.declaration,r.model);for(const c of r.commands)s.has(c)||(s.add(c),t.push(c))}return{commands:Object.freeze(t),frame:{commandRecords:new Map,models:e}}}class ke{frame;authority;boundCommands;closeTicket=0;isActive;lifetime;onClose;released=!1;rendererAttached=!1;renderListeners=new Set;state="detached";constructor(e,t){const s=++Ae;this.lifetime=_({id:`contribution.${String(s)}`}),this.isActive=t==null?void 0:t.isActive,this.onClose=t==null?void 0:t.onClose;const{commands:i,frame:r}=Oe(e);this.frame=r,this.boundCommands=i,this.buildCommandRecords(s)}attach(){if(this.state==="closing")return this.closeTicket+=1,this.state="active",this.rendererAttached=!0,!0;if(this.state==="closed")return!1;if(this.state==="active")throw new d("duplicate","One contribution mount cannot mount twice.");const e=this.createAuthority(this.lifetime.open());try{for(const t of this.frame.commandRecords.values())t.controller.activate()}catch(t){throw this.authority=e,this.state="active",this.close(),t}return this.authority=e,this.rendererAttached=!0,this.state="active",!0}close(){if(this.state==="closed")return;this.state="closed",this.closeTicket+=1,this.lifetime.close(),this.authority=void 0;for(const t of this.frame.commandRecords.values())t.controller.close();const e=this.onClose;this.onClose=void 0,e==null||e(),this.publishRenderable(),this.rendererAttached||this.releaseFrame()}detach(){if(!this.rendererAttached)return;if(this.rendererAttached=!1,this.state==="closed"){this.releaseFrame();return}if(this.state!=="active")return;this.state="closing";const e=++this.closeTicket;queueMicrotask(()=>{this.state==="closing"&&e===this.closeTicket&&this.close()})}diagnostics(){const e=[...this.frame.commandRecords.values()].map(t=>t.controller.diagnostics());return Object.freeze({active:this.state==="active",calls:Object.freeze(e),commandRecords:this.frame.commandRecords.size,models:this.frame.models.size})}getRenderableSnapshot=()=>this.state!=="closed"&&(this.isActive===void 0||this.isActive());releaseClosedFrame(){this.state==="closed"&&this.releaseFrame()}subscribeRenderable=e=>{if(this.state==="closed")return()=>{};const t={listener:C(e)};this.renderListeners.add(t);let s=!0;return()=>{s&&(s=!1,this.renderListeners.delete(t))}};buildCommandRecords(e){let t=0;for(const s of this.boundCommands){ge(s);const i=ee(s,{captureAuthority:this.captureAuthority,id:`contributionCommand.${String(e)}.${String(++t)}`,scheduling:{policy:"parallel"}});this.frame.commandRecords.set(s,{controller:i,invoker:Object.freeze({run:i.run})})}}captureAuthority=()=>{const e=this.authority;if(this.state!=="active"||e===void 0)throw new d("inactive","Contribution mount is not active.");return e.assertCurrent(),e};createAuthority(e){return Object.freeze({assertCurrent:()=>{if(this.state!=="active")throw new d("inactive","Contribution mount is not active.");e.assertCurrent()},isCurrent:()=>this.state==="active"&&e.isCurrent()})}publishRenderable(){for(const{listener:e}of[...this.renderListeners])try{e()}catch(t){R(t)}}releaseFrame(){this.released||(this.released=!0,this.frame.commandRecords.clear(),this.frame.models.clear(),this.boundCommands=[],this.renderListeners.clear())}}function Fe({children:n,mount:e}){const t=j(e.subscribeRenderable,e.getRenderableSnapshot,e.getRenderableSnapshot);return z(()=>{const s=h();let i;try{i=e.attach()}finally{m(s)}if(i)return()=>{const r=h();try{e.detach()}finally{m(r)}}},[e]),g(()=>{if(t)return;const s=h();try{e.releaseClosedFrame()}finally{m(s)}},[e,t]),t?p($,{value:e.frame,children:n}):null}function W(n){const e=n.bundle;n.bundle=void 0,e==null||e.frame.close()}function je(n,e){if(typeof e!="object"||e===null)return P(n,e);const t=i=>I(i)||A(i)||S(i)||typeof i=="function"||D(i),s=Object.entries(e).map(([i,r])=>[i,t(r)?r:pe(r)]);return P(n,Object.fromEntries(s))}function ze(n){return te(n)}const xe={models:[]};function U(n,e){try{n()}catch(t){throw x([e,t],"Contribution mount setup and cleanup failed.",{cause:e})}throw e}function Ie(n,e,t,s){const i=se(e),{models:r,reporter:c}=s??xe;try{const o=oe(n.models),a=o.length===0?void 0:ae(o,i,c);return{bundle:a,models:[...r,...(a==null?void 0:a.models)??[],...t],props:i}}catch(o){return U(()=>E(i),o)}}function Ee(n,e,t,s){const{bundle:i,models:r,props:c}=Ie(n,e,t,s);let o=!1;const a=()=>{if(!o){o=!0;try{i==null||i.close().catch(R)}finally{E(c)}}};try{return{frame:new ke(r.map(([l,f])=>je(l,f)),{isActive:()=>!o,onClose:a}),isOpen:()=>!o,props:c}}catch(u){return U(a,u)}}function $e(n,e){return p(n,{...e})}function Be({bundle:n,contribution:e}){const t=V(n.props),s=y(()=>e.props===void 0?t:e.props(t),[t,e]);return p(Fe,{mount:n.frame,children:$e(e.Component,s)})}function Te({authority:n,contribution:e,fixtures:t,slotProps:s}){const i=y(()=>({authority:n,bundle:void 0,contribution:e,fixtures:t,retired:!1}),[n,e,t]),[r,c]=Q(void 0),o=(r==null?void 0:r.owner)===i?r.bundle:void 0,a=F(s);return g(()=>{a.current=s}),z(()=>()=>{i.retired=!0,queueMicrotask(()=>{try{W(i)}catch(u){R(u)}})},[i]),g(()=>{const u=h();try{const l=i.bundle??(i.bundle=Ee(i.contribution,a.current,i.fixtures??[],i.authority));c(f=>(f==null?void 0:f.owner)===i?f:{bundle:l,owner:i})}finally{m(u)}return()=>{if(!i.retired)return;const l=h();try{W(i)}finally{m(l)}}},[i]),g(()=>{if((o==null?void 0:o.isOpen())!==!0)return;const u=h();try{ne(o.props,s)}finally{m(u)}},[o,s]),o===void 0?null:p(Be,{bundle:o,contribution:e})}function qe(n){const{authority:e,contribution:t,contributionId:s,fixtures:i,targetId:r}=n,c=ce(),o=y(()=>({authority:e,contribution:t,fixtures:i}),[e,t,i]),a=e==null?void 0:e.feature,u=y(()=>({contribution:s,feature:a,target:r}),[s,a,r]),l=e==null?void 0:e.reporter,f=M(K=>re(K,l),[l]);return p(de,{content:c,identity:o,report:f,source:u,children:p(Te,{...n})})}const Le=J(qe);export{Le as M,le as a,fe as b,ze as c,C as d,h as e,A as f,L as g,T as h,ue as i,m as l,B as p,he as r,V as u};
2
+ //# sourceMappingURL=contribution-frame-DL0dyVP4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contribution-frame-DL0dyVP4.js","sources":["../src/act-delivery.ts","../src/mount-context.tsx","../src/resource-command.ts","../src/model-selection-store.ts","../src/readable-hooks.ts","../src/command.ts","../src/model-binding.ts","../src/mount-frame.ts","../src/mount-provider.tsx","../src/contribution-frame.tsx"],"sourcesContent":["/*\n * D541: while a scenario given the renderer's `act` has a tree mounted, every delivery of this package to React — a\n * subscription of `useSyncExternalStore`, the status of a command or a Resource verb — runs inside that `act`. A\n * synchronous fixture write, a click that starts a command and an answer that arrives later then commit the way a\n * test wrapped in `act` commits them, and React reports no update outside one. A delivery reads the installed `act`\n * when it subscribes, so an application renders exactly as before when none is installed: the listener it hands\n * React is the listener itself.\n *\n * Every scope this package opens is synchronous. React pops a synchronous scope before `act` returns, so the scopes of\n * this package nest inside any other — the test's own, a second scenario's — and never overlap one; an asynchronous\n * scope would stay open across turns and interleave with the next one React opens. A wait therefore sleeps outside\n * `act`: what arrives while it sleeps is a delivery, and each delivery is its own scope.\n *\n * `depth` counts the scopes this package opened and has not left, and the React work this package runs itself while\n * an `act` is installed — the effects of its hooks, which commit leases and synchronize a status. A delivery inside either runs directly: React\n * queues it in the scope or the commit already running, while a scope opened inside the flush of another would end\n * the queue React is flushing.\n */\n\ntype ActFunction = (callback: () => unknown) => PromiseLike<unknown>;\n\n/** The installs in force, newest last: removing one leaves the `act` of the newest remaining install. */\nconst installs: { readonly act: ActFunction }[] = [];\nlet installed: ActFunction | undefined;\nlet depth = 0;\n\n/** Installs `act` for the deliveries made while it is installed; the answer removes this install, once. */\nfunction installAct(act: ActFunction): () => void {\n const entry = { act };\n installs.push(entry);\n installed = act;\n\n return () => {\n const at = installs.indexOf(entry);\n if (at < 0) return;\n\n installs.splice(at, 1);\n installed = installs[installs.length - 1]?.act;\n };\n}\n\n/**\n * The delivery React is handed: itself with no `act` installed, and otherwise the same call inside `act`. Deliveries\n * take at most two arguments — a listener none, a status `inFlight` and `outcome` — which are passed on as written.\n */\nfunction inAct<Deliver extends (first: never, second: never) => void>(deliver: Deliver): Deliver {\n const act = installed;\n if (act === undefined) return deliver;\n\n const call = deliver as unknown as (first: unknown, second: unknown) => void;\n const delivered = (first: unknown, second: unknown): void => {\n if (depth > 0) {\n call(first, second);\n return;\n }\n\n depth += 1;\n try {\n void act(() => call(first, second));\n } finally {\n depth -= 1;\n }\n };\n\n return delivered as unknown as Deliver;\n}\n\n/**\n * React work of this package — an effect of a hook, or the cleanup it answers — runs between `enterCommit` and\n * `leaveCommit`. A delivery it causes runs directly, inside the commit React is already running, whichever `act` that\n * commit belongs to. With no `act` installed the pair touches nothing, and it allocates nothing either way, so an\n * effect that runs on every commit can take it: `leaveCommit` is handed what `enterCommit` answered.\n */\nfunction enterCommit(): boolean {\n if (installed === undefined) return false;\n\n depth += 1;\n return true;\n}\n\nfunction leaveCommit(entered: boolean): void {\n if (entered) depth -= 1;\n}\n\n/** A step inside `act`: React flushes a synchronous scope, and pops it, before `act` returns. */\nfunction actNow<Value>(act: ActFunction, run: () => Value): Value {\n let result!: Value;\n depth += 1;\n try {\n void act(() => {\n result = run();\n });\n } finally {\n depth -= 1;\n }\n\n return result;\n}\n\nexport { actNow, enterCommit, inAct, installAct, leaveCommit };\nexport type { ActFunction };\n","import { createContext, useContext } from 'react';\n\nimport { ContributionError } from './errors';\nimport type { Frame } from './mount-frame';\n\nconst FrameContext = createContext<Frame | undefined>(undefined);\n\nfunction useFrame(): Frame {\n const frame = useContext(FrameContext);\n\n if (frame === undefined) {\n throw new ContributionError('missing', 'Opetope hook was called outside a contribution mount.');\n }\n\n return frame;\n}\n\nexport { FrameContext, useFrame };\n","/*\n * D359: the verbs of a Resource, exposed with their own outcome, and the recognition that answers\n * «is this selected field a Resource». A consumer keeps a status — `inFlight` until the operation settles, the\n * settled `outcome` — while the Resource stays owned by the model that declared it: cancelling this wait cancels the\n * wait and not the load.\n */\n\nimport type {\n PaginationOutcome,\n PaginationState,\n Resource,\n ResourceOperationOutcome,\n ResourcePagination,\n ResourceState,\n} from '@opetope/core';\nimport type { ResourceKey } from '@opetope/core/internal';\nimport { isResourceValue } from '@opetope/runtime/internal';\n\nimport type { ResourceVerbHook } from './resource-verb-hook';\n\n/**\n * D439: the widest Resource, and the name says so. `Resource<never, ResourceKey>` said the opposite in both\n * arguments — `never` is the narrowest `Data` a reader can be handed and a named `Key` *requires* `state.key`, so\n * hardly any member of the family fitted it. Nothing was refused, because every value reaches this name through a\n * cast, which is exactly why the name could drift. `ResourceKeyField<never>` requires no field, so\n * `Resource<unknown, never, 'consumers' | 'model'>` is the one form every Resource satisfies — keyed or not, paginated or not.\n */\ntype AnyResource = Resource<unknown, never, 'consumers' | 'model'>;\n\n/**\n * D349, D359: a Resource is a structural contract a host may implement with an ordinary object, so the question the\n * type of a selected field asked is answered by the runtime that owns it — the registry of the materializations it\n * built, and the structural contract for everything else. Asking it here a second time would let the two answers\n * drift, and a host adapter typed as a hook reaches the render where `state` is `undefined` and `refresh.run()`\n * throws.\n */\nfunction isResource(value: unknown): boolean {\n return isResourceValue(value);\n}\n\n/*\n * D356, D486: the nested capability — the projected pagination state and a stable `loadNext`. `state` is the one\n * source of the status a view shows: it is shared by every consumer and survives a remount, which a command's own\n * `inFlight` and `outcome` did not, and it keeps its identity until the cursor, the kind or the error moves, so it is\n * also the key a list asks for the next page by. `loadNext` is a plain function that stays the same while the\n * component holds the same Resource, and it answers the outcome of the page it asked for.\n */\n/**\n * The nested capability — the projected pagination state and a stable `loadNext`.\n */\ntype ResourcePaginationHook<Cursor extends ResourceKey> = Readonly<{\n loadNext: (options?: { readonly retry?: boolean }) => Promise<PaginationOutcome<Cursor>>;\n state: PaginationState<Cursor>;\n}>;\n\n/*\n * D359: what `useResource` answers, and what a field of a `useModel` selection whose value is a Resource answers.\n * Producer failures are settled Resource outcomes; the consumer's cancellation of a wait is `cancelled` directly.\n */\n/**\n * What `useResource` answers, and what a field of a `useModel` selection whose value is a Resource answers.\n */\ntype ResourceHook<Data, Key extends ResourceKey = never> = Readonly<{\n /**\n * Present when the Resource was paginated (`ctx.resource.paginate`); `undefined` for every other Resource.\n */\n pagination: ResourcePaginationHook<ResourceKey> | undefined;\n refresh: ResourceVerbHook;\n reset: ResourceVerbHook;\n retry: ResourceVerbHook;\n state: ResourceState<Data, Key>;\n}>;\n\ntype PaginatedResourceHook<Data, Key extends ResourceKey, Cursor extends ResourceKey> = Omit<\n ResourceHook<Data, Key>,\n 'pagination'\n> &\n Readonly<{ pagination: ResourcePaginationHook<Cursor> }>;\n\ntype ResourceInvokers = Readonly<{\n /** D486: not a command — the stable function `pagination.loadNext` is, one per Resource identity. */\n loadNext: (options?: { readonly retry?: boolean }) => Promise<unknown>;\n refresh: () => Promise<ResourceOperationOutcome>;\n reset: () => Promise<ResourceOperationOutcome>;\n retry: () => Promise<ResourceOperationOutcome>;\n}>;\n\nfunction paginationOf(resource: AnyResource): ResourcePagination<ResourceKey, 'consumers' | 'model'> | undefined {\n const capability = (resource as { readonly pagination?: unknown }).pagination;\n\n if (typeof capability !== 'object' || capability === null) return undefined;\n\n return capability as ResourcePagination<ResourceKey, 'consumers' | 'model'>;\n}\n\n/**\n * One set per Resource identity. Selected and standalone hooks both pick their controller by the identity of the\n * invoker, so a set rebuilt on every render would reset `inFlight`, drop `outcome` and change `run` — which is why it\n * is memoised against the Resource itself and never assembled during a render.\n */\nfunction createResourceInvokers(resource: AnyResource): ResourceInvokers {\n // D349: a Resource is a structural contract, so every verb is called through it and never as a detached function.\n return {\n // Only a paginated Resource hands this out, and the capability it calls through is the one it was selected with.\n loadNext: options => paginationOf(resource)!.loadNext(options),\n refresh: () => resource.refresh(),\n reset: () => resource.reset(),\n retry: () => resource.retry(),\n };\n}\n\nfunction resourceInvokers(resource: AnyResource, cache: WeakMap<object, ResourceInvokers>): ResourceInvokers {\n const existing = cache.get(resource);\n\n if (existing !== undefined) return existing;\n\n const invokers = createResourceInvokers(resource);\n cache.set(resource, invokers);\n\n return invokers;\n}\n\n/**\n * The one module of this package that talks to the runtime about a materialization, so the rest of React reads the\n * recognition and the key type from here instead of routing to `@opetope/runtime/internal` of its own.\n */\nexport { createResourceInvokers, isResource, paginationOf, resourceInvokers };\nexport type { AnyResource, PaginatedResourceHook, ResourceHook, ResourceInvokers, ResourceKey, ResourcePaginationHook };\n","import type { Readable } from '@opetope/core';\nimport { createAggregateError } from '@opetope/core/internal';\n\nimport type { ResourceDemand } from '@opetope/core/internal';\n\nimport { inAct } from './act-delivery';\n\ntype Subscription = { dispose: (() => void) | undefined };\ntype Listener = Readonly<{ notify: () => void }>;\n\nconst noLeases: ReadonlySet<ResourceDemand> = new Set();\n\nfunction releaseSubscriptions(subscriptions: Iterable<Subscription>, failures: unknown[] = []): void {\n for (const subscription of subscriptions) {\n const dispose = subscription.dispose;\n subscription.dispose = undefined;\n\n try {\n dispose?.();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length === 1) throw failures[0];\n\n if (failures.length > 1) throw createAggregateError(failures, 'Model selection sources failed to release.');\n}\n\n/** A subscription set, not a scheduler: source notifications use React's snapshot consistency check. */\nclass ModelSelectionStore {\n private enabled = false;\n /** D359: one lease per Resource identity, diffed like a subscription, so an unchanged selection takes none. */\n private readonly leases = new Map<ResourceDemand, Subscription>();\n private readonly listeners = new Set<Listener>();\n private retained: ReadonlySet<ResourceDemand> = noLeases;\n private sources: ReadonlySet<Readable<unknown>> = new Set();\n private readonly subscriptions = new Map<Readable<unknown>, Subscription>();\n\n close(): void {\n this.enabled = false;\n this.sources = new Set();\n this.retained = noLeases;\n this.releaseAll();\n }\n\n commit(sources: ReadonlySet<Readable<unknown>>, retained: ReadonlySet<ResourceDemand> = noLeases): void {\n this.sources = sources;\n this.retained = retained;\n this.enabled = true;\n\n try {\n this.synchronize();\n } catch (error) {\n this.enabled = false;\n this.releaseAll([error]);\n }\n }\n\n subscribe = (notify: () => void): (() => void) => {\n const listener = { notify: inAct(notify) };\n this.listeners.add(listener);\n\n try {\n this.subscribeSources();\n } catch (error) {\n this.listeners.delete(listener);\n this.releaseAll([error]);\n }\n\n return () => {\n this.listeners.delete(listener);\n\n if (this.listeners.size === 0) this.releaseAll();\n };\n };\n\n private add(source: Readable<unknown>): void {\n const subscription: Subscription = { dispose: undefined };\n // Reserve before foreign code: a synchronous notification may replace or close this selection.\n this.subscriptions.set(source, subscription);\n const dispose = source.subscribe(this.notify);\n\n if (typeof dispose !== 'function') throw new TypeError('Model selection source must return a disposer.');\n\n if (this.subscriptions.get(source) === subscription) subscription.dispose = dispose;\n else dispose();\n }\n\n private notify = (): void => {\n for (const listener of [...this.listeners]) {\n if (this.listeners.has(listener)) listener.notify();\n }\n };\n\n private releaseAll(failures?: unknown[]): void {\n const held = [...this.subscriptions.values(), ...this.leases.values()];\n this.subscriptions.clear();\n this.leases.clear();\n releaseSubscriptions(held, failures);\n }\n\n private removeUnselected(): void {\n const removed: Subscription[] = [];\n\n for (const [source, subscription] of this.subscriptions) {\n if (this.sources.has(source)) continue;\n\n this.subscriptions.delete(source);\n removed.push(subscription);\n }\n\n for (const [resource, lease] of this.leases) {\n if (this.retained.has(resource)) continue;\n\n this.leases.delete(resource);\n removed.push(lease);\n }\n\n releaseSubscriptions(removed);\n }\n\n /**\n * D321: `retain()` is reentrant — it reaches `activate()`, the target subscription, the first read and the\n * publication that follows, all synchronously — and a listener woken there may rebuild or close this selection.\n * The record is reserved first, the lease is taken second, and it is kept only if the record is still this one.\n */\n private retain(resource: ResourceDemand): void {\n const lease: Subscription = { dispose: undefined };\n this.leases.set(resource, lease);\n const release = resource.acquire();\n\n if (typeof release !== 'function') throw new TypeError('Model selection resource must answer a release disposer.');\n\n if (this.leases.get(resource) === lease) lease.dispose = release;\n else release();\n }\n\n /** Foreign code inside a subscription or a lease may replace this selection, so both loops ask again. */\n private ready(): boolean {\n return this.enabled && this.listeners.size > 0;\n }\n\n private retainSelected(): void {\n for (const resource of this.retained) {\n // A committed selection owns demand before React installs its passive subscription.\n if (!this.enabled) return;\n\n if (this.retained.has(resource) && !this.leases.has(resource)) this.retain(resource);\n }\n }\n\n private subscribeSources(): void {\n for (const source of this.sources) {\n if (!this.ready()) return;\n\n if (this.sources.has(source) && !this.subscriptions.has(source)) this.add(source);\n }\n }\n\n private synchronize(): void {\n this.removeUnselected();\n this.subscribeSources();\n this.retainSelected();\n }\n}\n\nexport { ModelSelectionStore };\n","import { useCallback, useLayoutEffect, useRef, useSyncExternalStore } from 'react';\n\nimport type { Readable, Resource, ResourceKey, ResourceView } from '@opetope/core';\nimport { isResourceView, resourceViewDemands } from '@opetope/core/internal';\nimport type { ResourceDemand } from '@opetope/core/internal';\n\nimport { enterCommit, inAct, leaveCommit } from './act-delivery';\nimport { ModelSelectionStore } from './model-selection-store';\n\ntype SourceValue<Source> =\n Source extends ResourceView<infer Value> ? Value : Source extends Readable<infer Value> ? Value : never;\n\n/**\n * D469: what a mount that has read a view keeps for the rest of its life. `observe()` is asked once per view, so a\n * structural view whose `observe()` answers a new Readable each time is not resubscribed by every render, and the\n * one store holds the demand roots of the committed view — two views over one root hand it over without a release.\n */\nclass ViewDemand {\n readonly store = new ModelSelectionStore();\n private readonly observations = new WeakMap<object, Readable<unknown>>();\n\n observe(view: ResourceView<unknown>): Readable<unknown> {\n let observed = this.observations.get(view);\n\n if (observed === undefined) {\n observed = view.observe();\n this.observations.set(view, observed);\n }\n\n return observed;\n }\n\n /** Demand follows the committed source: a view's roots, or none at all for a plain Readable. */\n commit(source: object): void {\n const observed = this.observations.get(source);\n\n if (observed === undefined) this.store.close();\n else\n this.store.commit(\n new Set([observed]),\n new Set<ResourceDemand>(resourceViewDemands(source as ResourceView<unknown>)),\n );\n }\n}\n\n/**\n * D469: demand follows only the source that committed. A mount may switch between a ResourceView and a plain\n * Readable; the store exists only after it has read a view.\n */\ninterface SelectionInstance {\n views: ViewDemand | undefined;\n}\n\nfunction useSourceValue<Value>(source: Readable<Value> | ResourceView<Value>): Value {\n const instanceRef = useRef<SelectionInstance | undefined>(undefined);\n let instance = instanceRef.current;\n\n if (instance === undefined) {\n instance = { views: undefined };\n instanceRef.current = instance;\n }\n\n // A valid dual-protocol host is a view first, as in the read of a model selection (D466).\n let readable: Readable<Value>;\n let target: Readable<unknown> | ModelSelectionStore;\n\n if (isResourceView(source)) {\n const demand = (instance.views ??= new ViewDemand());\n readable = demand.observe(source) as Readable<Value>;\n target = demand.store;\n } else {\n readable = source;\n target = readable;\n }\n\n const subscribe = useCallback((listener: () => void) => target.subscribe(inAct(listener)), [target]);\n const getSnapshot = useCallback(() => readable.getSnapshot(), [readable]);\n const selected = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n useLayoutEffect(() => {\n // Commit in layout: releasing A can synchronously mutate B. React must see that write before its\n // post-commit snapshot check, or B's displayed value can remain stale.\n // React replays layout setup before restoring passive subscriptions in StrictMode and Activity.\n const entered = enterCommit();\n try {\n instance.views?.commit(source);\n } finally {\n leaveCommit(entered);\n }\n }, [instance, source]);\n\n return selected;\n}\n\n/**\n * Subscribe to a Readable or lease a ResourceView for this committed mount.\n */\nexport function useReadable<\n Source extends Readable<unknown> | Resource<unknown, ResourceKey, 'consumers' | 'model'> | ResourceView<unknown>,\n>(\n source: Source extends Readable<unknown> | ResourceView<unknown>\n ? Source\n : 'read resource.state, or select the Resource in useModel',\n): SourceValue<Source> {\n return useSourceValue(source as Readable<SourceValue<Source>> | ResourceView<SourceValue<Source>>);\n}\n","import type { Command } from '@opetope/core';\nimport { isCallTarget } from '@opetope/core/internal';\n\nimport { ContributionError } from './errors';\n\n/**\n * A bound command is the authentic `Command` the model field declares, so the common path adds no wrapper. Observable\n * call state belongs to the model as a `Readable` field (D71), so a binding carries no mode.\n */\ntype CommandBindingIdentity = Command<never, unknown>;\ntype CommandBinding<Input, Output> = Command<Input, Output>;\n\ntype CommandOutcome<Output> =\n | { readonly error: unknown; readonly kind: 'failed' }\n | { readonly reason: unknown; readonly kind: 'cancelled' }\n | { readonly kind: 'ok'; readonly value: Output };\n\ntype AnyCommandBinding = CommandBinding<never, unknown>;\n\ntype CommandBindingDefinition<Input, Output> = {\n readonly target: Command<Input, Output>;\n};\n\nconst bindingDefinitions = new WeakMap<CommandBindingIdentity, CommandBindingDefinition<never, unknown>>();\n\nfunction bindCommand<Input, Output>(target: Command<Input, Output>): CommandBinding<Input, Output> {\n if (arguments.length > 1) {\n throw new ContributionError(\n 'binding-invalid',\n 'Command follows the target it binds; binding options are forbidden.',\n );\n }\n\n if (!isCallTarget(target)) throw new ContributionError('binding-invalid', 'Command target is not authentic.');\n\n bindingDefinitions.set(target, { target });\n\n return target;\n}\n\nfunction getCommandBindingDefinition<Input, Output>(\n binding: Command<Input, Output>,\n): CommandBindingDefinition<Input, Output> {\n const definition = bindingDefinitions.get(binding);\n\n if (definition === undefined) throw new ContributionError('binding-invalid', 'Command binding is not authentic.');\n\n return definition as CommandBindingDefinition<Input, Output>;\n}\n\nfunction isCommandBinding(value: unknown): value is AnyCommandBinding {\n return typeof value === 'object' && value !== null && bindingDefinitions.has(value as CommandBindingIdentity);\n}\n\nexport { bindCommand, getCommandBindingDefinition, isCommandBinding };\nexport type { CommandOutcome };\n","import type { Command, ModelOf } from '@opetope/core';\nimport { isModel, isReadable, isResourceView } from '@opetope/core/internal';\nimport type { ExactKeys, ModelIdentity } from '@opetope/core/internal';\n\nimport { isCommandBinding } from './command';\nimport { ContributionError } from './errors';\nimport { isResource } from './resource-command';\n\nconst modelBindingBrand = Symbol('opetope.model-binding');\nconst modelBindingIdentityBrand = Symbol('opetope.model-binding-identity');\nconst modelBindingMarker = Object.freeze({});\n\ntype AnyModel = ModelIdentity;\ntype AnyCommand = Command<never, unknown>;\n\ninterface ModelBindingIdentity {\n readonly [modelBindingIdentityBrand]: true;\n}\n\ninterface ModelBinding<Declaration extends AnyModel> extends ModelBindingIdentity {\n readonly [modelBindingBrand]: (declaration: Declaration) => Declaration;\n}\n\ntype ModelBindingMetadata = {\n readonly commands: readonly AnyCommand[];\n readonly declaration: AnyModel;\n readonly model: object;\n};\n\nconst registry = new WeakMap<ModelBindingIdentity, ModelBindingMetadata>();\n\n/**\n * The declaration carries the field shape in its type; binding also validates fields supplied by host code.\n * ResourceViews travel unchanged, so observing a model never acquires its dependencies.\n */\nfunction modelFieldValue(declaration: AnyModel, model: object, field: PropertyKey): unknown {\n if (typeof field !== 'string') {\n throw new ContributionError('binding-invalid', `Model ${declaration.id} accepts only string fields.`);\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(model, field);\n\n if (descriptor?.enumerable !== true || !('value' in descriptor)) {\n throw new ContributionError(\n 'binding-invalid',\n `Model ${declaration.id}.${field} requires an enumerable data binding.`,\n );\n }\n\n return descriptor.value;\n}\n\nfunction isObservedField(value: unknown): boolean {\n return isReadable(value) || isResource(value) || isResourceView(value) || typeof value === 'function';\n}\n\nfunction snapshotModelFields(declaration: AnyModel, model: object): readonly AnyCommand[] {\n const commands: AnyCommand[] = [];\n const fields = Reflect.ownKeys(model);\n\n if (fields.length === 0)\n throw new ContributionError('binding-invalid', `Model ${declaration.id} requires at least one field.`);\n\n for (const field of fields) {\n const value = modelFieldValue(declaration, model, field);\n\n // D349: a Resource is a field a model publishes, and it is not a `Readable`, so it is recognised by name.\n if (isObservedField(value)) continue;\n\n if (!isCommandBinding(value)) {\n throw new ContributionError(\n 'binding-invalid',\n `Model ${declaration.id}.${String(field)} requires a Readable, a Resource, a ResourceView or a bound command.`,\n );\n }\n\n commands.push(value);\n }\n\n return Object.freeze(commands);\n}\n\nfunction bindModel<Declaration extends AnyModel, const Keys extends PropertyKey = never>(\n declaration: Declaration,\n model: ExactKeys<Keys, ModelOf<Declaration>> & ModelOf<Declaration>,\n): ModelBinding<Declaration> {\n if (!isModel(declaration)) throw new ContributionError('binding-invalid', 'Model declaration is not authentic.');\n\n if (typeof model !== 'object' || model === null) {\n throw new ContributionError('binding-invalid', `Model ${declaration.id} requires a record binding.`);\n }\n\n const commands = snapshotModelFields(declaration, model);\n const binding = Object.freeze({\n [modelBindingBrand]: modelBindingMarker as unknown as (value: Declaration) => Declaration,\n [modelBindingIdentityBrand]: true as const,\n });\n registry.set(binding, { commands, declaration, model });\n\n return binding;\n}\n\nfunction getModelBindingMetadata(binding: ModelBindingIdentity): ModelBindingMetadata {\n const metadata = registry.get(binding);\n\n if (metadata === undefined) throw new ContributionError('binding-invalid', 'Model binding is not authentic.');\n\n return metadata;\n}\n\nexport { bindModel, getModelBindingMetadata };\nexport type { AnyCommand, AnyModel, ModelBindingIdentity };\n","import type {\n CallAuthority,\n CallController,\n CallDiagnostics,\n CallRunOptions,\n LifetimeLease,\n} from '@opetope/core/internal';\nimport { createCallController, createLifetimeController, reportDetachedError } from '@opetope/core/internal';\n\nimport { inAct } from './act-delivery';\nimport { getCommandBindingDefinition } from './command';\nimport { ContributionError } from './errors';\nimport { getModelBindingMetadata } from './model-binding';\nimport type { AnyCommand, AnyModel, ModelBindingIdentity } from './model-binding';\n\ntype RuntimeCommandInvoker = {\n readonly run: (input: never, options?: CallRunOptions<unknown>) => Promise<unknown>;\n};\n\ntype CommandRecord = {\n readonly controller: CallController<never, unknown>;\n readonly invoker: RuntimeCommandInvoker;\n};\n\n/** What a mounted contribution grants its components: the models it may read and the commands it may invoke. */\ntype Frame = {\n readonly commandRecords: Map<AnyCommand, CommandRecord>;\n readonly models: Map<AnyModel, unknown>;\n};\n\ntype MountFrameLifecycle = {\n readonly isActive: () => boolean;\n readonly onClose: () => void;\n};\n\ntype MountFrameDiagnostics = {\n readonly active: boolean;\n readonly calls: readonly CallDiagnostics[];\n readonly commandRecords: number;\n readonly models: number;\n};\n\nlet nextMountId = 0;\n\nfunction buildFrame(supplied: readonly ModelBindingIdentity[]): {\n readonly commands: readonly AnyCommand[];\n readonly frame: Frame;\n} {\n const models = new Map<AnyModel, unknown>();\n const commands: AnyCommand[] = [];\n const bound = new Set<AnyCommand>();\n\n for (const candidate of supplied) {\n const binding = getModelBindingMetadata(candidate);\n\n if (models.has(binding.declaration)) {\n throw new ContributionError('duplicate', `Model ${binding.declaration.id} is bound twice in one mount.`);\n }\n\n models.set(binding.declaration, binding.model);\n\n for (const command of binding.commands) {\n // D197: one Command is one command of the mount, however many fields of the models name it. A second name is an\n // alias, not a second command, so it shares the record, the activation and the fence.\n if (bound.has(command)) continue;\n\n bound.add(command);\n commands.push(command);\n }\n }\n\n return { commands: Object.freeze(commands), frame: { commandRecords: new Map(), models } };\n}\n\n/**\n * The lifetime of one mounted contribution. `attach` claims it for the renderer, `detach` schedules the close on the\n * next microtask so a StrictMode remount reuses the same mount, and `close` fences every command it granted (D85).\n */\nclass MountFrameImpl {\n readonly frame: Frame;\n private authority: CallAuthority | undefined;\n private boundCommands: readonly AnyCommand[];\n private closeTicket = 0;\n private readonly isActive: (() => boolean) | undefined;\n private readonly lifetime: ReturnType<typeof createLifetimeController>;\n private onClose: (() => void) | undefined;\n private released = false;\n private rendererAttached = false;\n private readonly renderListeners = new Set<{ readonly listener: () => void }>();\n private state: 'active' | 'closed' | 'closing' | 'detached' = 'detached';\n\n constructor(models: readonly ModelBindingIdentity[], lifecycle?: MountFrameLifecycle) {\n const mountId = ++nextMountId;\n this.lifetime = createLifetimeController({ id: `contribution.${String(mountId)}` });\n this.isActive = lifecycle?.isActive;\n this.onClose = lifecycle?.onClose;\n const { commands, frame } = buildFrame(models);\n this.frame = frame;\n this.boundCommands = commands;\n this.buildCommandRecords(mountId);\n }\n\n attach(): boolean {\n if (this.state === 'closing') {\n this.closeTicket += 1;\n this.state = 'active';\n this.rendererAttached = true;\n\n return true;\n }\n\n if (this.state === 'closed') return false;\n\n if (this.state === 'active') throw new ContributionError('duplicate', 'One contribution mount cannot mount twice.');\n\n const authority = this.createAuthority(this.lifetime.open());\n\n try {\n for (const record of this.frame.commandRecords.values()) record.controller.activate();\n } catch (error) {\n this.authority = authority;\n this.state = 'active';\n this.close();\n\n throw error;\n }\n\n this.authority = authority;\n this.rendererAttached = true;\n this.state = 'active';\n\n return true;\n }\n\n close(): void {\n if (this.state === 'closed') return;\n\n this.state = 'closed';\n this.closeTicket += 1;\n this.lifetime.close();\n this.authority = undefined;\n\n for (const record of this.frame.commandRecords.values()) record.controller.close();\n\n const onClose = this.onClose;\n this.onClose = undefined;\n onClose?.();\n this.publishRenderable();\n\n if (!this.rendererAttached) this.releaseFrame();\n }\n\n detach(): void {\n if (!this.rendererAttached) return;\n\n this.rendererAttached = false;\n\n if (this.state === 'closed') {\n this.releaseFrame();\n\n return;\n }\n\n if (this.state !== 'active') return;\n\n this.state = 'closing';\n const ticket = ++this.closeTicket;\n\n queueMicrotask(() => {\n if (this.state === 'closing' && ticket === this.closeTicket) this.close();\n });\n }\n\n diagnostics(): MountFrameDiagnostics {\n const calls = [...this.frame.commandRecords.values()].map(record => record.controller.diagnostics());\n\n return Object.freeze({\n active: this.state === 'active',\n calls: Object.freeze(calls),\n commandRecords: this.frame.commandRecords.size,\n models: this.frame.models.size,\n });\n }\n\n getRenderableSnapshot = (): boolean => this.state !== 'closed' && (this.isActive === undefined || this.isActive());\n\n releaseClosedFrame(): void {\n if (this.state === 'closed') this.releaseFrame();\n }\n\n subscribeRenderable = (listener: () => void): (() => void) => {\n if (this.state === 'closed') return (): void => undefined;\n\n const registration = { listener: inAct(listener) };\n this.renderListeners.add(registration);\n let subscribed = true;\n\n return (): void => {\n if (!subscribed) return;\n\n subscribed = false;\n this.renderListeners.delete(registration);\n };\n };\n\n private buildCommandRecords(mountId: number): void {\n let commandIndex = 0;\n\n // `buildFrame` already reduced the models to their distinct Commands, so every command here gets its own record.\n for (const command of this.boundCommands) {\n // Authenticity check only: the binding carries no mode since observe was removed (D71).\n getCommandBindingDefinition(command);\n const controller = createCallController(command, {\n captureAuthority: this.captureAuthority,\n id: `contributionCommand.${String(mountId)}.${String(++commandIndex)}`,\n scheduling: { policy: 'parallel' },\n });\n this.frame.commandRecords.set(command, { controller, invoker: Object.freeze({ run: controller.run }) });\n }\n }\n\n private captureAuthority = (): CallAuthority => {\n const authority = this.authority;\n\n if (this.state !== 'active' || authority === undefined) {\n throw new ContributionError('inactive', 'Contribution mount is not active.');\n }\n\n authority.assertCurrent();\n\n return authority;\n };\n\n private createAuthority(lease: LifetimeLease): CallAuthority {\n return Object.freeze({\n assertCurrent: (): void => {\n if (this.state !== 'active') throw new ContributionError('inactive', 'Contribution mount is not active.');\n\n lease.assertCurrent();\n },\n isCurrent: (): boolean => this.state === 'active' && lease.isCurrent(),\n });\n }\n\n private publishRenderable(): void {\n for (const { listener } of [...this.renderListeners]) {\n try {\n listener();\n } catch (error) {\n reportDetachedError(error);\n }\n }\n }\n\n private releaseFrame(): void {\n if (this.released) return;\n\n this.released = true;\n this.frame.commandRecords.clear();\n this.frame.models.clear();\n this.boundCommands = [];\n this.renderListeners.clear();\n }\n}\n\nexport { MountFrameImpl };\nexport type { Frame };\n","import { useInsertionEffect, useLayoutEffect, useSyncExternalStore } from 'react';\nimport type { PropsWithChildren, ReactElement } from 'react';\n\nimport { enterCommit, leaveCommit } from './act-delivery';\nimport { FrameContext } from './mount-context';\nimport type { MountFrameImpl } from './mount-frame';\n\nfunction MountProvider({\n children,\n mount,\n}: PropsWithChildren<{ readonly mount: MountFrameImpl }>): ReactElement | null {\n const renderable = useSyncExternalStore(\n mount.subscribeRenderable,\n mount.getRenderableSnapshot,\n mount.getRenderableSnapshot,\n );\n\n useInsertionEffect(() => {\n const entered = enterCommit();\n let attached: boolean;\n try {\n attached = mount.attach();\n } finally {\n leaveCommit(entered);\n }\n\n if (!attached) return undefined;\n\n return () => {\n const detaching = enterCommit();\n try {\n mount.detach();\n } finally {\n leaveCommit(detaching);\n }\n };\n }, [mount]);\n\n useLayoutEffect(() => {\n if (renderable) return;\n\n const entered = enterCommit();\n try {\n mount.releaseClosedFrame();\n } finally {\n leaveCommit(entered);\n }\n }, [mount, renderable]);\n\n return renderable ? <FrameContext value={mount.frame}>{children}</FrameContext> : null;\n}\n\nexport { MountProvider };\n","import { memo, useCallback, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ComponentType, ReactElement } from 'react';\n\nimport type { DeclarationId } from '@opetope/core';\nimport {\n closeStateFromOwner,\n createAggregateError,\n createState,\n getContributionOwner,\n isReadable,\n isResourceView,\n reportDetachedError,\n setStateFromOwner,\n} from '@opetope/core/internal';\nimport type { ModelIdentity, State } from '@opetope/core/internal';\nimport { openContributionModels, reportRuntimeFailure, requireContributionModelPlans } from '@opetope/runtime/internal';\nimport type { ContributionModelBundle, RuntimeErrorReporter } from '@opetope/runtime/internal';\n\nimport { enterCommit, leaveCommit } from './act-delivery';\nimport { bindCommand, isCommandBinding } from './command';\nimport { ContributionIsolation, useContributionErrorContent } from './contribution-isolation';\nimport { bindModel } from './model-binding';\nimport { isResource } from './resource-command';\nimport type { ModelBindingIdentity } from './model-binding';\nimport { MountFrameImpl } from './mount-frame';\nimport { MountProvider } from './mount-provider';\nimport { useReadable } from './readable-hooks';\n\ntype AnyModel = ModelIdentity;\ntype ContributionAuthority = {\n /** The feature whose generation published this contribution (D257). */\n readonly feature?: DeclarationId;\n readonly models: readonly (readonly [AnyModel, unknown])[];\n /** The reporter of the feature that published this contribution: a contained failure is its diagnostic, not ours. */\n readonly reporter?: RuntimeErrorReporter;\n};\ntype ModelFixture = readonly [declaration: AnyModel, model: unknown];\n\ntype ContributionValue = {\n readonly Component: ComponentType<never>;\n readonly models?: readonly object[] | undefined;\n readonly props?: ((slotProps: never) => object) | undefined;\n};\n\ntype ContributionMountProps = {\n readonly authority?: ContributionAuthority | undefined;\n readonly contribution: ContributionValue;\n /** The published entry this mount renders, and the slot it renders in: the identity of a contained failure (D257). */\n readonly contributionId: DeclarationId;\n readonly fixtures?: readonly ModelFixture[];\n readonly slotProps: object;\n readonly targetId: DeclarationId;\n};\n\ntype MountBundle = {\n readonly frame: MountFrameImpl;\n readonly isOpen: () => boolean;\n readonly props: State<object>;\n};\n\ntype MountOwner = {\n readonly authority: ContributionAuthority | undefined;\n bundle: MountBundle | undefined;\n readonly contribution: ContributionValue;\n readonly fixtures: readonly ModelFixture[] | undefined;\n retired: boolean;\n};\n\ntype CommittedMount = {\n readonly bundle: MountBundle;\n readonly owner: MountOwner;\n};\n\nfunction closeOwnedMount(owner: MountOwner): void {\n const bundle = owner.bundle;\n owner.bundle = undefined;\n bundle?.frame.close();\n}\n\n/**\n * Model fields arrive as authentic kernel calls; binding them registers the command records the frame needs. D349: a\n * Resource is none of those and needs none of it — it is a field the selection reads on its own terms, so it travels\n * to the frame unchanged instead of being offered to `bindCommand`, which would refuse it as inauthentic.\n */\nfunction bindFrameModel(declaration: AnyModel, model: unknown): ModelBindingIdentity {\n if (typeof model !== 'object' || model === null) return bindModel(declaration as never, model as never);\n\n const passesThrough = (value: unknown): boolean =>\n isReadable(value) ||\n isResource(value) ||\n isResourceView(value) ||\n typeof value === 'function' ||\n isCommandBinding(value);\n const fields = Object.entries(model).map(([key, value]): readonly [string, unknown] => [\n key,\n passesThrough(value) ? value : bindCommand(value as never),\n ]);\n\n return bindModel(declaration as never, Object.fromEntries(fields) as never);\n}\n\n/**\n * D70: the authority of a contribution belongs to the entry a feature published, not to the value it wrote. One\n * static contribution object may be published by two features, and each mount must read the models of its own.\n */\nfunction contributionAuthority(entry: unknown): ContributionAuthority | undefined {\n return getContributionOwner(entry) as ContributionAuthority | undefined;\n}\n\n/** A mount with no publishing generation behind it: a fixture of a component test grants nothing and reports nowhere. */\nconst unownedContribution: ContributionAuthority = { models: [] };\n\nfunction cleanupFailedMount(close: () => void, cause: unknown): never {\n try {\n close();\n } catch (error) {\n throw createAggregateError([cause, error], 'Contribution mount setup and cleanup failed.', { cause });\n }\n\n throw cause;\n}\n\nfunction contributionModels(\n contribution: ContributionValue,\n slotProps: object,\n fixtures: readonly ModelFixture[],\n owner: ContributionAuthority | undefined,\n): {\n readonly bundle: ContributionModelBundle | undefined;\n readonly models: readonly ModelFixture[];\n readonly props: State<object>;\n} {\n const props = createState(slotProps);\n const { models: granted, reporter } = owner ?? unownedContribution;\n\n try {\n const plans = requireContributionModelPlans(contribution.models);\n const bundle = plans.length === 0 ? undefined : openContributionModels(plans, props, reporter);\n\n return {\n bundle,\n models: [...granted, ...(bundle?.models ?? []), ...fixtures],\n props,\n };\n } catch (error) {\n return cleanupFailedMount(() => closeStateFromOwner(props), error);\n }\n}\n\nfunction createMountBundle(\n contribution: ContributionValue,\n slotProps: object,\n fixtures: readonly ModelFixture[],\n authority: ContributionAuthority | undefined,\n): MountBundle {\n const { bundle, models, props } = contributionModels(contribution, slotProps, fixtures, authority);\n let closed = false;\n const close = (): void => {\n if (closed) return;\n\n closed = true;\n\n try {\n void bundle?.close().catch(reportDetachedError);\n } finally {\n closeStateFromOwner(props);\n }\n };\n try {\n const frame = new MountFrameImpl(\n models.map(([declaration, model]) => bindFrameModel(declaration, model)),\n { isActive: () => !closed, onClose: close },\n );\n\n return { frame, isOpen: () => !closed, props };\n } catch (error) {\n return cleanupFailedMount(close, error);\n }\n}\n\nfunction createComponentElement(Component: ComponentType<never>, props: object): ReactElement {\n const Rendered = Component as ComponentType<object>;\n\n return <Rendered {...props} />;\n}\n\ntype MountedContributionProps = {\n readonly bundle: MountBundle;\n readonly contribution: ContributionValue;\n};\n\n/** Reads the committed props of one live mount: every hook here sees a bundle that already exists. */\nfunction MountedContribution({ bundle, contribution }: MountedContributionProps): ReactElement {\n const committedProps = useReadable(bundle.props);\n const componentProps = useMemo(\n () => (contribution.props === undefined ? committedProps : contribution.props(committedProps as never)),\n [committedProps, contribution],\n );\n\n return (\n <MountProvider mount={bundle.frame}>{createComponentElement(contribution.Component, componentProps)}</MountProvider>\n );\n}\n\n/**\n * D188: a mount is created in commit, never in render. The first pass renders nothing, the layout effect builds the\n * bundle from the props that committed and publishes it, and React flushes that update before paint. A render that\n * is thrown away — StrictMode's double invoke, an abandoned concurrent pass, a suspended sibling — therefore\n * creates no models at all, so there is nothing to sweep, adopt or replace.\n */\nfunction ContributionMount({\n authority,\n contribution,\n fixtures,\n slotProps,\n}: ContributionMountProps): ReactElement | null {\n const owner = useMemo<MountOwner>(\n () => ({ authority, bundle: undefined, contribution, fixtures, retired: false }),\n [authority, contribution, fixtures],\n );\n const [committed, setCommitted] = useState<CommittedMount | undefined>(undefined);\n const bundle = committed?.owner === owner ? committed.bundle : undefined;\n const committedSlotProps = useRef(slotProps);\n\n useLayoutEffect(() => {\n committedSlotProps.current = slotProps;\n });\n\n // Suspense disconnects layout effects while hiding, but insertion cleanup only retires an actual identity.\n // Do not close Readables in insertion: their listeners may update React. A hidden tree has no layout cleanup\n // left to run on unmount, so the microtask also releases a mount that never becomes visible again.\n useInsertionEffect(\n () => () => {\n owner.retired = true;\n queueMicrotask(() => {\n try {\n closeOwnedMount(owner);\n } catch (error) {\n reportDetachedError(error);\n }\n });\n },\n [owner],\n );\n\n // The identity of the contribution owns the mount; a reveal and StrictMode reuse what its first commit created.\n useLayoutEffect(() => {\n const entered = enterCommit();\n try {\n const created = (owner.bundle ??= createMountBundle(\n owner.contribution,\n committedSlotProps.current,\n owner.fixtures ?? [],\n owner.authority,\n ));\n setCommitted(current => (current?.owner === owner ? current : { bundle: created, owner }));\n } finally {\n leaveCommit(entered);\n }\n\n return () => {\n if (!owner.retired) return;\n\n const closing = enterCommit();\n try {\n closeOwnedMount(owner);\n } finally {\n leaveCommit(closing);\n }\n };\n }, [owner]);\n\n // Both the component and its models read the same committed snapshot, published before paint.\n useLayoutEffect(() => {\n if (bundle?.isOpen() !== true) return;\n\n const entered = enterCommit();\n try {\n setStateFromOwner(bundle.props, slotProps);\n } finally {\n leaveCommit(entered);\n }\n }, [bundle, slotProps]);\n\n if (bundle === undefined) return null;\n\n return <MountedContribution bundle={bundle} contribution={contribution} />;\n}\n\n/**\n * D256: every mount is a boundary. The isolation sits above `ContributionMount`, so it contains the render of the\n * component and the commit that builds the mount alike, and a retry rebuilds the mount instead of reusing the bundle\n * that failed. Containment is unconditional; the content a failure shows is the host policy of `ContributionBoundary`.\n */\nfunction IsolatedContributionMount(props: ContributionMountProps): ReactElement {\n const { authority, contribution, contributionId, fixtures, targetId } = props;\n const content = useContributionErrorContent();\n const identity = useMemo(() => ({ authority, contribution, fixtures }), [authority, contribution, fixtures]);\n const feature = authority?.feature;\n const source = useMemo(\n () => ({ contribution: contributionId, feature, target: targetId }),\n [contributionId, feature, targetId],\n );\n const reporter = authority?.reporter;\n const report = useCallback((error: unknown) => reportRuntimeFailure(error, reporter), [reporter]);\n\n return (\n <ContributionIsolation content={content} identity={identity} report={report} source={source}>\n <ContributionMount {...props} />\n </ContributionIsolation>\n );\n}\n\n/**\n * One mount, one memo: `Slot` recreates its children whenever `entries` changes, so publishing or withholding one\n * contribution used to re-render every other mount of that target. The props are the contribution, the slot props\n * and the fixtures, all of which are stable while nothing about that mount changed.\n */\nconst MemoizedContributionMount = memo(IsolatedContributionMount);\n\nexport { contributionAuthority, MemoizedContributionMount as ContributionMount };\nexport type { ContributionValue, ModelFixture };\n"],"names":["installs","installed","depth","installAct","act","entry","at","_a","inAct","deliver","call","first","second","enterCommit","leaveCommit","entered","actNow","run","result","FrameContext","createContext","useFrame","frame","useContext","ContributionError","isResource","value","isResourceValue","paginationOf","resource","capability","createResourceInvokers","options","resourceInvokers","cache","existing","invokers","noLeases","releaseSubscriptions","subscriptions","failures","subscription","dispose","error","createAggregateError","ModelSelectionStore","sources","retained","notify","listener","source","held","removed","lease","release","ViewDemand","view","observed","resourceViewDemands","useSourceValue","instanceRef","useRef","instance","readable","target","isResourceView","demand","subscribe","useCallback","getSnapshot","selected","useSyncExternalStore","useLayoutEffect","useReadable","bindingDefinitions","bindCommand","isCallTarget","getCommandBindingDefinition","binding","definition","isCommandBinding","modelBindingBrand","modelBindingIdentityBrand","modelBindingMarker","registry","modelFieldValue","declaration","model","field","descriptor","isObservedField","isReadable","snapshotModelFields","commands","fields","bindModel","isModel","getModelBindingMetadata","metadata","nextMountId","buildFrame","supplied","models","bound","candidate","command","MountFrameImpl","lifecycle","mountId","createLifetimeController","authority","record","onClose","ticket","calls","registration","subscribed","commandIndex","controller","createCallController","reportDetachedError","MountProvider","children","mount","renderable","useInsertionEffect","attached","detaching","_jsx","closeOwnedMount","owner","bundle","bindFrameModel","passesThrough","key","contributionAuthority","getContributionOwner","unownedContribution","cleanupFailedMount","close","cause","contributionModels","contribution","slotProps","fixtures","props","createState","granted","reporter","plans","requireContributionModelPlans","openContributionModels","closeStateFromOwner","createMountBundle","closed","createComponentElement","Component","MountedContribution","committedProps","componentProps","useMemo","ContributionMount","committed","setCommitted","useState","committedSlotProps","created","current","closing","setStateFromOwner","IsolatedContributionMount","contributionId","targetId","content","useContributionErrorContent","identity","feature","report","reportRuntimeFailure","ContributionIsolation","MemoizedContributionMount","memo"],"mappings":"mxBAsBA,MAAMA,EAA4C,CAAA,EAClD,IAAIC,EACAC,EAAQ,EAGZ,SAASC,GAAWC,EAAgB,CAClC,MAAMC,EAAQ,CAAE,IAAAD,CAAG,EACnB,OAAAJ,EAAS,KAAKK,CAAK,EACnBJ,EAAYG,EAEL,IAAK,OACV,MAAME,EAAKN,EAAS,QAAQK,CAAK,EAC7BC,EAAK,IAETN,EAAS,OAAOM,EAAI,CAAC,EACrBL,GAAYM,EAAAP,EAASA,EAAS,OAAS,CAAC,IAA5B,YAAAO,EAA+B,IAC7C,CACF,CAMA,SAASC,EAA6DC,EAAgB,CACpF,MAAML,EAAMH,EACZ,GAAIG,IAAQ,OAAW,OAAOK,EAE9B,MAAMC,EAAOD,EAeb,MAdkB,CAACE,EAAgBC,IAAyB,CAC1D,GAAIV,EAAQ,EAAG,CACbQ,EAAKC,EAAOC,CAAM,EAClB,MACF,CAEAV,GAAS,EACT,GAAI,CACGE,EAAI,IAAMM,EAAKC,EAAOC,CAAM,CAAC,CACpC,SACEV,GAAS,CACX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AE,CAAQ,GAAK,CAAClC,EAAWgC,EAAcE,CAAQ,CAAC,EACrGgC,EAAUlE,GAAA,YAAAA,EAAW,QACrB5D,EAAS8G,EACb,KAAO,CAAE,aAAcW,EAAgB,QAAAK,EAAS,OAAQJ,CAAQ,GAChE,CAACD,EAAgBK,EAASJ,CAAQ,CAAC,EAE/BxB,EAAWtC,GAAA,YAAAA,EAAW,SACtBmE,EAAS7G,EAAazB,GAAmBuI,GAAqBvI,EAAOyG,CAAQ,EAAG,CAACA,CAAQ,CAAC,EAEhG,OACEpB,EAACmD,GAAqB,CAAC,QAASN,EAAS,SAAUE,EAAU,OAAQE,EAAQ,OAAQ/H,EAAM,SACzF8E,EAACiC,GAAiB,CAAA,GAAKhB,CAAK,CAAA,EAAI,CAGtC,CAOA,MAAMmC,GAA4BC,EAAKX,EAAyB"}
@@ -1,2 +1,2 @@
1
- import{jsx as s}from"react/jsx-runtime";import{useRef as l,createContext as p,useContext as h,Component as u}from"react";import{markCancellation as a,isCancellation as C}from"@opetope/core/internal";class c extends Error{code;cause;contribution;feature;name="ContributionError";target;constructor(t,r,e={}){super(r),this.code=t,this.cause=e.cause,this.contribution=e.contribution,this.feature=e.feature,this.target=e.target,t==="inactive"&&a(this)}}const b={current:null},d=p(b);function m({children:n,error:t}){const r=l(null);return r.current=t,s(d,{value:r,children:n})}function y(){return h(d)}function f(n,t,r){const e=n==="render-failed"?"Contribution":"Error content of contribution",i=t.feature===void 0?"":` of feature ${String(t.feature)}`,o=new c(n,`${e} ${String(t.contribution)}${i} failed in slot ${String(t.target)}.`,{cause:r,...t});return C(r)?a(o):o}function g({content:n,error:t,retry:r,source:e}){return n({...e,error:t,retry:r})}class E extends u{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.report(f("error-content-failed",this.props.source,t))}render(){if(this.state.failed)return null;const{content:t,error:r,retry:e,source:i}=this.props,o=t.current;return typeof o=="function"?s(g,{content:o,error:r,retry:e,source:i}):o}}class x extends u{state={error:void 0,failed:!1,identity:void 0};static getDerivedStateFromError(t){return{error:t,failed:!0}}static getDerivedStateFromProps(t,r){return r.identity===t.identity?null:{error:void 0,failed:!1,identity:t.identity}}componentDidCatch(t){this.props.report(f("render-failed",this.props.source,t))}retry=()=>{this.setState(t=>t.failed?{error:void 0,failed:!1,identity:t.identity}:null)};render(){const{error:t,failed:r}=this.state;return r?s(E,{content:this.props.content,error:t,report:this.props.report,retry:this.retry,source:this.props.source}):this.props.children}}export{c as C,m as a,x as b,y as u};
2
- //# sourceMappingURL=contribution-isolation-Bzfbt4iM.js.map
1
+ import{jsx as s}from"react/jsx-runtime";import{useRef as l,createContext as p,useContext as h,Component as u}from"react";import{markCancellation as a,isCancellation as C}from"@opetope/core/internal";class c extends Error{code;cause;contribution;feature;name="ContributionError";target;constructor(t,r,e={}){super(r),this.code=t,this.cause=e.cause,this.contribution=e.contribution,this.feature=e.feature,this.target=e.target,t==="inactive"&&a(this)}}const b={current:null},d=p(b);function m({children:n,error:t}){const r=l(null);return r.current=t,s(d,{value:r,children:n})}function y(){return h(d)}function f(n,t,r){const e=n==="render-failed"?"Contribution":"Error content of contribution",i=t.feature===void 0?"":` of feature ${String(t.feature)}`,o=new c(n,`${e} ${String(t.contribution)}${i} failed in slot ${String(t.target)}.`,{cause:r,...t});return C(r)?a(o):o}function g({content:n,error:t,retry:r,source:e}){return n({...e,error:t,retry:r})}class E extends u{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.report(f("error-content-failed",this.props.source,t))}render(){if(this.state.failed)return null;const{content:t,error:r,retry:e,source:i}=this.props,o=t.current;return typeof o=="function"?s(g,{content:o,error:r,retry:e,source:i}):o}}class x extends u{state={error:void 0,failed:!1,identity:void 0};static getDerivedStateFromError(t){return{error:t,failed:!0}}static getDerivedStateFromProps(t,r){return r.identity===t.identity?null:{error:void 0,failed:!1,identity:t.identity}}componentDidCatch(t){this.props.report(f("render-failed",this.props.source,t))}retry=()=>{this.setState(t=>t.failed?{error:void 0,failed:!1,identity:t.identity}:null)};render(){const{error:t,failed:r}=this.state;return r?s(E,{content:this.props.content,error:t,report:this.props.report,retry:this.retry,source:this.props.source}):this.props.children}}export{m as C,c as a,x as b,y as u};
2
+ //# sourceMappingURL=contribution-isolation-Ig70xFiC.js.map