@opetope/react 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ru.md DELETED
@@ -1,414 +0,0 @@
1
- # `@opetope/react`
2
-
3
- React-привязка для моделей и UI-вкладов Opetope. Словарь пакета задаёт §3 [спецификации](../runtime/docs/spec.ru.md).
4
-
5
- ## Установка
6
-
7
- ```sh
8
- npm install @opetope/core @opetope/runtime @opetope/react 'react@^19.0.0' 'react-dom@^19.0.0'
9
- ```
10
-
11
- Используйте согласованные версии Opetope. Для release candidate добавьте `@next` каждому пакету `@opetope/*` в команде.
12
- API поставляется только в ESM; требуется Node 20.19+. Команды разработки ниже относятся к contributor checkout.
13
-
14
- Нормативные руководства EN/RU поставляются в `@opetope/runtime`: после его установки откройте
15
- `node_modules/@opetope/runtime/docs/spec.md` или `spec.ru.md`; рецепты находятся в `cookbook.md` и `cookbook.ru.md`.
16
- Для чтения установленных руководств доступ к GitHub не нужен.
17
-
18
- ## Hello UI
19
-
20
- ```tsx
21
- import { defineModel } from '@opetope/core';
22
- import type { Call, Readable } from '@opetope/core';
23
- import { defineSlot, requiresModels, Slot, useModel } from '@opetope/react';
24
-
25
- const CounterModel = defineModel<{
26
- readonly count: Readable<number>;
27
- readonly increment: Call<void, void>;
28
- }>('example.counter.model');
29
- const CounterSlot = defineSlot<{ readonly label: string }>('example.counter.slot');
30
-
31
- const CounterButton = requiresModels([CounterModel])(({ label }: { readonly label: string }) => {
32
- const {
33
- count,
34
- increment: { run, inFlight, outcome },
35
- } = useModel(CounterModel, (model, { read }) => ({
36
- count: read(model.count),
37
- increment: model.increment,
38
- }));
39
-
40
- return (
41
- <button disabled={inFlight} onClick={() => void run()}>
42
- {outcome?.status === 'failed' ? 'Retry' : `${label}: ${count}`}
43
- </button>
44
- );
45
- });
46
-
47
- function CounterArea() {
48
- return <Slot props={{ label: 'Count' }} target={CounterSlot} />;
49
- }
50
- ```
51
-
52
- Компонент не получает ни сервис, ни класс, ни ref рантайма. Монтирование вклада неявно выдаёт модели `own` его фичи;
53
- компонент или хук, читающий per-mount модель, объявляет её через `requiresModels`. `useModel` читает ровно этот кадр
54
- авторитета. `useCommand` отдаёт `{ run, inFlight, outcome }`
55
- и всегда resolve-ит исход, поэтому штатная отмена не становится unhandled rejection (D116, D292).
56
-
57
- `outcome` — последний завершившийся не-отменённый исход этого потребителя: `ok` встаёт на место прежнего `failed`,
58
- `failed` — на место прежнего `ok`, исход `cancelled` не двигает ничего, и старт прогона ничего не чистит, поэтому
59
- отказ читается, пока идёт повтор. До первого завершения он `undefined`. Читают его по дискриминанту —
60
- `outcome?.status === 'failed' ? outcome.error : null`.
61
-
62
- Команда без входа привязывается к событию стрелкой: `onClick={() => void logout.run()}`. Именно стрелка не пускает
63
- React-событие в Call и не оставляет промис висеть; `onClick={logout.run}` не компилируется, потому что `MouseEvent`
64
- не ложится в `void`. Для данных, исхода, callbacks или сигнала отдельного вызова используйте `run(input, options?)`.
65
- Там, где конфиг линтера запрещает стрелку прямо в пропсе (`react-perf/jsx-no-new-function-as-prop`,
66
- `react/jsx-no-bind`), её поднимают через `useCallback(() => void logout.run(), [logout.run])`: зависимость — `run`,
67
- а не объект хука (D290).
68
-
69
- `run` стабилен, пока invoker тот же; возвращённый объект — снимок того рендера, в котором его прочитали, и меняется
70
- вместе с `inFlight` или `outcome`, поэтому эффект или memo зависят от `run`, а не от хука, — правило
71
- `opetope/no-command-in-deps` держит это за автора (D290). Сохранённый `run` заменённого или
72
- размонтированного потребителя закрыт для новых вызовов и не перенаправляет работу на замену.
73
-
74
- Хук ничего не планирует. Каждый `run` доходит до вызова, и решает политика, с которой вызов создан (D203). Для
75
- setter абсолютного значения модель объявляет `policy: 'latest'` в `context.call`, и новый вход заменяет ожидающий
76
- именно там (D185). За потребителем остаётся своё: уже отменённый входной signal отвергается как `cancelled`, не
77
- доходя до вызова, `run` размонтированного потребителя отвергается так же, `inFlight` истинен, пока не завершился
78
- хоть один начатый им прогон, и у каждого прогона свои callbacks и signal.
79
-
80
- Чтобы объединить эквивалентную ожидающую или исполняющуюся работу, модель объявляет `dedupe: true` либо
81
- `dedupe: input => key` у `context.call`. Сохраняются первый вход и независимая отмена каждого вызывающего;
82
- обе формы запрещены с `latest` (D277). Это опции Call, а не хука.
83
-
84
- Для нескольких команд используйте объектный выбор (D174):
85
-
86
- ```tsx
87
- const { save, remove } = useCommands({ save: model.save, remove: other.remove });
88
-
89
- void save.run(input);
90
- const saving = save.inFlight;
91
- ```
92
-
93
- Импортируйте `useCommands` из `@opetope/react`. Каждое поле возвращает прежний `CommandHook`, как `useCommand`,
94
- со своими типами входа/выхода и своими `inFlight` и `outcome`. Ключи — локальные имена UI; команды могут быть
95
- из разных разрешённых моделей. Второго аргумента нет: политика есть у каждого вызова. Собственный случай у слова
96
- один — набор ключей, которого компонент не знает заранее: хуки в цикле не вызывают, а фиксированный набор это
97
- `useCommand` по слову или одна выборка `useModel`. Слово доказано упакованным потребителем `ci:pack` и остаётся
98
- кандидатом на вывод с этого входа до второго измеренного приложения (D301).
99
-
100
- Объекту прямо в рендере не нужен `useMemo`. Перестановка ключей и обновление соседнего поля сохраняют объект
101
- неизменившегося поля и `.run`. Добавление и удаление ключей не меняет число React hooks. Удаление ключа или
102
- замена его команды начинает новый локальный статус этого поля; отброшенный
103
- рендер не меняет текущий выбор. Два псевдонима одного Call имеют независимые локальные статусы, как два потребителя
104
- `useCommand`; они используют одну политику Call и одну command-запись монтирования (D197, D203). Группа не вводит общий busy, очередь или транзакцию; контролам, перезаписывающим одно значение,
105
- по-прежнему нужна одна смысловая команда. Выбираются только собственные enumerable-поля, включая symbol-ключи.
106
-
107
- ## Выбор данных и команд
108
-
109
- `useModel(Declaration, (model, { read }) => ({ ... }))` объединяет явный выбор данных и command consumers (D205, D214).
110
-
111
- Результат выбора модели может быть именованным interface без index signature (D217). Результат — плоская запись данных;
112
- arrays, functions, constructors и встроенные объекты коллекций, дат и promises не являются selection records.
113
- `read(source)` возвращает снимок; `read(source, project)` — проекцию. Authentic Calls, выбранные полями record,
114
- превращаются в тот же `CommandHook`, что у `useCommands`, с независимыми статусами aliases и стабильным `.run`.
115
- Одну команду можно выбрать без вложенных hooks:
116
-
117
- ```tsx
118
- const { logout } = useModel(AuthModel, auth => ({ logout: auth.logout }));
119
- return (
120
- <button disabled={logout.inFlight} onClick={() => void logout.run()}>
121
- Log out
122
- </button>
123
- );
124
- ```
125
-
126
- Форма с одним аргументом по-прежнему возвращает выданную модель; отдельные hooks сохраняются.
127
-
128
- Подписка создаётся только на явно прочитанные источники, одна на каждый различный Readable внутри selection.
129
- Поля данных сравниваются через `Object.is`: выбирайте скаляры, раскрывайте проекцию record в selection или
130
- возвращайте стабильные ссылки. Новый вложенный объект считается изменившимся полем. Callback чистый:
131
- без hooks, команд и side effects. Ошибка read/selector попадает в ближайший React error boundary.
132
- Изменение источников и ключей команд применяется в commit; abandoned render не меняет действующие полномочия.
133
-
134
- Hook не создаёт модель и не приобретает feature. Он арендует ровно те ресурсы, которые выборка назвала
135
- значениями: такое поле отвечает `ResourceHook`, и одна аренда на identity Resource покрывает всё монтирование, даже
136
- когда один Resource назвали два ключа (D321, D359). Больше ничего:
137
- `read(resource.state)` не арендует, и однопараметрическая форма тоже. Объединение hooks не обещает меньше подписок или
138
- более быстрый render; импорт обычного `useModel` теперь также включает реализацию selection. Дополнительного
139
- scheduler для Call нет.
140
-
141
- ## Application host
142
-
143
- Хост открывает граф фич через `openApplication`. Готовые фичи атомарно публикуют UI-вклады;
144
- обычный `Slot` монтирует их в consumer-owned целях:
145
-
146
- ```tsx
147
- <Slot target={exampleFooterSlot} />
148
- <Slot target={exampleSettingsSlot} />
149
- ```
150
-
151
- Приложение владеет временем жизни фич; UI каждой фичи монтируется через её вклады.
152
-
153
- ## Граница спроса на фичу
154
-
155
- ```tsx
156
- import { Slot } from '@opetope/react';
157
- import { FeatureBoundary, useFeatureRetry } from '@opetope/react/integration';
158
-
159
- function Retry() {
160
- return <button onClick={useFeatureRetry()}>Try again</button>;
161
- }
162
-
163
- <FeatureBoundary demand={host} error={<Retry />} fallback={<Spinner />}>
164
- <Slot props={{ itemId, onConfirmed }} target={confirmActionContentSlot} />
165
- </FeatureBoundary>;
166
-
167
- // или с render-колбэками, когда нужен сам готовый экземпляр (D177)
168
- <FeatureBoundary
169
- demand={host}
170
- error={({ error, retry }) => <Failure error={error} onRetry={retry} />}
171
- fallback={<Spinner />}
172
- >
173
- {({ exports }) => <TasksResourceLease resource={exports.tasks}>{children}</TasksResourceLease>}
174
- </FeatureBoundary>;
175
- ```
176
-
177
- `FeatureBoundary` принимает `FeatureDemandSource` от интеграции с хостом. Он держит спрос на фичу,
178
- показывает готовую ветвь после готовности спроса и изолирует `useFeatureRetry` в поддереве ошибки. Ветвь может быть узлом или
179
- render-колбэком: колбэк `children` получает готовый экземпляр, типизированный по `demand`, колбэк `error` получает
180
- `{ error, retry }`, и выполняется только показанная ветвь. Своего `useFeature` колбэку не нужно, поэтому готовый
181
- потребитель не берёт спрос второй раз; хуки по-прежнему живут в дочерних компонентах, а не в колбэке. Отдельного хука для чтения ошибки
182
- нет: хост сам передал её в `error`, поэтому знает её без второго слова (D142). UI входит в фичу через `Slot`: ни
183
- корня, ни секции `ui`, ни второго API привязки больше нет (D85).
184
-
185
- И boundary, и голый `useFeature` проверяет упакованный потребитель `ci:pack` — на общем для них законе: одна аренда
186
- на монтирование, сохраняется через севший `retry` и отпускается на размонтировании. `useFeature` это хуковая
187
- половина для случая, когда готовность рендерит сам хост, и он кандидат на вывод с этого входа до второго
188
- измеренного приложения; `FeatureBoundary` не пара `ContributionBoundary` и остаётся (D301).
189
-
190
- ## Contributions
191
-
192
- ```tsx
193
- import { defineSlot, defineSwitchSlot, Slot } from '@opetope/react';
194
-
195
- const HeaderEnd = defineSlot<{ readonly mode: 'desktop' | 'phone' }>('example.headerEnd');
196
- const PageEnd = defineSwitchSlot<'home' | 'wallet', { readonly compact: boolean }>('example.pageEnd');
197
-
198
- function Header({ mode }: { readonly mode: 'desktop' | 'phone' }) {
199
- return <Slot props={{ mode }} target={HeaderEnd} />;
200
- }
201
-
202
- function HomePageEnd() {
203
- return <Slot props={{ compact: true }} target={PageEnd('home')} />;
204
- }
205
- ```
206
-
207
- `defineSlot` создаёт подлинную цель с упорядоченным множеством вкладов; `defineSwitchSlot` лениво создаёт и
208
- кеширует стабильную цель на каждый маршрут. `Slot` читает атомарный снимок и рендерит каждый `{ Component }` в кадре
209
- авторитета того экземпляра, который вклад дал. Порядок и стабильный ключ приходят из записей вкладов ядра, поэтому
210
- React не вводит второй компаратор и второй реестр времени жизни. Упакованный потребитель `ci:pack` проверяет это
211
- кеширование и проводит через него один вклад (D301).
212
-
213
- `useResource(resource)` отвечает `{ invalidate, pagination, refresh, retry, state }`: `ResourceState` через
214
- `useSyncExternalStore`, арендой, которую отдаёт `resource.acquire()`, взятой в commit-эффекте на всё время
215
- монтирования компонента, и тремя глаголами как обычными потребителями `CommandHook` (D359). Поэтому прерванный
216
- render не открывает ничего, а при смене ссылки состояние следует новому Resource, и cleanup эффекта освобождает
217
- предыдущую аренду. Число React-хуков от Resource не зависит: объявление без `pagination` подписывается на
218
- постоянный источник и держит `loadNext`, который отвечает `skipped`, а объявление, несшее эту capability, отвечает
219
- `pagination` записью `{ loadNext, state }` (D356). Поле выборки `useModel`, значением которого является Resource,
220
- отвечает тем же хуком и берёт ту же аренду, поэтому модель не объявляет `Call<void, void>` вокруг
221
- `resource.refresh()` ради `inFlight` в кнопке. `useReadable(resource)` — это ошибка компиляции, потому что Resource
222
- не `Readable`; `useReadable(resource.state)` и `read(resource.state)` в селекторе остаются пассивными и не арендуют
223
- ничего: наблюдать и держать — независимые вопросы, поэтому селектор, читающий состояние, и стоящий рядом
224
- `useResource` подписываются дважды (D349). Обе стороны показывает компилируемый пример спецификации §2.13
225
- (D301, D321).
226
-
227
- `refresh.run()`, `retry.run()` и `invalidate.run()` доходят до Resource, которым владеет объявившая его модель:
228
- `inFlight` истинен, пока не осел исход операции, `outcome` несёт этот `ResourceOperationOutcome` значением `value`
229
- при статусе `ok`, а `run(undefined, { signal })` отменяет ожидание этого потребителя, а не работу, которой владеет
230
- модель. Два потребителя одного Resource держат раздельные статусы, а `run` сохраняет ссылку, пока та же
231
- идентичность Resource. Render, догнавший retirement, рисует терминальную запись — `idle` с причиной `retired` у Resource, которым
232
- владеет модель, и `unleased` у фасада фичи, потому что эта ссылка переживает экземпляр, — и размонтируется, отпустив
233
- аренду (D359, D364). Ничто здесь не отказывает в чтении из-за того, что кончилась чья-то жизнь: источник, у которого
234
- ушёл владелец, останавливается и продолжает отвечать последним значением, поэтому `useReadable`, `useSelector` с
235
- inline-селектором и `read` выборки просто читают дальше, и собственная память им не нужна. Оставшийся отказ — это
236
- упавшая работа: упавшее состояние, сломанный курсор пагинации, — и он по-прежнему доходит до рендера.
237
-
238
- Прямые пропсы компонента, `props`-адаптер вклада и props-`Readable` его модели используют один снимок
239
- монтирования. Входящие пропсы слота публикуются в layout до paint, поэтому прямой и адаптированный рендеры
240
- не смешивают новые пропсы со старым снимком модели. Отказ фабрики модели убирает частично созданный kernel.
241
- Модели принадлежат коммиту: брошенный рендер не создаёт модель, которую пришлось бы убирать (D170, D188).
242
- Повтор эффектов StrictMode и скрытие/раскрытие Suspense сохраняют закоммиченный набор моделей и состояние.
243
- Только реальная замена идентичности или размонтирование освобождает его; при скрытом размонтировании это делает
244
- микрозадача после того, как React отключил layout-эффекты (D209).
245
-
246
- Retry спроса привязан к источнику. После замены источника boundary новый retry может начаться, даже если retry
247
- старого ещё не завершён.
248
-
249
- Каждое монтирование — граница ошибок своего вклада (D256). Сбой рендера или коммита останавливается на нём, уходит в
250
- reporter опубликовавшей вклад фичи и не трогает остальные монтирования цели. `ContributionBoundary` один раз, над
251
- всеми слотами, говорит, что показывает упавшее монтирование:
252
-
253
- ```tsx
254
- import { ContributionBoundary } from '@opetope/react/integration';
255
-
256
- <ContributionBoundary error={({ error, retry }) => <FailedContribution error={error} onRetry={retry} />}>
257
- <Slot target={applicationSurface} />
258
- </ContributionBoundary>;
259
- ```
260
-
261
- `error` принимает узел или колбэк `{ contribution, error, feature, retry, target }` — форму отказа `FeatureBoundary`
262
- плюс идентичность упавшего: `contribution` — опубликованная запись `<фича>.<ключ provides>`, `target` — слот, поэтому
263
- одна ветвь может отвечать по поверхности. `retry` перемонтирует вклад, поэтому его модели создаются заново. Reporter
264
- опубликовавшей фичи получает ту же идентичность на `ContributionError`, у которого в `cause` исходная ошибка, с кодом
265
- `render-failed` или `error-content-failed`. Без провайдера упавшее монтирование рендерит пустоту:
266
- изоляция от него не зависит. Упавшее содержимое ошибки изолируется так же и сообщается, а не эскалируется.
267
-
268
- ## Сценарные тесты и физическая активность
269
-
270
- `createScenario(application, options)` из `@opetope/react/testing` открывает настоящее приложение и его существующую
271
- inspection session (D206, D215). Передайте обычные `imports`/`conditions` и принадлежащий тесту адаптер
272
- `host.mount(Component)`, возвращающий handle с `unmount()`. Пакет не добавляет зависимость от DOM renderer или test runner.
273
- `scenario.mount(target, { props })` использует опубликованные Slot contributions и возвращает
274
- `{ host, updateProps, unmount }`; `host` — исходный результат renderer. Typed targets требуют `options.props`,
275
- а targets без props опускают его, как в `Slot` (D217). Fixtures не обходят authority команд.
276
-
277
- Как и в `openApplication`, `conditions` можно опустить, если включённые фичи не требуют условий от хоста.
278
- Условия с `from`/`select` связываются автоматически; внешним условиям по-прежнему нужны источники (D271).
279
-
280
- Синхронный конструктор возвращает `ready`, поэтому pending lazy body можно исследовать до готовности.
281
- `waitFor(snapshot => predicate, { label, timeoutMs, pollIntervalMs })` просыпается от inspection и дополнительно
282
- опрашивает predicates внешнего UI; `notify()` будит его после изменения управляемой fixture. По умолчанию deadline
283
- равен 1000ms, polling predicate — 10ms. `ScenarioTimeoutError` содержит data-only snapshot, ограниченную историю и
284
- наблюдаемые conditions, фазы feature, body load, lane blockers и аренды ресурсов. Причины внутри repository
285
- или сети не выводятся из догадок. `getSnapshot()` и `history()` используют ту же модель наблюдения; по умолчанию
286
- хранятся 64 снимка, activity ограничена 256 записями. Capacities — целые от 1 до 10000.
287
- Не заменяйте predicates фиксированным числом ticks.
288
-
289
- `close()` синхронно ставит fence admission приложения, размонтирует зарегистрированные экраны и ждёт их cleanup
290
- вместе с physical application drain. Deadline не отменяет cleanup: последующий `close()` может дождаться того же drain.
291
- Deadline готовности также оставляет приложение доступным для inspection и явного закрытия.
292
- `ownership()` описывает только зарегистрированное владение runtime; при отсутствующих, stale или усечённых данных
293
- возвращается `unknown`. Терминальный stale-снимок считается полным лишь после подтверждённого сценарием успешного
294
- физического cleanup. Это допускает проверку нулевых счётчиков в данном scope, но не доказывает отсутствие произвольных
295
- host/UI/GC-утечек. Успешный cleanup очищает imports приложения и внутренние ссылки на renderer. Promise отказавшего
296
- cleanup может удерживать исходные ошибки и retry capabilities; сохранённый пользователем `mounted.host` удерживает его renderer result.
297
-
298
- Inspection использует схемы `opetope.devtools-graph/5` и `opetope.devtools-frame/5`, а также optional snapshots
299
- `opetope.runtime-activity/4` (D266, D275, D344, D358). В пределах одной session
300
- frame без `activity` сохраняет предыдущую activity; полный snapshot/reset без этого поля очищает наблюдение (D216).
301
- Frame с `activity` заменяет предыдущую activity целиком.
302
- Используйте согласованные версии runtime/devtools: предыдущие ревизии графа, кадров и activity отвергаются; presence слабого ребра требует graph `/5` и frame `/4`. Activity указывает execution,
303
- фактическое поколение feature, физические Calls, точных текущих lane blockers, а для каждого зарегистрированного
304
- Resource — его `kind`, `lifetime`, `epoch`, `state`, `activity` вместе с `operation`, `leases`, `subscribers`,
305
- `pagination` и `epoch` каждой физической загрузки: ни `attempt`, ни числового generation здесь нет, потому что
306
- Resource делает одну логическую попытку, а восстановление принадлежит транспорту (D358). Спрос хоста и UI-модели
307
- неизвестны. `freshness`
308
- и `truncated` отличают полное live-наблюдение от усечённого или отключённого. Закрытая session имеет stale-снимок;
309
- `closed: true` требует успешного физического drain приложения. Control authority и продуктовые payload не добавляются.
310
- Размер activity ограничен capacity записей. Сбор снимка обходит зарегистрированных owners, executors и resources,
311
- поэтому capacity не ограничивает стоимость обхода. Сбор останавливается после доказанного truncation;
312
- idle executors могут требовать обхода, чтобы подтвердить полноту данных. Обычный call dispatch не создаёт диагностических записей при
313
- выключенном наблюдении. Frames ограничены существующей ring capacity.
314
-
315
- ## Testing
316
-
317
- `@opetope/react/testing` экспортирует fixtures компонентов и сценарии приложения, а также реэкспортирует
318
- `@opetope/runtime/testing`, который, в свою очередь, реэкспортирует `@opetope/core/testing`, поэтому React-тест
319
- называет один вход (D285):
320
-
321
- - `renderSlot(target, { contribution, models, props })` монтирует опубликованную цель либо один вклад-фикстуру;
322
- - `command(run)` выдаёт подлинный `Call` для фикстуры модели плюс привязку вклада, которую читает монтирование;
323
- - `runCall(target, input?, options?)` запускает существующий подлинный `Call` без монтирования React (D261);
324
- - `testReadable(initial)`, `testResourceEpoch()`, `openModel`, `settled`, `waitFor`, `yieldTurn` и `eventually`
325
- приходят из входов ниже — для той части теста, в которой UI нет; `testResourceEpoch()` это то, что фикстура
326
- компонента, собирающая `ResourceState` руками, кладёт в её `epoch` (D362).
327
-
328
- Тест, который ничего не рендерит, должен импортировать `@opetope/runtime/testing` напрямую: React здесь нужен
329
- только `renderSlot` и привязочной половине `command`. Сам Call фикстуры чеканит `command` из
330
- `@opetope/core/testing` (D300), и это единственное имя цепочки реэкспортов, которое насквозь не проходит:
331
- React-`command` заслоняет его своим, более сильным.
332
-
333
- Харнесс `renderSlot` отдаёт `Slot` и `updateProps`: корней и их фикстур больше нет, UI входит в приложение
334
- вкладами (D85). Это не тестовое написание `<Slot>`: он монтирует фикстуру и принимает `reporter`, потому что у
335
- компонентного теста нет фичи, которой можно сообщить, — и упакованный потребитель `ci:pack` монтирует его из
336
- настоящего архива (D301).
337
-
338
- Тест, который раньше монтировал `useCommand` только ради вызова Call, может использовать `runCall` напрямую.
339
- Результат — выход Call; тест UI по-прежнему проверяет `CommandOutcome`, возвращённый смонтированным consumer:
340
-
341
- ```ts
342
- import assert from 'node:assert/strict';
343
- import { defineModel } from '@opetope/core';
344
- import type { Call } from '@opetope/core';
345
- import { defineFeature, openFeature } from '@opetope/runtime';
346
- import { runCall } from '@opetope/react/testing';
347
-
348
- const Arithmetic = defineModel<{ readonly double: Call<number, number> }>('example.testing.model');
349
- const arithmetic = defineFeature('example.testing.arithmetic', {
350
- own: ({ model }) => ({
351
- arithmetic: model(Arithmetic, context => ({
352
- double: context.call((input: number) => input * 2),
353
- })),
354
- }),
355
- exports: ({ own }) => ({ double: own.arithmetic.double }),
356
- });
357
- const instance = openFeature(arithmetic, { imports: {}, reporter: () => undefined });
358
- try {
359
- const ready = await instance.ready;
360
- const result = await runCall(ready.exports.double, 3);
361
- assert.equal(result, 6);
362
- } finally {
363
- await instance.close();
364
- }
365
- ```
366
-
367
- `runCall` возвращает `Promise<Output>` и сохраняет исходные ошибки и причины отклонения при отмене Call. Он не добавляет
368
- UI-статус, обёртку outcome, политику выполнения, создание модели или отдельное время жизни для cleanup. У Call остаются
369
- его владелец, lane и правила retirement; тест закрывает открытый экземпляр, в том числе при отказе readiness.
370
- Для void Call достаточно `runCall(target)`. Options всегда передаются третьим аргументом:
371
- `runCall(target, input, { signal })` или `runCall(voidTarget, undefined, { signal })`.
372
- `RunCallOptions` содержит только необязательный `signal`; уже отменённый сигнал отклоняет вызов до входа в его тело.
373
-
374
- `run`, `runCall` и вложенный `invoke` используют одно правило входа (D273): `void` и `undefined` можно опустить;
375
- остальные входы, включая `T | undefined`, требуют аргумент. `never` нельзя вызвать без входа.
376
- Обобщённые функции могут передавать цель и её явный вход с сохранением типов.
377
-
378
- ## Карта слов и входы
379
-
380
- | Вход | Что содержит |
381
- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
382
- | `@opetope/react` | `useModel`, `useCommand`, `useCommands`, `useReadable`, `useSelector`, `useResource`, `requiresModels`, `defineSlot`, `defineSwitchSlot`, `Slot`, `ContributionError`; типы `SlotTarget`, `SwitchSlotTarget`, `SlotContribution`, `CommandHook`, `CommandOutcome`, `ResourceHook`, `PaginatedResourceHook`, `ResourcePaginationHook` |
383
- | `@opetope/react/integration` | `FeatureBoundary`, `ContributionBoundary`, `useFeature`, `useFeatureRetry`, `FeatureBoundaryError` для integration-слоя; типы `FeatureBoundaryProps`, `ContributionBoundaryProps`, `ContributionErrorContent`, `ContributionFailure`, `FeatureDemandSource`, `FeatureDemandState`, `FeatureDemandResult`, `FeatureDemandLease` |
384
- | `@opetope/react/testing` | `renderSlot`, `command`, `createScenario`, `ScenarioTimeoutError` и типы fixtures/scenarios плюс всё, что публикуют `@opetope/runtime/testing` и `@opetope/core/testing`; только для тестов |
385
-
386
- `Call<Input, Output>` импортируется из `@opetope/core`, а UI-результат `CommandOutcome<Output>` — из `@opetope/react`. Прежний синоним `Command` и переэкспорт `CommandOutcome` из `@opetope/react/integration` удалены (D270).
387
-
388
- `Model` — типизированный ключ записи из `Readable`, `Call` и фабрик readable, которую используют UI-компоненты.
389
- Конструкторы integration-входа не переэкспортируются из безопасного входа и не могут вернуться в
390
- `ui/models/data/contracts` через локальный barrel фичи.
391
-
392
- ## Законы
393
-
394
- - `useModel(declaration)` читает только модели, объявленные вкладом;
395
- - один закоммиченный вклад владеет своим кадром моделей до размонтирования или retire;
396
- - брошенный concurrent-рендер кадр не удерживает;
397
- - `useCommand` не подписывается на invoker: наблюдаемое состояние вызова лежит в `Readable` модели;
398
- - исход `cancelled` не двигает `outcome`, и это только коды `CallError` `cancelled`
399
- и `closed`; вызов слабого порта без провайдера (`unavailable`) и отклонённая публикация
400
- (`publication-rejected`) приходят исходом `failed` и оседают в `outcome` (D138, D292);
401
- - вклад, упавший в рендере или коммите, изолируется своим монтированием и сообщается своей фиче;
402
- - `useSelector` читает свой `equals` там, где выбранное значение уже известно, поэтому именованная необобщённая
403
- функция компилируется рядом с выборкой, параметр которой выводится, — как в Core (D348);
404
- - `useSelector` сохраняет выбранную ссылку, когда изменилось что-то другое; его тождественный случай это
405
- `useReadable`, а случай поля модели — выборка `useModel`, поэтому доказывают его гейт памяти и упакованный
406
- потребитель, а не пример спецификации, и он кандидат на вывод с этого входа до второго измеренного
407
- приложения (D301);
408
- - закрытие и размонтирование синхронно фенсят новые вызовы и освобождают ссылки кадра.
409
-
410
- ## Compatibility contract
411
-
412
- ESM пакета собирается для Chrome 82+, Firefox 110+, Safari/iOS 15+, Android 82+ и Node 20.19+ и требует peer
413
- `react >=19.0.0 <20` (D251). React и ReactDOM это peers хоста, а не встроенные полифилы. Сырые модули исполняет smoke импорта
414
- по HTTP с локальным бандлом peer-ов; исторические сборки браузеров проверяет только внешняя ферма.
@@ -1,2 +0,0 @@
1
- import{jsx as m}from"react/jsx-runtime";import{useContext as T,createContext as V,useCallback as S,useRef as O,useMemo as p,useSyncExternalStore as k,useEffect as D,useInsertionEffect as A,useLayoutEffect as w,memo as N,useState as W}from"react";import{reportDetachedError as C,compatibleAbortReason as K,isCallTarget as _,isModel as G,isReadable as j,createLifetimeController as H,createCallController as J,getContributionOwner as Q,createState as U,createAggregateError as X}from"@opetope/core/internal";import{isResourceValue as Y,reportRuntimeFailure as Z,requireContributionModelPlans as ee,openContributionModels as te}from"@opetope/runtime/internal";import{C as u,u as ne,b as re}from"./contribution-isolation-Bzfbt4iM.js";import{CallError as ie}from"@opetope/core";const x=V(void 0);function oe(){const t=T(x);if(t===void 0)throw new u("missing","Opetope hook was called outside a contribution mount.");return t}function y(t){return Y(t)}function se(t,e){return new Promise((n,r)=>{const i=()=>{r(new ie("cancelled","Resource operation wait was cancelled.",K(e)))};if(e.aborted){i();return}e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function ae(t,e){var r;const n=(r=e==null?void 0:e.onSuccess)==null?void 0:r.call(e,t);return n!==void 0&&Promise.resolve(n).catch(C),t}function v(t){return{run:(e,n)=>{let r;try{r=Promise.resolve(t())}catch(o){return Promise.reject(o)}const i=n==null?void 0:n.signal;return(i===void 0?r:se(r,i)).then(o=>ae(o,n))}}}const ce=Object.freeze({kind:"skipped",reason:"resource-not-ready"});function de(t){const e=t.pagination;if(!(typeof e!="object"||e===null))return e}function E(t){return{invalidate:v(()=>t.invalidate()),loadNext:v(()=>{const e=t.pagination;return e===void 0?Promise.resolve(ce):e.loadNext()}),refresh:v(()=>t.refresh()),retry:v(()=>t.retry())}}function ue(t,e){const n=e.get(t);if(n!==void 0)return n;const r=E(t);return e.set(t,r),r}const le=t=>t;function F(t,e,n){const r=e,i=(n==null?void 0:n.equals)??Object.is,o=S(d=>t.subscribe(d),[t]),c=O(void 0);let s=c.current;s===void 0&&(s={hasValue:!1,value:void 0},c.current=s);const a=p(()=>{let d=!1,h,f;return()=>{const b=t.getSnapshot();if(d&&Object.is(h,b))return f;const g=r(b);if(!d){let R=g;return s.hasValue&&i(s.value,g)&&(R=s.value),d=!0,h=b,f=R,f}return i(f,g)?(h=b,f):(h=b,f=g,f)}},[s,i,t,r]),l=k(o,a,a);return D(()=>{s.hasValue=!0,s.value=l},[s,l]),l}function z(t){return F(t,le)}const M=new WeakMap;function I(t){if(arguments.length>1)throw new u("binding-invalid","Command follows the target it binds; binding options are forbidden.");if(!_(t))throw new u("binding-invalid","Command target is not authentic.");return M.set(t,{target:t}),t}function fe(t){const e=M.get(t);if(e===void 0)throw new u("binding-invalid","Command binding is not authentic.");return e}function $(t){return typeof t=="object"&&t!==null&&M.has(t)}const he=Symbol("opetope.model-binding"),me=Symbol("opetope.model-binding-identity"),be=Object.freeze({}),L=new WeakMap;function pe(t,e,n){if(typeof n!="string")throw new u("binding-invalid",`Model ${t.id} accepts only string fields.`);const r=Object.getOwnPropertyDescriptor(e,n);if((r==null?void 0:r.enumerable)!==!0||!("value"in r))throw new u("binding-invalid",`Model ${t.id}.${n} requires an enumerable data binding.`);return r.value}function ge(t,e){const n=[],r=Reflect.ownKeys(e);if(r.length===0)throw new u("binding-invalid",`Model ${t.id} requires at least one field.`);for(const i of r){const o=pe(t,e,i);if(!(j(o)||y(o)||typeof o=="function")){if(!$(o))throw new u("binding-invalid",`Model ${t.id}.${String(i)} requires a Readable, a Resource or a bound command.`);n.push(o)}}return Object.freeze(n)}function q(t,e){if(!G(t))throw new u("binding-invalid","Model declaration is not authentic.");if(typeof e!="object"||e===null)throw new u("binding-invalid",`Model ${t.id} requires a record binding.`);const n=ge(t,e),r=Object.freeze({[he]:be,[me]:!0});return L.set(r,{commands:n,declaration:t,model:e}),r}function we(t){const e=L.get(t);if(e===void 0)throw new u("binding-invalid","Model binding is not authentic.");return e}let Ce=0;function ve(t){const e=new Map,n=[],r=new Set;for(const i of t){const o=we(i);if(e.has(o.declaration))throw new u("duplicate",`Model ${o.declaration.id} is bound twice in one mount.`);e.set(o.declaration,o.model);for(const c of o.commands)r.has(c)||(r.add(c),n.push(c))}return{commands:Object.freeze(n),frame:{commandRecords:new Map,models:e}}}class ye{frame;authority;boundCommands;closeTicket=0;isActive;lifetime;onClose;released=!1;rendererAttached=!1;renderListeners=new Set;state="detached";constructor(e,n){const r=++Ce;this.lifetime=H({id:`contribution.${String(r)}`}),this.isActive=n==null?void 0:n.isActive,this.onClose=n==null?void 0:n.onClose;const{commands:i,frame:o}=ve(e);this.frame=o,this.boundCommands=i,this.buildCommandRecords(r)}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 u("duplicate","One contribution mount cannot mount twice.");const e=this.createAuthority(this.lifetime.open());try{for(const n of this.frame.commandRecords.values())n.controller.activate()}catch(n){throw this.authority=e,this.state="active",this.close(),n}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 n of this.frame.commandRecords.values())n.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(n=>n.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 n={listener:e};this.renderListeners.add(n);let r=!0;return()=>{r&&(r=!1,this.renderListeners.delete(n))}};buildCommandRecords(e){let n=0;for(const r of this.boundCommands){fe(r);const i=J(r,{captureAuthority:this.captureAuthority,id:`contributionCommand.${String(e)}.${String(++n)}`,scheduling:{policy:"parallel"}});this.frame.commandRecords.set(r,{controller:i,invoker:Object.freeze({run:i.run})})}}captureAuthority=()=>{const e=this.authority;if(this.state!=="active"||e===void 0)throw new u("inactive","Contribution mount is not active.");return e.assertCurrent(),e};createAuthority(e){return Object.freeze({assertCurrent:()=>{if(this.state!=="active")throw new u("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(n){C(n)}}releaseFrame(){this.released||(this.released=!0,this.frame.commandRecords.clear(),this.frame.models.clear(),this.boundCommands=[],this.renderListeners.clear())}}function Me({children:t,mount:e}){const n=k(e.subscribeRenderable,e.getRenderableSnapshot,e.getRenderableSnapshot);return A(()=>{if(e.attach())return()=>e.detach()},[e]),w(()=>{n||e.releaseClosedFrame()},[e,n]),n?m(x,{value:e.frame,children:t}):null}function B(t){const e=t.bundle;t.bundle=void 0,e==null||e.frame.close()}function Re(t,e){if(typeof e!="object"||e===null)return q(t,e);const n=i=>j(i)||y(i)||typeof i=="function"||$(i),r=Object.entries(e).map(([i,o])=>[i,n(o)?o:I(o)]);return q(t,Object.fromEntries(r))}function Se(t){return Q(t)}const Oe={models:[]};function P(t,e){try{t()}catch(n){throw X([e,n],"Contribution mount setup and cleanup failed.",{cause:e})}throw e}function ke(t,e,n,r){const i=U(e),{models:o,reporter:c}=r??Oe;try{const s=ee(t.models),a=s.length===0?void 0:te(s,i,c);return{bundle:a,models:[...o,...(a==null?void 0:a.models)??[],...n],props:i}}catch(s){return P(i.close,s)}}function Ae(t,e,n,r){const{bundle:i,models:o,props:c}=ke(t,e,n,r);let s=!1;const a=()=>{if(!s){s=!0;try{i==null||i.close().catch(C)}finally{c.close()}}};try{return{frame:new ye(o.map(([d,h])=>Re(d,h)),{isActive:()=>!s,onClose:a}),isOpen:()=>!s,props:c}}catch(l){return P(a,l)}}function je(t,e){return m(t,{...e})}function xe({bundle:t,contribution:e}){const n=z(t.props),r=p(()=>e.props===void 0?n:e.props(n),[n,e]);return m(Me,{mount:t.frame,children:je(e.Component,r)})}function Ee({authority:t,contribution:e,fixtures:n,slotProps:r}){const i=p(()=>({authority:t,bundle:void 0,contribution:e,fixtures:n,retired:!1}),[t,e,n]),[o,c]=W(void 0),s=(o==null?void 0:o.owner)===i?o.bundle:void 0,a=O(r);return w(()=>{a.current=r}),A(()=>()=>{i.retired=!0,queueMicrotask(()=>{try{B(i)}catch(l){C(l)}})},[i]),w(()=>{const l=i.bundle??(i.bundle=Ae(i.contribution,a.current,i.fixtures??[],i.authority));return c(d=>(d==null?void 0:d.owner)===i?d:{bundle:l,owner:i}),()=>{i.retired&&B(i)}},[i]),w(()=>{(s==null?void 0:s.isOpen())===!0&&s.props.set(r)},[s,r]),s===void 0?null:m(xe,{bundle:s,contribution:e})}function Fe(t){const{authority:e,contribution:n,contributionId:r,fixtures:i,targetId:o}=t,c=ne(),s=p(()=>({authority:e,contribution:n,fixtures:i}),[e,n,i]),a=e==null?void 0:e.feature,l=p(()=>({contribution:r,feature:a,target:o}),[r,a,o]),d=e==null?void 0:e.reporter,h=S(f=>Z(f,d),[d]);return m(re,{content:c,identity:s,report:h,source:l,children:m(Ee,{...t})})}const ze=N(Fe);export{ze as M,z as a,Se as b,E as c,F as d,I as e,y as i,de as p,ue as r,oe as u};
2
- //# sourceMappingURL=contribution-frame-DkNmjChZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"contribution-frame-DkNmjChZ.js","sources":["../src/mount-context.tsx","../src/resource-command.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":["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, dressed as the commands a button already knows, 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 { CallError } from '@opetope/core';\nimport type {\n PaginationOutcome,\n PaginationState,\n Resource,\n ResourceOperationOutcome,\n ResourceState,\n} from '@opetope/core';\nimport { compatibleAbortReason, reportDetachedError } from '@opetope/core/internal';\nimport type { CallRunOptions, ResourceKey } from '@opetope/core/internal';\nimport { isResourceValue } from '@opetope/runtime/internal';\n\nimport type { CommandHook } from './command-hook';\nimport type { CommandInvoker } from './command-hook-controller';\n\ntype AnyResource = Resource<never, ResourceKey>;\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/** D356: the nested capability, with `loadNext` as a command and the projected pagination state beside it. */\ntype ResourcePaginationHook<Cursor extends ResourceKey> = Readonly<{\n loadNext: CommandHook<void, 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 * The verbs never reject (a Resource answers an outcome), so the ordinary path of `outcome` is\n * `{ status: 'ok', value }`; `failed` stays in the type because the controller turns a synchronous throw of an\n * invoker into it, and the wrapper below carries its own test that it never throws synchronously.\n */\ntype ResourceHook<Data, Key extends ResourceKey = never> = Readonly<{\n invalidate: CommandHook<void, ResourceOperationOutcome>;\n /** Present when the declaration carried `pagination`; `undefined` for every other Resource. */\n pagination: ResourcePaginationHook<ResourceKey> | undefined;\n refresh: CommandHook<void, ResourceOperationOutcome>;\n retry: CommandHook<void, ResourceOperationOutcome>;\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 invalidate: CommandInvoker;\n loadNext: CommandInvoker;\n refresh: CommandInvoker;\n retry: CommandInvoker;\n}>;\n\n/** The consumer's own cancellation: it ends this wait, and the work the model owns keeps running. */\nfunction awaitCancellable(operation: Promise<unknown>, signal: AbortSignal): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const cancel = (): void => {\n reject(new CallError('cancelled', 'Resource operation wait was cancelled.', compatibleAbortReason(signal)));\n };\n\n if (signal.aborted) {\n cancel();\n\n return;\n }\n\n signal.addEventListener('abort', cancel, { once: true });\n operation.then(\n value => {\n signal.removeEventListener('abort', cancel);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener('abort', cancel);\n reject(error);\n },\n );\n });\n}\n\nfunction notifySuccess(value: unknown, options: CallRunOptions<unknown> | undefined): unknown {\n const notification = options?.onSuccess?.(value);\n\n // The failure of a consumer's own callback is detached from the operation it watched, as it is for a command.\n if (notification !== undefined) void Promise.resolve(notification).catch(reportDetachedError);\n\n return value;\n}\n\n/**\n * The invariant of this wrapper: it never throws synchronously, so the `failed` outcome a consumer can see is the one\n * the verb itself produced and never one this layer invented in the middle of a render commit.\n */\nfunction operationInvoker(start: () => Promise<unknown>): CommandInvoker {\n return {\n run: (_input: never, options?: CallRunOptions<unknown>): Promise<unknown> => {\n let operation: Promise<unknown>;\n\n try {\n operation = Promise.resolve(start());\n } catch (error) {\n return Promise.reject(error);\n }\n\n const signal = options?.signal;\n\n return (signal === undefined ? operation : awaitCancellable(operation, signal)).then(value =>\n notifySuccess(value, options),\n );\n },\n };\n}\n\n/** A Resource without the capability still answers a `loadNext` invoker, so the hook count never moves. */\nconst unavailablePage: PaginationOutcome<ResourceKey> = Object.freeze({\n kind: 'skipped',\n reason: 'resource-not-ready',\n});\n\nfunction paginationOf(resource: AnyResource): ResourcePaginationHook<ResourceKey> | 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 unknown as ResourcePaginationHook<ResourceKey>;\n}\n\n/**\n * One set per Resource identity. `selectEntry` and `useCommandSlot` 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 invalidate: operationInvoker(() => resource.invalidate()),\n loadNext: operationInvoker(() => {\n const capability = (resource as { readonly pagination?: { loadNext(): Promise<unknown> } }).pagination;\n\n return capability === undefined ? Promise.resolve(unavailablePage) : capability.loadNext();\n }),\n refresh: operationInvoker(() => resource.refresh()),\n retry: operationInvoker(() => 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 { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\n\nimport type { Readable } from '@opetope/core';\nimport type { EqualityOption } from '@opetope/core/internal';\n\nconst identity = <Value>(value: Value): Value => value;\n\n/**\n * D364: what this mount answered last, and nothing about closes. A source whose owner retired stops instead of\n * refusing — it keeps answering its last value — so a render that races a retirement shows its last frame and\n * unmounts (G13) without the reader having to remember anything for it.\n */\ninterface SelectionInstance<Selected> {\n hasValue: boolean;\n value: Selected | undefined;\n}\n\n/**\n * D279: the source and the selection are positional; `equals` is the one modifier, spelled as in Core — including\n * D348's rule for where the comparator is read, so a named non-generic one compiles here as it does in `derive`.\n */\nexport function useSelector<Value, Selected>(\n readable: Readable<Value>,\n select: (value: NoInfer<Value>) => Selected,\n options?: { readonly equals?: EqualityOption<NoInfer<Selected>> },\n): Selected {\n const selector = select;\n const isEqual = options?.equals ?? Object.is;\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const instanceRef = useRef<SelectionInstance<Selected> | undefined>(undefined);\n let instance = instanceRef.current;\n\n if (instance === undefined) {\n instance = { hasValue: false, value: undefined };\n instanceRef.current = instance;\n }\n\n const getSelectedSnapshot = useMemo(() => {\n let initialized = false;\n let sourceSnapshot: Value;\n let selectedSnapshot: Selected;\n\n return (): Selected => {\n const nextSource = readable.getSnapshot();\n\n if (initialized && Object.is(sourceSnapshot, nextSource)) return selectedSnapshot;\n\n const nextSelected = selector(nextSource);\n\n if (!initialized) {\n let nextSelectedSnapshot = nextSelected;\n\n if (instance.hasValue && isEqual(instance.value, nextSelected)) {\n nextSelectedSnapshot = instance.value as Selected;\n }\n\n initialized = true;\n sourceSnapshot = nextSource;\n selectedSnapshot = nextSelectedSnapshot;\n\n return selectedSnapshot;\n }\n\n if (isEqual(selectedSnapshot, nextSelected)) {\n sourceSnapshot = nextSource;\n\n return selectedSnapshot;\n }\n\n sourceSnapshot = nextSource;\n selectedSnapshot = nextSelected;\n\n return selectedSnapshot;\n };\n }, [instance, isEqual, readable, selector]);\n\n const selected = useSyncExternalStore(subscribe, getSelectedSnapshot, getSelectedSnapshot);\n\n useEffect(() => {\n instance.hasValue = true;\n instance.value = selected;\n }, [instance, selected]);\n\n return selected;\n}\n\nexport function useReadable<Value>(readable: Readable<Value>): Value {\n return useSelector(readable, identity);\n}\n","import type { Call } from '@opetope/core';\nimport { isCallTarget } from '@opetope/core/internal';\n\nimport { ContributionError } from './errors';\n\n/**\n * A bound command is the authentic `Call` 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 = Call<never, unknown>;\ntype CommandBinding<Input, Output> = Call<Input, Output>;\n\ntype CommandOutcome<Output> =\n | { readonly error: unknown; readonly status: 'failed' }\n | { readonly reason: unknown; readonly status: 'cancelled' }\n | { readonly status: 'ok'; readonly value: Output };\n\ntype AnyCommandBinding = CommandBinding<never, unknown>;\n\ntype CommandBindingDefinition<Input, Output> = {\n readonly target: Call<Input, Output>;\n};\n\nconst bindingDefinitions = new WeakMap<CommandBindingIdentity, CommandBindingDefinition<never, unknown>>();\n\nfunction bindCommand<Input, Output>(target: Call<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: Call<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 { Call, ModelOf } from '@opetope/core';\nimport { isModel, isReadable } from '@opetope/core/internal';\nimport type { ModelIdentity, NoExtraKeys } 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 = Call<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 * A model field is either a stable Readable or a bound command. The declaration carries the shape in its type, so\n * binding authority is the runtime check that every published field is one of those two authentic kinds.\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 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 (isReadable(value) || isResource(value) || typeof value === 'function') continue;\n\n if (!isCommandBinding(value)) {\n throw new ContributionError(\n 'binding-invalid',\n `Model ${declaration.id}.${String(field)} requires a Readable, a Resource 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 Actual extends ModelOf<Declaration>>(\n declaration: Declaration,\n model: Actual & NoExtraKeys<Actual, 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 { 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 Call 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 };\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 Calls, 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 { 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 attached = mount.attach();\n\n if (!attached) return undefined;\n\n return () => mount.detach();\n }, [mount]);\n\n useLayoutEffect(() => {\n if (!renderable) mount.releaseClosedFrame();\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, State } from '@opetope/core';\nimport {\n createAggregateError,\n createState,\n getContributionOwner,\n isReadable,\n reportDetachedError,\n} from '@opetope/core/internal';\nimport type { ModelIdentity } from '@opetope/core/internal';\nimport { openContributionModels, reportRuntimeFailure, requireContributionModelPlans } from '@opetope/runtime/internal';\nimport type { ContributionModelBundle, RuntimeErrorReporter } from '@opetope/runtime/internal';\n\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) || isResource(value) || typeof value === 'function' || 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(props.close, 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 props.close();\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 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\n return () => {\n if (owner.retired) closeOwnedMount(owner);\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) bundle.props.set(slotProps);\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":["FrameContext","createContext","useFrame","frame","useContext","ContributionError","isResource","value","isResourceValue","awaitCancellable","operation","signal","resolve","reject","cancel","CallError","compatibleAbortReason","error","notifySuccess","options","notification","_a","reportDetachedError","operationInvoker","start","_input","unavailablePage","paginationOf","resource","capability","createResourceInvokers","resourceInvokers","cache","existing","invokers","identity","useSelector","readable","select","selector","isEqual","subscribe","useCallback","listener","instanceRef","useRef","instance","getSelectedSnapshot","useMemo","initialized","sourceSnapshot","selectedSnapshot","nextSource","nextSelected","nextSelectedSnapshot","selected","useSyncExternalStore","useEffect","useReadable","bindingDefinitions","bindCommand","target","isCallTarget","getCommandBindingDefinition","binding","definition","isCommandBinding","modelBindingBrand","modelBindingIdentityBrand","modelBindingMarker","registry","modelFieldValue","declaration","model","field","descriptor","snapshotModelFields","commands","fields","isReadable","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","lease","MountProvider","children","mount","renderable","useInsertionEffect","useLayoutEffect","_jsx","closeOwnedMount","owner","bundle","bindFrameModel","passesThrough","key","contributionAuthority","entry","getContributionOwner","unownedContribution","cleanupFailedMount","close","cause","createAggregateError","contributionModels","contribution","slotProps","fixtures","props","createState","granted","reporter","plans","requireContributionModelPlans","openContributionModels","createMountBundle","closed","createComponentElement","Component","MountedContribution","committedProps","componentProps","ContributionMount","committed","setCommitted","useState","committedSlotProps","created","current","IsolatedContributionMount","contributionId","targetId","content","useContributionErrorContent","feature","source","report","reportRuntimeFailure","ContributionIsolation","MemoizedContributionMount","memo"],"mappings":"qwBAKA,MAAMA,EAAeC,EAAiC,MAAS,EAE/D,SAASC,IAAQ,CACf,MAAMC,EAAQC,EAAWJ,CAAY,EAErC,GAAIG,IAAU,OACZ,MAAM,IAAIE,EAAkB,UAAW,uDAAuD,EAGhG,OAAOF,CACT,CCgBA,SAASG,EAAWC,EAAc,CAChC,OAAOC,EAAgBD,CAAK,CAC9B,CAqCA,SAASE,GAAiBC,EAA6BC,EAAmB,CACxE,OAAO,IAAI,QAAiB,CAACC,EAASC,IAAU,CAC9C,MAAMC,EAAS,IAAW,CACxBD,EAAO,IAAIE,GAAU,YAAa,yCAA0CC,EAAsBL,CAAM,CAAC,CAAC,CAC5G,EAEA,GAAIA,EAAO,QAAS,CAClBG,EAAM,EAEN,MACF,CAEAH,EAAO,iBAAiB,QAASG,EAAQ,CAAE,KAAM,GAAM,EACvDJ,EAAU,KACRH,GAAQ,CACNI,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