@burojs/react 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -6
- package/dist/flows-runtime.cjs +1162 -0
- package/dist/flows-runtime.cjs.map +1 -0
- package/dist/flows-runtime.d.cts +153 -0
- package/dist/flows-runtime.d.ts +153 -0
- package/dist/flows-runtime.js +1157 -0
- package/dist/flows-runtime.js.map +1 -0
- package/dist/index.cjs +1629 -3862
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2259 -723
- package/dist/index.d.ts +2259 -723
- package/dist/index.js +1412 -3692
- package/dist/index.js.map +1 -1
- package/dist/present-flow-BM8vaiZX.cjs +10152 -0
- package/dist/present-flow-BM8vaiZX.cjs.map +1 -0
- package/dist/present-flow-pFzbn0cZ.js +9015 -0
- package/dist/present-flow-pFzbn0cZ.js.map +1 -0
- package/dist/types-DH3beUOO.d.cts +488 -0
- package/dist/types-DH3beUOO.d.ts +488 -0
- package/package.json +24 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"present-flow-pFzbn0cZ.js","names":["cancelledError","samePortableValue","isCurrentGeneration","execute","cancelledError","#descriptor","#runtime","#queryClient","#key","#lease","#consumerGeneration","#listeners","#state","#stateForLease","#consumeLease","#unsubscribeLease","#unsubscribeSession","#retire","#active","#dirtyBeforeFirstQuery","#hasStartedQuery","#retired","#reduceQuery","#scheduleDirtyRefetch","#close","#protocolFailure","#withProtocolFailure","#seenEvent","#markDirty","#reduceSnapshot","#publish","#failProtocol","#latestRevision","#latestValue","#compare","#equals","#failConflict","#protocolReconciliationRequested","#protocolTerminal","#dirtyGeneration","#scheduled","#refetching","samePortableValue","NO_SUBSCRIBE","AppContext","resourceHandle","isRecord","AppContext","AppContext","reportedMissing","NO_SCOPE","AppContext","AppContext","PENDING","ABSENT","PENDING","#client","#requests","#state","NO_UNSUBSCRIBE","CLOSED","PENDING","READY_NULL","#reading","#note","#via","#query","#inherit","#row","#read","#operand","NO_ACCESS","segment","EMPTY","PENDING","NONE","NONE","AppContext"],"sources":["../src/data/query-execution.ts","../src/data/live/query-live-observer.ts","../src/data/live/live-queries.ts","../src/data/context.tsx","../src/data/query-options.ts","../src/hooks/data/use-query-descriptor.ts","../src/runtime.tsx","../src/context.ts","../src/hooks/use-t.ts","../src/hooks/data/use-standard-query-descriptor.ts","../src/hooks/data/use-list.ts","../src/hooks/data/use-one.ts","../src/hooks/data/retry-record-read.ts","../src/hooks/data/use-many.ts","../src/data/count-policy.ts","../src/data/invalidation.ts","../src/data/mutation-options.ts","../src/hooks/data/use-standard-mutation-descriptor.ts","../src/hooks/data/use-create.ts","../src/hooks/data/use-update.ts","../src/audit/context.ts","../src/hooks/router/router-adapter.tsx","../src/hooks/relation-aggregator.tsx","../src/hooks/url-state/codec.ts","../src/hooks/url-state/hidden-predicates.ts","../src/hooks/url-state/write-search-params.ts","../src/hooks/url-state/list-state-store.ts","../src/hooks/url-state/use-resource-url-state.ts","../src/hooks/url-state/get-resource-params.ts","../src/navigation/resolve-route.ts","../src/navigation/dismiss-scope.tsx","../src/navigation/navigation-guard.tsx","../src/navigation/use-route-navigate.ts","../src/notifications/notification-sink.tsx","../src/hooks/use-app.ts","../src/ui/context.tsx","../src/hooks/use-component.ts","../src/ui/ui-presentations.tsx","../src/ui/mount.tsx","../src/ui/use-ui-present.ts","../src/hooks/use-ctx.ts","../src/quick/entry-gate.ts","../src/quick/quick-entry-context.ts","../src/quick/quick-stack.ts","../src/quick/use-quick.ts","../src/dispatch/default-effects.ts","../src/dispatch/dispatcher-context.tsx","../src/fields/definitions.ts","../src/fields/provider.tsx","../src/data/use-session-participant.ts","../src/flows/row-batch.ts","../src/forms/controller/placements.ts","../src/forms/controller/query-pool.ts","../src/forms/controller/inline-blockers.tsx","../src/flows/inline-holder.ts","../src/forms/controller/screen-state.tsx","../src/forms/controller/use-source-resolver.ts","../src/hooks/use-current-user-id.ts","../src/flows/attempts-channel.ts","../src/flows/attempts-store.ts","../src/flows/attempts-binding.tsx","../src/forms/controller/draft.ts","../src/forms/controller/draft-session-binding.tsx","../src/data/action-data-access.ts","../src/forms/controller/route-source.ts","../src/audit/internal.ts","../src/audit/use-form-submit-audit.ts","../src/hooks/use-permissions.ts","../src/checks/use-check-gate.ts","../src/checks/use-checks.ts","../src/forms/use-form-screen.ts","../src/forms/conditional.ts","../src/forms/select-seeds.ts","../src/flows/run-registry.ts","../src/forms/controller/seeds.ts","../src/forms/controller/payload.ts","../src/forms/controller/pipeline.ts","../src/fields/meta-validation.ts","../src/fields/use-field-implementation.ts","../src/fields/use-field-meta-outcomes.ts","../src/policy-side-channel.ts","../src/forms/controller/resource-less-placements.ts","../src/forms/controller/use-form-controller.ts","../src/hooks/use-field-access.ts","../src/hooks/use-record-title.ts","../src/hooks/use-projected-record.ts","../src/navigation/use-page-access.ts","../src/flows/page-host.ts","../src/flows/page-flow-gate.ts","../src/flows/present-flow.ts"],"sourcesContent":["import {\n isDataError,\n normalizeDataError,\n resolveDataCapability,\n type DataError,\n type DataSessionSnapshot,\n type ErasedQueryDescriptor,\n type QueryContext,\n type QueryResultFor,\n} from '@burojs/core';\n\nimport type { DataRuntimeContextValue } from './runtime.js';\n\nfunction cancelledError(code: 'aborted' | 'stale-generation' = 'aborted'): DataError {\n return {\n kind: 'cancelled',\n code,\n message:\n code === 'aborted'\n ? 'Data query was aborted.'\n : 'Data query completed after its session generation changed.',\n };\n}\n\nfunction sameSnapshot(left: DataSessionSnapshot, right: DataSessionSnapshot): boolean {\n return left.sessionKey === right.sessionKey && left.generation === right.generation;\n}\n\nfunction samePortableValue(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object')\n return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => samePortableValue(value, right[index]))\n );\n }\n const leftEntries = Object.entries(left);\n const rightRecord = right as Record<string, unknown>;\n return (\n leftEntries.length === Object.keys(rightRecord).length &&\n leftEntries.every(\n ([key, value]) =>\n Object.prototype.hasOwnProperty.call(rightRecord, key) &&\n samePortableValue(value, rightRecord[key]),\n )\n );\n}\n\nfunction replayStillMatches<T extends ErasedQueryDescriptor>(\n runtime: DataRuntimeContextValue,\n descriptor: T,\n captured: DataSessionSnapshot,\n): boolean {\n const state = runtime.dataSession.getState();\n return (\n state.status === 'ready' &&\n sameSnapshot(state.snapshot, captured) &&\n descriptor.sessionKey === captured.sessionKey &&\n samePortableValue(descriptor.scopeKey, captured.scopeKey)\n );\n}\n\nfunction linkedAbortController(signals: readonly AbortSignal[]): {\n readonly controller: AbortController;\n dispose(): void;\n} {\n const controller = new AbortController();\n const abort = () => controller.abort();\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort();\n break;\n }\n signal.addEventListener('abort', abort, { once: true });\n }\n return {\n controller,\n dispose() {\n for (const signal of signals) signal.removeEventListener('abort', abort);\n },\n };\n}\n\nfunction isCurrentGeneration<T extends ErasedQueryDescriptor>(\n runtime: DataRuntimeContextValue,\n descriptor: T,\n snapshot: DataSessionSnapshot,\n serviceIdentity: object,\n): boolean {\n const state = runtime.dataSession.getState();\n if (state.status !== 'ready' || !sameSnapshot(state.snapshot, snapshot)) return false;\n try {\n return runtime.providers.resolve(descriptor.providerId).identity === serviceIdentity;\n } catch {\n return false;\n }\n}\n\n/**\n * Executes a descriptor only within the active core session generation. A\n * provider that ignores abort still cannot return data for a replacement\n * provider/session identity.\n */\nexport async function executeQuery<T extends ErasedQueryDescriptor>(args: {\n readonly descriptor: T;\n readonly runtime: DataRuntimeContextValue;\n readonly signal: AbortSignal;\n readonly replayCount?: 0 | 1;\n readonly replaySnapshot?: DataSessionSnapshot;\n}): Promise<QueryResultFor<T>> {\n if (\n args.replaySnapshot !== undefined &&\n !replayStillMatches(args.runtime, args.descriptor, args.replaySnapshot)\n ) {\n throw cancelledError('stale-generation');\n }\n let captured: DataSessionSnapshot | undefined;\n try {\n return await executeQueryAttempt(args, (snapshot) => {\n captured = snapshot;\n });\n } catch (error) {\n const failure = normalizeDataError(error);\n if (\n args.replayCount !== 1 &&\n failure.kind === 'auth' &&\n captured !== undefined &&\n args.runtime.authController !== undefined\n ) {\n const recovery = await args.runtime.authController.recover(failure, captured);\n if (recovery === 'replay') {\n return executeQuery({ ...args, replayCount: 1, replaySnapshot: captured });\n }\n throw recovery;\n }\n throw failure;\n }\n}\n\nasync function executeQueryAttempt<T extends ErasedQueryDescriptor>(\n args: {\n readonly descriptor: T;\n readonly runtime: DataRuntimeContextValue;\n readonly signal: AbortSignal;\n readonly replaySnapshot?: DataSessionSnapshot;\n },\n capture: (snapshot: DataSessionSnapshot) => void,\n): Promise<QueryResultFor<T>> {\n const linked = linkedAbortController([args.signal]);\n let stopObservingGeneration: (() => void) | undefined;\n\n try {\n const snapshot = await args.runtime.waitUntilReady(linked.controller.signal);\n if (\n args.replaySnapshot !== undefined &&\n !replayStillMatches(args.runtime, args.descriptor, args.replaySnapshot)\n ) {\n throw cancelledError('stale-generation');\n }\n capture(snapshot);\n if (linked.controller.signal.aborted) throw cancelledError();\n\n const service = args.runtime.providers.resolve(args.descriptor.providerId);\n if (!sameSnapshot(service.session, snapshot)) throw cancelledError('stale-generation');\n stopObservingGeneration = args.runtime.dataSession.subscribe(() => {\n if (!isCurrentGeneration(args.runtime, args.descriptor, snapshot, service.identity)) {\n linked.controller.abort();\n }\n });\n if (!isCurrentGeneration(args.runtime, args.descriptor, snapshot, service.identity)) {\n throw cancelledError('stale-generation');\n }\n const batch = service.provider.batch?.queries;\n const result =\n batch === undefined\n ? await executeDirectQuery(args.descriptor, service.provider, {\n signal: linked.controller.signal,\n requestContext: args.runtime.app.requestContext,\n session: snapshot,\n providerServiceKey: service.id,\n })\n : await args.runtime.batchCoordinator.execute<QueryResultFor<T>>(\n { id: '', descriptor: args.descriptor },\n {\n serviceIdentity: service.identity,\n providerServiceKey: service.id,\n requestContext: args.runtime.app.requestContext,\n session: snapshot,\n signal: linked.controller.signal,\n batch,\n },\n );\n\n if (\n linked.controller.signal.aborted ||\n !isCurrentGeneration(args.runtime, args.descriptor, snapshot, service.identity)\n ) {\n throw cancelledError(linked.controller.signal.aborted ? 'aborted' : 'stale-generation');\n }\n return result;\n } catch (error) {\n if (linked.controller.signal.aborted) throw cancelledError();\n throw normalizeDataError(error);\n } finally {\n stopObservingGeneration?.();\n linked.dispose();\n }\n}\n\nasync function executeDirectQuery<T extends ErasedQueryDescriptor>(\n descriptor: T,\n provider: Parameters<typeof resolveDataCapability>[0],\n context: QueryContext,\n): Promise<QueryResultFor<T>> {\n const capability = resolveDataCapability(provider, {\n lifecycle: 'query',\n kind: descriptor.kind,\n });\n if (isDataError(capability)) throw capability;\n const execute = capability as unknown as (\n current: T,\n value: QueryContext,\n ) => Promise<QueryResultFor<T>>;\n return execute(descriptor, context);\n}\n","import {\n normalizeDataError,\n queryKeyFor,\n type DataError,\n type ErasedQueryDescriptor,\n type LivePlan,\n type QueryResultFor,\n} from '@burojs/core';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport { executeQuery } from '../query-execution.js';\nimport type { DataRuntimeContextValue } from '../runtime.js';\nimport type { LiveLease, LiveState } from './types.js';\n\nexport interface QueryLiveObserverState {\n readonly live: LiveState;\n /** Only observer-detected protocol violations synthesize query failure. */\n readonly protocolError?: DataError;\n}\n\nconst OFF_STATE: QueryLiveObserverState = Object.freeze({\n live: Object.freeze({ status: 'off' as const }),\n});\n\nfunction cancelledError(): DataError {\n return { kind: 'cancelled', code: 'aborted', message: 'Live query observer was disposed.' };\n}\n\nfunction protocolError(code: string, message: string): DataError {\n return { kind: 'protocol', code, message };\n}\n\nfunction revisionOf(value: unknown): string | number | undefined {\n if (value === null || typeof value !== 'object') return undefined;\n const revision = (value as { readonly revision?: unknown }).revision;\n return typeof revision === 'string' || typeof revision === 'number' ? revision : undefined;\n}\n\nfunction asSnapshotPlan(\n plan: LivePlan | undefined,\n): Extract<LivePlan, { readonly kind: 'snapshot'; readonly initial: 'query' }> | undefined {\n return plan?.kind === 'snapshot' && plan.initial === 'query' ? plan : undefined;\n}\n\n/**\n * Reduces a descriptor's shared live lease into its canonical TanStack cache\n * entry. It owns no provider resources beyond its lease and becomes inert as\n * soon as that lease is released, which prevents retired session work from\n * writing into a replacement cache partition.\n */\nexport class QueryLiveObserver<T extends ErasedQueryDescriptor = ErasedQueryDescriptor> {\n readonly #descriptor: T;\n readonly #runtime: DataRuntimeContextValue;\n readonly #queryClient: QueryClient;\n readonly #key: ReturnType<typeof queryKeyFor>;\n readonly identity: string;\n readonly #lease: LiveLease<QueryResultFor<T>>;\n readonly #consumerGeneration: number;\n readonly #listeners = new Set<() => void>();\n #unsubscribeLease: (() => void) | undefined;\n #unsubscribeSession: (() => void) | undefined;\n #active = true;\n #retired = false;\n #state: QueryLiveObserverState;\n #seenEvent: unknown;\n #latestValue: QueryResultFor<T> | undefined;\n #latestRevision: string | number | undefined;\n #protocolFailure: DataError | undefined;\n #protocolReconciliationRequested = false;\n #protocolTerminal = false;\n #hasStartedQuery = false;\n #dirtyBeforeFirstQuery = false;\n #dirtyGeneration = 0;\n #scheduled = false;\n #refetching = false;\n\n constructor(args: {\n readonly descriptor: T;\n readonly runtime: DataRuntimeContextValue;\n readonly queryClient: QueryClient;\n }) {\n this.#descriptor = args.descriptor;\n this.#runtime = args.runtime;\n this.#queryClient = args.queryClient;\n this.#key = queryKeyFor(this.#descriptor);\n this.identity = JSON.stringify(this.#key);\n const session = this.#runtime.dataSession.getState();\n this.#consumerGeneration =\n session.status === 'ready' ? session.snapshot.generation : session.target.generation;\n this.#lease = this.#runtime.liveCoordinator.acquire<QueryResultFor<T>>(\n this.#descriptor,\n this.#consumerGeneration,\n );\n this.#state = this.#stateForLease();\n this.#consumeLease();\n this.#unsubscribeLease = this.#lease.subscribe(() => this.#consumeLease());\n this.#unsubscribeSession = this.#runtime.dataSession.subscribe(() => {\n const current = this.#runtime.dataSession.getState();\n const generation =\n current.status === 'ready' ? current.snapshot.generation : current.target.generation;\n if (generation !== this.#consumerGeneration) this.#retire();\n });\n }\n\n getState = (): QueryLiveObserverState => this.#state;\n\n subscribe = (listener: () => void): (() => void) => {\n if (!this.#active) return () => undefined;\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n };\n\n /** Whether a regular query should execute after the selected live plan is ready. */\n get queryEnabled(): boolean {\n if (!this.#active) return false;\n const live = this.#state.live;\n if (live.status === 'connecting') return false;\n return !(\n live.status === 'connected' &&\n live.plan?.kind === 'snapshot' &&\n live.plan.initial === 'stream'\n );\n }\n\n async execute(signal: AbortSignal): Promise<QueryResultFor<T>> {\n if (!this.#active) throw cancelledError();\n const requiresFollowingRefetch = this.#dirtyBeforeFirstQuery;\n this.#dirtyBeforeFirstQuery = false;\n this.#hasStartedQuery = true;\n const result = await executeQuery({\n descriptor: this.#descriptor,\n runtime: this.#runtime,\n signal,\n });\n if (!this.#active) {\n // Retired by a session-generation change: the answer belongs to a\n // generation that is gone (executeQuery normally rejects it already).\n if (this.#retired) throw cancelledError();\n // Released by its last consumer (unmounted, or the query was disabled)\n // while this request was in flight: the answer is still current for\n // this generation, so it lands in the cache unreduced, as a plain query.\n return result;\n }\n const reduced = this.#reduceQuery(result);\n if (requiresFollowingRefetch) this.#scheduleDirtyRefetch();\n return reduced;\n }\n\n dispose(): void {\n if (!this.#active) return;\n this.#close(false);\n }\n\n #retire(): void {\n if (!this.#active) return;\n this.#retired = true;\n this.#close(true);\n }\n\n #close(notify: boolean): void {\n this.#active = false;\n this.#unsubscribeLease?.();\n this.#unsubscribeLease = undefined;\n this.#unsubscribeSession?.();\n this.#unsubscribeSession = undefined;\n this.#lease.release();\n this.#state = OFF_STATE;\n if (notify) {\n for (const listener of this.#listeners) listener();\n }\n this.#listeners.clear();\n }\n\n #publish(): void {\n if (!this.#active) return;\n this.#state = this.#stateForLease();\n for (const listener of this.#listeners) listener();\n }\n\n #stateForLease(): QueryLiveObserverState {\n return this.#protocolFailure === undefined\n ? { live: this.#lease.getState() }\n : {\n live: this.#withProtocolFailure(this.#lease.getState()),\n protocolError: this.#protocolFailure,\n };\n }\n\n #withProtocolFailure(live: LiveState): LiveState {\n return this.#protocolFailure === undefined ? live : { ...live, error: this.#protocolFailure };\n }\n\n #consumeLease(): void {\n if (!this.#active) return;\n const state = this.#lease.getState();\n const event = state.event;\n if (event !== undefined && event !== this.#seenEvent) {\n this.#seenEvent = event;\n if (event.type === 'invalidate') {\n this.#markDirty();\n } else {\n this.#reduceSnapshot(event.value as QueryResultFor<T>, state.plan);\n }\n }\n this.#publish();\n }\n\n #reduceSnapshot(value: QueryResultFor<T>, plan: LivePlan | undefined): void {\n if (!this.#active) return;\n const snapshotQuery = asSnapshotPlan(plan);\n if (snapshotQuery !== undefined) {\n const revision = revisionOf(value);\n if (revision === undefined) {\n this.#failProtocol(\n 'live-revision-required',\n 'Snapshot-query live values must include a comparable revision.',\n );\n return;\n }\n if (this.#latestRevision !== undefined && this.#latestValue !== undefined) {\n const comparison = this.#compare(snapshotQuery, revision, this.#latestRevision);\n if (comparison === undefined) return;\n if (comparison < 0) return;\n if (comparison === 0) {\n if (!this.#equals(snapshotQuery, value, this.#latestValue)) {\n this.#failConflict();\n }\n return;\n }\n }\n this.#latestRevision = revision;\n }\n this.#latestValue = value;\n this.#queryClient.setQueryData(this.#key, value);\n }\n\n #reduceQuery(value: QueryResultFor<T>): QueryResultFor<T> {\n const snapshotQuery = asSnapshotPlan(this.#lease.getState().plan);\n if (snapshotQuery === undefined) return value;\n const revision = revisionOf(value);\n if (revision === undefined) {\n this.#failProtocol(\n 'live-revision-required',\n 'Snapshot-query query results must include a comparable revision.',\n );\n return this.#latestValue ?? value;\n }\n if (this.#latestRevision === undefined || this.#latestValue === undefined) {\n this.#latestRevision = revision;\n this.#latestValue = value;\n return value;\n }\n const comparison = this.#compare(snapshotQuery, revision, this.#latestRevision);\n if (comparison === undefined) return this.#latestValue;\n if (comparison < 0) return this.#latestValue;\n if (comparison === 0) {\n if (!this.#equals(snapshotQuery, value, this.#latestValue)) {\n const snapshot = this.#latestValue;\n this.#failConflict();\n return snapshot;\n }\n return this.#latestValue;\n }\n this.#latestRevision = revision;\n this.#latestValue = value;\n return value;\n }\n\n #compare(\n plan: Extract<LivePlan, { readonly kind: 'snapshot'; readonly initial: 'query' }>,\n left: string | number,\n right: string | number,\n ): number | undefined {\n try {\n const result = plan.compareRevision(left, right);\n if (!Number.isFinite(result))\n throw new Error('Revision comparator returned a non-finite value.');\n return result;\n } catch (error) {\n this.#failProtocol(\n 'live-revision-non-comparable',\n error instanceof Error ? error.message : 'Live revisions are not comparable.',\n );\n return undefined;\n }\n }\n\n #equals(\n plan: Extract<LivePlan, { readonly kind: 'snapshot'; readonly initial: 'query' }>,\n left: QueryResultFor<T>,\n right: QueryResultFor<T>,\n ): boolean {\n try {\n return plan.equalsSnapshot(left, right);\n } catch (error) {\n this.#failProtocol(\n 'live-snapshot-equality-failed',\n error instanceof Error ? error.message : 'Live snapshot equality comparison failed.',\n );\n return false;\n }\n }\n\n #failConflict(): void {\n this.#failProtocol(\n 'live-revision-conflict',\n 'Equal live revisions carried unequal mapped result envelopes.',\n );\n // The reconciliation response is the next authoritative baseline. Keeping\n // the conflicting snapshot here would turn that response into a second,\n // spurious equal-revision conflict.\n this.#latestValue = undefined;\n this.#latestRevision = undefined;\n }\n\n #failProtocol(code: string, message: string): void {\n if (!this.#active) return;\n this.#protocolFailure ??= protocolError(code, message);\n if (!this.#protocolReconciliationRequested && !this.#protocolTerminal) {\n this.#protocolReconciliationRequested = true;\n this.#scheduleDirtyRefetch();\n } else {\n this.#protocolTerminal = true;\n }\n this.#publish();\n }\n\n #markDirty(): void {\n if (!this.#active) return;\n this.#dirtyGeneration += 1;\n if (!this.#hasStartedQuery) {\n this.#dirtyBeforeFirstQuery = true;\n return;\n }\n this.#scheduleDirtyRefetch();\n }\n\n #scheduleDirtyRefetch(): void {\n if (!this.#active || this.#protocolTerminal) return;\n if (this.#scheduled || this.#refetching) return;\n this.#scheduled = true;\n queueMicrotask(() => {\n this.#scheduled = false;\n if (!this.#active || this.#refetching) return;\n const generation = this.#dirtyGeneration;\n const query = this.#queryClient.getQueryCache().find({ queryKey: this.#key, exact: true });\n const wasFetching = query?.state.fetchStatus === 'fetching';\n this.#refetching = true;\n void this.#queryClient\n .invalidateQueries({ queryKey: this.#key, exact: true }, { cancelRefetch: false })\n .then(() =>\n wasFetching && this.#active\n ? this.#queryClient.refetchQueries(\n { queryKey: this.#key, exact: true },\n { cancelRefetch: false },\n )\n : undefined,\n )\n .catch((error) => {\n this.#protocolFailure ??= normalizeDataError(error);\n this.#publish();\n })\n .finally(() => {\n this.#refetching = false;\n if (this.#active && this.#dirtyGeneration > generation) this.#markDirty();\n });\n });\n }\n}\n\nexport function offLiveQueryState(): QueryLiveObserverState {\n return OFF_STATE;\n}\n","import { queryKeyFor, type DataSessionController, type ErasedQueryDescriptor } from '@burojs/core';\n\nimport { executeQuery } from '../query-execution.js';\nimport type { DataRuntimeContextValue } from '../runtime.js';\nimport { QueryLiveObserver } from './query-live-observer.js';\n\n/** One consumer's hold on the shared observer of a descriptor. */\nexport interface LiveQueryRetention {\n readonly observer: QueryLiveObserver;\n /** Drops this hold. Idempotent; the last release disposes the observer. */\n release(): void;\n}\n\n/**\n * The runtime's one `QueryLiveObserver` per descriptor identity and session\n * generation, shared by every mounted consumer of that descriptor and kept\n * alive while any of them retains it. Invariant: `queryFn` resolves the\n * observer when the request runs, never when the options were built, because\n * TanStack runs the `queryFn` of whichever consumer rendered last.\n */\nexport interface LiveQueryRegistry {\n /**\n * Retains the shared observer for `descriptor` at the current session\n * generation, creating it (and acquiring its live lease) on the first hold.\n * Call it from a committed effect, and only for an enabled query.\n */\n retain(descriptor: ErasedQueryDescriptor): LiveQueryRetention;\n /**\n * The TanStack `queryFn` for `descriptor`. It executes through the retained\n * observer of the current generation when a consumer holds one, and falls\n * back to a plain `executeQuery` when none does (a disabled query's manual\n * `refetch()`, for instance).\n *\n * During a session-generation change there is a short window between the\n * old observer retiring and the consumer's effect retaining the new one; a\n * request started there also takes the fallback. That is harmless: the\n * transition's own `cancelQueries()` cancels it, or its `clear()` has\n * already detached the query it would write to, and the re-retained\n * observer runs the next generation's first fetch itself.\n */\n queryFn(\n descriptor: ErasedQueryDescriptor,\n ): (context: { readonly signal: AbortSignal }) => Promise<unknown>;\n /** Number of live entries, for diagnostics and tests. */\n readonly size: number;\n}\n\ninterface Entry {\n readonly observer: QueryLiveObserver;\n holds: number;\n}\n\n/**\n * The generation a live observer must be bound to right now. A transition\n * publishes its TARGET generation before the session reports ready, so\n * reading the target keeps a fresh observer on the incoming generation\n * instead of one that is already retiring. `QueryLiveObserver` binds itself\n * the same way.\n */\nexport function sessionGenerationOf(session: DataSessionController): number {\n const state = session.getState();\n return state.status === 'ready' ? state.snapshot.generation : state.target.generation;\n}\n\n/**\n * Creates the registry. `runtime` is read lazily because the registry is a\n * member of the runtime object it serves.\n */\nexport function createLiveQueryRegistry(runtime: () => DataRuntimeContextValue): LiveQueryRegistry {\n const entries = new Map<string, Entry>();\n\n function entryKey(descriptor: ErasedQueryDescriptor, generation: number): string {\n return `${generation}:${JSON.stringify(queryKeyFor(descriptor))}`;\n }\n\n return {\n retain(descriptor) {\n const current = runtime();\n const key = entryKey(descriptor, sessionGenerationOf(current.dataSession));\n let entry = entries.get(key);\n if (entry === undefined) {\n entry = {\n observer: new QueryLiveObserver({\n descriptor,\n runtime: current,\n queryClient: current.queryClient,\n }),\n holds: 0,\n };\n entries.set(key, entry);\n }\n const held = entry;\n held.holds += 1;\n let released = false;\n return {\n observer: held.observer,\n release() {\n if (released) return;\n released = true;\n held.holds -= 1;\n if (held.holds > 0) return;\n if (entries.get(key) === held) entries.delete(key);\n held.observer.dispose();\n },\n };\n },\n queryFn(descriptor) {\n return ({ signal }) => {\n const current = runtime();\n const entry = entries.get(entryKey(descriptor, sessionGenerationOf(current.dataSession)));\n return entry === undefined\n ? executeQuery({ descriptor, runtime: current, signal })\n : entry.observer.execute(signal);\n };\n },\n get size() {\n return entries.size;\n },\n };\n}\n","import type { ReactElement, ReactNode } from 'react';\nimport { createContext, useContext } from 'react';\n\nimport type { DataRuntimeContextValue } from './runtime.js';\n\nexport const DataRuntimeContext = createContext<DataRuntimeContextValue | null>(null);\n\nexport interface DataRuntimeProviderProps {\n readonly value: DataRuntimeContextValue;\n readonly children: ReactNode;\n}\n\n/** Attaches an externally owned native data-runtime lease to the React tree. */\nexport function DataRuntimeProvider({ value, children }: DataRuntimeProviderProps): ReactElement {\n return <DataRuntimeContext.Provider value={value}>{children}</DataRuntimeContext.Provider>;\n}\n\nexport function useDataRuntime(): DataRuntimeContextValue {\n const runtime = useContext(DataRuntimeContext);\n if (runtime === null) {\n throw new Error('useDataRuntime must be used within BuroProvider.');\n }\n return runtime;\n}\n\n/**\n * Like {@link useDataRuntime}, but tolerant of a missing native data runtime —\n * returns `null` instead of throwing. Mirrors the codebase's established\n * `useOptionalT` (`../hooks/use-t.ts`) / `useOptionalVisibilityCtx`\n * (`../hooks/use-permissions.ts`) / `useOptionalFileStorage`\n * (`../hooks/file/use-file-storage.ts`) precedent for \"may run outside a\n * full provider tree\".\n *\n * `<BuroProvider>` without a `dataRuntime` prop (the \"compat\" mode used by\n * most component-only tests, and by hosts that haven't adopted the native\n * data runtime) never mounts a `DataRuntimeProvider`, so `useDataRuntime()`\n * throws for ANY consumer — appropriate for `useAction` (dispatching an\n * action genuinely requires one), but wrong for a hook whose feature is\n * meaningful even without one (`useChecks`/`useCheckGate`: a check that\n * never touches `di.data` must keep working). Consumers needing the latter\n * behavior read this instead and degrade gracefully.\n */\nexport function useOptionalDataRuntime(): DataRuntimeContextValue | null {\n return useContext(DataRuntimeContext);\n}\n","import {\n queryKeyFor,\n type DataError,\n type DataQueryKey,\n type ErasedQueryDescriptor,\n type QueryResultFor,\n} from '@burojs/core';\nimport type { UseQueryOptions } from '@tanstack/react-query';\n\n/** Returns the canonical cache identity for a native data descriptor. */\nexport function buroQueryOptions<T extends ErasedQueryDescriptor>(\n descriptor: T,\n): UseQueryOptions<QueryResultFor<T>, DataError, QueryResultFor<T>, DataQueryKey> {\n return { queryKey: queryKeyFor(descriptor) };\n}\n","import {\n type DataDescriptorIdentity,\n listContinuityIdentityFor,\n type DataError,\n type DataQueryKey,\n type ErasedQueryDescriptor,\n type PortableValue,\n queryKeyFor,\n} from '@burojs/core';\nimport {\n useQuery,\n type Query,\n type UseQueryOptions,\n type UseQueryResult,\n} from '@tanstack/react-query';\nimport { useEffect, useState, useSyncExternalStore } from 'react';\n\nimport { buroQueryOptions } from '../../data/query-options.js';\nimport { useDataRuntime } from '../../data/context.js';\nimport { sessionGenerationOf } from '../../data/live/live-queries.js';\nimport { type QueryLiveObserver, offLiveQueryState } from '../../data/live/query-live-observer.js';\n\nexport type NativeQueryOptions<TData, TSelected = TData> = Omit<\n UseQueryOptions<TData, DataError, TSelected, DataQueryKey>,\n 'queryKey' | 'queryFn' | 'placeholderData' | 'refetchInterval'\n> & {\n /**\n * Poll this query at N ms (TanStack semantics) — forwarded verbatim into\n * TanStack Query's `refetchInterval` (see `queryOptions` assembly below).\n * Omit for the default `undefined`: no polling, behavior unchanged.\n */\n readonly refetchInterval?: number | false;\n};\n\nexport type NativeQueryResult<TData, TSelected = TData> = UseQueryResult<TSelected, DataError> & {\n readonly isCurrentData: boolean;\n readonly live: import('../../data/live/types.js').LiveState;\n};\n\nconst subscribeOff = (): (() => void) => () => undefined;\n\nfunction samePortableValue(left: PortableValue, right: PortableValue): boolean {\n if (Object.is(left, right)) return true;\n if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {\n return false;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n return left.every((value, index) => samePortableValue(value, right[index]!));\n }\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n const rightObject = right as Readonly<Record<string, PortableValue>>;\n return leftKeys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(rightObject, key) &&\n samePortableValue((left as Readonly<Record<string, PortableValue>>)[key]!, rightObject[key]!),\n );\n}\n\ntype ListIdentityDescriptor = DataDescriptorIdentity & { readonly kind: 'list' };\n\nfunction listDescriptorFromQuery(\n query: Query<unknown, DataError, unknown, DataQueryKey>,\n): ListIdentityDescriptor | undefined {\n const key = query.queryKey;\n if (key[0] !== 'buro-data' || key[1] !== 1) return undefined;\n const descriptor = key[2];\n if (descriptor === null || typeof descriptor !== 'object' || Array.isArray(descriptor))\n return undefined;\n return (descriptor as { readonly kind?: unknown }).kind === 'list'\n ? (descriptor as unknown as ListIdentityDescriptor)\n : undefined;\n}\n\n/** Framework-owned placeholder policy: only list descriptors can retain same-boundary rows. */\nfunction safeListPlaceholderData<TData>(\n descriptor: ListIdentityDescriptor,\n): (\n previousData: TData | undefined,\n previousQuery: Query<unknown, DataError, unknown, DataQueryKey> | undefined,\n) => TData | undefined {\n const continuity = listContinuityIdentityFor(descriptor);\n return (previousData, previousQuery) => {\n if (previousQuery === undefined) return undefined;\n const previous = listDescriptorFromQuery(previousQuery);\n if (previous === undefined) return undefined;\n return samePortableValue(listContinuityIdentityFor(previous), continuity)\n ? previousData\n : undefined;\n };\n}\n\n/** Executes a canonical descriptor with framework-owned cache and continuity policy. */\nexport function useQueryDescriptor<TData, TSelected = TData>(\n descriptor: ErasedQueryDescriptor | DataError,\n options: NativeQueryOptions<TData, TSelected> | undefined,\n): NativeQueryResult<TData, TSelected> {\n const runtime = useDataRuntime();\n const isError =\n 'kind' in descriptor &&\n descriptor.kind !== 'list' &&\n descriptor.kind !== 'one' &&\n descriptor.kind !== 'many' &&\n descriptor.kind !== 'count' &&\n descriptor.kind !== 'custom';\n const placeholderData =\n !isError && descriptor.kind === 'list'\n ? (safeListPlaceholderData<TData>(descriptor) as unknown as UseQueryOptions<\n TData,\n DataError,\n TSelected,\n readonly unknown[]\n >['placeholderData'])\n : undefined;\n const descriptorKey = isError ? undefined : JSON.stringify(queryKeyFor(descriptor));\n // The observer is bound to a session GENERATION: when the generation changes\n // it retires itself and never lets a request through again. The descriptor\n // key may stay the same across that change (a scope change with identical\n // contents, which is exactly what the host does on mount), so the generation\n // must be an effect dependency: otherwise the retired observer stays forever\n // and the query never reaches the network.\n const sessionGeneration = useSyncExternalStore(\n runtime.dataSession.subscribe,\n () => sessionGenerationOf(runtime.dataSession),\n () => sessionGenerationOf(runtime.dataSession),\n );\n const requestedEnabled = options?.enabled !== false;\n const [liveObserver, setLiveObserver] = useState<QueryLiveObserver | undefined>();\n useEffect(() => {\n // A disabled query holds no observer and therefore no live lease: a lease\n // opens provider work for data nobody asked for. Its manual `refetch()`\n // runs through the registry's plain-executor fallback instead.\n if (isError || descriptorKey === undefined || !requestedEnabled) {\n setLiveObserver(undefined);\n return undefined;\n }\n // Acquiring a live lease opens provider work, so it belongs to React's\n // committed lifecycle rather than render/memo evaluation. This also makes\n // discarded and StrictMode probe renders resource-free. The observer is\n // shared with every other consumer of this descriptor in this session\n // generation and outlives this one while any of them stays mounted.\n const { observer, release } = runtime.liveQueries.retain(descriptor);\n setLiveObserver(observer);\n return () => {\n release();\n setLiveObserver((previous) => (previous === observer ? undefined : previous));\n };\n }, [descriptorKey, isError, requestedEnabled, runtime, sessionGeneration]);\n const activeLiveObserver = liveObserver?.identity === descriptorKey ? liveObserver : undefined;\n const liveState = useSyncExternalStore(\n activeLiveObserver?.subscribe ?? subscribeOff,\n activeLiveObserver?.getState ?? offLiveQueryState,\n offLiveQueryState,\n );\n const enabled = isError\n ? requestedEnabled\n : requestedEnabled && activeLiveObserver?.queryEnabled === true;\n const queryOptions = {\n // `...options` carries every native TanStack option (e.g. `select`,\n // `staleTime`, `refetchInterval`) straight through to `useQuery` below;\n // only the framework-owned keys after it are overridden.\n ...(options as NativeQueryOptions<TData, TSelected>),\n queryKey: isError\n ? ['buro-data-error', 1, descriptor.kind, descriptor.code, descriptor.message]\n : buroQueryOptions(descriptor).queryKey,\n // TanStack runs the queryFn of whichever consumer rendered last, so it\n // must not close over this consumer's observer: the registry resolves the\n // shared one when the request runs.\n queryFn: isError\n ? () => Promise.reject(descriptor)\n : (runtime.liveQueries.queryFn(descriptor) as (context: {\n readonly signal: AbortSignal;\n }) => Promise<TData>),\n placeholderData,\n enabled,\n } as unknown as UseQueryOptions<TData, DataError, TSelected, readonly unknown[]>;\n const result = useQuery(queryOptions);\n const error = liveState.protocolError ?? result.error;\n const syntheticProtocolError = liveState.protocolError !== undefined;\n const hasData = result.data !== undefined;\n return {\n ...result,\n error,\n ...(syntheticProtocolError\n ? {\n // `UseQueryResult` is a discriminated state machine. A live\n // protocol failure is surfaced through that public result, so every\n // status-derived flag must agree with `status: 'error'` rather than\n // retaining TanStack's last successful discriminator.\n status: 'error' as const,\n isError: true,\n isSuccess: false,\n isPending: false,\n isLoading: false,\n isInitialLoading: false,\n isLoadingError: !hasData,\n isRefetchError: hasData,\n isRefetching: result.isFetching,\n // Retained list rows are a continuity presentation state, not a\n // valid result while the observer reports a protocol violation.\n isPlaceholderData: false,\n }\n : {}),\n isCurrentData: result.data !== undefined && !result.isPlaceholderData,\n live: liveState.live,\n } as NativeQueryResult<TData, TSelected>;\n}\n","import {\n type ApplicationSnapshot,\n type BlockLookup,\n type LayerRuntime,\n type LayerStatus,\n type PortableProjection,\n type PortableValue,\n type SnapshotEntityTargetInput,\n snapshotBlockLookup,\n} from '@burojs/core';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react';\n\nconst LayerRuntimeContext = createContext<LayerRuntime | null>(null);\n\nexport interface BuroRuntimeProviderProps {\n readonly runtime: LayerRuntime;\n readonly children: ReactNode;\n}\n\nexport function BuroRuntimeProvider({ runtime, children }: BuroRuntimeProviderProps): ReactElement {\n return <LayerRuntimeContext.Provider value={runtime}>{children}</LayerRuntimeContext.Provider>;\n}\n\nexport function useLayerRuntime(): LayerRuntime {\n const runtime = useContext(LayerRuntimeContext);\n if (runtime === null) {\n throw new Error('useLayerRuntime must be used within BuroRuntimeProvider.');\n }\n return runtime;\n}\n\n/** @internal The mounted layer runtime, or `null` outside a `BuroRuntimeProvider`. */\nexport function useOptionalLayerRuntime(): LayerRuntime | null {\n return useContext(LayerRuntimeContext);\n}\n\nconst NO_SUBSCRIBE = (): (() => void) => () => undefined;\nconst NO_SNAPSHOT = (): null => null;\n\n/** @internal The committed snapshot, or `null` outside a `BuroRuntimeProvider`. */\nexport function useOptionalApplicationSnapshot(): ApplicationSnapshot | null {\n const runtime = useContext(LayerRuntimeContext);\n return useSyncExternalStore(\n runtime?.subscribe ?? NO_SUBSCRIBE,\n runtime?.getSnapshot ?? NO_SNAPSHOT,\n runtime?.getServerSnapshot ?? NO_SNAPSHOT,\n );\n}\n\nexport function useApplicationSnapshot(): ApplicationSnapshot {\n const runtime = useLayerRuntime();\n return useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getServerSnapshot);\n}\n\ntype CommittedSelection<T> =\n | { readonly hasValue: false }\n | { readonly hasValue: true; readonly value: T };\n\nexport function useRuntimeSelection<T>(\n getClientValue: (runtime: LayerRuntime) => T,\n getServerValue: (runtime: LayerRuntime) => T,\n isEqual: (left: T, right: T) => boolean = Object.is,\n): T {\n const runtime = useLayerRuntime();\n const committed = useRef<CommittedSelection<T>>({ hasValue: false });\n\n const [getSnapshot, getServerSnapshot] = useMemo(() => {\n let hasMemo = false;\n let memoizedValue: T;\n\n const select = (nextValue: T): T => {\n if (!hasMemo) {\n hasMemo = true;\n const current = committed.current;\n if (current.hasValue && isEqual(current.value, nextValue)) {\n memoizedValue = current.value;\n return memoizedValue;\n }\n memoizedValue = nextValue;\n return nextValue;\n }\n if (Object.is(memoizedValue, nextValue)) return memoizedValue;\n if (isEqual(memoizedValue, nextValue)) return memoizedValue;\n memoizedValue = nextValue;\n return nextValue;\n };\n\n return [() => select(getClientValue(runtime)), () => select(getServerValue(runtime))] as const;\n }, [getClientValue, getServerValue, isEqual, runtime]);\n\n const value = useSyncExternalStore(runtime.subscribe, getSnapshot, getServerSnapshot);\n useEffect(() => {\n committed.current = { hasValue: true, value };\n }, [value]);\n return value;\n}\n\nfunction samePortableValue(left: PortableValue, right: PortableValue): boolean {\n if (Object.is(left, right)) return true;\n if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {\n return false;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1) {\n if (!samePortableValue(left[index]!, right[index]!)) return false;\n }\n return true;\n }\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n const leftObject = left as { readonly [key: string]: PortableValue };\n const rightObject = right as { readonly [key: string]: PortableValue };\n if (leftKeys.length !== rightKeys.length) return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(rightObject, key)) return false;\n if (!samePortableValue(leftObject[key]!, rightObject[key]!)) return false;\n }\n return true;\n}\n\nfunction sameProjection(\n left: PortableProjection | undefined,\n right: PortableProjection | undefined,\n): boolean {\n if (Object.is(left, right)) return true;\n if (left === undefined || right === undefined) return false;\n return (\n left.kind === right.kind &&\n left.schemaVersion === right.schemaVersion &&\n left.ref.namespace === right.ref.namespace &&\n left.ref.id === right.ref.id &&\n samePortableValue(left.value, right.value)\n );\n}\n\nexport function useProjection(target: SnapshotEntityTargetInput): PortableProjection | undefined {\n const getProjection = useCallback(\n (runtime: LayerRuntime) => runtime.getSnapshot().getProjection(target),\n [target],\n );\n const getServerProjection = useCallback(\n (runtime: LayerRuntime) => runtime.getServerSnapshot().getProjection(target),\n [target],\n );\n return useRuntimeSelection(getProjection, getServerProjection, sameProjection);\n}\n\nexport function useLayerStatus(id: string): LayerStatus {\n const getStatus = useCallback((runtime: LayerRuntime) => runtime.getLayerStatus(id), [id]);\n return useRuntimeSelection(getStatus, getStatus);\n}\n\nconst selectBlockLookup = (runtime: LayerRuntime): BlockLookup =>\n snapshotBlockLookup(runtime.getSnapshot());\nconst selectServerBlockLookup = (runtime: LayerRuntime): BlockLookup =>\n snapshotBlockLookup(runtime.getServerSnapshot());\n\n/**\n * @internal The app's trusted block catalogue over the committed snapshot (P4-D): the built-in\n * blocks and every registered one. A flow's form and review tree compile against it, so\n * `l.place(appBlock)` resolves (spec 3.6). One lookup per snapshot, so a compile memoised by the\n * lookup hits across renders.\n */\nexport function useFlowFormCatalog(): BlockLookup {\n return useRuntimeSelection(selectBlockLookup, selectServerBlockLookup);\n}\n","import type { Resolver } from '@burojs/context';\nimport type { AppRuntime } from '@burojs/core';\nimport type { I18nFacade } from '@burojs/i18n-core';\nimport { createContext } from 'react';\n\nexport const AppContext = createContext<AppRuntime | null>(null);\nexport const ResolverContext = createContext<Resolver<never> | null>(null);\nexport const I18nContext = createContext<I18nFacade | null>(null);\nexport const ComponentsContext = createContext<Record<string, unknown>>({});\n\nexport interface TestIdContextValue {\n resource?: string;\n view?: string;\n recordId?: string;\n}\nexport const TestIdContext = createContext<TestIdContextValue>({});\n\nexport interface ResourceContextValue {\n resource?: string;\n}\nexport const ResourceContext = createContext<ResourceContextValue>({});\n\n/** Where the chosen locale is persisted unless `<BuroProvider languageStorageKey>` says otherwise. */\nexport const DEFAULT_LANGUAGE_STORAGE_KEY = 'buro:language';\n\n/** The `localStorage` key the language control persists the chosen locale under. */\nexport const LanguageStorageKeyContext = createContext<string>(DEFAULT_LANGUAGE_STORAGE_KEY);\n","import type { I18nCaps } from '@burojs/core';\nimport { type ResourceI18n, createResourceI18n } from '@burojs/i18n-core';\nimport { useCallback, useContext, useMemo, useSyncExternalStore } from 'react';\nimport { I18nContext, LanguageStorageKeyContext, ResourceContext } from '../context.js';\n\nexport function useT(): (\n key: string,\n options?: { resource?: string; params?: Record<string, unknown>; count?: number },\n) => string {\n const i18n = useContext(I18nContext);\n if (!i18n) throw new Error('[useT] must be used within a BuroProvider');\n const ctx = useContext(ResourceContext);\n // Subscribe to locale so a live language switch re-renders every consumer\n // (the returned closure reads the facade fresh, but the component must\n // re-render to call it again). Without this, `useT`-only components stay\n // frozen at the boot locale while `useI18nCaps` ones flip.\n useLocale();\n\n return (key, options) =>\n i18n.t(key, {\n resource: options?.resource ?? ctx.resource,\n params: options?.params,\n ...(options?.count === undefined ? {} : { count: options.count }),\n });\n}\n\n/** `{{name}}` → params.name interpolation for the no-provider fallback path. */\nfunction interpolate(template: string, params?: Record<string, unknown>): string {\n if (!params) return template;\n return template.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_m, k: string) =>\n params[k] == null ? '' : String(params[k]),\n );\n}\n\n/**\n * Provider-OPTIONAL translator. Behaves like {@link useT} when mounted inside a\n * `BuroProvider`, but does NOT throw when there is no i18n context —\n * instead it returns the supplied `defaultValue` (interpolated with `params`,\n * and with `count` as `{{count}}` when one is given), falling back to the raw\n * key.\n *\n * Use this for components that ship in `@burojs/ui-shadcn` yet may render\n * standalone (outside the provider) — e.g. `<LoginForm>` on a pre-auth screen,\n * or filter toolbars mounted in isolation by tests / Storybook. In-app (with a\n * provider) they translate normally; standalone they degrade to English.\n */\nexport function useOptionalT(): (\n key: string,\n options?: {\n resource?: string;\n params?: Record<string, unknown>;\n defaultValue?: string;\n count?: number;\n },\n) => string {\n const i18n = useContext(I18nContext);\n const ctx = useContext(ResourceContext);\n // Re-render on locale change (see useT) so translations flip live.\n useLocale();\n\n return (key, options) => {\n const count = options?.count;\n if (i18n) {\n return i18n.t(key, {\n resource: options?.resource ?? ctx.resource,\n params: options?.params,\n ...(count === undefined ? {} : { count }),\n });\n }\n return interpolate(\n options?.defaultValue ?? key,\n count === undefined ? options?.params : { ...options?.params, count },\n );\n };\n}\n\n/**\n * The active locale code (e.g. `'ru'` / `'en'`), or `'en'` when no i18n\n * provider is mounted. Powers locale-dependent formatting and re-renders a\n * component on a language switch. Provider-optional so ui-shadcn components\n * can render standalone.\n */\nexport function useLocale(): string {\n const i18n = useContext(I18nContext);\n // Subscribe to the facade's locale-change event so the whole render-time\n // content model (labels, enums, actions, nav) flips live on a language switch\n // — no page reload. Provider-optional: without a facade the subscription is a\n // no-op and the snapshot is a constant `'en'`, so this stays hook-safe.\n const subscribe = useCallback((cb: () => void) => i18n?.onLocaleChange(cb) ?? (() => {}), [i18n]);\n const getSnapshot = useCallback(() => i18n?.getCurrentLocale() ?? 'en', [i18n]);\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * The active locale code, or `undefined` when NO i18n provider is mounted.\n *\n * The difference from {@link useLocale} is the whole point: `useLocale`\n * collapses \"the app is running in English\" and \"there is no app\" into the same\n * `'en'`, which is fine for picking a label language (English is a defensible\n * last resort) and wrong for anything that has its own fallback to\n * fall back TO. A caller that already knows what \"nobody chose a locale\" means\n * for it — `@burojs/ui-shadcn`'s `Intl` formatters resolve a stored preference\n * in that case — must be able to tell the two apart, and with `useLocale` it\n * cannot.\n *\n * Same subscription as `useLocale`, so a live language switch re-renders the\n * consumer either way.\n */\nexport function useOptionalLocale(): string | undefined {\n const i18n = useContext(I18nContext);\n const subscribe = useCallback((cb: () => void) => i18n?.onLocaleChange(cb) ?? (() => {}), [i18n]);\n const getSnapshot = useCallback(() => i18n?.getCurrentLocale(), [i18n]);\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Returns a `changeLocale(locale)` that switches the active locale IN PLACE\n * (i18next `changeLanguage`) — every component reading {@link useLocale} /\n * {@link useI18nCaps} re-renders and the render-time content model flips without\n * a page reload. The caller is responsible for persistence (e.g. `saveLanguage`)\n * so the choice survives a real reload. No-op without a provider.\n */\nexport function useChangeLocale(): (locale: string) => void {\n const i18n = useContext(I18nContext);\n return useCallback(\n (locale: string) => {\n void i18n?.changeLocale(locale);\n },\n [i18n],\n );\n}\n\n/**\n * The `localStorage` key a language control persists the chosen locale under:\n * `<BuroProvider languageStorageKey>`, or `'buro:language'` without one.\n */\nexport function useLanguageStorageKey(): string {\n return useContext(LanguageStorageKeyContext);\n}\n\n/**\n * Render-time translator, resource-scoped and provider-optional. The canonical\n * name for the i18n content model (react-admin `useTranslate` / i18next `t`).\n * Without a provider it degrades to the raw key. Prefer this over {@link useT}\n * for new code; `useT` is retained for existing call sites.\n */\nexport function useTranslate(): (\n key: string,\n options?: { resource?: string; params?: Record<string, unknown>; count?: number },\n) => string {\n const i18n = useContext(I18nContext);\n const ctx = useContext(ResourceContext);\n // Re-render on locale change (see useT) so translations flip live.\n useLocale();\n return (key, options) =>\n i18n\n ? i18n.t(key, {\n resource: options?.resource ?? ctx.resource,\n params: options?.params,\n ...(options?.count === undefined ? {} : { count: options.count }),\n })\n : key;\n}\n\n/**\n * The `has` + `t` capabilities bound to the ambient resource, for the pure\n * content-slot resolver (`resolveContentSlot` from `@burojs/core`). `has`\n * probes bundle presence (so an absent optional slot renders nothing instead of\n * the raw key). Provider-optional: without a provider `has` is always false and\n * `t` returns the key, so slot resolution falls through to the inline default /\n * humanize. Recomputes on locale change (reactivity lands in Phase 1).\n */\nexport function useI18nCaps(resource?: string): I18nCaps {\n const i18n = useContext(I18nContext);\n const ctx = useContext(ResourceContext);\n const locale = useLocale();\n // Explicit `resource` arg wins over the ambient ResourceContext — for\n // components that call this at their own top (where the provider they'd mount\n // in their return is not yet an ancestor), e.g. ResourceList.\n const boundResource = resource ?? ctx.resource;\n return useMemo<I18nCaps>(\n () => ({\n has: (key, options) =>\n i18n\n ? i18n.has(key, {\n resource: options?.resource ?? boundResource,\n ...(options?.count === undefined ? {} : { count: options.count }),\n })\n : false,\n t: (key, options) =>\n i18n\n ? i18n.t(key, {\n resource: options?.resource ?? boundResource,\n params: options?.params,\n ...(options?.count === undefined ? {} : { count: options.count }),\n })\n : key,\n }),\n // `locale` participates so caps re-resolve when the active locale changes.\n [i18n, boundResource, locale],\n );\n}\n\nexport function useResourceI18n(resource?: string): ResourceI18n {\n const i18n = useContext(I18nContext);\n if (!i18n) throw new Error('[useResourceI18n] must be used within a BuroProvider');\n const ctx = useContext(ResourceContext);\n const name = resource ?? ctx.resource ?? '_';\n return useMemo(() => createResourceI18n(i18n, name), [i18n, name]);\n}\n","import {\n type ApplicationSnapshot,\n type DataError,\n type DataSessionSnapshot,\n type ErasedResourceHandle,\n type FieldDefBase,\n type PortableObject,\n type QueryDescriptor,\n type ResourceHandle,\n createQueryDescriptor,\n normalizeDataError,\n normalizeEntityRef,\n resolveDescriptorLocale,\n} from '@burojs/core';\nimport { useSyncExternalStore } from 'react';\n\nimport { useDataRuntime } from '../../data/context.js';\nimport { useApplicationSnapshot } from '../../runtime.js';\nimport { useLocale } from '../use-t.js';\n\ntype AnyResource = ResourceHandle<any, Record<string, FieldDefBase>, string, string>;\nexport type ResourceInput<R extends AnyResource> = R | string;\n\nfunction sessionSnapshot(runtime: ReturnType<typeof useDataRuntime>): DataSessionSnapshot {\n const state = runtime.dataSession.getState();\n return state.status === 'ready' ? state.snapshot : state.target;\n}\n\nfunction resourceHandle<R extends AnyResource>(\n resource: ResourceInput<R>,\n): R | ErasedResourceHandle {\n return typeof resource === 'string'\n ? ({ kind: 'resource', ref: normalizeEntityRef(resource) } as ErasedResourceHandle)\n : resource;\n}\n\n/** What {@link buildStandardQueryDescriptor} reads besides the resource and the input. */\nexport interface StandardDescriptorContext {\n readonly runtime: ReturnType<typeof useDataRuntime>;\n readonly snapshot: ApplicationSnapshot;\n readonly session: DataSessionSnapshot;\n readonly locale: string;\n}\n\n/**\n * A standard query's descriptor from the live app projection, outside a hook (the screen source\n * resolver builds several per render): a resource the registry lacks, or one whose binding does\n * not resolve, is a configuration `DataError`, never a throw.\n */\nexport function buildStandardQueryDescriptor<R extends AnyResource, TDescriptor>(\n context: StandardDescriptorContext,\n resource: ResourceInput<R>,\n input: object,\n providerOptionsOverride?: PortableObject,\n): TDescriptor | DataError {\n const { runtime, snapshot, session, locale } = context;\n const handle = resourceHandle(resource);\n const projection = runtime.app.registry.get(handle);\n if (projection === undefined) {\n return normalizeDataError(\n Object.assign(\n new Error(`Resource '${handle.ref.namespace}:${handle.ref.id}' is unavailable.`),\n {\n kind: 'configuration' as const,\n code: 'resource-unavailable',\n },\n ),\n );\n }\n let binding;\n try {\n binding = runtime.app.resolveDataBinding(handle);\n } catch (error) {\n return normalizeDataError(\n Object.assign(\n new Error(error instanceof Error ? error.message : 'Resource data binding is unavailable.'),\n {\n kind: 'configuration' as const,\n code: 'data-binding-unavailable',\n cause: error,\n },\n ),\n );\n }\n return createQueryDescriptor<R>({\n ...input,\n providerId: binding.providerId,\n ref: binding.ref,\n resource: binding.resource,\n sessionKey: session.sessionKey,\n scopeKey: session.scopeKey,\n ...resolveDescriptorLocale(projection.data, locale),\n bindingRevision: snapshot.manifest.snapshotId,\n ...(projection.data?.providerOptions === undefined\n ? {}\n : { providerOptions: projection.data.providerOptions }),\n ...(projection.data?.dependencies === undefined\n ? {}\n : { dependencies: projection.data.dependencies }),\n ...(providerOptionsOverride === undefined ? {} : { providerOptionsOverride }),\n } as never) as TDescriptor;\n}\n\n/** The session snapshot a descriptor is keyed by: the target while a transition runs. */\nexport function useDescriptorSession(\n runtime: ReturnType<typeof useDataRuntime>,\n): DataSessionSnapshot {\n return useSyncExternalStore(\n runtime.dataSession.subscribe,\n () => sessionSnapshot(runtime),\n () => sessionSnapshot(runtime),\n );\n}\n\n/** Resolves descriptors from the live app projection rather than authoring handles. */\nexport function useStandardQueryDescriptor<R extends AnyResource, TDescriptor>(\n resource: ResourceInput<R>,\n input: object,\n providerOptionsOverride?: PortableObject,\n): TDescriptor | DataError {\n const runtime = useDataRuntime();\n const snapshot = useApplicationSnapshot();\n const session = useDescriptorSession(runtime);\n // Subscribed unconditionally (hooks cannot be conditional, and the early\n // returns below come after it). Every data hook therefore RE-RENDERS on a\n // language switch — but only a resource declaring `data.localeVarying` gets\n // the locale into its descriptor, so only that resource's query key changes\n // and only that resource re-fetches. See `@burojs/core`'s `data/locale.ts`.\n const locale = useLocale();\n return buildStandardQueryDescriptor<R, TDescriptor>(\n { runtime, snapshot, session, locale },\n resource,\n input,\n providerOptionsOverride,\n );\n}\n","import type {\n ErasedResourceHandle,\n ErasedQueryDescriptor,\n ListDescriptor,\n FieldDefBase,\n PortableObject,\n QueryResultFor,\n ResourceHandle,\n} from '@burojs/core';\n\nimport {\n type NativeQueryOptions,\n type NativeQueryResult,\n useQueryDescriptor,\n} from './use-query-descriptor.js';\nimport { type ResourceInput, useStandardQueryDescriptor } from './use-standard-query-descriptor.js';\n\ntype AnyResource = ResourceHandle<unknown, Record<string, FieldDefBase>, string, string>;\nexport type UseListOptions<R extends AnyResource, TSelected = QueryResultFor<ListDescriptor<R>>> = {\n readonly pagination?: ListDescriptor<R> extends { readonly pagination?: infer T } ? T : never;\n readonly filter?: ListDescriptor<R> extends { readonly filter?: infer T } ? T : never;\n readonly sort?: ListDescriptor<R> extends { readonly sort?: infer T } ? T : never;\n readonly projection?: readonly string[];\n readonly providerOptionsOverride?: PortableObject;\n} & NativeQueryOptions<QueryResultFor<ListDescriptor<R>>, TSelected>;\n\nexport function useList<R extends AnyResource, TSelected = QueryResultFor<ListDescriptor<R>>>(\n resource: R,\n options?: UseListOptions<R, TSelected>,\n): NativeQueryResult<QueryResultFor<ListDescriptor<R>>, TSelected>;\nexport function useList<TSelected = QueryResultFor<ListDescriptor<ErasedResourceHandle>>>(\n resource: string,\n options?: UseListOptions<ErasedResourceHandle, TSelected>,\n): NativeQueryResult<QueryResultFor<ListDescriptor<ErasedResourceHandle>>, TSelected>;\nexport function useList(resource: AnyResource | string, options: any = {}): any {\n const { providerOptionsOverride, pagination, filter, sort, projection, ...queryOptions } =\n options;\n const descriptor = useStandardQueryDescriptor<AnyResource, ListDescriptor<AnyResource>>(\n resource,\n {\n kind: 'list',\n ...(pagination === undefined ? {} : { pagination }),\n ...(filter === undefined ? {} : { filter }),\n ...(sort === undefined ? {} : { sort }),\n ...(projection === undefined ? {} : { projection }),\n },\n providerOptionsOverride,\n );\n return useQueryDescriptor(descriptor as unknown as ErasedQueryDescriptor, queryOptions);\n}\n","import type {\n ErasedQueryDescriptor,\n ErasedResourceHandle,\n FieldDefBase,\n OneDescriptor,\n PortableObject,\n QueryResultFor,\n ResourceHandle,\n} from '@burojs/core';\n\nimport {\n type NativeQueryOptions,\n type NativeQueryResult,\n useQueryDescriptor,\n} from './use-query-descriptor.js';\nimport { type ResourceInput, useStandardQueryDescriptor } from './use-standard-query-descriptor.js';\n\ntype AnyResource = ResourceHandle<unknown, Record<string, FieldDefBase>, string, string>;\nexport type UseOneOptions<R extends AnyResource, TSelected = QueryResultFor<OneDescriptor<R>>> = {\n readonly id: OneDescriptor<R> extends { readonly id: infer T } ? T : never;\n readonly providerOptionsOverride?: PortableObject;\n readonly projection?: readonly string[];\n} & NativeQueryOptions<QueryResultFor<OneDescriptor<R>>, TSelected>;\n\nexport function useOne<R extends AnyResource, TSelected = QueryResultFor<OneDescriptor<R>>>(\n resource: R,\n options: UseOneOptions<R, TSelected>,\n): NativeQueryResult<QueryResultFor<OneDescriptor<R>>, TSelected>;\nexport function useOne<TSelected = QueryResultFor<OneDescriptor<ErasedResourceHandle>>>(\n resource: string,\n options: UseOneOptions<ErasedResourceHandle, TSelected>,\n): NativeQueryResult<QueryResultFor<OneDescriptor<ErasedResourceHandle>>, TSelected>;\nexport function useOne(resource: AnyResource | string, options: any): any {\n const { providerOptionsOverride, projection, id, ...queryOptions } = options;\n const descriptor = useStandardQueryDescriptor<AnyResource, OneDescriptor<AnyResource>>(\n resource,\n {\n kind: 'one',\n id,\n ...(projection === undefined ? {} : { projection }),\n },\n providerOptionsOverride,\n );\n return useQueryDescriptor(descriptor as unknown as ErasedQueryDescriptor, queryOptions);\n}\n","import type { DataError } from '@burojs/core';\n\n/**\n * Record reads retry only what the provider called retryable, at most twice.\n * TanStack's default — three retries, about seven seconds before an error\n * shows — would also retry a `not-found` or a `forbidden` that cannot succeed.\n */\nexport function retryRecordRead(failureCount: number, error: DataError): boolean {\n return error.retryable === true && failureCount < 2;\n}\n","import type {\n ErasedQueryDescriptor,\n ErasedResourceHandle,\n FieldDefBase,\n ManyDescriptor,\n PortableObject,\n QueryResultFor,\n ResourceHandle,\n} from '@burojs/core';\n\nimport {\n type NativeQueryOptions,\n type NativeQueryResult,\n useQueryDescriptor,\n} from './use-query-descriptor.js';\nimport { type ResourceInput, useStandardQueryDescriptor } from './use-standard-query-descriptor.js';\n\ntype AnyResource = ResourceHandle<unknown, Record<string, FieldDefBase>, string, string>;\nexport type UseManyOptions<R extends AnyResource, TSelected = QueryResultFor<ManyDescriptor<R>>> = {\n readonly ids: ManyDescriptor<R> extends { readonly ids: infer T } ? T : never;\n readonly providerOptionsOverride?: PortableObject;\n readonly projection?: readonly string[];\n} & NativeQueryOptions<QueryResultFor<ManyDescriptor<R>>, TSelected>;\n\nexport function useMany<R extends AnyResource, TSelected = QueryResultFor<ManyDescriptor<R>>>(\n resource: R,\n options: UseManyOptions<R, TSelected>,\n): NativeQueryResult<QueryResultFor<ManyDescriptor<R>>, TSelected>;\nexport function useMany<TSelected = QueryResultFor<ManyDescriptor<ErasedResourceHandle>>>(\n resource: string,\n options: UseManyOptions<ErasedResourceHandle, TSelected>,\n): NativeQueryResult<QueryResultFor<ManyDescriptor<ErasedResourceHandle>>, TSelected>;\nexport function useMany(resource: AnyResource | string, options: any): any {\n const { providerOptionsOverride, projection, ids, ...queryOptions } = options;\n const descriptor = useStandardQueryDescriptor<AnyResource, ManyDescriptor<AnyResource>>(\n resource,\n {\n kind: 'many',\n ids,\n ...(projection === undefined ? {} : { projection }),\n },\n providerOptionsOverride,\n );\n return useQueryDescriptor(descriptor as unknown as ErasedQueryDescriptor, queryOptions);\n}\n","import type { CountPolicy, DataError } from '@burojs/core';\n\nexport type CountExecution =\n | { readonly kind: 'off' }\n | { readonly kind: 'inline'; readonly total: number }\n | { readonly kind: 'manual'; readonly enabled: false }\n | { readonly kind: 'query'; readonly enabled: true }\n | { readonly kind: 'live'; readonly enabled: true };\n\ntype CountCapability = {\n readonly query: boolean;\n readonly live: boolean;\n};\n\nfunction missingCapability(lifecycle: 'query' | 'live'): DataError {\n const capability = lifecycle === 'query' ? 'queries.count' : 'live.open';\n return {\n kind: 'capability',\n code: 'missing-data-capability',\n message: `Data provider does not implement ${capability}.`,\n details: Object.freeze({ lifecycle, capability }),\n };\n}\n\n/** Resolves count execution without creating a query descriptor or making requests. */\nexport function resolveCountExecution(\n policy: CountPolicy,\n inlineTotal: number | undefined,\n capability: CountCapability,\n): CountExecution | DataError {\n if (policy === 'off') return { kind: 'off' };\n if (policy === 'live') {\n return capability.live ? { kind: 'live', enabled: true } : missingCapability('live');\n }\n if (inlineTotal !== undefined) return { kind: 'inline', total: inlineTotal };\n if (policy === 'provided') return { kind: 'off' };\n if (!capability.query) return missingCapability('query');\n return policy === 'manual'\n ? { kind: 'manual', enabled: false }\n : { kind: 'query', enabled: true };\n}\n","import {\n dependencyTagsForQuery,\n normalizeEntityRef,\n sameEntityRef,\n type ErasedMutationDescriptor,\n type ErasedQueryDescriptor,\n type MutationEffectTarget,\n type PartitionedDependencyTag,\n type RecordId,\n} from '@burojs/core';\nimport type { Query, QueryClient } from '@tanstack/react-query';\n\nimport type { ProviderServiceRef } from './provider-registry.js';\nimport type { DataRuntimeContextValue } from './runtime.js';\n\ntype DataQuery = Query<unknown, unknown, unknown, readonly unknown[]>;\n\n/** True for every query the native data runtime owns: keys that start with `['buro-data', 1]`. */\nexport function isBuroDataQueryKey(key: readonly unknown[]): boolean {\n return key[0] === 'buro-data' && key[1] === 1;\n}\n\nfunction descriptorFor(query: DataQuery): ErasedQueryDescriptor | undefined {\n const key = query.queryKey;\n if (!isBuroDataQueryKey(key)) return undefined;\n const descriptor = key[2];\n if (descriptor === null || typeof descriptor !== 'object' || Array.isArray(descriptor))\n return undefined;\n const kind = (descriptor as { readonly kind?: unknown }).kind;\n return kind === 'list' ||\n kind === 'one' ||\n kind === 'many' ||\n kind === 'count' ||\n kind === 'custom'\n ? (descriptor as ErasedQueryDescriptor)\n : undefined;\n}\n\nfunction equalPortable(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {\n return false;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => equalPortable(value, right[index]))\n );\n }\n const leftRecord = left as Readonly<Record<string, unknown>>;\n const rightRecord = right as Readonly<Record<string, unknown>>;\n const keys = Object.keys(leftRecord);\n return (\n keys.length === Object.keys(rightRecord).length &&\n keys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(rightRecord, key) &&\n equalPortable(leftRecord[key], rightRecord[key]),\n )\n );\n}\n\nfunction queryPartition(\n runtime: DataRuntimeContextValue,\n query: DataQuery,\n mutation: ErasedMutationDescriptor,\n provider: ProviderServiceRef,\n): readonly PartitionedDependencyTag[] | undefined {\n const descriptor = descriptorFor(query);\n if (\n descriptor === undefined ||\n descriptor.providerId !== mutation.providerId ||\n descriptor.sessionKey !== mutation.sessionKey ||\n !equalPortable(descriptor.scopeKey, mutation.scopeKey)\n )\n return undefined;\n try {\n const queryService = runtime.providers.resolve(descriptor.providerId);\n if (queryService.identity !== provider.identity) return undefined;\n return dependencyTagsForQuery(descriptor, { providerServiceKey: queryService.id });\n } catch {\n return undefined;\n }\n}\n\nfunction resourceTagMatches(\n tag: PartitionedDependencyTag,\n resource: ErasedMutationDescriptor['ref'],\n family?: 'collection' | 'record',\n id?: RecordId,\n): boolean {\n const logical = tag[5];\n if (logical[0] !== 'resource' || logical[1] !== 1) return false;\n if (family !== undefined && logical[2] !== family) return false;\n if (!sameEntityRef(logical[3], resource)) return false;\n return id === undefined || (logical[2] === 'record' && Object.is(logical[4], id));\n}\n\nfunction hasResourceTag(\n runtime: DataRuntimeContextValue,\n query: DataQuery,\n provider: ProviderServiceRef,\n mutation: ErasedMutationDescriptor,\n resource: ErasedMutationDescriptor['ref'],\n family?: 'collection' | 'record',\n id?: RecordId,\n): boolean {\n return (\n queryPartition(runtime, query, mutation, provider)?.some((tag) =>\n resourceTagMatches(tag, resource, family, id),\n ) ?? false\n );\n}\n\nfunction descriptorMatchesResource(\n runtime: DataRuntimeContextValue,\n query: DataQuery,\n provider: ProviderServiceRef,\n mutation: ErasedMutationDescriptor,\n resource: ErasedMutationDescriptor['ref'],\n): boolean {\n return hasResourceTag(runtime, query, provider, mutation, resource);\n}\n\nfunction effectResource(effect: MutationEffectTarget): ErasedMutationDescriptor['ref'] {\n const resource = effect.resource;\n return normalizeEntityRef(\n typeof resource === 'object' && resource !== null && 'kind' in resource\n ? resource.ref\n : resource,\n );\n}\n\nfunction hasDeclaredTag(\n runtime: DataRuntimeContextValue,\n query: DataQuery,\n provider: ProviderServiceRef,\n mutation: ErasedMutationDescriptor,\n tag: string,\n): boolean {\n return (\n queryPartition(runtime, query, mutation, provider)?.some((candidate) => {\n const logical = candidate[5];\n return logical[0] === 'declared' && logical[1] === 1 && logical[2] === tag;\n }) ?? false\n );\n}\n\nfunction resultRecord(\n result: unknown,\n): { readonly id: RecordId; readonly record: unknown } | undefined {\n if (result === null || typeof result !== 'object' || Array.isArray(result)) return undefined;\n const value = result as {\n readonly kind?: unknown;\n readonly id?: unknown;\n readonly completeness?: unknown;\n readonly record?: unknown;\n };\n return value.kind === 'record' &&\n value.completeness === 'full' &&\n (typeof value.id === 'string' || typeof value.id === 'number')\n ? { id: value.id, record: value.record }\n : undefined;\n}\n\nfunction writeCompleteOneRecord(\n runtime: DataRuntimeContextValue,\n queryClient: QueryClient,\n provider: ProviderServiceRef,\n mutation: ErasedMutationDescriptor,\n result: unknown,\n): Set<string> {\n const record = resultRecord(result);\n const written = new Set<string>();\n if (record === undefined || (mutation.kind !== 'createOne' && mutation.kind !== 'updateOne'))\n return written;\n for (const query of queryClient.getQueryCache().getAll() as DataQuery[]) {\n const descriptor = descriptorFor(query);\n if (\n descriptor?.kind !== 'one' ||\n descriptor.projection !== undefined ||\n !Object.is(descriptor.id, record.id) ||\n !descriptorMatchesResource(runtime, query, provider, mutation, mutation.ref)\n )\n continue;\n queryClient.setQueryData(query.queryKey, (previous: unknown) =>\n previous !== null && typeof previous === 'object' && !Array.isArray(previous)\n ? { ...(previous as Record<string, unknown>), data: record.record }\n : previous,\n );\n written.add(query.queryHash);\n }\n return written;\n}\n\nfunction mutationRecordIds(\n mutation: ErasedMutationDescriptor,\n result: unknown,\n): readonly RecordId[] | undefined {\n if (mutation.kind === 'updateOne' || mutation.kind === 'deleteOne') return [mutation.id];\n if (\n (mutation.kind === 'updateMany' || mutation.kind === 'deleteMany') &&\n mutation.target.kind === 'ids'\n ) {\n return mutation.target.ids;\n }\n if (\n result !== null &&\n typeof result === 'object' &&\n (result as { target?: unknown }).target === 'ids'\n ) {\n return (result as { succeededIds?: readonly RecordId[] }).succeededIds;\n }\n return undefined;\n}\n\n/**\n * Reconciles canonical cache dependencies after a validated, current mutation.\n * It deliberately uses only core-produced query tags; React never constructs\n * a resource tag or a dependency partition itself.\n */\nexport function reconcileMutation(args: {\n readonly runtime: DataRuntimeContextValue;\n readonly queryClient: QueryClient;\n readonly provider: ProviderServiceRef;\n readonly descriptor: ErasedMutationDescriptor;\n readonly result: unknown;\n readonly effects?: readonly MutationEffectTarget[] | 'none';\n}): void {\n const { runtime, queryClient, provider, descriptor, result } = args;\n const written = writeCompleteOneRecord(runtime, queryClient, provider, descriptor, result);\n const ids = mutationRecordIds(descriptor, result);\n\n if (descriptor.kind === 'deleteOne') {\n queryClient.removeQueries({\n predicate: (query) =>\n hasResourceTag(\n runtime,\n query as DataQuery,\n provider,\n descriptor,\n descriptor.ref,\n 'record',\n descriptor.id,\n ),\n });\n }\n\n queryClient.invalidateQueries({\n predicate: (query) => {\n const current = query as DataQuery;\n const queryDescriptor = descriptorFor(current);\n if (queryDescriptor === undefined) return false;\n const standard = descriptor.kind !== 'custom';\n if (\n standard &&\n descriptorMatchesResource(runtime, current, provider, descriptor, descriptor.ref)\n ) {\n if (queryDescriptor.kind === 'list' || queryDescriptor.kind === 'count') return true;\n if (descriptor.kind === 'createOne') return false;\n if (queryDescriptor.kind === 'one' && written.has(current.queryHash)) return false;\n if (ids === undefined) return true;\n return ids.some((id) =>\n hasResourceTag(runtime, current, provider, descriptor, descriptor.ref, 'record', id),\n );\n }\n\n if (args.effects === undefined || args.effects === 'none') return false;\n return args.effects.some((effect) => {\n const resource = effectResource(effect);\n const resourceMatches = descriptorMatchesResource(\n runtime,\n current,\n provider,\n descriptor,\n resource,\n );\n const recordsMatch =\n effect.records === undefined\n ? resourceMatches\n : effect.records.some((id) =>\n hasResourceTag(runtime, current, provider, descriptor, resource, 'record', id),\n ) ||\n ((queryDescriptor.kind === 'list' || queryDescriptor.kind === 'count') &&\n resourceMatches);\n const tagsMatch =\n effect.tags?.some((tag) => hasDeclaredTag(runtime, current, provider, descriptor, tag)) ??\n false;\n return recordsMatch || tagsMatch;\n });\n },\n });\n}\n","import {\n createIdempotencyKey,\n isDataError,\n isMutationReplaySafe,\n normalizeDataError,\n resolveDataCapability,\n validateMutationResult,\n type DataError,\n type DataErrorKind,\n type DataSessionSnapshot,\n type DeliveryStage,\n type ErasedMutationDescriptor,\n type MutationReplayCapability,\n type MutationEffectTarget,\n type MutationResultFor,\n} from '@burojs/core';\nimport type { UseMutationOptions } from '@tanstack/react-query';\n\nimport { reconcileMutation } from './invalidation.js';\nimport type { DataRuntimeContextValue } from './runtime.js';\n\nfunction cancelledError(code: 'aborted' | 'stale-generation' = 'aborted'): DataError {\n return {\n kind: 'cancelled',\n code,\n message:\n code === 'aborted'\n ? 'Data mutation was aborted.'\n : 'Data mutation completed after its session generation changed.',\n };\n}\n\n/**\n * A provider's definite \"no\": the server answered and refused, so the write was not applied.\n * A handler rejecting with one of these is tagged `answered`, not `handed-over` (spec 4.7).\n */\nconst DEFINITE_REFUSALS: ReadonlySet<DataErrorKind> = new Set<DataErrorKind>([\n 'validation',\n 'conflict',\n 'forbidden',\n 'not-found',\n]);\n\n/**\n * The one exit for every rejection of {@link executeMutation}: it normalizes the value and sets\n * `stage`. A copy is made, because provider errors are often frozen and an `Error`'s `message`\n * is not an enumerable own property a spread would carry.\n */\nfunction withStage(error: unknown, stage: DeliveryStage): DataError {\n const failure = normalizeDataError(error);\n if (failure.stage === stage) return failure;\n return Object.freeze({\n kind: failure.kind,\n code: failure.code,\n message: failure.message,\n ...(failure.status === undefined ? {} : { status: failure.status }),\n ...(failure.retryable === undefined ? {} : { retryable: failure.retryable }),\n ...(failure.details === undefined ? {} : { details: failure.details }),\n ...(failure.cause === undefined ? {} : { cause: failure.cause }),\n stage,\n });\n}\n\nconst STAGE_ORDER: Readonly<Record<DeliveryStage, number>> = {\n 'before-handover': 0,\n 'handed-over': 1,\n answered: 2,\n};\n\n/** The later of two stages: a stage never moves backwards across one call's attempts. */\nfunction laterStage(a: DeliveryStage, b: DeliveryStage): DeliveryStage {\n return STAGE_ORDER[a] >= STAGE_ORDER[b] ? a : b;\n}\n\nfunction isCurrentGeneration(\n runtime: DataRuntimeContextValue,\n descriptor: ErasedMutationDescriptor,\n sessionKey: string,\n generation: number,\n serviceIdentity: object,\n): boolean {\n const state = runtime.dataSession.getState();\n if (\n state.status !== 'ready' ||\n descriptor.sessionKey !== sessionKey ||\n state.snapshot.sessionKey !== sessionKey ||\n state.snapshot.generation !== generation\n )\n return false;\n try {\n return runtime.providers.resolve(descriptor.providerId).identity === serviceIdentity;\n } catch {\n return false;\n }\n}\n\nfunction customEffects(\n runtime: DataRuntimeContextValue,\n descriptor: ErasedMutationDescriptor,\n result: unknown,\n): readonly MutationEffectTarget[] | 'none' | undefined {\n if (descriptor.kind !== 'custom') return undefined;\n const projection = runtime.app.runtime\n .getSnapshot()\n .getProjection({ kind: 'custom-mutation', ref: descriptor.ref });\n const value = projection?.value as Readonly<Record<string, unknown>> | undefined;\n if (value?.effects === 'none') return 'none';\n const attachment = value?.effects as Readonly<Record<string, unknown>> | undefined;\n if (attachment?.capability !== 'mutation-effects' || typeof attachment.id !== 'string') {\n throw {\n kind: 'configuration',\n code: 'custom-mutation-effects-unavailable',\n message: 'Custom mutation effects are unavailable from the current application snapshot.',\n } satisfies DataError;\n }\n const declared = runtime.app.getPluginCapability<unknown>('mutation-effects', attachment.id);\n if (typeof declared === 'function') {\n try {\n return declared({\n input: descriptor.input,\n output: result,\n }) as readonly MutationEffectTarget[];\n } catch (cause) {\n // The write was applied; the app's effects function failed afterwards. It is a setup\n // defect, never a transport failure a retry could fix.\n throw {\n kind: 'configuration',\n code: 'mutation-effects-threw',\n message: `The mutation-effects attachment '${attachment.id}' threw: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n retryable: false,\n cause,\n } satisfies DataError;\n }\n }\n if (!Array.isArray(declared)) {\n throw {\n kind: 'configuration',\n code: 'custom-mutation-effects-unavailable',\n message: 'Custom mutation effects are unavailable from the current application snapshot.',\n } satisfies DataError;\n }\n return declared as readonly MutationEffectTarget[];\n}\n\n/**\n * Executes one pessimistic provider mutation and commits only its active generation.\n *\n * Every rejection is a {@link DataError} carrying `stage` ({@link DeliveryStage}): whether the\n * provider was never called, was called and did not answer, or answered (spec 4.7).\n *\n * - `idempotencyKey`: the key sent to the provider, and reused by its auth replay. Without it,\n * each call mints its own key (one call, one attempt).\n * - `replay: 'never'`: forbids the one auth replay a replay-safe mutation is otherwise allowed;\n * an `auth` failure rejects as it came back.\n */\nexport async function executeMutation<D extends ErasedMutationDescriptor>(args: {\n readonly descriptor: D;\n readonly runtime: DataRuntimeContextValue;\n readonly idempotencyKey?: string;\n readonly replay?: 'never';\n}): Promise<MutationResultFor<D>> {\n // One call is one attempt: its key is minted here (unless the caller holds\n // one) and travels with the attempt into the auth replay below, never\n // re-minted for it. The function is `async` so a missing Web Crypto rejects\n // the returned promise, as every other failure does, instead of throwing\n // before the caller holds one.\n let idempotencyKey: string;\n if (args.idempotencyKey !== undefined) {\n idempotencyKey = args.idempotencyKey;\n } else {\n try {\n idempotencyKey = createIdempotencyKey();\n } catch (error) {\n // The runtime has no Web Crypto: a setup problem no retry can fix.\n throw withStage(\n {\n kind: 'configuration',\n code: 'idempotency-key-unavailable',\n message:\n error instanceof Error ? error.message : 'An idempotency key could not be created.',\n retryable: false,\n cause: error,\n } satisfies DataError,\n 'before-handover',\n );\n }\n }\n return executeKeyedMutation({\n descriptor: args.descriptor,\n runtime: args.runtime,\n idempotencyKey,\n replayCount: 0,\n replayAllowed: args.replay !== 'never',\n floor: 'before-handover',\n });\n}\n\nasync function executeKeyedMutation<D extends ErasedMutationDescriptor>(args: {\n readonly descriptor: D;\n readonly runtime: DataRuntimeContextValue;\n readonly idempotencyKey: string;\n readonly replayCount: 0 | 1;\n readonly replayAllowed: boolean;\n /**\n * The stage an earlier attempt of this call reached. The auth replay is the same call: when\n * its own attempt fails before hand-over, the request the first attempt sent still reached\n * the backend, so the rejection keeps the earlier, later stage.\n */\n readonly floor: DeliveryStage;\n}): Promise<MutationResultFor<D>> {\n let captured:\n | { readonly snapshot: DataSessionSnapshot; readonly replaySafe: boolean }\n | undefined;\n try {\n return await executeMutationAttempt(args, (value) => {\n captured = value;\n });\n } catch (error) {\n // `executeMutationAttempt` rejects only through `withStage`, so the stage is set.\n const failure = normalizeDataError(error);\n const stage = laterStage(failure.stage ?? 'handed-over', args.floor);\n if (\n args.replayAllowed &&\n args.replayCount !== 1 &&\n failure.kind === 'auth' &&\n captured?.replaySafe === true &&\n args.runtime.authController !== undefined\n ) {\n const state = args.runtime.dataSession.getState();\n if (\n state.status === 'ready' &&\n state.snapshot.sessionKey === captured.snapshot.sessionKey &&\n state.snapshot.generation === captured.snapshot.generation\n ) {\n let recovery: DataError | 'replay';\n try {\n recovery = await args.runtime.authController.recover(failure, captured.snapshot);\n } catch (recoveryError) {\n throw withStage(recoveryError, stage);\n }\n if (recovery === 'replay')\n return executeKeyedMutation({ ...args, replayCount: 1, floor: stage });\n // The answer that started the recovery decides the stage, whatever recovery says.\n throw withStage(recovery, stage);\n }\n }\n throw withStage(failure, stage);\n }\n}\n\nasync function executeMutationAttempt<D extends ErasedMutationDescriptor>(\n args: {\n readonly descriptor: D;\n readonly runtime: DataRuntimeContextValue;\n readonly idempotencyKey: string;\n },\n capture: (value: {\n readonly snapshot: DataSessionSnapshot;\n readonly replaySafe: boolean;\n }) => void,\n): Promise<MutationResultFor<D>> {\n let controller: AbortController | undefined;\n let unsubscribe: (() => void) | undefined;\n // Where a failure happened (spec 4.7). It moves forward only: to `handed-over`\n // immediately before the provider handler is called, to `answered` the moment\n // it resolves. Every rejection below leaves through `withStage` with it.\n let stage: DeliveryStage = 'before-handover';\n try {\n const snapshot = await args.runtime.waitUntilReady();\n const service = args.runtime.providers.resolve(args.descriptor.providerId);\n if (\n args.descriptor.sessionKey !== snapshot.sessionKey ||\n service.session.sessionKey !== snapshot.sessionKey ||\n service.session.generation !== snapshot.generation ||\n !isCurrentGeneration(\n args.runtime,\n args.descriptor,\n snapshot.sessionKey,\n snapshot.generation,\n service.identity,\n )\n )\n throw cancelledError('stale-generation');\n controller = new AbortController();\n unsubscribe = args.runtime.dataSession.subscribe(() => {\n if (\n !isCurrentGeneration(\n args.runtime,\n args.descriptor,\n snapshot.sessionKey,\n snapshot.generation,\n service.identity,\n )\n ) {\n controller?.abort();\n }\n });\n const capability = resolveDataCapability(service.provider, {\n lifecycle: 'mutation',\n kind: args.descriptor.kind,\n });\n if (isDataError(capability)) throw capability;\n const handler = capability as unknown as ((\n descriptor: D,\n context: {\n readonly signal: AbortSignal;\n readonly requestContext: typeof args.runtime.app.requestContext;\n readonly session: typeof snapshot;\n readonly providerServiceKey: string;\n readonly idempotencyKey: string;\n },\n ) => Promise<unknown>) & { readonly replay: MutationReplayCapability };\n capture({\n snapshot,\n replaySafe: isMutationReplaySafe(args.descriptor, handler.replay),\n });\n stage = 'handed-over';\n const response = await handler(args.descriptor, {\n signal: controller.signal,\n requestContext: args.runtime.app.requestContext,\n session: snapshot,\n providerServiceKey: service.id,\n idempotencyKey: args.idempotencyKey,\n });\n stage = 'answered';\n const result = validateMutationResult(args.descriptor, response) as MutationResultFor<D>;\n if (\n controller.signal.aborted ||\n !isCurrentGeneration(\n args.runtime,\n args.descriptor,\n snapshot.sessionKey,\n snapshot.generation,\n service.identity,\n )\n )\n throw cancelledError(controller.signal.aborted ? 'aborted' : 'stale-generation');\n reconcileMutation({\n runtime: args.runtime,\n queryClient: args.runtime.queryClient,\n provider: service,\n descriptor: args.descriptor,\n result,\n effects: customEffects(args.runtime, args.descriptor, result),\n });\n return result;\n } catch (error) {\n if (controller?.signal.aborted) throw withStage(cancelledError(), stage);\n const failure = normalizeDataError(error);\n // A handler that rejected with a definite refusal was answered by the server.\n throw withStage(\n failure,\n stage === 'handed-over' && DEFINITE_REFUSALS.has(failure.kind) ? 'answered' : stage,\n );\n } finally {\n unsubscribe?.();\n }\n}\n\nexport type NativeMutationOptions<TData, TVariables> = Omit<\n UseMutationOptions<TData, DataError, TVariables>,\n 'mutationFn' | 'retry'\n>;\n\n/** Direct TanStack builder with fixed pessimistic execution and no retries. */\nexport function buroMutationOptions<TVariables, D extends ErasedMutationDescriptor>(\n descriptorFor: (variables: TVariables) => D,\n runtime: DataRuntimeContextValue,\n): UseMutationOptions<MutationResultFor<D>, DataError, TVariables> {\n return {\n retry: false,\n mutationFn: (variables) => executeMutation({ descriptor: descriptorFor(variables), runtime }),\n };\n}\n","import {\n createMutationDescriptor,\n normalizeDataError,\n normalizeEntityRef,\n type DataError,\n type DataSessionSnapshot,\n type ErasedMutationDescriptor,\n type ErasedResourceHandle,\n type PortableObject,\n type ResourceHandle,\n} from '@burojs/core';\nimport { useCallback, useSyncExternalStore } from 'react';\n\nimport { useDataRuntime } from '../../data/context.js';\nimport { useApplicationSnapshot } from '../../runtime.js';\n\ntype AnyResource = ResourceHandle<any, any, any, any>;\n\nfunction currentSession(runtime: ReturnType<typeof useDataRuntime>): DataSessionSnapshot {\n const state = runtime.dataSession.getState();\n return state.status === 'ready' ? state.snapshot : state.target;\n}\n\nfunction resourceHandle(resource: AnyResource | string): AnyResource | ErasedResourceHandle {\n return typeof resource === 'string'\n ? ({ kind: 'resource', ref: normalizeEntityRef(resource) } as ErasedResourceHandle)\n : resource;\n}\n\n/** Creates standard mutation descriptors from the live app/session snapshot. */\nexport function useStandardMutationDescriptor(\n resource: AnyResource | string,\n providerOptionsOverride?: PortableObject,\n): (input: Readonly<Record<string, unknown>>) => ErasedMutationDescriptor {\n const runtime = useDataRuntime();\n const snapshot = useApplicationSnapshot();\n const session = useSyncExternalStore(\n runtime.dataSession.subscribe,\n () => currentSession(runtime),\n () => currentSession(runtime),\n );\n const handle = resourceHandle(resource);\n const projection = runtime.app.registry.get(handle);\n\n return useCallback(\n (input) => {\n if (projection === undefined) {\n throw normalizeDataError(\n Object.assign(\n new Error(`Resource '${handle.ref.namespace}:${handle.ref.id}' is unavailable.`),\n {\n kind: 'configuration' as const,\n code: 'resource-unavailable',\n },\n ),\n ) as DataError;\n }\n let binding;\n try {\n binding = runtime.app.resolveDataBinding(handle);\n } catch (error) {\n throw normalizeDataError(\n Object.assign(\n new Error(\n error instanceof Error ? error.message : 'Resource data binding is unavailable.',\n ),\n { kind: 'configuration' as const, code: 'data-binding-unavailable', cause: error },\n ),\n ) as DataError;\n }\n return createMutationDescriptor({\n ...input,\n providerId: binding.providerId,\n ref: binding.ref,\n resource: binding.resource,\n sessionKey: session.sessionKey,\n scopeKey: session.scopeKey,\n bindingRevision: snapshot.manifest.snapshotId,\n idField: projection.data?.idField ?? 'id',\n ...(projection.data?.providerOptions === undefined\n ? {}\n : { providerOptions: projection.data.providerOptions }),\n ...(projection.data?.dependencies === undefined\n ? {}\n : { dependencies: projection.data.dependencies }),\n ...(providerOptionsOverride === undefined ? {} : { providerOptionsOverride }),\n } as never) as ErasedMutationDescriptor;\n },\n [\n handle,\n projection,\n providerOptionsOverride,\n runtime.app,\n session,\n snapshot.manifest.snapshotId,\n ],\n );\n}\n","import type {\n CreateOneDescriptor,\n DataError,\n ErasedResourceHandle,\n FieldDefBase,\n InferCreateInput,\n MutationResultFor,\n PortableObject,\n ResourceHandle,\n} from '@burojs/core';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\nimport { buroMutationOptions, type NativeMutationOptions } from '../../data/mutation-options.js';\nimport { useDataRuntime } from '../../data/context.js';\nimport { useStandardMutationDescriptor } from './use-standard-mutation-descriptor.js';\n\ntype AnyResource = ResourceHandle<any, Record<string, FieldDefBase>, string, string>;\nexport type UseCreateOneOptions<R extends AnyResource> = NativeMutationOptions<\n MutationResultFor<CreateOneDescriptor<R>>,\n { readonly values: InferCreateInput<R> }\n> & { readonly providerOptionsOverride?: PortableObject };\n\nexport function useCreateOne<R extends AnyResource>(\n resource: R,\n options?: UseCreateOneOptions<R>,\n): UseMutationResult<\n MutationResultFor<CreateOneDescriptor<R>>,\n DataError,\n { readonly values: InferCreateInput<R> }\n>;\nexport function useCreateOne(\n resource: string,\n options?: UseCreateOneOptions<ErasedResourceHandle>,\n): UseMutationResult<\n MutationResultFor<CreateOneDescriptor<ErasedResourceHandle>>,\n DataError,\n { readonly values: unknown }\n>;\nexport function useCreateOne(resource: AnyResource | string, options: any = {}): any {\n const runtime = useDataRuntime();\n const { providerOptionsOverride, ...mutationOptions } = options;\n const descriptorFor = useStandardMutationDescriptor(resource, providerOptionsOverride);\n return useMutation({\n ...mutationOptions,\n ...buroMutationOptions(\n (variables: { readonly values: unknown }) =>\n descriptorFor({ kind: 'createOne', input: variables.values }),\n runtime,\n ),\n });\n}\n","import type {\n BulkTarget,\n DataError,\n ErasedResourceHandle,\n FieldDefBase,\n InferUpdateInput,\n MutationResultFor,\n PortableObject,\n ResourceHandle,\n UpdateManyDescriptor,\n UpdateOneDescriptor,\n} from '@burojs/core';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\nimport { buroMutationOptions, type NativeMutationOptions } from '../../data/mutation-options.js';\nimport { useDataRuntime } from '../../data/context.js';\nimport { useStandardMutationDescriptor } from './use-standard-mutation-descriptor.js';\n\ntype AnyResource = ResourceHandle<any, Record<string, FieldDefBase>, string, string>;\ntype UpdateOneVariables<R extends AnyResource> = {\n readonly id: UpdateOneDescriptor<R>['id'];\n readonly values: InferUpdateInput<R>;\n};\ntype UpdateManyVariables<R extends AnyResource> = {\n readonly target: BulkTarget<R>;\n readonly values: InferUpdateInput<R>;\n};\nexport type UseUpdateOneOptions<R extends AnyResource> = NativeMutationOptions<\n MutationResultFor<UpdateOneDescriptor<R>>,\n UpdateOneVariables<R>\n> & { readonly providerOptionsOverride?: PortableObject };\nexport type UseUpdateManyOptions<R extends AnyResource> = NativeMutationOptions<\n MutationResultFor<UpdateManyDescriptor<R>>,\n UpdateManyVariables<R>\n> & { readonly providerOptionsOverride?: PortableObject };\n\nexport function useUpdateOne<R extends AnyResource>(\n resource: R,\n options?: UseUpdateOneOptions<R>,\n): UseMutationResult<MutationResultFor<UpdateOneDescriptor<R>>, DataError, UpdateOneVariables<R>>;\nexport function useUpdateOne(\n resource: string,\n options?: UseUpdateOneOptions<ErasedResourceHandle>,\n): UseMutationResult<\n MutationResultFor<UpdateOneDescriptor<ErasedResourceHandle>>,\n DataError,\n UpdateOneVariables<ErasedResourceHandle>\n>;\nexport function useUpdateOne(resource: AnyResource | string, options: any = {}): any {\n const runtime = useDataRuntime();\n const { providerOptionsOverride, ...mutationOptions } = options;\n const descriptorFor = useStandardMutationDescriptor(resource, providerOptionsOverride);\n return useMutation({\n ...mutationOptions,\n ...buroMutationOptions(\n (variables: { readonly id: unknown; readonly values: unknown }) =>\n descriptorFor({ kind: 'updateOne', id: variables.id, input: variables.values }),\n runtime,\n ),\n });\n}\n\nexport function useUpdateMany<R extends AnyResource>(\n resource: R,\n options?: UseUpdateManyOptions<R>,\n): UseMutationResult<MutationResultFor<UpdateManyDescriptor<R>>, DataError, UpdateManyVariables<R>>;\nexport function useUpdateMany(\n resource: string,\n options?: UseUpdateManyOptions<ErasedResourceHandle>,\n): UseMutationResult<\n MutationResultFor<UpdateManyDescriptor<ErasedResourceHandle>>,\n DataError,\n UpdateManyVariables<ErasedResourceHandle>\n>;\nexport function useUpdateMany(resource: AnyResource | string, options: any = {}): any {\n const runtime = useDataRuntime();\n const { providerOptionsOverride, ...mutationOptions } = options;\n const descriptorFor = useStandardMutationDescriptor(resource, providerOptionsOverride);\n return useMutation({\n ...mutationOptions,\n ...buroMutationOptions(\n (variables: { readonly target: unknown; readonly values: unknown }) =>\n descriptorFor({ kind: 'updateMany', target: variables.target, input: variables.values }),\n runtime,\n ),\n });\n}\n","'use client';\nimport type { AppAuditEventInput, Audit } from '@burojs/core';\nimport { createContext, useContext, useMemo } from 'react';\n\nexport const AuditContext = createContext<Audit | null>(null);\n\n// Bundlers fold the development branch out of a production build.\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } };\n\n/** What an application emits through: its own `app.*` events, and the correlation it shares. */\nexport interface AppAudit {\n /**\n * Emits an application event. Its `type` must start with `app.`: a framework type\n * (`form.submit`, `flow.submit`, `nav.enter`) is dropped — the framework emits those itself —\n * with a development `console.error` naming it.\n */\n emit(input: AppAuditEventInput, options?: { readonly initiates?: boolean }): void;\n /** The id shared by everything the current user action caused. */\n currentCorrelationId(): string;\n readonly sessionId: string;\n}\n\n/**\n * The application's audit emitter, or `null` when `<BuroProvider>` got no\n * `audit` prop.\n *\n * Call sites guard with `audit?.emit(...)`, and that guard is deliberate: it is\n * what makes an app without auditing pay nothing, because the work of building\n * an event (a list snapshot) never starts.\n *\n * Applications use it to write their own events into the same stream — custom\n * pages and hand-written components are otherwise blind spots by construction:\n *\n * const audit = useAudit();\n * audit?.emit({ type: 'app.export.started', payload: { format: 'xlsx' } });\n *\n * Only `app.*` events pass (REF-29): the framework's own events go through an internal emitter,\n * so an application can never forge a `form.submit` or a `flow.submit`. The `Audit` object\n * `createAudit` returns is unchanged for the application's own transport code.\n */\nexport function useAudit(): AppAudit | null {\n const audit = useContext(AuditContext);\n return useMemo(() => (audit === null ? null : narrow(audit)), [audit]);\n}\n\nfunction narrow(audit: Audit): AppAudit {\n return Object.freeze({\n emit(input: AppAuditEventInput, options?: { readonly initiates?: boolean }) {\n // One copy, read once: the check and the emit see the same values, so a getter cannot\n // answer `app.*` to the check and a framework type to the emit (P4-B review I1).\n let event: AppAuditEventInput;\n try {\n event = Object.freeze({ ...input });\n } catch {\n return;\n }\n const type = (event as { readonly type?: unknown }).type;\n if (typeof type !== 'string' || !type.startsWith('app.')) {\n if (process.env.NODE_ENV !== 'production')\n console.error(\n `[burojs] useAudit().emit takes app.* events only; '${String(type)}' was dropped. The framework emits its own events.`,\n );\n return;\n }\n audit.emit(event, options);\n },\n currentCorrelationId: () => audit.currentCorrelationId(),\n sessionId: audit.sessionId,\n });\n}\n","'use client';\nimport * as React from 'react';\n\n/**\n * The framework's whole dependency on a router: where the app is and how to\n * move. It is the router's only binding — route matching, the active nav item,\n * breadcrumbs, URL state and every framework navigation read or write through\n * it — and `LinkComponentProvider` only renders anchors. Mount it with\n * `RouterAdapterProvider`.\n *\n * Every member is app-space: `pathname` without the router's basename, and\n * `push` / `replace` take a path the router prefixes itself.\n */\nexport interface RouterAdapter {\n /** The current path, without the router's basename. */\n pathname: string;\n searchParams: URLSearchParams;\n /** Navigate without adding a history entry — used for URL-state sync. */\n replace: (url: string) => void;\n push: (url: string) => void;\n}\n\nconst RouterAdapterContext = React.createContext<RouterAdapter | null>(null);\n\nexport interface RouterAdapterProviderProps {\n adapter: RouterAdapter;\n children: React.ReactNode;\n}\n\n/**\n * Binds your router to the framework. Required: mount it **above**\n * `<BuroProvider>`, once for the whole app. Without it no route matches\n * (`<NavAreaPage>` renders not-found and says so in development), no nav item\n * is active, and every framework navigation falls back to a full page load.\n * The default `redirect` and the navigation guard's \"Leave\" read the adapter\n * from where `<BuroProvider>` sits, so one mounted inside it is invisible to\n * them. `LinkComponentProvider` (`@burojs/ui-shadcn`) only renders anchors;\n * it is not a router binding.\n *\n * react-router (v7; v6 exports the same hooks from `react-router-dom`):\n *\n * ```tsx\n * import { RouterAdapterProvider } from '@burojs/react';\n * import * as React from 'react';\n * import { useLocation, useNavigate, useSearchParams } from 'react-router';\n *\n * export function ReactRouterAdapter({ children }: { children: React.ReactNode }) {\n * const location = useLocation();\n * const navigate = useNavigate();\n * const [searchParams] = useSearchParams();\n * const adapter = React.useMemo(\n * () => ({\n * pathname: location.pathname,\n * searchParams,\n * replace: (url: string) => navigate(url, { replace: true }),\n * push: (url: string) => navigate(url),\n * }),\n * [location.pathname, searchParams, navigate],\n * );\n * return <RouterAdapterProvider adapter={adapter}>{children}</RouterAdapterProvider>;\n * }\n * ```\n *\n * Next App Router (a client component):\n *\n * ```tsx\n * 'use client';\n * import { RouterAdapterProvider } from '@burojs/react';\n * import { usePathname, useRouter, useSearchParams } from 'next/navigation';\n * import * as React from 'react';\n *\n * export function NextRouterAdapter({ children }: { children: React.ReactNode }) {\n * const router = useRouter();\n * const pathname = usePathname();\n * const search = useSearchParams();\n * const adapter = React.useMemo(\n * () => ({\n * pathname,\n * searchParams: new URLSearchParams(search.toString()),\n * replace: (url: string) => router.replace(url, { scroll: false }),\n * push: (url: string) => router.push(url),\n * }),\n * [pathname, search, router],\n * );\n * return <RouterAdapterProvider adapter={adapter}>{children}</RouterAdapterProvider>;\n * }\n * ```\n *\n * Then: `<ReactRouterAdapter><BuroProvider app={app}>…</BuroProvider></ReactRouterAdapter>`.\n */\nexport function RouterAdapterProvider({\n adapter,\n children,\n}: RouterAdapterProviderProps): React.ReactElement {\n return <RouterAdapterContext.Provider value={adapter}>{children}</RouterAdapterContext.Provider>;\n}\n\nexport function useRouterAdapter(): RouterAdapter {\n return requireRouterAdapter(React.useContext(RouterAdapterContext));\n}\n\n/**\n * @internal The mounted adapter, or the \"no RouterAdapterProvider\" error: what\n * `useRouterAdapter` throws, for a hook that needs a router only in some modes.\n */\nexport function requireRouterAdapter(found: RouterAdapter | null): RouterAdapter {\n if (!found) {\n throw new Error(\n 'No RouterAdapterProvider found. URL state (filters, sorting, paging) needs to ' +\n 'read and write the address bar; without a router it would appear to work and ' +\n 'silently never persist. Wrap the app:\\n\\n' +\n ' // Next App Router\\n' +\n ' const adapter = {\\n' +\n ' pathname: usePathname(),\\n' +\n ' searchParams: new URLSearchParams(useSearchParams().toString()),\\n' +\n ' replace: (u) => router.replace(u, { scroll: false }),\\n' +\n ' push: (u) => router.push(u),\\n' +\n ' };\\n\\n' +\n ' // react-router\\n' +\n ' const [sp] = useSearchParams();\\n' +\n ' const navigate = useNavigate();\\n' +\n ' const adapter = {\\n' +\n ' pathname: useLocation().pathname,\\n' +\n ' searchParams: sp,\\n' +\n ' replace: (u) => navigate(u, { replace: true }),\\n' +\n ' push: (u) => navigate(u),\\n' +\n ' };',\n );\n }\n return found;\n}\n\n/**\n * The router adapter, or `null` when none is mounted.\n *\n * `useRouterAdapter` throws by design — URL state that silently never persists\n * is worse than a crash. Audit is the opposite case: an app with no router is\n * legitimate, and auditing must never be the thing that breaks it.\n */\nexport function useOptionalRouterAdapter(): RouterAdapter | null {\n return React.useContext(RouterAdapterContext);\n}\n","'use client';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport { dtoFields, relationAmbiguousError } from '@burojs/core';\nimport { useDataRuntime } from '../data/context.js';\nimport { useDescriptorSession } from './data/use-standard-query-descriptor.js';\nimport { useList } from './data/use-list.js';\nimport { useLocale } from './use-t.js';\nimport { useMany } from './data/use-many.js';\nimport { useOne } from './data/use-one.js';\n\n/**\n * The most keys of one `by` read when the application declares no provider maximum: a batch asks\n * for `2 × keys` rows, so it is read in chunks of half this many keys.\n */\nexport const RELATION_BATCH_MAX_PAGE = 100;\n\n/**\n * A resolved relation record. Mirrors the shape used by the legacy\n * per-cell `useRelatedRecord` (see the deleted\n * `ui-shadcn/src/fields/use-related-record.ts`).\n */\nexport type RelatedRecord = { id: unknown } & Record<string, unknown>;\n\n/** Result returned by `useRelatedRecord`. Signature UNCHANGED from today. */\nexport interface UseRelatedRecordResult {\n /** Resolved record, or `undefined` while loading / on error / when id is falsy. */\n record: RelatedRecord | undefined;\n /** True from first render until the record settles. */\n isLoading: boolean;\n /** Set when resolution errors (fallback path) — the aggregator path never\n * surfaces a per-id error (a dangling FK degrades to `record: undefined`\n * instead, matching today's fail-soft display behaviour). */\n error: Error | null;\n /**\n * True when the key matched more than one row of the target (a `by` key the backend does not\n * keep unique): `record` stays undefined, the display renders the key muted, and one\n * development error names the target, the field and the key. Never picks either row.\n */\n ambiguous: boolean;\n}\n\n/** Options of `useRelatedRecord`: the target field the key holds, and the display's resolve. */\nexport interface UseRelatedRecordOptions {\n /** The target field the key is matched on; the target's id field when absent. */\n readonly by?: string;\n /** `'lazy'` registers nothing and reads nothing (spec 4.3); `'eager'` is the default. */\n readonly resolve?: 'eager' | 'lazy';\n}\n\n/** A key matching two rows: kept apart from a resolved record and from a confirmed miss. */\nconst AMBIGUOUS = Symbol('relation-ambiguous');\n/**\n * A key a full (cut-off) page saw at most once: more rows may hold it beyond the page, so it is\n * neither one row nor a confirmed miss. Fails closed, as an error (spec 4.2, 4.3).\n */\nconst TRUNCATED = Symbol('relation-truncated');\n\n/**\n * `records.get(pair).get(key)` semantics (a pair is `(resource, by ?? id)`):\n * - key absent → never requested / still in flight.\n * - value is a record → resolved.\n * - value is `null` → the batch that covered this id came back\n * without it (dangling FK / deleted row) — a CONFIRMED miss, distinct\n * from \"still loading\", so the cell can fall back to the raw id\n * immediately instead of spinning forever.\n */\ntype ResolvedEntry = RelatedRecord | null | typeof AMBIGUOUS | typeof TRUNCATED;\n\ninterface ResourceStatus {\n isLoading: boolean;\n error: Error | null;\n}\n\ntype KeySnapshot = UseRelatedRecordResult;\n\n/** Stable, frozen snapshot for the \"no id\" case — never register, never fetch. */\nconst STABLE_EMPTY: KeySnapshot = Object.freeze({\n record: undefined,\n isLoading: false,\n error: null,\n ambiguous: false,\n});\n\nfunction keyOf(pair: string, idStr: string): string {\n return `${pair}\\u0000${idStr}`;\n}\n\n/** The batch a key joins: one per `(resource, by)`; the id pair is the resource's name. */\nfunction pairOf(resource: string, by: string | undefined): string {\n return by === undefined ? resource : `${resource}\\u0001${by}`;\n}\n\nfunction splitPair(pair: string): { readonly resource: string; readonly by?: string } {\n const at = pair.indexOf('\\u0001');\n return at === -1 ? { resource: pair } : { resource: pair.slice(0, at), by: pair.slice(at + 1) };\n}\n\n/**\n * A key a read may send (spec 4.1): a non-empty string or a finite number. `null`, `undefined`,\n * `''`, `NaN`, a boolean or an object is no key — nothing registers and nothing is read.\n */\nexport function relationKeyString(key: unknown): string | null {\n if (typeof key === 'string') return key.length === 0 ? null : key;\n if (typeof key === 'number') return Number.isFinite(key) ? String(key) : null;\n return null;\n}\n\n/**\n * The vanilla external store backing the relation aggregator. One instance\n * is created per `<BuroProvider>` (its `RelationAggregatorMount`, via `useRef`) and shared,\n * via context, by every `useRelatedRecord` call underneath it and by the\n * provider's own `ResourceBatch` fetchers.\n *\n * Design notes (see docs/specs/relation-aggregation.md +\n * docs/superpowers/plans/2026-07-25-relation-aggregation.md Task 1):\n * - `refcounts` is mutated synchronously and O(1) on register/unregister;\n * the (possibly large) burst of registrations from mounting a\n * 1000-row list therefore costs one Map write per cell, not one React\n * state update per cell.\n * - Notifications are coalesced: a burst of register/unregister calls\n * schedules exactly ONE `fetchListeners` flush via `queueMicrotask`\n * (guarded by `flushScheduled`), so the provider re-renders once per\n * burst rather than once per row.\n * - `snapshotCache` gives `useSyncExternalStore` a STABLE object\n * reference per `(resource, id)` key: `getSnapshotKey` returns the\n * cached object until that key is explicitly invalidated by\n * `applyResults` / `setResourceStatus`, which only touch the ids that\n * were actually part of the batch that just settled. A cell whose id\n * is unaffected by another id's resolution therefore never sees its\n * snapshot reference change and never re-renders — this is what makes\n * per-cell subscriptions selective instead of \"every cell re-renders\n * whenever anything resolves\".\n */\nclass RelationAggregatorStore {\n private readonly records = new Map<string, Map<string, ResolvedEntry>>();\n private readonly status = new Map<string, ResourceStatus>();\n private readonly refcounts = new Map<string, Map<string, number>>();\n private readonly listeners = new Map<string, Set<() => void>>();\n private readonly fetchListeners = new Set<() => void>();\n private readonly snapshotCache = new Map<string, KeySnapshot>();\n\n private registeredCache: Map<string, string[]> | null = null;\n private flushScheduled = false;\n\n /** True once `resource`/`idStr` has an entry in `records` — a resolved\n * record OR a confirmed-missing `null` (dangling FK). Public so\n * `ResourceBatch` can compute its `unresolved` filter set without\n * reaching into store internals. */\n isResolved(resource: string, idStr: string): boolean {\n return this.records.get(resource)?.has(idStr) ?? false;\n }\n\n /** Refcount++. Schedules a coalesced fetch-listener notify when the id\n * transitions from unregistered → registered, or when it's genuinely\n * new work (not already resolved) so `status` reflects fresh loading. */\n register(resource: string, idStr: string): void {\n let idMap = this.refcounts.get(resource);\n if (!idMap) {\n idMap = new Map();\n this.refcounts.set(resource, idMap);\n }\n const count = idMap.get(idStr) ?? 0;\n idMap.set(idStr, count + 1);\n if (count === 0) {\n if (!this.isResolved(resource, idStr)) {\n // Fresh, unresolved work for this resource — (re-)arm loading so a\n // resource that had gone idle (previous batch settled) reports\n // isLoading again for ids ResourceBatch hasn't fetched yet.\n this.status.set(resource, { isLoading: true, error: null });\n }\n this.invalidateRegistered();\n this.scheduleFetchNotify();\n }\n }\n\n /** Refcount--. Removes the id at zero and schedules a coalesced notify. */\n unregister(resource: string, idStr: string): void {\n const idMap = this.refcounts.get(resource);\n if (!idMap) return;\n const count = idMap.get(idStr) ?? 0;\n if (count <= 1) {\n idMap.delete(idStr);\n if (idMap.size === 0) this.refcounts.delete(resource);\n this.invalidateRegistered();\n this.scheduleFetchNotify();\n } else {\n idMap.set(idStr, count - 1);\n }\n }\n\n private invalidateRegistered(): void {\n this.registeredCache = null;\n }\n\n private scheduleFetchNotify(): void {\n if (this.flushScheduled) return;\n this.flushScheduled = true;\n queueMicrotask(() => {\n this.flushScheduled = false;\n for (const cb of this.fetchListeners) cb();\n });\n }\n\n subscribeFetch = (cb: () => void): (() => void) => {\n this.fetchListeners.add(cb);\n return () => {\n this.fetchListeners.delete(cb);\n };\n };\n\n /** Stable per-call snapshot: `Map<resource, idStr[]>` of every currently\n * registered (refcount > 0) id, rebuilt only when the registered SET\n * actually changed (register/unregister at the 0↔1 boundary). */\n getRegistered = (): Map<string, string[]> => {\n if (this.registeredCache) return this.registeredCache;\n const out = new Map<string, string[]>();\n for (const [resource, idMap] of this.refcounts) {\n if (idMap.size > 0) out.set(resource, Array.from(idMap.keys()));\n }\n this.registeredCache = out;\n return out;\n };\n\n subscribeKey = (resource: string, idStr: string, cb: () => void): (() => void) => {\n const key = keyOf(resource, idStr);\n let set = this.listeners.get(key);\n if (!set) {\n set = new Set();\n this.listeners.set(key, set);\n }\n set.add(cb);\n return () => {\n set?.delete(cb);\n if (set && set.size === 0) this.listeners.delete(key);\n };\n };\n\n getSnapshotKey = (resource: string, idStr: string): KeySnapshot => {\n const key = keyOf(resource, idStr);\n const cached = this.snapshotCache.get(key);\n if (cached) return cached;\n\n const entry = this.records.get(resource)?.get(idStr);\n let snap: KeySnapshot;\n if (entry === AMBIGUOUS) {\n snap = { record: undefined, isLoading: false, error: null, ambiguous: true };\n } else if (entry === TRUNCATED) {\n const { resource: target, by } = splitPair(resource);\n snap = {\n record: undefined,\n isLoading: false,\n error: new Error(\n `${target}: the read of ${by ?? 'id'} ${JSON.stringify(idStr)} came back on a full page; it cannot tell one row from several, nor a missing row from one past the page.`,\n ),\n ambiguous: false,\n };\n } else if (entry !== undefined) {\n // Resolved (a record) or confirmed-missing (null) — either way, no\n // longer loading, and never depends on resource-level status again.\n snap = { record: entry ?? undefined, isLoading: false, error: null, ambiguous: false };\n } else {\n const st = this.status.get(resource);\n snap = {\n record: undefined,\n isLoading: st?.isLoading ?? true,\n error: st?.error ?? null,\n ambiguous: false,\n };\n }\n this.snapshotCache.set(key, snap);\n return snap;\n };\n\n private notifyKey(resource: string, idStr: string): void {\n const key = keyOf(resource, idStr);\n this.snapshotCache.delete(key);\n const set = this.listeners.get(key);\n if (!set) return;\n for (const cb of set) cb();\n }\n\n /**\n * Apply a settled `getList` batch for `resource`. `requestedIds` is the\n * EXACT set of ids that batch's `in` filter covered (captured by\n * `ResourceBatch` at query time) — only those ids' snapshots are\n * invalidated/notified, so ids resolved by an EARLIER batch (already in\n * `records`) are left untouched and never re-render their cells. Ids in\n * `requestedIds` not present in `found` are recorded as confirmed-missing\n * (`null`) — dangling FK fail-soft, same as the old per-cell `useOne`.\n */\n applyResults(\n resource: string,\n requestedIds: readonly string[],\n found: readonly RelatedRecord[],\n matchOn: string,\n by?: string,\n truncated = false,\n ): void {\n let recMap = this.records.get(resource);\n if (!recMap) {\n recMap = new Map();\n this.records.set(resource, recMap);\n }\n // Rows are matched on the field the keys hold: `by` for a `by` pair, the target's id field\n // otherwise. Never on `id` for a `by` pair — a gtin may equal another row's id.\n const byKey = new Map<string, RelatedRecord | typeof AMBIGUOUS>();\n for (const rec of found) {\n const key = relationKeyString(rec[matchOn]);\n if (key === null) continue;\n byKey.set(key, byKey.has(key) ? AMBIGUOUS : rec);\n }\n for (const idStr of requestedIds) {\n const seen = byKey.get(idStr);\n // A cut-off page settles only what it proves: a key seen twice is ambiguous whatever lies\n // past the page; a key seen once or not at all is not known.\n const entry: ResolvedEntry = truncated && seen !== AMBIGUOUS ? TRUNCATED : (seen ?? null);\n if (entry === AMBIGUOUS && process.env.NODE_ENV !== 'production') {\n const target = splitPair(resource).resource;\n console.error(`[burojs] ${relationAmbiguousError(target, by ?? matchOn, idStr).message}`);\n }\n recMap.set(idStr, entry);\n }\n this.status.set(resource, { isLoading: false, error: null });\n for (const idStr of requestedIds) this.notifyKey(resource, idStr);\n }\n\n /**\n * Forget every resolved and pending entry (P3-29): the rows belong to the previous user, scope\n * or locale. Demand (`refcounts`) is kept, so every key still on screen is read again under the\n * new session. Runs during the mount's render, so it notifies nobody here: `notifyAll` does,\n * from a layout effect, before anything is painted.\n */\n clear(): void {\n this.records.clear();\n this.status.clear();\n this.snapshotCache.clear();\n this.invalidateRegistered();\n }\n\n /** Re-render every subscribed key and schedule a fetch flush (after `clear`). */\n notifyAll(): void {\n for (const set of [...this.listeners.values()]) for (const cb of [...set]) cb();\n this.scheduleFetchNotify();\n }\n\n /** A batch fetch errored. Only the ids that batch was requesting are\n * notified (they'll surface the error via resource-level `status` since\n * they still have no `records` entry); already-resolved ids elsewhere on\n * the same resource are untouched. */\n setResourceStatus(resource: string, next: ResourceStatus, requestedIds: readonly string[]): void {\n this.status.set(resource, next);\n for (const idStr of requestedIds) this.notifyKey(resource, idStr);\n }\n}\n\nconst RelationAggregatorContext = createContext<RelationAggregatorStore | null>(null);\n\ninterface ResourceBatchProps {\n /** The pair key: the resource name for an id pair. */\n resource: string;\n ids: string[];\n store: RelationAggregatorStore;\n}\n\n/** The record DTO of `resource` and its id field, read from the registry. */\nfunction useTargetShape(resource: string): {\n readonly projection?: readonly string[];\n readonly idField: string;\n} {\n const def = useDataRuntime().app.registry.get(resource);\n const idField = (def?.data as { readonly idField?: unknown } | undefined)?.idField;\n return {\n ...(def === undefined ? {} : { projection: dtoFields(def, 'record') }),\n idField: typeof idField === 'string' && idField.length > 0 ? idField : 'id',\n };\n}\n\n/**\n * The un-resolved registered ids of one resource, read in chunks of `maxPage` ids (plan ruling\n * 17): an id `in` read returns at most one row per id, so a chunk fits the provider's page. This is\n * the O(relationColumns) observer in place of the O(rows × relationColumns) per-cell `useOne`\n * fleet. Renders nothing of its own.\n */\nfunction ResourceBatch({\n resource,\n ids,\n maxPage,\n store,\n}: ResourceBatchProps & { readonly maxPage: number }): ReactElement {\n const unresolved = ids.filter((id) => !store.isResolved(resource, id));\n const size = Math.max(1, Math.floor(maxPage));\n const chunks: string[][] = [];\n for (let index = 0; index < unresolved.length; index += size) {\n chunks.push(unresolved.slice(index, index + size));\n }\n return (\n <>\n {chunks.map((keys) => (\n <IdChunk key={keys[0]} resource={resource} ids={keys} store={store} />\n ))}\n </>\n );\n}\n\n/**\n * One native `useMany` over one chunk of ids. It settles only the ids of its own request (Known\n * finding 13): a row its response carries for another chunk's id is ignored, and an id its\n * response lacks is a confirmed miss for this chunk alone.\n */\nfunction IdChunk({ resource, ids, store }: ResourceBatchProps): null {\n const unresolved = ids.filter((id) => !store.isResolved(resource, id));\n const { idField } = useTargetShape(resource);\n\n const query = useMany(resource, {\n ids: unresolved,\n enabled: unresolved.length > 0,\n retry: false,\n });\n\n useEffect(() => {\n if (query.error) {\n store.setResourceStatus(\n resource,\n { isLoading: false, error: query.error as unknown as Error },\n unresolved,\n );\n return;\n }\n if (query.data) {\n store.applyResults(resource, unresolved, query.data.data as RelatedRecord[], idField);\n }\n // `unresolved` intentionally excluded: it's a new array every render,\n // and we only want to react when the QUERY actually settles (a new\n // `data`/`error` reference from react-query). The closure still\n // captures the `unresolved` that was in scope for the render that\n // triggered THIS query, which is exactly the set that query covers.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, resource, idField, query.data, query.error]);\n\n return null;\n}\n\ninterface ByChunkProps {\n pair: string;\n target: string;\n by: string;\n keys: readonly string[];\n maxPage: number;\n store: RelationAggregatorStore;\n}\n\n/**\n * One chunk of a `by` pair (spec 4.3): a list read of the target `where <by> in [keys]`, asking\n * for `2 × keys` rows (at most `maxPage`) so a duplicate is seen rather than cut off by the\n * provider's default page, with the record DTO projection. Renders nothing.\n */\nfunction ByChunk({ pair, target, by, keys, maxPage, store }: ByChunkProps): null {\n const unresolved = keys.filter((key) => !store.isResolved(pair, key));\n const shape = useTargetShape(target);\n // The record DTO, plus what the read itself needs: the `by` field it matches rows on and the\n // id field a display links with, declared or not.\n const projection =\n shape.projection === undefined\n ? undefined\n : [...new Set([...shape.projection, by, shape.idField])];\n const enabled = unresolved.length > 0;\n const pageSize = Math.min(2 * unresolved.length, maxPage);\n const query = useList(target, {\n ...(enabled\n ? {\n filter: { field: by, op: 'in', value: unresolved } as never,\n pagination: { kind: 'offset', page: 1, pageSize } as never,\n }\n : {}),\n ...(projection === undefined ? {} : { projection }),\n enabled,\n retry: false,\n });\n\n useEffect(() => {\n if (query.error) {\n store.setResourceStatus(\n pair,\n { isLoading: false, error: query.error as unknown as Error },\n unresolved,\n );\n return;\n }\n // A placeholder is the previous keys' page (a list keeps it across a filter change): it\n // proves nothing about these keys, so nothing settles until their own page arrives.\n if (query.data && !query.isPlaceholderData) {\n const page = query.data as {\n readonly data: readonly RelatedRecord[];\n readonly total?: unknown;\n };\n // A full page (or a total above it) may have cut rows off: what it did not prove fails closed.\n const truncated =\n page.data.length >= pageSize ||\n (typeof page.total === 'number' && page.total > page.data.length);\n store.applyResults(pair, unresolved, page.data, by, by, truncated);\n }\n // As `ResourceBatch`: react to the query settling, with the keys it covered.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, pair, by, pageSize, query.data, query.isPlaceholderData, query.error]);\n\n return null;\n}\n\n/** A `by` pair's registered keys, read in chunks of `floor(maxPage / 2)` keys. */\nfunction ByBatch({\n pair,\n ids,\n maxPage,\n store,\n}: {\n pair: string;\n ids: readonly string[];\n maxPage: number;\n store: RelationAggregatorStore;\n}): ReactElement {\n const { resource, by } = splitPair(pair);\n const size = Math.max(1, Math.floor(maxPage / 2));\n const chunks: string[][] = [];\n for (let index = 0; index < ids.length; index += size)\n chunks.push(ids.slice(index, index + size));\n return (\n <>\n {chunks.map((keys) => (\n <ByChunk\n key={keys[0]}\n pair={pair}\n target={resource}\n by={by as string}\n keys={keys}\n maxPage={maxPage}\n store={store}\n />\n ))}\n </>\n );\n}\n\n/** @internal Props of the aggregator `<BuroProvider>` mounts. */\nexport interface RelationAggregatorMountProps {\n readonly children?: ReactNode;\n /**\n * The largest page the application's provider serves (`<BuroProvider relationBatch={{ maxPage\n * }}>`): an id batch is read in chunks of this many ids, and a `by` read asks for at most this\n * many rows (`2 × keys`), in chunks of half as many keys. Default {@link RELATION_BATCH_MAX_PAGE}.\n */\n readonly maxPage?: number;\n}\n\n/**\n * @internal The relation aggregator, mounted once by `<BuroProvider>` (when a data runtime is\n * present) around the app's children and the presentation stack, so relation cells in an overlay\n * batch with the page's. Its store belongs to the data session's `sessionKey` and `scopeKey` and\n * to the locale: a change of any empties it, so no title of the previous user, scope or locale is\n * ever shown again (P3-29, Known finding 19).\n */\nexport function RelationAggregatorMount({\n children,\n maxPage = RELATION_BATCH_MAX_PAGE,\n}: RelationAggregatorMountProps): ReactElement {\n const session = useDescriptorSession(useDataRuntime());\n const locale = useLocale();\n const resetKey = JSON.stringify([session.sessionKey, session.scopeKey, locale]);\n return (\n <AggregatorStoreMount maxPage={maxPage} resetKey={resetKey}>\n {children}\n </AggregatorStoreMount>\n );\n}\n\n/**\n * The store and its batches. Every `useRelatedRecord` call underneath registers its key here\n * instead of holding its own react-query observer; this component renders one batch per pair that\n * currently has un-resolved registered keys.\n */\nfunction AggregatorStoreMount({\n children,\n maxPage,\n resetKey,\n}: {\n readonly children?: ReactNode;\n readonly maxPage: number;\n readonly resetKey: string;\n}): ReactElement {\n const storeRef = useRef<RelationAggregatorStore | null>(null);\n if (!storeRef.current) storeRef.current = new RelationAggregatorStore();\n const store = storeRef.current;\n\n // Checked during render, so no child renders a row of the previous session even once:\n // the store is emptied before any of them reads it, and every subscriber re-renders from\n // the layout effect below, before paint. Idempotent: a re-render with the same key does nothing.\n const lastResetKey = useRef(resetKey);\n if (lastResetKey.current !== resetKey) {\n lastResetKey.current = resetKey;\n store.clear();\n }\n const notifiedResetKey = useRef(resetKey);\n useLayoutEffect(() => {\n if (notifiedResetKey.current === resetKey) return;\n notifiedResetKey.current = resetKey;\n store.notifyAll();\n }, [store, resetKey]);\n\n // 3rd arg (getServerSnapshot): `getRegistered` is itself SSR-safe (an\n // empty store just returns an empty Map), so it doubles as the server\n // snapshot — without it, SSR-rendering a 'use client' tree under this\n // provider throws \"Missing getServerSnapshot\".\n const registered = useSyncExternalStore(\n store.subscribeFetch,\n store.getRegistered,\n store.getRegistered,\n );\n\n // Keyed by the reset key too: after a reset every batch mounts fresh observers, so no query\n // of the previous session (nor its placeholder data) can settle a key of the new one.\n return (\n <RelationAggregatorContext.Provider value={store}>\n {children}\n {Array.from(registered.entries()).map(([pair, ids]) =>\n splitPair(pair).by === undefined ? (\n <ResourceBatch\n key={`${resetKey}\\u0002${pair}`}\n resource={pair}\n ids={ids}\n maxPage={maxPage}\n store={store}\n />\n ) : (\n <ByBatch\n key={`${resetKey}\\u0002${pair}`}\n pair={pair}\n ids={ids}\n maxPage={maxPage}\n store={store}\n />\n ),\n )}\n </RelationAggregatorContext.Provider>\n );\n}\n\n/**\n * Resolve a single record by `(targetResource, key)` for relation display: by the target's id\n * field, or by `options.by` (one batched `where <by> in [...]` list read per pair and flush).\n *\n * Under a `<BuroProvider>` with a data runtime (which mounts the aggregator): registers demand\n * (refcounted) and reads from the shared external store via\n * `useSyncExternalStore` — NO react-query observer per call. All calls for\n * the same resource on screen share ONE batched `getList(id in [...])`.\n *\n * Without a provider (standalone usage / tests): falls back to the\n * original per-id `useOne`-based behaviour verbatim (same options, same\n * retry/error-notification policy) — belt-and-suspenders backward safety,\n * not a required setup path.\n *\n * Rules of hooks: every hook below is called unconditionally on every\n * render; behaviour is selected by branching on VALUES (`store`, `idStr`),\n * never by skipping a hook call.\n */\nexport function useRelatedRecord(\n targetResource: string,\n id: string | number | null | undefined,\n options: UseRelatedRecordOptions = {},\n): UseRelatedRecordResult {\n const store = useContext(RelationAggregatorContext);\n const by = options.by;\n const lazy = options.resolve === 'lazy';\n // A lazy display reads nothing: no key is registered (spec 4.3).\n const idStr = lazy ? null : relationKeyString(id);\n const pair = pairOf(targetResource, by);\n\n // Fallback path — does nothing when a store is mounted (enabled: false).\n // Kept unconditional so hook order never depends on whether a provider\n // happens to be mounted.\n const fallbackEnabled = store == null && idStr != null;\n const fallbackQuery = useOne(targetResource, {\n id: fallbackEnabled && by === undefined ? (id as string | number) : '',\n enabled: fallbackEnabled && by === undefined,\n retry: false,\n });\n // A `by` key read alone (spec 4.2): `where <by> eq <key>`, two rows, so a duplicate is seen.\n const fallbackByEnabled = fallbackEnabled && by !== undefined;\n const fallbackBy = useList(targetResource, {\n ...(fallbackByEnabled\n ? {\n filter: { field: by, op: 'eq', value: idStr } as never,\n pagination: { kind: 'offset', page: 1, pageSize: 2 } as never,\n }\n : {}),\n enabled: fallbackByEnabled,\n retry: false,\n });\n\n // Memoized so `useSyncExternalStore` doesn't see a NEW subscribe/getSnapshot\n // closure on every render — an unmemoized subscribe forces React to\n // unsubscribe+resubscribe the per-key listener Set on every re-render,\n // which is an avoidable O(cells) cost across a large list. `getSnapshot`\n // doubles as `getServerSnapshot` (3rd arg): both branches (`STABLE_EMPTY`\n // / the cached key snapshot) are pure reads, safe to call during SSR —\n // without a 3rd arg, SSR-rendering this 'use client' hook throws \"Missing\n // getServerSnapshot\". Same pattern as `useLocale` in use-t.ts.\n const subscribe = useCallback(\n (cb: () => void) => (store && idStr != null ? store.subscribeKey(pair, idStr, cb) : () => {}),\n [store, pair, idStr],\n );\n const getSnapshot = useCallback(\n () => (store && idStr != null ? store.getSnapshotKey(pair, idStr) : STABLE_EMPTY),\n [store, pair, idStr],\n );\n const storeSnapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n useEffect(() => {\n if (store && idStr != null) {\n store.register(pair, idStr);\n return () => store.unregister(pair, idStr);\n }\n return undefined;\n }, [store, pair, idStr]);\n\n if (store != null && idStr != null) {\n return storeSnapshot;\n }\n if (idStr == null) {\n return STABLE_EMPTY;\n }\n\n if (by !== undefined) {\n const error = fallbackBy.isError ? (fallbackBy.error as unknown as Error) : null;\n const rows = (fallbackBy.data as { readonly data?: readonly RelatedRecord[] } | undefined)\n ?.data;\n const ambiguous = rows !== undefined && rows.length > 1;\n return {\n record: ambiguous ? undefined : rows?.[0],\n isLoading: fallbackBy.isLoading,\n error,\n ambiguous,\n };\n }\n // No provider mounted — mirror the old use-related-record.ts mapping.\n const error = fallbackQuery.isError ? (fallbackQuery.error as unknown as Error) : null;\n const record = fallbackQuery.data?.data as RelatedRecord | undefined;\n return { record, isLoading: fallbackQuery.isLoading, error, ambiguous: false };\n}\n","import {\n EMPTY_FILTER_GROUP,\n isFilterGroup,\n type ErasedResourceHandle,\n type FilterExpression,\n type FilterGroup,\n type SortExpression,\n} from '@burojs/core';\n\ntype ResourceFilter = FilterExpression<ErasedResourceHandle>;\ntype ResourceSort = SortExpression<ErasedResourceHandle>;\n\n/**\n * Deliberate bounds for untrusted URL AST payloads. The values are large\n * enough for an interactive list, while preventing a pasted URL from making\n * server rendering or the first client render do unbounded recursive work.\n */\nexport const RESOURCE_URL_STATE_LIMITS = {\n maxEncodedBytes: 16_384,\n maxFilters: 50,\n maxFilterDepth: 16,\n maxFilterNodes: 200,\n maxSortEntries: 20,\n} as const;\n\n/** Typed, router-independent state for an interactive resource list. */\n/**\n * Suffixes of a list namespace that are not list state (P3-26): `?<namespace>.open=<id>`, a\n * placement's deep link, is page state. A list write keeps them; the codec ignores them.\n */\nexport const RESERVED_LIST_SUFFIXES = ['open'] as const;\n\nexport interface ResourceUrlState {\n filters: readonly ResourceFilter[];\n /** The builder group. `filters` above is the PINNED slot — always ANDed. */\n filterGroup: FilterGroup;\n sort: ResourceSort;\n page: number;\n pageSize: number;\n search: string;\n visibleColumns: string[] | null;\n}\n\n/**\n * Kept temporarily as a source-level migration seam for the list controller.\n * URL AST values preserve their JSON primitive type and no longer use this\n * hint for serialization or decoding.\n */\nexport type FieldType = 'string' | 'number' | 'boolean' | 'enum' | 'relation' | 'date';\n\nexport interface CodecOptions {\n /** Resource key — used as the parameter namespace prefix. */\n resource: string;\n /** Values equal to these defaults are omitted from the URL. */\n defaults: ResourceUrlState;\n /** @deprecated AST envelopes preserve primitive value types directly. */\n fieldTypes?: Record<string, FieldType>;\n}\n\ntype JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\ntype JsonRecord = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasOnlyKeys(value: JsonRecord, keys: readonly string[]): boolean {\n return Object.keys(value).every((key) => keys.includes(key));\n}\n\nfunction isJsonValue(value: unknown, depth = 0): value is JsonValue {\n if (depth > RESOURCE_URL_STATE_LIMITS.maxFilterDepth) return false;\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (Array.isArray(value)) return value.every((item) => isJsonValue(item, depth + 1));\n if (!isRecord(value)) return false;\n return Object.values(value).every((item) => isJsonValue(item, depth + 1));\n}\n\nfunction isFilterExpression(\n value: unknown,\n budget: { nodes: number },\n depth = 0,\n): value is ResourceFilter {\n if (depth > RESOURCE_URL_STATE_LIMITS.maxFilterDepth || !isRecord(value)) return false;\n budget.nodes += 1;\n if (budget.nodes > RESOURCE_URL_STATE_LIMITS.maxFilterNodes) return false;\n\n if (\n typeof value.field === 'string' &&\n value.field.length > 0 &&\n typeof value.op === 'string' &&\n value.op.length > 0\n ) {\n return (\n hasOnlyKeys(value, ['field', 'op', 'value']) &&\n (!Object.hasOwn(value, 'value') || isJsonValue(value.value))\n );\n }\n\n if (Array.isArray(value.and) && hasOnlyKeys(value, ['and'])) {\n return value.and.every((child) => isFilterExpression(child, budget, depth + 1));\n }\n if (Array.isArray(value.or) && hasOnlyKeys(value, ['or'])) {\n return value.or.every((child) => isFilterExpression(child, budget, depth + 1));\n }\n return hasOnlyKeys(value, ['not']) && isFilterExpression(value.not, budget, depth + 1);\n}\n\nfunction isFilterList(\n value: unknown,\n budget: { nodes: number },\n): value is readonly ResourceFilter[] {\n if (!Array.isArray(value) || value.length > RESOURCE_URL_STATE_LIMITS.maxFilters) return false;\n return value.every((item) => isFilterExpression(item, budget));\n}\n\n/** A group row is a bare term or a nested group — never `and`/`or`/`not`. */\nfunction isGroupRow(value: unknown, budget: { nodes: number }, depth: number): boolean {\n if (!isRecord(value)) return false;\n if (Object.hasOwn(value, 'join') || Object.hasOwn(value, 'rows')) {\n return isFilterGroupValue(value, budget, depth);\n }\n return typeof value.field === 'string' && isFilterExpression(value, budget, depth);\n}\n\nfunction isFilterGroupValue(\n value: unknown,\n budget: { nodes: number },\n depth = 0,\n): value is FilterGroup {\n if (depth > RESOURCE_URL_STATE_LIMITS.maxFilterDepth || !isRecord(value)) return false;\n if (!hasOnlyKeys(value, ['join', 'rows'])) return false;\n if (value.join !== 'and' && value.join !== 'or') return false;\n if (!Array.isArray(value.rows) || value.rows.length > RESOURCE_URL_STATE_LIMITS.maxFilters)\n return false;\n // An empty group is a valid, zero-cost shape: `serializeResourceState`\n // always writes SOME `g` (substituting EMPTY_FILTER_GROUP when the panel\n // slot is unused), so charging a node here would tax every v2 envelope\n // for a group nobody populated — silently shrinking the pinned slot's\n // real budget below its documented maxFilterNodes.\n if (value.rows.length === 0) return true;\n budget.nodes += 1;\n if (budget.nodes > RESOURCE_URL_STATE_LIMITS.maxFilterNodes) return false;\n return value.rows.every((row) => isGroupRow(row, budget, depth + 1));\n}\n\nfunction isSortExpression(value: unknown): value is ResourceSort {\n return (\n Array.isArray(value) &&\n value.length <= RESOURCE_URL_STATE_LIMITS.maxSortEntries &&\n value.every(\n (item) =>\n isRecord(item) &&\n hasOnlyKeys(item, ['field', 'direction', 'nulls']) &&\n typeof item.field === 'string' &&\n item.field.length > 0 &&\n (item.direction === 'asc' || item.direction === 'desc') &&\n (item.nulls === undefined || item.nulls === 'first' || item.nulls === 'last'),\n )\n );\n}\n\nfunction encodeEnvelope(payload: unknown): string | null {\n const json = JSON.stringify(payload);\n if (typeof json !== 'string') return null;\n const bytes = new TextEncoder().encode(json);\n if (bytes.length > RESOURCE_URL_STATE_LIMITS.maxEncodedBytes) return null;\n return toBase64Url(bytes);\n}\n\nfunction decodeEnvelope(raw: string): unknown | null {\n if (\n raw.length === 0 ||\n raw.length > RESOURCE_URL_STATE_LIMITS.maxEncodedBytes ||\n !/^[A-Za-z0-9_-]+$/.test(raw)\n ) {\n return null;\n }\n try {\n const bytes = fromBase64Url(raw);\n if (bytes === null) return null;\n if (bytes.length > RESOURCE_URL_STATE_LIMITS.maxEncodedBytes) return null;\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n } catch {\n return null;\n }\n}\n\nconst BASE64_URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\n/** Browser and Node neutral; avoids relying on optional global btoa/atob. */\nfunction toBase64Url(bytes: Uint8Array): string {\n let encoded = '';\n for (let index = 0; index < bytes.length; index += 3) {\n const first = bytes[index] ?? 0;\n const second = bytes[index + 1];\n const third = bytes[index + 2];\n encoded += BASE64_URL_ALPHABET[first >> 2];\n encoded += BASE64_URL_ALPHABET[((first & 0b11) << 4) | ((second ?? 0) >> 4)];\n if (second !== undefined)\n encoded += BASE64_URL_ALPHABET[((second & 0b1111) << 2) | ((third ?? 0) >> 6)];\n if (third !== undefined) encoded += BASE64_URL_ALPHABET[third & 0b111111];\n }\n return encoded;\n}\n\nfunction fromBase64Url(encoded: string): Uint8Array | null {\n if (encoded.length % 4 === 1) return null;\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of encoded) {\n const value = BASE64_URL_ALPHABET.indexOf(char);\n if (value < 0) return null;\n buffer = (buffer << 6) | value;\n bits += 6;\n while (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n buffer = bits === 0 ? 0 : buffer & ((1 << bits) - 1);\n }\n // Base64url has no padding here, but its remaining bits must be zero for a\n // canonical encoding. Reject aliases such as a final non-zero pad sextet.\n if (bits > 0 && (buffer & ((1 << bits) - 1)) !== 0) return null;\n return Uint8Array.from(bytes);\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\n/** Serialize one resource's URL slice. AST state is versioned JSON/base64url. */\nexport function serializeResourceState(\n state: ResourceUrlState,\n opts: CodecOptions,\n): URLSearchParams {\n const params = new URLSearchParams();\n const resource = opts.resource;\n\n if (state.page !== opts.defaults.page) params.set(`${resource}.page`, String(state.page));\n if (state.pageSize !== opts.defaults.pageSize)\n params.set(`${resource}.size`, String(state.pageSize));\n if (state.search !== opts.defaults.search && state.search !== '')\n params.set(`${resource}.q`, state.search);\n\n const writeBudget = { nodes: 0 };\n const hasPinned =\n isFilterList(state.filters, writeBudget) &&\n state.filters.length > 0 &&\n !sameJson(state.filters, opts.defaults.filters);\n const groupPopulated = isFilterGroup(state.filterGroup) && state.filterGroup.rows.length > 0;\n // The group comes from the (SP2) filter-panel builder, which — unlike the\n // pinned slot's fixed, adopter-declared control set — has no upper bound\n // on how many rows a user can add. A shallow shape check is not enough\n // here: `deserializeResourceState` re-validates with the STRICT\n // `isFilterGroupValue` (maxFilters per level, maxFilterDepth, and this\n // SAME shared node budget), so a group that fails it would write a URL\n // this app cannot read back. Re-running that exact validator against the\n // exact same budget object — continuing from wherever `isFilterList` above\n // left it, exactly like the read path does — is what keeps \"whatever this\n // writes, it can read back\" true.\n const hasGroup = groupPopulated && isFilterGroupValue(state.filterGroup, writeBudget);\n if (groupPopulated && !hasGroup) {\n // Drop the group but KEEP the pinned slot. Atomic reset is the right\n // call on READ for attacker-supplied/tampered input; applying it here,\n // to input the app itself just produced, would silently throw away a\n // perfectly valid pinned slot alongside the oversized group.\n console.warn(\n `[serializeResourceState] dropping the filter group for resource \"${resource}\": it exceeds the URL-state limits ` +\n `(maxFilters=${RESOURCE_URL_STATE_LIMITS.maxFilters} per level, maxFilterDepth=${RESOURCE_URL_STATE_LIMITS.maxFilterDepth}, ` +\n `or the shared maxFilterNodes=${RESOURCE_URL_STATE_LIMITS.maxFilterNodes} budget with the pinned slot) and would not survive a reload.`,\n );\n }\n if (hasPinned || hasGroup) {\n const encoded = encodeEnvelope({\n v: 2,\n p: hasPinned ? state.filters : [],\n g: hasGroup ? state.filterGroup : EMPTY_FILTER_GROUP,\n });\n if (encoded) params.set(`${resource}.filters`, encoded);\n }\n // ⚠️ Compare against the DEFAULT, not against emptiness. `state.sort.length\n // > 0` used to gate this write, which made \"no sort\" and \"matches the\n // default\" the same condition — harmless while every default was `[]`\n // (both were empty), but once a resource declares a non-empty\n // `defaults.sort` (`views.list.defaultSort`, `@burojs/core`) the two\n // diverge: clearing the sort (`state.sort = []`) no longer matches the\n // default, so it MUST write a param (an empty envelope), or the very next\n // decode falls through to `opts.defaults.sort` and the clear silently\n // undoes itself. `sameJson([], [])` still elides for the ordinary case —\n // an undeclared resource writes no `.sort` param for an empty sort,\n // exactly as before.\n if (isSortExpression(state.sort) && !sameJson(state.sort, opts.defaults.sort)) {\n const encoded = encodeEnvelope({ v: 1, sort: state.sort });\n if (encoded) params.set(`${resource}.sort`, encoded);\n }\n\n if (state.visibleColumns !== null && state.visibleColumns.length > 0) {\n const safeColumns = state.visibleColumns.filter((column) => !column.includes(','));\n const matchesDefaults =\n opts.defaults.visibleColumns !== null &&\n opts.defaults.visibleColumns !== undefined &&\n sameJson(safeColumns, opts.defaults.visibleColumns);\n if (safeColumns.length > 0 && !matchesDefaults)\n params.set(`${resource}.cols`, safeColumns.join(','));\n }\n return params;\n}\n\n/** Decode one resource's URL slice; malformed AST envelopes reset atomically. */\nexport function deserializeResourceState(\n params: URLSearchParams,\n opts: CodecOptions,\n): ResourceUrlState {\n const prefix = `${opts.resource}.`;\n const out: ResourceUrlState = {\n filters: [],\n filterGroup: EMPTY_FILTER_GROUP,\n // Unlike `filters`/`filterGroup` (which have no non-empty default in\n // practice today), `sort` DOES: `views.list.defaultSort`\n // (`@burojs/core`) flows in here as `opts.defaults.sort`. Falling back\n // to a literal `[]` instead — as this used to — meant a declared\n // default sort was silently ignored on every cold load / URL-carries-\n // none render, because the branch below only ever runs when the `sort`\n // param IS present.\n //\n // `?? []` guards `deserializeResourceState`'s public-API surface: the\n // `CodecOptions['defaults']` type says `sort` is a required, complete\n // `ResourceSort`, but callers pass a spread `Partial` at both merge\n // sites (`use-resource-url-state.ts`'s `codecOpts`, and every hand-built\n // `CodecOptions` a test constructs), and `exactOptionalPropertyTypes`\n // is off — so an adopter passing `{ sort: undefined }` would otherwise\n // get `out.sort = undefined` where the old hardcoded `[]` used to\n // shield them by construction.\n sort: opts.defaults.sort ?? [],\n page: opts.defaults.page,\n pageSize: opts.defaults.pageSize,\n search: opts.defaults.search,\n visibleColumns: opts.defaults.visibleColumns ?? null,\n };\n\n const single = (suffix: string): string | null | undefined => {\n const values = params.getAll(`${prefix}${suffix}`);\n return values.length === 0 ? undefined : values.length === 1 ? values[0]! : null;\n };\n const page = single('page');\n if (page !== undefined && page !== null) {\n const parsed = Number(page);\n out.page = Number.isFinite(parsed) ? Math.max(1, Math.floor(parsed)) : opts.defaults.page;\n }\n const pageSize = single('size');\n if (pageSize !== undefined && pageSize !== null) {\n const parsed = Number(pageSize);\n out.pageSize =\n Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : opts.defaults.pageSize;\n }\n const search = single('q');\n if (search !== undefined && search !== null) out.search = search;\n const columns = single('cols');\n if (columns !== undefined && columns !== null) {\n const parsed = columns\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n out.visibleColumns = parsed.length > 0 ? parsed : (opts.defaults.visibleColumns ?? null);\n }\n const filters = single('filters');\n if (filters !== undefined) {\n const envelope = filters === null ? null : decodeEnvelope(filters);\n const budget = { nodes: 0 };\n if (isRecord(envelope) && envelope.v === 2 && hasOnlyKeys(envelope, ['v', 'p', 'g'])) {\n const pinnedOk = isFilterList(envelope.p, budget);\n const groupOk = isFilterGroupValue(envelope.g, budget);\n // Atomic: a half-valid envelope is a tampered or truncated link, and\n // restoring half of it would silently show a different result set.\n if (pinnedOk && groupOk) {\n out.filters = envelope.p as readonly ResourceFilter[];\n out.filterGroup = envelope.g as FilterGroup;\n }\n } else if (\n isRecord(envelope) &&\n envelope.v === 1 &&\n hasOnlyKeys(envelope, ['v', 'filters']) &&\n isFilterList(envelope.filters, budget)\n ) {\n out.filters = envelope.filters;\n }\n }\n const sort = single('sort');\n if (sort !== undefined) {\n const envelope = sort === null ? null : decodeEnvelope(sort);\n out.sort =\n isRecord(envelope) &&\n hasOnlyKeys(envelope, ['v', 'sort']) &&\n envelope.v === 1 &&\n isSortExpression(envelope.sort)\n ? envelope.sort\n : [];\n }\n return out;\n}\n","import {\n type ErasedResourceHandle,\n type FilterExpression,\n type FilterGroup,\n type FilterGroupRow,\n isFilterGroup,\n} from '@burojs/core';\nimport type { ResourceUrlState } from './codec.js';\n\n/** The parts of a list's URL state that are predicates: what a hidden field may not appear in. */\nexport type PredicateState = Pick<ResourceUrlState, 'filters' | 'filterGroup' | 'sort'>;\n\ntype Expression = FilterExpression<ErasedResourceHandle>;\n\n/** Every field an expression names, in order, duplicates kept out. */\nexport function filterFields(expression: Expression): readonly string[] {\n const out = new Set<string>();\n const walk = (node: unknown): void => {\n if (node === null || typeof node !== 'object') return;\n const value = node as {\n readonly field?: unknown;\n readonly and?: unknown;\n readonly or?: unknown;\n readonly not?: unknown;\n };\n if (typeof value.field === 'string') out.add(value.field);\n if (Array.isArray(value.and)) for (const entry of value.and) walk(entry);\n if (Array.isArray(value.or)) for (const entry of value.or) walk(entry);\n if (value.not !== undefined) walk(value.not);\n };\n walk(expression);\n return [...out];\n}\n\n/** A builder group with every row naming a hidden field left out; empty nested groups go too. */\nfunction dropFromGroup(\n group: FilterGroup,\n visible: (field: string) => boolean,\n count: { dropped: number },\n): FilterGroup {\n let changed = false;\n const rows: FilterGroupRow[] = [];\n for (const row of group.rows) {\n if (isFilterGroup(row)) {\n const inner = dropFromGroup(row, visible, count);\n if (inner !== row) changed = true;\n if (inner.rows.length > 0 || row.rows.length === 0) rows.push(inner);\n else changed = true;\n continue;\n }\n if (filterFields(row as Expression).every(visible)) rows.push(row);\n else {\n changed = true;\n count.dropped += 1;\n }\n }\n return changed ? { join: group.join, rows } : group;\n}\n\n/**\n * A list's user predicates without any that name a field its user may not view (P5 spec 3.7,\n * decision P5-17): a filter, a filter-group leaf or a sort entry naming a hidden field is dropped\n * whole — never narrowed — and `dropped` counts the dropped leaves and sort entries. Applied where\n * the URL state is read and before a saved view writes it, so a hidden value never reaches a\n * chip, the address bar or a request. The same `state` object when nothing is dropped.\n */\nexport function dropHiddenPredicates(\n state: PredicateState,\n visible: (field: string) => boolean,\n): { readonly state: PredicateState; readonly dropped: number } {\n const count = { dropped: 0 };\n const filters = state.filters.filter((entry) => {\n const keep = filterFields(entry).every(visible);\n if (!keep) count.dropped += 1;\n return keep;\n });\n const filterGroup = dropFromGroup(state.filterGroup, visible, count);\n const sort = state.sort.filter((entry) => {\n const keep = visible(entry.field);\n if (!keep) count.dropped += 1;\n return keep;\n });\n if (count.dropped === 0) return { state, dropped: 0 };\n return { state: { filters, filterGroup, sort }, dropped: count.dropped };\n}\n","import type { RouterAdapter } from '../router/router-adapter.js';\n\n/**\n * @internal Writes an in-page URL (the same pathname, new search params)\n * through the router adapter, past the navigation guard. With\n * `navigation/navigation-guard.tsx`, the one place in the framework that calls\n * `adapter.push` / `adapter.replace`: in-page URL state (tabs, list state) is\n * never guarded (P1b+P1c decision 30).\n */\nexport function writeSearchParams(\n router: RouterAdapter,\n url: string,\n mode: 'push' | 'replace',\n): void {\n if (mode === 'push') router.push(url);\n else router.replace(url);\n}\n","import { useMemo, useState } from 'react';\nimport { requireRouterAdapter, useOptionalRouterAdapter } from '../router/router-adapter.js';\nimport type { HistoryMode } from './use-resource-url-state.js';\nimport { writeSearchParams } from './write-search-params.js';\n\n/**\n * Where a list keeps its state (P1b+P1c decision 58): `'memory'`, which never touches the URL, or\n * the URL under a namespace (`{ url: 'lines' }` writes `?lines.page=2`).\n */\nexport type ListState = 'memory' | { readonly url: string };\n\n/** @internal The query string a list's state is read from and written to. */\nexport interface ListStateStore {\n /** The current query string. */\n readonly search: string;\n readonly pathname: string;\n write(next: string, mode: HistoryMode): void;\n}\n\n/**\n * @internal The store of a list's state and the namespace its params live under: the URL\n * (through the router adapter, past the navigation guard) under `state.url`, else the resource's\n * registry key; or memory, under the resource (never written to the URL).\n */\nexport function useListStateStore(\n resource: string,\n state: ListState | undefined,\n): { readonly store: ListStateStore; readonly namespace: string } {\n const optional = useOptionalRouterAdapter();\n const [memory, setMemory] = useState('');\n const isMemory = state === 'memory';\n // A URL store needs a router: without one, URL state would silently never persist.\n const router = isMemory ? optional : requireRouterAdapter(optional);\n const search = isMemory ? memory : router!.searchParams.toString();\n const pathname = router?.pathname ?? '';\n const store = useMemo<ListStateStore>(\n () =>\n isMemory\n ? { search, pathname, write: (next) => setMemory(next) }\n : {\n search,\n pathname,\n write: (next, mode) =>\n writeSearchParams(router!, next.length > 0 ? `${pathname}?${next}` : pathname, mode),\n },\n [isMemory, search, pathname, router],\n );\n const namespace = state === undefined || state === 'memory' ? resource : state.url;\n return { store, namespace };\n}\n","import {\n EMPTY_FILTER_GROUP,\n type ErasedResourceHandle,\n type FilterExpression,\n type FilterGroup,\n} from '@burojs/core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n type CodecOptions,\n type FieldType,\n type ResourceUrlState,\n RESERVED_LIST_SUFFIXES,\n deserializeResourceState,\n serializeResourceState,\n} from './codec.js';\nimport { dropHiddenPredicates } from './hidden-predicates.js';\nimport { type ListState, useListStateStore } from './list-state-store.js';\n\nconst HOOK_DEFAULTS: ResourceUrlState = {\n filters: [],\n filterGroup: EMPTY_FILTER_GROUP,\n sort: [],\n page: 1,\n pageSize: 10,\n search: '',\n visibleColumns: null,\n};\n\n/**\n * History mode for a single setter call. `'push'` creates a new browser\n * history entry (back-button returns the user to the prior URL).\n * `'replace'` overwrites the current entry (back-button skips the\n * change). See {@link DEFAULT_HISTORY_MODE} for per-setter defaults and\n * adopter-override semantics.\n */\nexport type HistoryMode = 'push' | 'replace';\n\n/**\n * Per-setter default {@link HistoryMode}. The policy splits setters\n * into two groups by interaction frequency / intent:\n *\n * - **`push`** for intentional, low-frequency mutations the user\n * expects to back-out one click at a time:\n * - `setFilters` (chip add/edit/remove)\n * - `setSort` (header click)\n * - `setVisibleColumns` (column-toggle)\n * - **`replace`** for high-frequency or implicit mutations that\n * would flood the back-stack:\n * - `setPage` (next/prev pagination clicks)\n * - `setPageSize` (rare but typically combined with setPage(1))\n * - `setSearch` (per-keystroke writes)\n *\n * Same-tick batching: when multiple setters fire synchronously\n * (e.g. via `applyViewToUrlState`), the URL change uses `push` if ANY\n * of the called setters defaults (or is overridden) to push. The first\n * push in the tick wins; subsequent setters cannot downgrade. This\n * yields the desired behaviour for saved-view application (one push\n * entry covering all six setters) and for clear-all\n * (`setSearch + setFilters + setPage + setVisibleIds` → push because\n * `setFilters` defaults to push).\n *\n * Adopter override: each setter accepts an optional second argument\n * `{ historyMode?: 'push' | 'replace' }`. Useful for adopter-controlled\n * flows where the default isn't right (e.g. an \"auto-suggest\" filter\n * that should NOT push because the user didn't explicitly opt into the\n * mutation):\n *\n * ```ts\n * setFilters(filters, { historyMode: 'replace' }); // override\n * setSort(sort); // default 'push'\n * ```\n */\nexport const DEFAULT_HISTORY_MODE = {\n filters: 'push',\n filterGroup: 'push',\n sort: 'push',\n visibleColumns: 'push',\n page: 'replace',\n pageSize: 'replace',\n search: 'replace',\n} as const satisfies Record<string, HistoryMode>;\n\n/**\n * Optional second argument accepted by every setter returned from\n * {@link useResourceUrlState}. Override the per-setter default\n * {@link HistoryMode} for explicit adopter control. Pass nothing /\n * undefined to use the default for that setter (see\n * {@link DEFAULT_HISTORY_MODE}).\n */\nexport interface SetterOptions {\n historyMode?: HistoryMode;\n}\n\n/**\n * Foundation hook for URL-state sync of a list page's interactive state.\n *\n * Mirrors `{ filters, sort, page, pageSize, search, visibleColumns }`\n * into the router's search params (via {@link useRouterAdapter}) under the\n * `?<resource>.<key>=<value>` namespace.\n *\n * **Browser history semantics (A5).** Setters use a hybrid policy:\n * intentional low-frequency mutations (`setFilters`, `setSort`,\n * `setVisibleColumns`) call `router.push` so back-button returns the\n * user to the prior URL; high-frequency mutations (`setPage`,\n * `setPageSize`, `setSearch`) call `router.replace` to avoid flooding\n * the back-stack with micro-edits. Same-tick batching: when multiple\n * setters fire synchronously, the URL change is `push` if ANY of the\n * called setters defaults (or is overridden) to push. See\n * {@link DEFAULT_HISTORY_MODE} for the full policy and the per-setter\n * adopter override pattern (`{ historyMode }` second arg).\n *\n * Cross-resource isolation: params NOT prefixed with `<resource>.` are\n * preserved verbatim on every update. Two list views on the same page\n * (`related-list` placements in URL state) can each call this hook for their\n * own resource without colliding.\n *\n * Cold deep links: the initial render reads the router adapter's\n * `searchParams` synchronously, so an AST envelope produces the filtered\n * view on first paint with no flash-of-unfiltered-rows.\n *\n * Returned setters are stable across renders (memoized via `useCallback`).\n *\n * **Stable-reference requirement.** Keep `opts.defaults` stable across\n * renders (module scope or `useMemo`) so setter identities remain stable.\n * Filter values are serialized as JSON AST, therefore their primitive types\n * do not need per-field URL coercion hints.\n *\n * **`opts.defaults.search` should remain `''` for v0.2.** A non-empty\n * default for `search` does not round-trip cleanly: the encoder elides\n * the param when `state.search === defaults.search` AND when\n * `state.search === ''`, which means clearing search to empty when the\n * default is non-empty produces a URL that re-decodes back to the\n * non-empty default. If you need a non-empty initial search value, set\n * it once at mount via `setSearch(...)` rather than via `defaults`.\n *\n * @example\n * const { filters, sort, page, search,\n * setFilters, setSort, setPage, setSearch } =\n * useResourceUrlState('document_document');\n */\nexport function useResourceUrlState(\n resource: string,\n opts?: {\n defaults?: Partial<ResourceUrlState>;\n fieldTypes?: Record<string, FieldType>;\n /**\n * Where the state lives: the URL under `?<resource>.` by default, the URL under another\n * namespace (`{ url: 'lines' }`), or `'memory'`, which never writes the URL.\n */\n state?: ListState;\n /**\n * The list's field view (P5 spec 3.7): a filter, group leaf or sort entry naming a field for\n * which `visible` is false is dropped when the state is read — before any chip or request —\n * and from every write. Once `ready` (the list's decisions are settled) the address is\n * rewritten without it, as a `replace`, through the same writer. Absent: nothing is dropped.\n */\n predicates?: {\n readonly visible: (field: string) => boolean;\n readonly ready: boolean;\n };\n },\n): ResourceUrlState & {\n /** How many predicates on hidden fields the address has carried and lost so far. */\n droppedPredicates: number;\n setFilters: (\n filters: readonly FilterExpression<ErasedResourceHandle>[],\n options?: SetterOptions,\n ) => void;\n setFilterGroup: (group: FilterGroup, options?: SetterOptions) => void;\n setSort: (sort: ResourceUrlState['sort'], options?: SetterOptions) => void;\n setPage: (page: number, options?: SetterOptions) => void;\n setPageSize: (size: number, options?: SetterOptions) => void;\n setSearch: (q: string, options?: SetterOptions) => void;\n /**\n * Replace the user-toggled visible-column set in the URL.\n *\n * Elision rules (URL stays clean for the canonical defaults view):\n * - `setVisibleColumns(null)` resets to defaults: drops the\n * `?<r>.cols=` param and the next deserialize returns\n * `defaults.visibleColumns ?? null`.\n * - `setVisibleColumns([])` is treated as `null` (empty arrays\n * collapse so the canonical defaults state is reachable from a\n * single sentinel).\n * - `setVisibleColumns(arr)` where `arr` matches `defaults.visibleColumns`\n * set-equality (same length AND same ids in the same order) ALSO\n * elides — the codec compares directly so a \"manual reset\" via\n * `setVisibleColumns([...defaults])` produces the same clean URL\n * as `setVisibleColumns(null)`.\n * - Any other non-empty array writes the URL.\n *\n * Constraint: column ids MUST NOT contain a comma (`,`). The codec\n * uses `,` as the wire-format separator; an embedded comma would\n * corrupt the parse. The serializer defensively skips offending ids\n * and emits a console.warn — rename the column id to fix.\n *\n * The codec stores ONLY the user-toggled set; the page is responsible\n * for unioning with `requiredColumns` at render time. This keeps the\n * URL compact (typically 2-3 short ids) and means a malformed URL\n * omitting a required column still renders that column.\n */\n setVisibleColumns: (cols: string[] | null, options?: SetterOptions) => void;\n} {\n const { store, namespace } = useListStateStore(resource, opts?.state);\n const search = store.search;\n\n // ---------------------------------------------------------------\n // Same-tick batching refs.\n //\n // These two refs accumulate state across SYNCHRONOUS setter calls\n // within a single React commit cycle. Both are reset in the next\n // render's `useMemo` body (below) — a fresh `searchParams` value is\n // our signal that a commit happened and the in-flight tick is done.\n //\n // Lifecycle:\n // 1. First setter in tick reads `pendingQsRef === null`, computes a\n // new URL from `searchParams`, writes it, stores the qs in the\n // ref so the next synchronous setter sees the merged state.\n // 2. Second setter reads the ref, layers its patch on top, writes.\n // 3. React commits → `searchParams` changes → `useMemo` reruns and\n // resets both refs to null. Next tick starts fresh.\n //\n // Concurrent-React caveat (known limitation). If React 18+ cancels\n // a render mid-flight (concurrent mode rebasing on higher-priority\n // work), a setter's mode contribution could be \"dropped\" — e.g. a\n // push setter fired in a cancelled render leaves the resolved tick\n // mode at replace. In practice this is exceedingly rare for synchronous\n // event handlers (which is the only context where two URL setters\n // fire same-tick today). Adopters who need bulletproof behaviour can\n // pass an explicit `{ historyMode: 'push' }` to the setter that MUST\n // produce a back entry — that override is observed on every call.\n //\n // Why a ref and not state: state would trigger a re-render between\n // the two setter calls, defeating same-tick batching entirely.\n // ---------------------------------------------------------------\n const pendingQsRef = useRef<string | null>(null);\n\n // Tracks the \"highest\" history mode requested this tick. Push beats\n // replace — once a push has been requested in this tick, subsequent\n // replace calls cannot downgrade. Reset alongside `pendingQsRef`.\n const pendingHistoryModeRef = useRef<HistoryMode | null>(null);\n\n // Build the codec options once per render. Defaults are the merged\n // hook-defaults + caller-supplied overrides.\n const codecOpts = useMemo<CodecOptions>(() => {\n const merged: ResourceUrlState = {\n ...HOOK_DEFAULTS,\n ...(opts?.defaults as Partial<ResourceUrlState> | undefined),\n };\n return {\n resource: namespace,\n defaults: merged,\n fieldTypes: opts?.fieldTypes,\n };\n // We intentionally deep-spread `defaults` and `fieldTypes` from opts;\n // adopter code is expected to keep these stable across renders. Re-running\n // the memo when the identity changes is fine (rare).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [namespace, opts?.defaults, opts?.fieldTypes]);\n\n // Derived: current state from URL. Reading `searchParams` here also\n // resets the same-tick batching caches: a fresh render means React\n // has committed the latest URL, so any in-flight pendingQsRef /\n // pendingHistoryModeRef is stale.\n const visible = opts?.predicates?.visible;\n const read = useMemo(() => {\n pendingQsRef.current = null;\n pendingHistoryModeRef.current = null;\n const params = new URLSearchParams(search);\n const raw = deserializeResourceState(params, codecOpts);\n if (visible === undefined) return { state: raw, dropped: 0 };\n const kept = dropHiddenPredicates(raw, visible);\n return kept.dropped === 0\n ? { state: raw, dropped: 0 }\n : { state: { ...raw, ...kept.state }, dropped: kept.dropped };\n }, [search, codecOpts, visible]);\n const state = read.state;\n\n // The address loses what was dropped (Known finding 25): a `replace` through the list's own\n // writer, only once the decisions are settled — an undecided field is held, not erased.\n const ready = opts?.predicates?.ready === true;\n const [droppedPredicates, setDroppedPredicates] = useState(0);\n const rewritten = useRef<string | null>(null);\n useEffect(() => {\n if (!ready || read.dropped === 0 || rewritten.current === search) return;\n rewritten.current = search;\n setDroppedPredicates((count) => count + read.dropped);\n const params = new URLSearchParams(search);\n const prefix = `${codecOpts.resource}.`;\n const reserved = new Set(RESERVED_LIST_SUFFIXES.map((suffix) => `${prefix}${suffix}`));\n const merged = new URLSearchParams();\n for (const [k, v] of params.entries())\n if (!k.startsWith(prefix) || reserved.has(k)) merged.append(k, v);\n for (const [k, v] of serializeResourceState(read.state, codecOpts).entries())\n merged.append(k, v);\n store.write(merged.toString(), 'replace');\n }, [ready, read, search, codecOpts, store]);\n\n /**\n * Apply a partial patch to the URL: deserialize this resource's slice,\n * merge the patch, re-serialize, then combine with all OTHER params\n * (other resources + non-prefixed) preserved verbatim. Calls\n * `router.push` or `router.replace` based on the resolved history\n * mode for this tick (push wins same-tick).\n */\n const applyPatch = useCallback(\n (patch: Partial<ResourceUrlState>, mode: HistoryMode) => {\n // Choose the most-recently-known URL: the same-tick cache wins\n // (so two synchronous setters merge), then `searchParams` from\n // the current render (covers deep links + external nav). We\n // intentionally avoid `window.location.search` because some\n // routers update it asynchronously, which would race with our\n // own writes in the same tick.\n const live = pendingQsRef.current ?? search;\n const liveParams = new URLSearchParams(live);\n\n // Decode this resource's current state, apply patch — never writing back a predicate on a\n // field its user may not view, whether the address or the patch carried it.\n const current = deserializeResourceState(liveParams, codecOpts);\n const patched: ResourceUrlState = { ...current, ...patch };\n const next: ResourceUrlState =\n visible === undefined\n ? patched\n : { ...patched, ...dropHiddenPredicates(patched, visible).state };\n\n // Re-encode this resource's slice, then preserve everything else.\n const ownParams = serializeResourceState(next, codecOpts);\n const prefix = `${codecOpts.resource}.`;\n const merged = new URLSearchParams();\n // Everything outside the namespace stays, and so do its reserved suffixes (the deep link).\n const reserved = new Set(RESERVED_LIST_SUFFIXES.map((suffix) => `${prefix}${suffix}`));\n for (const [k, v] of liveParams.entries()) {\n if (!k.startsWith(prefix) || reserved.has(k)) merged.append(k, v);\n }\n for (const [k, v] of ownParams.entries()) {\n merged.append(k, v);\n }\n\n const qs = merged.toString();\n pendingQsRef.current = qs;\n\n // Resolve the history mode for this tick: push wins. The first\n // setter sets the mode; subsequent setters can upgrade to push\n // but cannot downgrade.\n const prior = pendingHistoryModeRef.current;\n const resolved: HistoryMode = prior === 'push' || mode === 'push' ? 'push' : 'replace';\n pendingHistoryModeRef.current = resolved;\n\n // A same-tick push must create one history entry, not one per setter.\n // Once that entry exists, replace its URL with subsequent merged\n // patches. A prior replace may be upgraded by the first push; a later\n // push never needs another entry in the same batch.\n // In-page URL state: written past the navigation guard (P1b+P1c decision 30).\n store.write(qs, resolved === 'push' && prior !== 'push' ? 'push' : 'replace');\n },\n [store, search, codecOpts, visible],\n );\n\n const setFilters = useCallback(\n (filters: readonly FilterExpression<ErasedResourceHandle>[], options?: SetterOptions) => {\n if (filters === undefined) {\n throw new Error(\n '[useResourceUrlState] setFilters(undefined) is invalid — pass [] to clear filters.',\n );\n }\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.filters;\n applyPatch({ filters }, mode);\n },\n [applyPatch],\n );\n\n const setFilterGroup = useCallback(\n (group: FilterGroup, options?: SetterOptions) => {\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.filterGroup;\n applyPatch({ filterGroup: group }, mode);\n },\n [applyPatch],\n );\n\n const setSort = useCallback(\n (sort: ResourceUrlState['sort'], options?: SetterOptions) => {\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.sort;\n applyPatch({ sort }, mode);\n },\n [applyPatch],\n );\n\n const setPage = useCallback(\n (page: number, options?: SetterOptions) => {\n const safe = Number.isFinite(page) && page >= 1 ? Math.floor(page) : 1;\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.page;\n applyPatch({ page: safe }, mode);\n },\n [applyPatch],\n );\n\n const setPageSize = useCallback(\n (size: number, options?: SetterOptions) => {\n const safe =\n Number.isFinite(size) && size > 0 ? Math.floor(size) : codecOpts.defaults.pageSize;\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.pageSize;\n applyPatch({ pageSize: safe }, mode);\n },\n [applyPatch, codecOpts.defaults.pageSize],\n );\n\n const setSearch = useCallback(\n (q: string, options?: SetterOptions) => {\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.search;\n applyPatch({ search: q ?? '' }, mode);\n },\n [applyPatch],\n );\n\n const setVisibleColumns = useCallback(\n (cols: string[] | null, options?: SetterOptions) => {\n // Empty arrays collapse to null so the canonical \"use defaults\"\n // state is reachable from a single sentinel — the codec's\n // serializer also elides empty arrays, so this is just defence\n // in depth + a clearer return-shape contract.\n const next = cols !== null && cols.length > 0 ? cols : null;\n const mode = options?.historyMode ?? DEFAULT_HISTORY_MODE.visibleColumns;\n applyPatch({ visibleColumns: next }, mode);\n },\n [applyPatch],\n );\n\n return {\n ...state,\n droppedPredicates,\n setFilters,\n setFilterGroup,\n setSort,\n setPage,\n setPageSize,\n setSearch,\n setVisibleColumns,\n };\n}\n","import { EMPTY_FILTER_GROUP } from '@burojs/core';\nimport {\n type CodecOptions,\n type FieldType,\n type ResourceUrlState,\n deserializeResourceState,\n} from './codec.js';\n\n/**\n * SSR-friendly helper that decodes a list page's URL state from raw\n * searchParams without React. Useful in Next App Router server\n * components, getServerSideProps, RSC route handlers, or anywhere a\n * `URLSearchParams`/plain-object map is available before render.\n *\n * Mirrors the runtime decoding done inside `useResourceUrlState`\n * — both call the same codec under the hood, so an SSR-prefetched\n * `useList({ filters, sorters })` will hit the same query as the\n * client renders without a refetch on hydration.\n *\n * @example\n * // Next App Router server component\n * export default async function DocumentsPage({ searchParams }) {\n * const { filters, sort, page, pageSize } = getResourceParams(\n * 'docs',\n * searchParams,\n * { fieldTypes: { status: 'enum' } }\n * );\n * const data = await fetchDocs({ filters, sort, page, pageSize });\n * return <DocList initialData={data} />;\n * }\n *\n * @example\n * // Next pages-router getServerSideProps\n * export async function getServerSideProps({ query }) {\n * const state = getResourceParams('docs', query);\n * return { props: { state } };\n * }\n *\n * @param resource Resource id used as the URL namespace prefix.\n * @param searchParams Raw URL search params. Accepts:\n * - `URLSearchParams` (e.g. from `request.nextUrl.searchParams`)\n * - Plain object map `{ key: string | string[] | undefined }` (the\n * shape Next App Router passes to server-component `searchParams`\n * props and that pages-router `getServerSideProps` exposes via\n * `context.query`). Array values are appended in order so range\n * filters (e.g. `?docs.price=gt:10&docs.price=lt:100`) round-trip\n * correctly.\n * - `undefined` / `null` → returns defaults verbatim.\n * @param opts.defaults Override the framework defaults that govern\n * default-elision. Same rules as `useResourceUrlState`'s\n * `opts.defaults` — values matching defaults are NOT serialized.\n * @param opts.fieldTypes Deprecated migration seam. Versioned AST envelopes\n * retain JSON primitive types, so no per-field coercion is needed.\n * @returns The decoded `ResourceUrlState` — same shape as\n * `useResourceUrlState`'s return (minus the setters).\n */\nexport function getResourceParams(\n resource: string,\n searchParams: URLSearchParams | Record<string, string | string[] | undefined> | undefined | null,\n opts?: {\n defaults?: Partial<ResourceUrlState>;\n fieldTypes?: Record<string, FieldType>;\n },\n): ResourceUrlState {\n const params = normalizeSearchParams(searchParams);\n const merged: ResourceUrlState = {\n filters: [],\n filterGroup: EMPTY_FILTER_GROUP,\n sort: [],\n page: 1,\n pageSize: 10,\n search: '',\n visibleColumns: null,\n ...(opts?.defaults as Partial<ResourceUrlState> | undefined),\n };\n const codecOpts: CodecOptions = {\n resource,\n defaults: merged,\n fieldTypes: opts?.fieldTypes,\n };\n return deserializeResourceState(params, codecOpts);\n}\n\n/**\n * Coerce all supported `searchParams` input shapes into a uniform\n * `URLSearchParams`. Array-valued plain-object entries (the form Next\n * pages-router uses for repeated query keys) are `append()`ed in\n * order so range filters with two values for the same field survive.\n */\nfunction normalizeSearchParams(\n raw: URLSearchParams | Record<string, string | string[] | undefined> | undefined | null,\n): URLSearchParams {\n if (raw == null) return new URLSearchParams();\n if (raw instanceof URLSearchParams) {\n return new URLSearchParams(raw.toString());\n }\n // Plain-object form (Next App Router pattern, getServerSideProps).\n const out = new URLSearchParams();\n for (const [key, value] of Object.entries(raw)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const v of value) {\n out.append(key, v);\n }\n } else {\n out.append(key, value);\n }\n }\n return out;\n}\n","import {\n type AppRuntime,\n EMPTY_FILTER_GROUP,\n type FilterGroup,\n hrefFor,\n type PortableValue,\n type RouteDescriptor,\n} from '@burojs/core';\nimport { type ResourceUrlState, serializeResourceState } from '../hooks/url-state/index.js';\n\ntype RouteDescriptorObject = Exclude<RouteDescriptor, string>;\n\n/** Neutral list state — everything at its default so only filters serialize. */\nconst EMPTY_LIST_STATE: ResourceUrlState = {\n filters: [],\n filterGroup: EMPTY_FILTER_GROUP,\n sort: [],\n page: 1,\n pageSize: 10,\n search: '',\n visibleColumns: null,\n};\n\n/**\n * Encode `RouteDescriptor.filters` into the query the target list READS,\n * through the same `serializeResourceState` the list's own URL sync uses, and\n * into the BUILDER group rather than the pinned slot — so a \"show me the\n * related rows\" link arrives exactly as if the user had built the filter by\n * hand and can see and edit it in the filter panel.\n */\nfunction filtersToQuery(\n resource: string,\n filters: NonNullable<RouteDescriptorObject['filters']>,\n): URLSearchParams {\n const rows = filters.map((f) => ({\n field: f.field,\n op: f.op,\n value: f.value as PortableValue,\n })) as FilterGroup['rows'];\n return serializeResourceState(\n { ...EMPTY_LIST_STATE, filterGroup: { join: 'and', rows } },\n { resource, defaults: EMPTY_LIST_STATE },\n );\n}\n\n/**\n * Resolve a `RouteDescriptor` (string or object form) into an app-space URL.\n *\n * - string: returned as-is.\n * - object: the target's canonical href via `hrefFor` (nesting-aware: a\n * resource behind nav groups lives at its group-prefixed path), plus every\n * non-id `param` in the query and `filters` encoded in the target list's\n * own URL format. An unregistered target keeps the literal `/<resource>…`\n * form, so a descriptor pointing outside the registry still resolves.\n *\n * The one resolver every navigation goes through: link actions, the\n * dispatcher's default `redirect`, the record pages' navigation targets and\n * the navigation guard's \"leave\".\n */\nexport function resolveRoute(to: RouteDescriptor, registry?: AppRuntime['registry']): string {\n if (typeof to === 'string') return to;\n const action = to.action ?? 'list';\n const params = to.params ?? {};\n const id = params.id;\n\n let path: string;\n const known = registry?.get(to.resource);\n if (registry && known) {\n path = hrefFor(registry, to.resource, {\n action,\n ...(id != null ? { id: id as string | number } : {}),\n });\n } else {\n const base = `/${to.resource}`;\n if (action === 'list') path = base;\n else if (action === 'create') path = `${base}/create`;\n else if (action === 'edit') path = id != null ? `${base}/${id}/edit` : `${base}/edit`;\n else path = id != null ? `${base}/${id}` : base;\n }\n\n const search = to.filters?.length\n ? filtersToQuery(to.resource, to.filters)\n : new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (k === 'id' || v == null) continue;\n search.set(k, String(v));\n }\n const qs = search.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\n/** The path of a resolved href, without its query or fragment. */\nexport function routePathname(href: string): string {\n const withoutHash = href.split('#')[0] ?? href;\n return withoutHash.split('?')[0] ?? withoutHash;\n}\n","'use client';\nimport {\n type Context,\n type ReactElement,\n type ReactNode,\n createContext,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n} from 'react';\n\n/**\n * One overlay's dismiss scope: a presentation instance, a flow's host, the export\n * dialog, or an app dialog under `useDismissGuard`. Scopes form a tree (P3-30): a dialog\n * rendered inside an overlay is a child of the enclosing scope, and an overlay presented\n * from inside another is a child of the scope it was presented from. A scope is dirty while\n * any navigation blocker in it or in a descendant is active, and locked while any form in it\n * or in a descendant submits.\n */\nexport interface DismissScopeValue {\n readonly id: string;\n /**\n * Ask before leaving: a locked scope ignores the request, a clean one calls `onLeave` at\n * once, a dirty one holds it for the guard's prompt (Leave calls it, Stay drops it).\n */\n request(onLeave: () => void): void;\n /** True while a form in this scope or a descendant scope submits. */\n isLocked(): boolean;\n}\n\n/**\n * @internal The scope tree the navigation guard owns. Blockers and pending forms are keyed\n * by their own id and carry the scope they were registered in, so a child's effect may run\n * before its scope's own registration (React runs child effects first).\n */\nexport interface DismissRegistry {\n /** Add a scope; the returned function removes it and drops a dismissal held for it. */\n registerScope(id: string, parent: string | null, close: () => void): () => void;\n /** Record that the presentation `childId` was presented from inside the scope `parentId`. */\n recordParent(childId: string, parentId: string): void;\n /** The scope a presentation was presented from, or `null`. */\n parentOf(id: string): string | null;\n /** Count (or stop counting) a submitting form in `scopeId`. */\n setPending(pendingId: string, scopeId: string, pending: boolean): void;\n /** The guarded dismissal of `scopeId` (see `DismissScopeValue.request`). */\n request(scopeId: string, onLeave: () => void): void;\n /** Close every descendant scope deepest-first, then the scope itself. */\n closeSubtree(scopeId: string): void;\n isLocked(scopeId: string): boolean;\n}\n\n/** @internal Provided by `NavigationGuardProvider`. */\nexport const DismissRegistryContext: Context<DismissRegistry | null> =\n createContext<DismissRegistry | null>(null);\n\n/** @internal The nearest enclosing dismiss scope. */\nexport const DismissScopeContext: Context<DismissScopeValue | null> =\n createContext<DismissScopeValue | null>(null);\n\n/** The scope tree's pure half: parent links and the subtree walks the guard needs. */\nexport interface ScopeNode {\n readonly parent: string | null;\n readonly close: () => void;\n}\n\n/** `scopeId` and every scope below it, parents before children. */\nexport function subtreeOf(scopes: ReadonlyMap<string, ScopeNode>, scopeId: string): string[] {\n const out: string[] = [scopeId];\n for (let i = 0; i < out.length; i++) {\n for (const [id, node] of scopes) {\n if (node.parent === out[i] && !out.includes(id)) out.push(id);\n }\n }\n return out;\n}\n\n/**\n * @internal Register a scope with `id` under `parent` (the enclosing scope when omitted)\n * and return its value. `close` is read through a ref, so an inline function never\n * re-registers the scope.\n */\nexport function useDismissScope(\n id: string,\n close: () => void,\n parent?: string | null,\n): DismissScopeValue {\n const registry = useContext(DismissRegistryContext);\n const enclosing = useContext(DismissScopeContext);\n const parentId = parent === undefined ? (enclosing?.id ?? null) : parent;\n const closeRef = useRef(close);\n closeRef.current = close;\n useEffect(() => {\n if (registry === null) return;\n return registry.registerScope(id, parentId, () => closeRef.current());\n }, [registry, id, parentId]);\n return useMemo<DismissScopeValue>(\n () =>\n registry === null\n ? { id, request: (onLeave) => onLeave(), isLocked: () => false }\n : {\n id,\n request: (onLeave) => registry.request(id, onLeave),\n isLocked: () => registry.isLocked(id),\n },\n [registry, id],\n );\n}\n\n/**\n * Provide `value` as the dismiss scope of everything below: the forms rendered inside register\n * their unsaved-changes blockers and their submitting state in it.\n */\nexport function DismissGuardScope({\n value,\n children,\n}: {\n readonly value: DismissScopeValue;\n readonly children: ReactNode;\n}): ReactElement {\n return <DismissScopeContext.Provider value={value}>{children}</DismissScopeContext.Provider>;\n}\n\n/** What `useDismissGuard` returns. */\nexport interface DismissGuard {\n /** Close through the guard: asks first when a form in the scope (or below it) is dirty. */\n dismiss(): void;\n /** Pass to `<DismissGuardScope value={…}>` around the dialog's content. */\n readonly scope: DismissScopeValue;\n}\n\n/**\n * Guard an app's own dialog against losing a dirty form (P3-33): wrap its content in\n * `<DismissGuardScope value={guard.scope}>` and route its close through `guard.dismiss()`.\n * Outside a `BuroProvider` `dismiss()` calls `onDismiss` at once.\n *\n * ```tsx\n * const guard = useDismissGuard(() => setOpen(false));\n * <Dialog open={open} onOpenChange={(next) => { if (!next) guard.dismiss(); }}>\n * <DismissGuardScope value={guard.scope}><MyForm /></DismissGuardScope>\n * </Dialog>\n * ```\n */\nexport function useDismissGuard(onDismiss: () => void): DismissGuard {\n const registry = useContext(DismissRegistryContext);\n const id = useId();\n const scope = useDismissScope(id, onDismiss);\n const onDismissRef = useRef(onDismiss);\n onDismissRef.current = onDismiss;\n return useMemo<DismissGuard>(\n () => ({\n scope,\n dismiss: () =>\n registry === null\n ? onDismissRef.current()\n : scope.request(() => registry.closeSubtree(scope.id)),\n }),\n [registry, scope],\n );\n}\n\n/**\n * @internal Lock the enclosing dismiss scope while `pending` is true: a submitting form's\n * overlay ignores Escape, an outside click and ✕ (P3-34). A no-op outside a scope.\n */\nexport function useDismissPending(pending: boolean): void {\n const registry = useContext(DismissRegistryContext);\n const scope = useContext(DismissScopeContext);\n const id = useId();\n const scopeId = scope?.id ?? null;\n useEffect(() => {\n if (registry === null || scopeId === null) return;\n registry.setPending(id, scopeId, pending);\n return () => registry.setPending(id, scopeId, false);\n }, [registry, scopeId, id, pending]);\n}\n","'use client';\nimport {\n type Context,\n type ReactElement,\n type ReactNode,\n createContext,\n createElement,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useOptionalRouterAdapter } from '../hooks/router/router-adapter.js';\nimport { useOptionalT } from '../hooks/use-t.js';\nimport {\n type DismissRegistry,\n DismissRegistryContext,\n DismissScopeContext,\n type ScopeNode,\n subtreeOf,\n} from './dismiss-scope.js';\n\n/**\n * @internal The no-router fallback, behind an object so a test can observe it:\n * jsdom's `Location` methods cannot be spied on.\n */\nexport const documentNavigation = {\n assign(url: string): void {\n window.location.assign(url);\n },\n replace(url: string): void {\n window.location.replace(url);\n },\n};\n\ninterface FallbackNotice {\n warned: boolean;\n}\n\nconst FallbackNoticeContext = createContext<FallbackNotice | null>(null);\n\n/**\n * @internal Mounted by `BuroProvider`: the scope its one fallback warning\n * belongs to. Its presence is also what \"inside an app\" means here — outside\n * a provider, an app with no router is legitimate and nothing is said.\n */\nexport function RouteNavigationScope({ children }: { readonly children: ReactNode }): ReactElement {\n const [notice] = useState<FallbackNotice>(() => ({ warned: false }));\n return createElement(FallbackNoticeContext.Provider, { value: notice }, children);\n}\n\n/**\n * @internal The navigation no guard asks about: the mounted `RouterAdapter`'s\n * `push` (or `replace`), or a document navigation without one. The guard's own\n * Leave uses it, and so does every framework navigation outside a\n * `NavigationGuardProvider`; nothing public reaches it. Inside a `BuroProvider`\n * the document fallback logs one development warning per provider naming\n * `RouterAdapterProvider`.\n */\nexport function useUnguardedNavigate(): (\n href: string,\n options?: { readonly replace?: boolean },\n) => void {\n const adapter = useOptionalRouterAdapter();\n const notice = useContext(FallbackNoticeContext);\n return useCallback(\n (href: string, options: { readonly replace?: boolean } = {}) => {\n if (adapter !== null) {\n if (options.replace === true) adapter.replace(href);\n else adapter.push(href);\n return;\n }\n if (typeof window === 'undefined') return;\n // Inside a BuroProvider a missing adapter is a host mistake that shows\n // only as full page reloads. Say so once per provider, in development.\n if (notice !== null && !notice.warned && process.env.NODE_ENV !== 'production') {\n notice.warned = true;\n console.warn(\n '[burojs] A framework navigation fell back to a full page load: no ' +\n 'RouterAdapterProvider is mounted above <BuroProvider>. Mount your router’s ' +\n 'adapter (RouterAdapterProvider from @burojs/react) there; until then every ' +\n 'framework navigation reloads the page.',\n );\n }\n if (options.replace === true) documentNavigation.replace(href);\n else documentNavigation.assign(href);\n },\n [adapter, notice],\n );\n}\n\n/**\n * Marks an anchor a quick opener owns (a relation display, a related-list row). The attribute\n * alone changes nothing: the guard leaves a click to its opener only when the opener has also\n * claimed the element (`quickAnchorRef`, internal), so an app's own `<a data-buro-quick>` is\n * guarded like any link. A claimed anchor whose click the opener does not take (no\n * `preventDefault`) is held by the guard after all, at the bubble phase.\n */\nexport const QUICK_ANCHOR_ATTRIBUTE = 'data-buro-quick';\n\n/** The anchors a framework quick opener rendered: never exported, set only by `quickAnchorRef`. */\nconst claimedQuickAnchors = new WeakSet<Element>();\n\n/**\n * @internal The ref a framework quick opener puts on its anchor (with `QUICK_ANCHOR_ATTRIBUTE`):\n * its click goes to the opener, which opens an overlay or navigates through the guarded gate.\n */\nexport function quickAnchorRef(element: Element | null): void {\n if (element !== null) claimedQuickAnchors.add(element);\n}\n\nfunction isClaimedQuickAnchor(anchor: Element): boolean {\n return anchor.hasAttribute(QUICK_ANCHOR_ATTRIBUTE) && claimedQuickAnchors.has(anchor);\n}\n\nlet sentinelSequence = 0;\n\n/** Push a Back sentinel over the current entry and return its token. */\nfunction pushSentinel(): string {\n sentinelSequence += 1;\n const token = `buro-guard-${sentinelSequence}`;\n window.history.pushState({ buroGuardSentinel: token }, '', window.location.href);\n return token;\n}\n\nfunction sentinelOf(state: unknown): unknown {\n return state !== null && typeof state === 'object'\n ? (state as { buroGuardSentinel?: unknown }).buroGuardSentinel\n : undefined;\n}\n\n/** A navigation or a dismissal the guard holds for its prompt. */\ntype HeldRequest =\n | { readonly reason: 'navigation'; readonly href: string; readonly replace: boolean }\n | {\n readonly reason: 'dismiss';\n readonly scopeId: string;\n readonly onLeave: () => void;\n /** What had focus when the dismissal was requested; Stay gives it back. */\n readonly returnFocus: unknown;\n };\n\n/** The gate every framework navigation asks (`useRouteNavigate`). */\nexport interface NavigationGate {\n request(href: string, options: { readonly replace?: boolean }): void;\n}\n\n/**\n * @internal The guard's one gate for framework navigation (P1b+P1c decision\n * 30): `useRouteNavigate` asks it inside a provider. There is no public way\n * around it; a host's own `useRouterAdapter()` call is its explicit escape hatch.\n */\nexport const NavigationGateContext: Context<NavigationGate | null> =\n createContext<NavigationGate | null>(null);\n\n/**\n * Translate a DOM `href`'s pathname into the app space the router's push\n * takes. A rendered anchor's `href` carries the router BASENAME\n * (`/marketplace/documents`); `RouterAdapter.push` prepends it again. The\n * basename is recovered rather than configured: `currentPath` is the\n * basename-free `RouterAdapter.pathname`, and `window.location.pathname` is the\n * same location with the basename on the front. Every step falls back to\n * \"hand it over unchanged\", which is right for an app with no basename.\n */\nexport function stripRouterBasename(absolutePath: string, currentPath: string): string {\n if (typeof window === 'undefined') return absolutePath;\n const here = window.location.pathname;\n if (currentPath === '' || !here.endsWith(currentPath)) return absolutePath;\n const basename = here.slice(0, here.length - currentPath.length);\n if (basename === '' || basename === '/') return absolutePath;\n if (!absolutePath.startsWith(basename)) return absolutePath;\n const stripped = absolutePath.slice(basename.length);\n return stripped.startsWith('/') ? stripped : `/${stripped}`;\n}\n\nexport interface NavigationGuardText {\n readonly title: string;\n readonly body: string;\n readonly stay: string;\n readonly leave: string;\n /** Leave's label when the prompt holds a dismissal (`reason: 'dismiss'`). */\n readonly discard: string;\n}\n\n/** The guard's strings: `navGuard.*` in the framework bundles, English literals without one. */\nexport function useNavigationGuardText(): NavigationGuardText {\n const t = useOptionalT();\n const tr = (key: string, fallback: string): string => t(key, { defaultValue: fallback });\n return {\n title: tr('navGuard.title', 'Unsaved changes'),\n body: tr(\n 'navGuard.body',\n 'This page has unsaved changes. If you leave now, they will be lost.',\n ),\n stay: tr('navGuard.stay', 'Stay'),\n leave: tr('navGuard.leave', 'Leave without saving'),\n discard: tr('navGuard.discard', 'Discard changes'),\n };\n}\n\n/**\n * What the guard is holding, for the registered dialog to answer: a navigation (`href` is\n * the app-space destination the user tried to reach) or the dismissal of an overlay holding\n * a dirty form (`href` is `null`). Narrow on `reason`.\n */\nexport type NavigationGuardPrompt = {\n /**\n * The labels of the active blockers that carry one (P6 3.12): an inline flow whose node is not\n * on screen but holds unsaved input. The dialog says so after its text.\n */\n readonly labels: readonly string[];\n} & (\n | {\n readonly reason: 'navigation';\n /** App-space destination the user tried to reach. */\n readonly href: string;\n /** Leave without saving: performs the deferred navigation. */\n leave(): void;\n /** Stay: drops the pending navigation. */\n stay(): void;\n }\n | {\n readonly reason: 'dismiss';\n readonly href: null;\n /** Discard: releases the overlay's forms and closes it with every overlay above it. */\n leave(): void;\n /** Stay: keeps every overlay open and gives focus back. */\n stay(): void;\n }\n);\n\ninterface BlockerRegistry {\n register(id: string, active: boolean, scopeId: string | null, label?: string): void;\n}\n\ninterface DialogRegistry {\n /** Add `id` as the most recent registrant; the returned function removes it again. */\n registerDialog(id: string): () => void;\n /** The registrant the held navigation goes to: the most recently registered one still mounted. */\n readonly currentDialog: string | null;\n readonly prompt: NavigationGuardPrompt | null;\n}\n\nconst BlockerContext = createContext<BlockerRegistry | null>(null);\n\ninterface HoldRegistry {\n setHold(id: string, active: boolean): void;\n}\nconst HoldContext = createContext<HoldRegistry | null>(null);\n\n// Bundlers fold the development branch out of a production build.\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } };\n\n/**\n * @internal Holds every route change while `active` (P4 plan ruling 7): a flow's pending lock\n * spans the write, so a framework navigation or an in-app anchor click is dropped without a\n * prompt (a development `console.info` names the hold) and `beforeunload` is armed. Registered\n * in an effect, so a React StrictMode remount registers it again (Known finding 20).\n */\nexport function useNavigationHold(active: boolean): void {\n const ctx = useContext(HoldContext);\n const id = useId();\n useEffect(() => {\n if (!ctx || !active) return;\n ctx.setHold(id, true);\n return () => ctx.setHold(id, false);\n }, [ctx, id, active]);\n}\nconst DialogContext = createContext<DialogRegistry | null>(null);\n\n/** What `useNavigationBlocker` takes besides `active`. */\nexport interface NavigationBlockerOptions {\n /**\n * Names what holds the unsaved input when its node is not on screen: the guard's dialog adds\n * `navigation.unsavedAction` and the label (P6 3.12).\n */\n readonly label?: string;\n}\n\n/** What `useNavigationBlocker` returns. */\nexport interface NavigationBlockerHandle {\n /** Unregister now, synchronously; the blocker registers again the next time `active` turns true. */\n release(): void;\n}\n\n/**\n * Arm the guard while the calling component holds unsaved changes (a dirty\n * form). A no-op outside a `BuroProvider`. `release()` disarms it at once — a\n * successful submit calls it before the navigation that follows, which must\n * not wait for a render to unregister the blocker.\n */\nexport function useNavigationBlocker(\n active: boolean,\n opts: NavigationBlockerOptions = {},\n): NavigationBlockerHandle {\n const label = opts.label;\n const ctx = useContext(BlockerContext);\n // The nearest dismiss scope: an overlay holding this form asks before it closes (P3-30).\n const scopeId = useContext(DismissScopeContext)?.id ?? null;\n const id = useId();\n useEffect(() => {\n if (!ctx) return;\n ctx.register(id, active, scopeId, label);\n return () => ctx.register(id, false, scopeId);\n }, [ctx, id, active, scopeId, label]);\n return useMemo(() => ({ release: () => ctx?.register(id, false, scopeId) }), [ctx, id, scopeId]);\n}\n\n/**\n * Register the calling component as the guard's leave dialog for as long as\n * it is mounted, and return the navigation being held — to the CURRENT dialog\n * only: the most recently registered one still mounted. Every other\n * registrant gets `null`, so two dialogs (`<AppLayout>`'s and an explicit\n * `<NavigationGuardDialog>`, say) never stack; unmounting the current one hands\n * the prompt back to the previous registrant. With no dialog registered the\n * guard asks through `window.confirm`.\n */\nexport function useRegisterNavigationGuardDialog(): NavigationGuardPrompt | null {\n const ctx = useContext(DialogContext);\n const id = useId();\n const registerDialog = ctx?.registerDialog;\n useEffect(() => registerDialog?.(id), [registerDialog, id]);\n return ctx !== null && ctx.currentDialog === id ? ctx.prompt : null;\n}\n\n/**\n * The unsaved-changes guard's state and listeners, mounted by `BuroProvider`:\n *\n * - every framework navigation (`useRouteNavigate`) asks its gate, and in-app\n * anchor clicks (capture phase, before the router) are held the same way:\n * answered by the registered dialog, or by `window.confirm` without one;\n * \"leave\" navigates through `useUnguardedNavigate`. The first held\n * navigation wins while the prompt is open; it is dropped when the location\n * moves on or nothing blocks any more, and never proceeds by itself;\n * - tab close / reload get the browser's native `beforeunload` prompt;\n * - back / forward are best-effort: a history sentinel and a native confirm\n * on `popstate`.\n *\n * No DOM of its own; the dialog is a UI kit's (`@burojs/ui-shadcn`'s\n * `<AppLayout>` registers one).\n */\nexport function NavigationGuardProvider({\n children,\n}: {\n readonly children: ReactNode;\n}): ReactElement {\n const navigate = useUnguardedNavigate();\n const adapter = useOptionalRouterAdapter();\n const text = useNavigationGuardText();\n // Every active blocker, with the dismiss scope it was registered in (`null`: none).\n const blockers = useRef<Map<string, string | null>>(new Map());\n /** The labels of the active blockers that carry one. */\n const labels = useRef<Map<string, string>>(new Map());\n // The dismiss-scope tree (P3-30): scopes, the parents recorded at present() time, and\n // the submitting forms with the scope each one locks.\n const scopes = useRef<Map<string, ScopeNode>>(new Map());\n const presentedFrom = useRef<Map<string, string>>(new Map());\n const pendings = useRef<Map<string, string>>(new Map());\n const dialogs = useRef<string[]>([]);\n const [currentDialog, setCurrentDialog] = useState<string | null>(null);\n const [pending, setPending] = useState<HeldRequest | null>(null);\n const [blockedCount, setBlockedCount] = useState(0);\n const blocked = blockedCount > 0;\n // Refs, because the document/window listeners below are registered once and\n // must read the freshest values without re-subscribing.\n const pendingRef = useRef<HeldRequest | null>(null);\n pendingRef.current = pending;\n const navigateRef = useRef(navigate);\n navigateRef.current = navigate;\n // Counts the framework navigations this guard performs: the Back sentinel is popped only\n // when none happened since it was pushed (an async router may not have written history yet).\n const navigationCount = useRef(0);\n const textRef = useRef(text);\n textRef.current = text;\n const currentPathRef = useRef(adapter?.pathname ?? '');\n currentPathRef.current = adapter?.pathname ?? '';\n const currentSearch = adapter?.searchParams.toString() ?? '';\n const currentUrlRef = useRef('');\n currentUrlRef.current = `${adapter?.pathname ?? ''}${currentSearch === '' ? '' : `?${currentSearch}`}`;\n\n const isBlocked = useCallback(() => blockers.current.size > 0, []);\n /** The navigation holds (a flow's pending lock): while any is active, nothing navigates. */\n const holds = useRef<Set<string>>(new Set());\n const isHeld = useCallback(() => holds.current.size > 0, []);\n const [heldCount, setHeldCount] = useState(0);\n const holdRegistry = useMemo<HoldRegistry>(\n () => ({\n setHold(id, active) {\n if (active) holds.current.add(id);\n else holds.current.delete(id);\n setHeldCount(holds.current.size);\n },\n }),\n [],\n );\n const dropHeld = useCallback((href: string) => {\n if (process.env.NODE_ENV !== 'production')\n console.info(\n `[burojs] A navigation to ${href} was held: a flow is writing, and the page cannot be left until it answers.`,\n );\n }, []);\n const clearHeld = useCallback(() => {\n pendingRef.current = null;\n setPending(null);\n }, []);\n /** Any entry of `registered` whose scope is `scopeId` or one of its descendants. */\n const anyInSubtree = useCallback(\n (registered: ReadonlyMap<string, string | null>, scopeId: string): boolean => {\n const subtree = new Set(subtreeOf(scopes.current, scopeId));\n for (const owner of registered.values())\n if (owner !== null && subtree.has(owner)) return true;\n return false;\n },\n [],\n );\n const isDirty = useCallback(\n (scopeId: string) => anyInSubtree(blockers.current, scopeId),\n [anyInSubtree],\n );\n const isLocked = useCallback(\n (scopeId: string) => anyInSubtree(pendings.current, scopeId),\n [anyInSubtree],\n );\n /** A held dismissal is dropped once its scope turns clean or unmounts. */\n const dropCleanDismissal = useCallback(() => {\n const held = pendingRef.current;\n if (held === null || held.reason !== 'dismiss') return;\n if (!scopes.current.has(held.scopeId) || !isDirty(held.scopeId)) clearHeld();\n }, [isDirty, clearHeld]);\n const register = useCallback(\n (id: string, active: boolean, scopeId: string | null, label?: string) => {\n if (active) blockers.current.set(id, scopeId);\n else blockers.current.delete(id);\n if (active && label !== undefined) labels.current.set(id, label);\n else labels.current.delete(id);\n setBlockedCount(blockers.current.size);\n dropCleanDismissal();\n },\n [dropCleanDismissal],\n );\n const blockerRegistry = useMemo<BlockerRegistry>(() => ({ register }), [register]);\n\n const registerDialog = useCallback((id: string) => {\n dialogs.current = [...dialogs.current.filter((entry) => entry !== id), id];\n setCurrentDialog(id);\n return () => {\n dialogs.current = dialogs.current.filter((entry) => entry !== id);\n setCurrentDialog(dialogs.current[dialogs.current.length - 1] ?? null);\n };\n }, []);\n /** Performs a held request the user chose to leave for. */\n const perform = useCallback(\n (held: HeldRequest) => {\n if (held.reason === 'navigation') {\n navigationCount.current += 1;\n navigateRef.current(held.href, { replace: held.replace });\n return;\n }\n // Release the subtree's blockers first, so nothing still counts its forms as dirty,\n // then close the scope and every overlay above it.\n const subtree = new Set(subtreeOf(scopes.current, held.scopeId));\n for (const [id, owner] of [...blockers.current]) {\n if (owner !== null && subtree.has(owner)) register(id, false, owner);\n }\n held.onLeave();\n },\n [register],\n );\n const leave = useCallback(() => {\n const held = pendingRef.current;\n clearHeld();\n if (held !== null) perform(held);\n }, [clearHeld, perform]);\n const stay = useCallback(() => {\n const held = pendingRef.current;\n clearHeld();\n if (held?.reason !== 'dismiss') return;\n const element = held.returnFocus as { focus?: () => void; isConnected?: boolean } | null;\n if (element !== null && element.isConnected === true && typeof element.focus === 'function') {\n element.focus();\n }\n }, [clearHeld]);\n /** Holds a request for the prompt; the first one held wins while it is open. */\n const hold = useCallback(\n (held: HeldRequest) => {\n if (pendingRef.current !== null) return;\n if (dialogs.current.length > 0) {\n pendingRef.current = held;\n setPending(held);\n return;\n }\n const { title, body } = textRef.current;\n if (window.confirm(`${title}\\n\\n${body}`)) perform(held);\n },\n [perform],\n );\n const gate = useMemo<NavigationGate>(\n () => ({\n request(href, options) {\n const replace = options.replace === true;\n if (isHeld()) {\n dropHeld(href);\n return;\n }\n // Unblocked, or the exact URL the page is already on: nothing to lose.\n if (!isBlocked() || href === currentUrlRef.current) {\n navigationCount.current += 1;\n navigateRef.current(href, { replace });\n return;\n }\n hold({ reason: 'navigation', href, replace });\n },\n }),\n [isBlocked, isHeld, dropHeld, hold],\n );\n const dismissRegistry = useMemo<DismissRegistry>(\n () => ({\n registerScope(id, parent, close) {\n scopes.current.set(id, { parent, close });\n return () => {\n scopes.current.delete(id);\n dropCleanDismissal();\n // The parent link outlives a StrictMode (or `<Activity>`) unmount-and-remount, which\n // re-registers the scope in the same commit: forget it only once the scope stays gone.\n queueMicrotask(() => {\n if (!scopes.current.has(id)) presentedFrom.current.delete(id);\n });\n };\n },\n recordParent(childId, parentId) {\n presentedFrom.current.set(childId, parentId);\n },\n parentOf(id) {\n return presentedFrom.current.get(id) ?? null;\n },\n setPending(pendingId, scopeId, isPending) {\n if (isPending) pendings.current.set(pendingId, scopeId);\n else pendings.current.delete(pendingId);\n },\n request(scopeId, onLeave) {\n // A submitting form locks its overlay: nothing closes it mid-write (P3-34).\n if (isLocked(scopeId)) return;\n if (!isDirty(scopeId)) {\n onLeave();\n return;\n }\n hold({\n reason: 'dismiss',\n scopeId,\n onLeave,\n returnFocus: typeof document === 'undefined' ? null : document.activeElement,\n });\n },\n closeSubtree(scopeId) {\n // Deepest first, so no overlay is ever left above a closed parent.\n const order = subtreeOf(scopes.current, scopeId).reverse();\n const closers = order.map((id) => scopes.current.get(id)?.close);\n for (const close of closers) close?.();\n },\n isLocked,\n }),\n [dropCleanDismissal, hold, isDirty, isLocked],\n );\n const labelsNow = () => [...new Set(labels.current.values())];\n const dialogRegistry = useMemo<DialogRegistry>(\n () => ({\n registerDialog,\n currentDialog,\n prompt:\n pending === null\n ? null\n : pending.reason === 'navigation'\n ? { reason: 'navigation', href: pending.href, leave, stay, labels: labelsNow() }\n : { reason: 'dismiss', href: null, leave, stay, labels: labelsNow() },\n }),\n [registerDialog, currentDialog, pending, leave, stay],\n );\n\n // A held navigation never proceeds by itself: it is dropped when the location\n // moves on (the pathname or the search changes) or nothing blocks any more.\n // A held dismissal belongs to its scope instead (dropped when it turns clean or unmounts).\n const location = `${adapter?.pathname ?? ''}?${currentSearch}`;\n const lastLocation = useRef(location);\n useEffect(() => {\n if (lastLocation.current === location) return;\n lastLocation.current = location;\n if (pendingRef.current?.reason === 'navigation') clearHeld();\n }, [location, clearHeld]);\n useEffect(() => {\n if (blocked) return;\n clearHeld();\n }, [blocked, clearHeld]);\n\n // ---- In-app anchor clicks (capture phase, before the router) ----\n useEffect(() => {\n /** The in-app anchor a plain primary click targets, or `null`. */\n const anchorOf = (e: MouseEvent): HTMLAnchorElement | null => {\n if ((!isBlocked() && !isHeld()) || e.defaultPrevented) return null;\n if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;\n return (e.target as HTMLElement | null)?.closest('a') ?? null;\n };\n const intercept = (e: MouseEvent, anchor: HTMLAnchorElement) => {\n if (anchor.hasAttribute('download')) return;\n const target = anchor.getAttribute('target');\n if (target && target !== '_self') return;\n const href = anchor.getAttribute('href');\n if (!href || href.startsWith('#')) return;\n let url: URL;\n try {\n url = new URL(href, window.location.href);\n } catch {\n return;\n }\n if (url.origin !== window.location.origin) return;\n if (url.pathname === window.location.pathname && url.search === window.location.search)\n return;\n e.preventDefault();\n e.stopPropagation();\n const destination =\n stripRouterBasename(url.pathname, currentPathRef.current) + url.search + url.hash;\n if (isHeld()) {\n dropHeld(destination);\n return;\n }\n hold({ reason: 'navigation', href: destination, replace: false });\n };\n const onCapture = (e: MouseEvent) => {\n const anchor = anchorOf(e);\n if (anchor === null) return;\n // A claimed quick opener's anchor: its own click handler decides first (P3-41).\n if (isClaimedQuickAnchor(anchor)) return;\n intercept(e, anchor);\n };\n // Its opener did not take the click (no `preventDefault`): the browser would follow the\n // link, so the guard holds it after all.\n const onBubble = (e: MouseEvent) => {\n const anchor = anchorOf(e);\n if (anchor === null || !isClaimedQuickAnchor(anchor)) return;\n intercept(e, anchor);\n };\n document.addEventListener('click', onCapture, true);\n document.addEventListener('click', onBubble);\n return () => {\n document.removeEventListener('click', onCapture, true);\n document.removeEventListener('click', onBubble);\n };\n }, [isBlocked, isHeld, dropHeld, hold]);\n\n // ---- Tab close / reload / external navigation ----\n useEffect(() => {\n const handler = (e: BeforeUnloadEvent) => {\n if (!isBlocked() && !isHeld()) return;\n e.preventDefault();\n e.returnValue = '';\n };\n window.addEventListener('beforeunload', handler);\n return () => window.removeEventListener('beforeunload', handler);\n }, [isBlocked, isHeld]);\n\n // ---- Browser Back / Forward: a sentinel entry, best-effort ----\n // Pushed when the guard arms; popped again when the last blocker clears while the\n // sentinel is still the current entry (P3-43), so a dirtied-then-closed overlay leaves\n // no dead Back step. A sentinel the user has navigated past is left alone, and so is one\n // after any framework navigation since it was pushed: a successful submit releases its\n // blocker and then redirects, and an async router (Next's app router, a data router with\n // loaders) writes history later — popping then would race that push.\n const sentinelRef = useRef<{ readonly token: string; readonly navigations: number } | null>(null);\n const ignorePopRef = useRef(false);\n const leavingRef = useRef(false);\n // Back/Forward is held by a dirty form and by a flow's pending lock alike (P4-B review M3).\n const historyArmed = blocked || heldCount > 0;\n const blockedRef = useRef(historyArmed);\n blockedRef.current = historyArmed;\n const arm = useCallback(() => {\n sentinelRef.current = { token: pushSentinel(), navigations: navigationCount.current };\n }, []);\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const current = sentinelRef.current;\n if (historyArmed) {\n // Armed again before a pending pop: the sentinel still in place serves again.\n if (current !== null && sentinelOf(window.history.state) === current.token) return;\n leavingRef.current = false;\n arm();\n return;\n }\n if (current === null) return;\n // Decided after the current task, once a redirect that follows the release has been asked.\n // The ref is kept until then, so an effect re-run (StrictMode) schedules the same decision.\n const timer = window.setTimeout(() => {\n if (sentinelRef.current !== current) return;\n sentinelRef.current = null;\n if (navigationCount.current !== current.navigations) return;\n if (sentinelOf(window.history.state) !== current.token) return;\n ignorePopRef.current = true;\n window.history.back();\n }, 0);\n return () => window.clearTimeout(timer);\n }, [historyArmed, arm]);\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const onPop = () => {\n // The guard's own pop of its sentinel.\n if (ignorePopRef.current) {\n ignorePopRef.current = false;\n return;\n }\n if (!blockedRef.current || leavingRef.current) return;\n // The user's Back took the sentinel off.\n sentinelRef.current = null;\n // A flow is writing: the Back is held without a prompt, as every route change is.\n if (isHeld()) {\n dropHeld('the previous page');\n arm();\n return;\n }\n const { title, body } = textRef.current;\n if (window.confirm(`${title}\\n\\n${body}`)) {\n leavingRef.current = true;\n window.history.go(-1);\n } else {\n arm();\n }\n };\n window.addEventListener('popstate', onPop);\n return () => window.removeEventListener('popstate', onPop);\n }, [arm, isHeld, dropHeld]);\n\n return (\n <BlockerContext.Provider value={blockerRegistry}>\n <HoldContext.Provider value={holdRegistry}>\n <NavigationGateContext.Provider value={gate}>\n <DialogContext.Provider value={dialogRegistry}>\n <DismissRegistryContext.Provider value={dismissRegistry}>\n {children}\n </DismissRegistryContext.Provider>\n </DialogContext.Provider>\n </NavigationGateContext.Provider>\n </HoldContext.Provider>\n </BlockerContext.Provider>\n );\n}\n","'use client';\nimport type { RouteDescriptor } from '@burojs/core';\nimport { useCallback, useContext } from 'react';\nimport { AppContext } from '../context.js';\nimport { NavigationGateContext, useUnguardedNavigate } from './navigation-guard.js';\nimport { resolveRoute } from './resolve-route.js';\n\nexport interface RouteNavigateOptions {\n /** Navigate without adding a history entry. */\n readonly replace?: boolean;\n}\n\nexport type RouteNavigate = (to: RouteDescriptor, options?: RouteNavigateOptions) => void;\n\n/**\n * The framework's one navigation seam. Resolves a `RouteDescriptor` against the\n * app registry and asks the navigation guard's gate (P1b+P1c decision 30):\n * unblocked, or to the exact current URL, it navigates at once; with unsaved\n * changes it holds the navigation for the guard's prompt. Outside a\n * `NavigationGuardProvider` it navigates directly. Either way the navigation\n * is the mounted `RouterAdapter`'s `push` (`replace` when asked), or a document\n * navigation without one.\n */\nexport function useRouteNavigate(): RouteNavigate {\n const app = useContext(AppContext);\n const gate = useContext(NavigationGateContext);\n const unguarded = useUnguardedNavigate();\n return useCallback(\n (to: RouteDescriptor, options: RouteNavigateOptions = {}) => {\n const href = resolveRoute(to, app?.registry);\n const replace = options.replace === true ? { replace: true } : {};\n if (gate !== null) gate.request(href, replace);\n else unguarded(href, replace);\n },\n [app, gate, unguarded],\n );\n}\n","'use client';\nimport {\n type ReactElement,\n type ReactNode,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n} from 'react';\n\nexport interface NotificationSinkMessage {\n /** `info` is a plain notice that dismisses itself, never a progress indicator. */\n readonly type: 'success' | 'error' | 'info';\n readonly message: string;\n readonly description?: string;\n}\n\n/** Where the dispatcher's default `notify` delivers — a UI kit's toaster. */\nexport interface NotificationSink {\n open(notification: NotificationSinkMessage): void;\n}\n\ninterface NotificationSinkRegistry {\n register(sink: NotificationSink): () => void;\n /** The most recently registered sink still mounted. */\n current(): NotificationSink | undefined;\n}\n\nconst NotificationSinkContext = createContext<NotificationSinkRegistry | null>(null);\n\n/** Mounted by `BuroProvider`. One registry per provider tree. */\nexport function NotificationSinkProvider({\n children,\n}: {\n readonly children: ReactNode;\n}): ReactElement {\n const sinks = useRef<NotificationSink[]>([]);\n const registry = useMemo<NotificationSinkRegistry>(\n () => ({\n register(sink) {\n sinks.current = [...sinks.current, sink];\n return () => {\n sinks.current = sinks.current.filter((entry) => entry !== sink);\n };\n },\n current: () => sinks.current[sinks.current.length - 1],\n }),\n [],\n );\n return (\n <NotificationSinkContext.Provider value={registry}>{children}</NotificationSinkContext.Provider>\n );\n}\n\n/** @internal The registry, for the dispatcher's default `notify`. */\nexport function useNotificationSinkRegistry(): NotificationSinkRegistry | null {\n return useContext(NotificationSinkContext);\n}\n\n/**\n * Register `sink` for as long as the calling component is mounted. Outside a\n * `BuroProvider` it registers nothing and throws nothing, so a toaster mounted\n * at an app root keeps working standalone.\n *\n * `sink` must be stable (memoised, e.g. with `useMemo`): it is an effect\n * dependency, so an inline object re-registers on every render.\n */\nexport function useRegisterNotificationSink(sink: NotificationSink | null): void {\n const registry = useContext(NotificationSinkContext);\n useEffect(() => {\n if (registry === null || sink === null) return undefined;\n return registry.register(sink);\n }, [registry, sink]);\n}\n","import type { AppRuntime } from '@burojs/core';\nimport { useContext } from 'react';\nimport { AppContext } from '../context.js';\n\nexport function useApp(): AppRuntime {\n const app = useContext(AppContext);\n if (!app) {\n throw new Error('[useApp] must be used within a BuroProvider');\n }\n return app;\n}\n","import type { UIActivationContext, UIActivationSurface, UIPresentationRuntime } from '@burojs/core';\nimport { createContext, useContext, type ReactNode } from 'react';\n\n/**\n * What a component presented via `useUIPresent` sees about itself: the\n * runtime-assigned id, a way to close itself, and the activation it was\n * launched with (captured once, at present-time, by the runtime — see\n * `@burojs/core`'s `presentation-runtime.ts`).\n */\nexport interface UIInstance {\n readonly id: string;\n dismiss(): void;\n readonly activation: UIActivationContext;\n}\n\n/** The subset of `UIInstance` a component only needs for a close affordance. */\nexport interface UIPresentationLifecycle {\n dismiss(): void;\n}\n\nconst UIInstanceContext = createContext<UIInstance | null>(null);\nconst UIPresentationContext = createContext<UIPresentationLifecycle | undefined>(undefined);\nconst UIActivationSurfaceContext = createContext<UIActivationSurface | undefined>(undefined);\nconst UIPresentationRuntimeContext = createContext<UIPresentationRuntime | null>(null);\n\n/**\n * Frames the activation surface (the \"why\" behind a presentation) for\n * everything rendered underneath — e.g. a resource show page wraps its tree\n * so any `useUIPresent()` call inside picks up `{ type: 'item', ... }`\n * without every call site having to repeat it.\n */\nexport function UIActivationSurfaceProvider({\n surface,\n children,\n}: {\n readonly surface: UIActivationSurface;\n readonly children: ReactNode;\n}) {\n return (\n <UIActivationSurfaceContext.Provider value={surface}>\n {children}\n </UIActivationSurfaceContext.Provider>\n );\n}\n\n/** The nearest `UIActivationSurfaceProvider` frame, or `undefined` outside one. */\nexport function useOptionalUIActivationSurface(): UIActivationSurface | undefined {\n return useContext(UIActivationSurfaceContext);\n}\n\n/** Supplies the `UIPresentationRuntime` instance `useUIPresent` presents into. */\nexport function UIPresentationRuntimeProvider({\n runtime,\n children,\n}: {\n readonly runtime: UIPresentationRuntime;\n readonly children: ReactNode;\n}) {\n return (\n <UIPresentationRuntimeContext.Provider value={runtime}>\n {children}\n </UIPresentationRuntimeContext.Provider>\n );\n}\n\n/** The runtime supplied by the nearest `UIPresentationRuntimeProvider`; throws otherwise. */\nexport function useUIPresentationRuntime(): UIPresentationRuntime {\n const runtime = useContext(UIPresentationRuntimeContext);\n if (runtime === null) {\n throw new Error('useUIPresent must be used within a UIPresentationRuntimeProvider.');\n }\n return runtime;\n}\n\n/** The current `UIInstance`; throws when called outside a presented component. */\nexport function useUIInstance(): UIInstance {\n const instance = useOptionalUIInstance();\n if (instance === null) {\n throw new Error('useUIInstance must be used inside a component presented via useUIPresent.');\n }\n return instance;\n}\n\n/** The current `UIInstance`, or `null` when not inside a presented component. */\nexport function useOptionalUIInstance(): UIInstance | null {\n return useContext(UIInstanceContext);\n}\n\n/** The current dismiss-only lifecycle, or `undefined` when not inside a presented component. */\nexport function useOptionalUIPresentation(): UIPresentationLifecycle | undefined {\n return useContext(UIPresentationContext);\n}\n\n/**\n * Wraps a presented component's tree with its `UIInstance` (and, optionally,\n * a narrower dismiss-only `presentation` lifecycle for children that only\n * need a close affordance). The host renderer that turns a\n * `UIPresentationDescriptor` into a mounted component (Task 4+) is the\n * expected — not the only possible — caller.\n */\nexport function UIInstanceProvider({\n instance,\n presentation,\n children,\n}: {\n readonly instance: UIInstance;\n readonly presentation?: UIPresentationLifecycle;\n readonly children: ReactNode;\n}) {\n return (\n <UIInstanceContext.Provider value={instance}>\n <UIPresentationContext.Provider value={presentation}>\n {children}\n </UIPresentationContext.Provider>\n </UIInstanceContext.Provider>\n );\n}\n","import { useContext } from 'react';\nimport { ComponentsContext } from '../context.js';\n\n/**\n * `slot` is optional so that a caller computing a key conditionally can say\n * \"no slot\" directly. Without it the natural spelling is a sentinel string,\n * which the registry would dutifully look up — `undefined` would resolve the\n * literal key `\"undefined\"`, and `''` a key nothing can register.\n */\nexport function useComponent<T = unknown>(slot: string | undefined): T | undefined {\n const components = useContext(ComponentsContext);\n if (slot === undefined || slot === '') return undefined;\n return components[slot] as T | undefined;\n}\n\n/**\n * useDefaultComponent — placeholder for default-component lookup.\n * Real implementation requires the provider to track defaults separately\n * from overrides. For v0.1, we just look up the same slot.\n */\nexport function useDefaultComponent<T = unknown>(slot: string): T | undefined {\n return useComponent<T>(slot);\n}\n","import type {\n CompiledFlow,\n DispatcherEffects,\n FlowRef,\n FlowResult,\n FlowRun,\n FlowTarget,\n Row,\n UIPresentAnchor,\n UIPresentHost,\n UIPresentationDescriptor,\n UIPresentationRuntime,\n} from '@burojs/core';\nimport {\n type ComponentType,\n type ReactElement,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport type { QuickStack } from '../quick/quick-stack.js';\nimport { useComponent } from '../hooks/use-component.js';\nimport {\n DismissRegistryContext,\n DismissScopeContext,\n useDismissScope,\n} from '../navigation/dismiss-scope.js';\nimport { type UIInstance, UIInstanceProvider, useUIPresentationRuntime } from './context.js';\n\n/**\n * What a concrete host (dialog/sheet chrome, supplied by the app — e.g.\n * ui-shadcn) receives for one active presentation: the already-resolved\n * component plus the portable `props`/`options` off the descriptor. The\n * host decides how to frame it (title, width, side, ...); dismissal is read\n * via `useOptionalUIPresentation()` from inside the host or the presented\n * component, since both render under the matching `UIInstanceProvider`.\n */\nexport interface UIPresentationHostProps {\n readonly component: ComponentType<Record<string, unknown>>;\n readonly props: Readonly<Record<string, unknown>>;\n readonly options: Readonly<Record<string, unknown>>;\n /** A popover's anchor, passed through by reference (`host: 'popover'` only). */\n readonly anchor?: UIPresentAnchor;\n}\n\n/** The reserved component key of a quick entry: resolved from `presentationHosts.screens.quick`. */\nexport const QUICK_COMPONENT = 'buro:quick';\n/** The reserved component key of a peek: resolved from `presentationHosts.screens.peek`. */\nexport const PEEK_COMPONENT = 'buro:peek';\n/** The reserved component key of a flow's host: resolved from `presentationHosts.screens.flow`. */\nexport const FLOW_COMPONENT = 'buro:flow';\n/** The reserved component key of a modal action's block: resolved from `presentationHosts.screens.block`. */\nexport const BLOCK_COMPONENT = 'buro:block';\n/** Component keys under this prefix are the framework's; an app never registers one. */\nexport const RESERVED_COMPONENT_PREFIX = 'buro:';\n\n/**\n * What the block screen receives (P7 3.16): the block a modal action presents and its portable\n * props. For an item action the clicked row and its resource ride along: the screen reads the row\n * projected by field view, binds `ref('record', …)` from it, and draws nothing until that is decided.\n */\nexport interface BlockScreenProps {\n readonly block: { readonly namespace: string; readonly id: string };\n readonly props: Readonly<Record<string, unknown>>;\n readonly resource?: string;\n readonly record?: Row;\n readonly label?: string;\n}\n\n/** What the quick screen receives: the overlay's history, whose top entry it renders. */\nexport interface QuickScreenProps {\n readonly stack: QuickStack;\n}\n\n/** What the peek screen receives: the target and the key it previews. */\nexport interface PeekScreenProps {\n readonly target: string;\n readonly id?: string;\n readonly by?: { readonly field: string; readonly key: string };\n}\n\n/** A flow the host starts itself (P4-C review I1): what to run, on what. */\nexport interface FlowStart {\n readonly target: FlowRef | FlowTarget;\n readonly record?: Row;\n readonly args?: Row;\n readonly selection?: { readonly ids: readonly string[]; readonly count: number };\n}\n\n/**\n * What a flow's host screen receives (P4 spec 4.15). Either a run its opener holds (`run` and\n * `compiled`: a `{ label, submit }` flow's outcome, drawn in a dialog), or a flow to start\n * (`start`): the host then owns the run, so the host outlives its opener — a row that left the\n * page, a menu item that closed — and its form, its draft and a pending write with it. `then`\n * runs through the opener's dispatcher scope (`effects`) after the host closed; `onSettle`\n * reports each outcome to the opener.\n */\nexport interface FlowScreenProps {\n readonly run?: FlowRun;\n readonly start?: FlowStart;\n /** `'page'` and `'inline'` are the screen drawn in a route or a show tree (P6), not presented. */\n readonly host: 'dialog' | 'sheet' | 'page' | 'inline';\n readonly label: string;\n readonly title?: string;\n readonly compiled?: CompiledFlow;\n readonly record?: Row;\n readonly args?: Row;\n readonly selection?: { readonly ids: readonly string[]; readonly count: number };\n /** The effects of the dispatcher scope the flow was started in (4.13, I12). */\n readonly effects?: () => DispatcherEffects;\n readonly onSettle?: (result: FlowResult) => void;\n}\n\n/**\n * @internal How a flow's screen props travel through the presentation runtime: the runtime\n * deep-freezes plain-object props into copies, and a flow's run is a plain object whose identity\n * is its claim (the form controller honours only a run `useFlowRun` created). A class instance is\n * kept by reference, so the props ride in one and are unwrapped where the screen renders.\n */\nexport class FlowScreenEntry {\n constructor(readonly props: FlowScreenProps) {}\n}\n\n/**\n * The UI kit's overlay screens (P3-6): the framework presents them under the reserved keys\n * `buro:quick`, `buro:peek` and `buro:flow` and resolves those keys from here only, never from\n * the app's `components`.\n */\nexport interface UIPresentationScreens {\n readonly quick?: ComponentType<QuickScreenProps>;\n readonly peek?: ComponentType<PeekScreenProps>;\n /** A flow's host screen (P4 spec 4.15), in a dialog or a sheet. */\n readonly flow?: ComponentType<FlowScreenProps>;\n /** A modal action's block (P7 3.16), in a dialog or a sheet. */\n readonly block?: ComponentType<BlockScreenProps>;\n}\n\n/**\n * What a host declares it understands about its `options` record: a flat\n * `key → primitive type` map, all keys optional. Anything the host does not\n * list is refused once `useUIPresent` sees the schema. No nesting, no\n * unions, no custom validators — the real vocabulary today is three string\n * keys and one boolean, so a flat map is all this needs to be.\n */\nexport type UIPresentationOptionsSchema = Readonly<Record<string, 'string' | 'boolean' | 'number'>>;\n\n/**\n * A host component keyed by `UIPresentationDescriptor['host']`. May carry an\n * `optionsSchema` static describing the `options` keys it reads; a host\n * without one accepts any options, since hosts are injected by the adopter\n * and third-party hosts have no obligation to describe themselves.\n *\n * Deliberately `ComponentType<...>`, not a bare function-component call\n * signature: a class component, a `React.memo(...)` result, or a\n * `forwardRef(...)` result all satisfy `ComponentType` (and can all carry a\n * static `optionsSchema`), and all three were valid hosts before this type\n * existed. A narrower call-signature alias would silently drop that support\n * at the type level while runtime behaviour stayed identical.\n */\nexport type UIPresentationHost = ComponentType<UIPresentationHostProps> & {\n optionsSchema?: UIPresentationOptionsSchema;\n};\n\n/**\n * Host components keyed by `UIPresentationDescriptor['host']`. Injected, not\n * imported — this keeps `packages/react` DOM-free and independent of any\n * concrete component library. A descriptor whose host has no entry here\n * simply renders nothing (no crash, no console noise): that is the expected\n * shape for an app that has not wired concrete hosts (yet).\n */\nexport type UIPresentationHosts = Readonly<Partial<Record<UIPresentHost, UIPresentationHost>>> & {\n /** The UI kit's overlay screens (`shadcnPresentationHosts.screens`). */\n readonly screens?: UIPresentationScreens;\n};\n\nexport interface UIPresentationsProps {\n readonly hosts: UIPresentationHosts;\n}\n\n/**\n * Framework-owned overlay mount. Subscribes to the app's\n * `UIPresentationRuntime` and renders every active descriptor through its\n * injected host, resolving `descriptor.component` from the same registry\n * `useComponent` reads (the `components` map on `BuroProvider`, plus any\n * plugin-contributed `ui-component` capabilities).\n *\n * Unlike the legacy single-slot overlay controller this replaces — which\n * silently rendered `null` for an unresolved component key — an unregistered\n * key here is a loud\n * `console.error` naming the descriptor and its component key, because a\n * `present()` call that can never render anything is an app bug, not a\n * legitimate steady state.\n */\nexport function UIPresentations({ hosts }: UIPresentationsProps): ReactElement {\n const runtime = useUIPresentationRuntime();\n const descriptors = useSyncExternalStore(\n runtime.subscribe,\n runtime.getSnapshot,\n runtime.getSnapshot,\n );\n return (\n <>\n {descriptors.map((descriptor) => (\n <UIPresentationInstance\n key={descriptor.id}\n descriptor={descriptor}\n runtime={runtime}\n hosts={hosts}\n />\n ))}\n </>\n );\n}\n\nfunction UIPresentationInstance({\n descriptor,\n runtime,\n hosts,\n}: {\n readonly descriptor: UIPresentationDescriptor;\n readonly runtime: UIPresentationRuntime;\n readonly hosts: UIPresentationHosts;\n}): ReactElement | null {\n // A `buro:` key is the framework's own overlay screen: it resolves from `hosts.screens`\n // only, and the app registry is never asked for it (P3-6).\n const reserved = descriptor.component.startsWith(RESERVED_COMPONENT_PREFIX);\n const registered = useComponent<ComponentType<Record<string, unknown>>>(\n reserved ? undefined : descriptor.component,\n );\n const Component = reserved ? reservedScreen(hosts, descriptor.component) : registered;\n const reportedMissing = useRef(false);\n // Rebuilding this object every render gave every open overlay a new\n // `UIInstanceProvider` value on ANY stack change (a sibling presentation\n // opening/closing re-renders `<UIPresentations/>`, which re-ran this for\n // every existing instance too), re-rendering every open overlay's subtree\n // even though nothing about THIS instance changed. Memoized on the pieces\n // that can actually change per-descriptor identity: `dismiss`/`runtime`\n // stay referentially stable in practice (dismiss closes over `runtime` +\n // the stable `descriptor.id`), so this settles to one stable identity for\n // the instance's whole lifetime.\n //\n // Computed unconditionally, ABOVE both early returns below: hooks must run\n // in the same order every render, and `Component`/`Host` resolution can\n // flip between defined/undefined across renders (registry or `hosts` prop\n // changes), so a conditional `useMemo` after either early return would be\n // a hook-order violation.\n //\n // Every presentation is a dismiss scope (P3-30): its parent is the scope it was presented\n // from (recorded by `useUIPresent` at present() time), its `close` the core's\n // unconditional dismiss. `UIInstance.dismiss()` — what every host calls for Escape, an\n // outside click and ✕ — asks before closing a dirty subtree; the core\n // `runtime.dismiss(id)` stays unconditional.\n const registry = useContext(DismissRegistryContext);\n // Pinned once known: the link is recorded at present() time and never changes, so a later\n // render never loses it (StrictMode's simulated unmount clears the registry's copy).\n const parentRef = useRef<string | null>(null);\n if (parentRef.current === null) parentRef.current = registry?.parentOf(descriptor.id) ?? null;\n const scope = useDismissScope(\n descriptor.id,\n () => runtime.dismiss(descriptor.id),\n parentRef.current,\n );\n const instance: UIInstance = useMemo(\n () => ({\n id: descriptor.id,\n dismiss: () =>\n registry === null\n ? runtime.dismiss(descriptor.id)\n : scope.request(() => registry.closeSubtree(descriptor.id)),\n activation: descriptor.activation,\n }),\n [descriptor.id, descriptor.activation, runtime, registry, scope],\n );\n if (Component === undefined && reserved) {\n if (!reportedMissing.current && process.env.NODE_ENV !== 'production') {\n reportedMissing.current = true;\n console.error(\n `[burojs] The overlay screen \"${descriptor.component}\" (presentation \"${descriptor.id}\") resolves from presentationHosts.${screenMember(descriptor.component)}, and none is supplied for it; spread shadcnPresentationHosts (or its screens) into your hosts.`,\n );\n }\n return null;\n }\n if (Component === undefined) {\n console.error(\n `UIPresentations: no component registered for key \"${descriptor.component}\" (presentation \"${descriptor.id}\", host \"${descriptor.host}\"). Register it in the \\`components\\` map passed to BuroProvider (or via a plugin's \\`ui-component\\` capability).`,\n );\n return null;\n }\n\n const Host = hosts[descriptor.host];\n if (Host === undefined) return null;\n\n return (\n <DismissScopeContext.Provider value={scope}>\n <UIInstanceProvider instance={instance} presentation={instance}>\n <Host\n component={Component}\n props={screenProps(descriptor)}\n options={descriptor.options}\n {...(descriptor.anchor === undefined ? {} : { anchor: descriptor.anchor })}\n />\n </UIInstanceProvider>\n </DismissScopeContext.Provider>\n );\n}\n\n/** A descriptor's props, a flow's unwrapped from its entry (see `FlowScreenEntry`). */\nfunction screenProps(descriptor: UIPresentationDescriptor): Readonly<Record<string, unknown>> {\n const entry = descriptor.props.entry;\n return descriptor.component === FLOW_COMPONENT && entry instanceof FlowScreenEntry\n ? (entry.props as unknown as Readonly<Record<string, unknown>>)\n : descriptor.props;\n}\n\n/** The `presentationHosts` member a reserved key resolves from (`screens.quick`, …). */\nfunction screenMember(key: string): string {\n if (key === QUICK_COMPONENT) return 'screens.quick';\n if (key === PEEK_COMPONENT) return 'screens.peek';\n if (key === FLOW_COMPONENT) return 'screens.flow';\n if (key === BLOCK_COMPONENT) return 'screens.block';\n return 'screens';\n}\n\n/** The overlay screen a reserved key names, or `undefined` (an unknown `buro:` key included). */\nfunction reservedScreen(\n hosts: UIPresentationHosts,\n key: string,\n): ComponentType<Record<string, unknown>> | undefined {\n const screen =\n key === QUICK_COMPONENT\n ? hosts.screens?.quick\n : key === PEEK_COMPONENT\n ? hosts.screens?.peek\n : key === FLOW_COMPONENT\n ? hosts.screens?.flow\n : key === BLOCK_COMPONENT\n ? hosts.screens?.block\n : undefined;\n return screen as ComponentType<Record<string, unknown>> | undefined;\n}\n","import {\n type ReactElement,\n type ReactNode,\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n} from 'react';\nimport { type UIPresentationHosts, UIPresentations } from './ui-presentations.js';\n\n/**\n * Who renders the presentation stack.\n *\n * `'framework'` (default) — `BuroProvider` mounts it beside `{children}`,\n * inside every framework provider. Presented components reach field\n * implementations, i18n, UI settings and the doc panel, but NOT providers the\n * app mounts inside `{children}` (the link component): those render strictly\n * below the framework's own mount. The dispatcher, the navigation guard and the\n * relation aggregator are mounted by `BuroProvider` around both, so they are\n * reachable in either mode.\n *\n * `'app'` — the app renders `<BuroPresentationOutlet/>` itself, typically as\n * the last child of its own provider stack. Presented components then render\n * inside BOTH the framework's providers and the app's, sharing the very same\n * instances instead of a second copy.\n */\nexport type PresentationsMode = 'framework' | 'app';\n\n/**\n * Tracks the single app-owned outlet, so `useUIPresent()` can refuse loudly\n * when the app asked for `presentations=\"app\"` and then forgot to render one.\n */\nexport interface PresentationOutletRegistry {\n /** Registers the outlet and returns its release. Throws if one is already mounted. */\n claim(): () => void;\n isMounted(): boolean;\n}\n\nexport function createPresentationOutletRegistry(): PresentationOutletRegistry {\n let claimed = false;\n return {\n claim() {\n if (claimed) {\n throw Object.assign(\n new Error(\n 'Only one <BuroPresentationOutlet/> may be mounted per BuroProvider. ' +\n 'Two outlets would race over which one renders the presentation stack.',\n ),\n { kind: 'configuration' as const, code: 'presentation-outlet-duplicate' as const },\n );\n }\n claimed = true;\n return () => {\n claimed = false;\n };\n },\n isMounted() {\n return claimed;\n },\n };\n}\n\n/** What `BuroProvider` hands down so an app-owned outlet can render the stack. */\nexport interface PresentationMount {\n readonly mode: PresentationsMode;\n readonly hosts: UIPresentationHosts;\n readonly registry: PresentationOutletRegistry;\n}\n\nconst PresentationMountContext = createContext<PresentationMount | null>(null);\n\nexport function PresentationMountProvider({\n mount,\n children,\n}: {\n readonly mount: PresentationMount;\n readonly children: ReactNode;\n}): ReactElement {\n return (\n <PresentationMountContext.Provider value={mount}>{children}</PresentationMountContext.Provider>\n );\n}\n\n/** The mount contract from the nearest `BuroProvider`, or `null` outside one. */\nexport function useOptionalPresentationMount(): PresentationMount | null {\n return useContext(PresentationMountContext);\n}\n\n// `useLayoutEffect` warns during server render; the outlet is a client-side\n// mount either way, so fall back to `useEffect` when there is no DOM.\nconst useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\n/**\n * App-owned mount point for the presentation stack. Render it inside your own\n * provider stack when `BuroProvider` is given `presentations=\"app\"`; presented\n * components then see the same app-level context instances the rest of the app\n * does, instead of a re-mounted copy.\n */\nexport function BuroPresentationOutlet(): ReactElement {\n const mount = useOptionalPresentationMount();\n const registry = mount?.registry;\n // A layout effect, not a plain effect: it runs before paint and long before\n // any user interaction can call present(), so a correctly wired app never\n // observes a spurious `outlet-missing`.\n useIsomorphicLayoutEffect(() => registry?.claim(), [registry]);\n if (mount === null) {\n throw Object.assign(\n new Error('<BuroPresentationOutlet/> must be rendered inside a BuroProvider.'),\n { kind: 'configuration' as const, code: 'presentation-outlet-orphan' as const },\n );\n }\n if (mount.mode !== 'app') {\n throw Object.assign(\n new Error(\n '<BuroPresentationOutlet/> requires <BuroProvider presentations=\"app\">; ' +\n 'in framework mode BuroProvider mounts the presentation stack itself.',\n ),\n { kind: 'configuration' as const, code: 'presentation-outlet-unexpected' as const },\n );\n }\n return <UIPresentations hosts={mount.hosts} />;\n}\n","import type { UIActivationContext, UIPresentRequest, UIPresentResult } from '@burojs/core';\nimport { useCallback, useContext, useSyncExternalStore } from 'react';\nimport { ResolverContext } from '../context.js';\nimport { DismissRegistryContext, DismissScopeContext } from '../navigation/dismiss-scope.js';\nimport { useOptionalUIActivationSurface, useUIPresentationRuntime } from './context.js';\nimport { useOptionalPresentationMount } from './mount.js';\nimport { RESERVED_COMPONENT_PREFIX, type UIPresentationOptionsSchema } from './ui-presentations.js';\n\nconst GLOBAL_SURFACE = Object.freeze({ type: 'global' as const });\nconst EMPTY_SLICES: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/**\n * Reads the current activation: the surface from the nearest\n * `UIActivationSurfaceProvider` (defaulting to `{ type: 'global' }` when\n * there isn't one) plus a live snapshot of the app's resolver slices, if a\n * `BuroProvider` is mounted above. Outside one, `slices` is `{}` — this\n * hook (and `useUIPresent`, which is built on it) works standalone, e.g. in\n * a unit test that only wires up `UIPresentationRuntimeProvider`.\n */\nexport function useCurrentUIActivation(): UIActivationContext {\n const resolver = useContext(ResolverContext);\n const subscribe = useCallback(\n (listener: () => void) => (resolver === null ? () => undefined : resolver.subscribe(listener)),\n [resolver],\n );\n const getSnapshot = useCallback(\n () =>\n resolver === null ? EMPTY_SLICES : (resolver.snapshot() as Readonly<Record<string, unknown>>),\n [resolver],\n );\n const slices = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const surface = useOptionalUIActivationSurface() ?? GLOBAL_SURFACE;\n return Object.freeze({ slices, surface });\n}\n\n/** An imperative present request; `activation` is captured automatically and need not (usually) be supplied. */\nexport type UIPresentInput = Omit<UIPresentRequest, 'activation'> & {\n readonly activation?: Partial<UIActivationContext>;\n};\n\nexport type UIPresent = (request: UIPresentInput) => UIPresentResult;\n\n/**\n * Checks `options` against a host's declared `optionsSchema`, returning a\n * loud, specific message — naming the component, the key(s), the host, and\n * (for a type mismatch) both the expected and received type — or `null`\n * when every key is known and correctly typed. `schema === undefined` is\n * not represented here: the caller skips the check entirely in that case,\n * since a host with no schema accepts anything.\n *\n * Every offending key is collected and reported together in one message\n * (and one `console.error`) rather than stopping at the first, so three\n * typos cost one fix-and-rerun cycle, not three.\n *\n * A key present with value `undefined` is treated as absent for the type\n * check: `Object.entries` yields explicitly-`undefined` keys same as any\n * other, but every reader downstream of `options` (e.g. ui-shadcn's\n * `copy.ts`, which already treats a non-string `description` as \"not\n * supplied\") cannot tell an omitted key from one set to `undefined` — so\n * refusing the latter would punish an ordinary `{ description: maybeUndef }`\n * spread for a distinction nothing reads. An *unknown* key set to\n * `undefined` is still a typo and is still refused below.\n */\n/** @internal Also the block opener's check (`usePresentBlock`): one options contract for both. */\nexport function findInvalidOptionsMessage(\n component: string,\n host: string,\n schema: UIPresentationOptionsSchema,\n options: Readonly<Record<string, unknown>> | undefined,\n): string | null {\n if (options === undefined) return null;\n const issues: string[] = [];\n for (const [key, value] of Object.entries(options)) {\n const expected = schema[key];\n if (expected === undefined) {\n const known = Object.keys(schema);\n issues.push(\n `option \"${key}\" was refused — host \"${host}\" does not declare it in its ` +\n `optionsSchema. ${known.length > 0 ? `Known keys: ${known.join(', ')}.` : 'It declares no keys at all.'}`,\n );\n continue;\n }\n if (value === undefined) continue;\n const received = typeof value;\n if (received !== expected) {\n issues.push(\n `option \"${key}\" was refused — host \"${host}\" expects type \"${expected}\" ` +\n `but received \"${received}\".`,\n );\n }\n }\n if (issues.length === 0) return null;\n return `useUIPresent: present(\"${component}\") was refused — ${issues.join(' ')}`;\n}\n\n/**\n * Returns a `present` function that captures the current activation\n * (surface + resolver slices) at call time and forwards the request to the\n * `UIPresentationRuntime` supplied by the nearest `UIPresentationRuntimeProvider`.\n * A caller may override `surface` and/or `slices` explicitly via the\n * `activation` field of the request; anything left unset falls back to the\n * captured activation.\n */\nexport function useUIPresent(): UIPresent {\n const runtime = useUIPresentationRuntime();\n const activation = useCurrentUIActivation();\n const mount = useOptionalPresentationMount();\n const dismissRegistry = useContext(DismissRegistryContext);\n const openerScope = useContext(DismissScopeContext);\n return useCallback(\n (request: UIPresentInput): UIPresentResult => {\n // `buro:` keys are the framework's overlay screens: only its openers present them, after\n // the entry gate. An app presenting one would skip the gate (and has no stack to give).\n if (\n typeof request.component === 'string' &&\n request.component.startsWith(RESERVED_COMPONENT_PREFIX)\n ) {\n console.error(\n `useUIPresent: present(\"${request.component}\") was refused — buro: keys are the framework's overlay screens; open a record with useQuick() instead.`,\n );\n return Object.freeze({ ok: false, code: 'invalid-request' as const });\n }\n // An app that asked to own the mount and then never rendered the outlet\n // would otherwise register descriptors nothing can ever render. Refuse\n // before touching the runtime, so the stack keeps no ghost entries.\n if (mount !== null && mount.mode === 'app' && !mount.registry.isMounted()) {\n console.error(\n `useUIPresent: present(\"${request.component}\") was refused — BuroProvider is in presentations=\"app\" mode but no <BuroPresentationOutlet/> is mounted. Render <BuroPresentationOutlet/> inside your provider stack, or drop presentations=\"app\" to let the framework mount the stack itself.`,\n );\n return Object.freeze({ ok: false, code: 'outlet-missing' as const });\n }\n // The options schema belongs to the host, not to the core runtime: core\n // knows the host NAMES (`host: 'dialog' | 'sheet'` — see `VALID_HOSTS`\n // in presentation-runtime.ts) but never learns their option\n // VOCABULARIES, which is what makes this decidable only here, the same\n // layer that owns `outlet-missing`, before the request ever reaches\n // `runtime.present()`.\n const schema = mount?.hosts[request.host]?.optionsSchema;\n if (schema !== undefined) {\n const message = findInvalidOptionsMessage(\n request.component,\n request.host,\n schema,\n request.options,\n );\n if (message !== null) {\n console.error(message);\n return Object.freeze({ ok: false, code: 'invalid-options' as const });\n }\n }\n const { activation: overrides, ...rest } = request;\n const resolvedActivation: UIActivationContext =\n overrides === undefined\n ? activation\n : Object.freeze({\n surface: overrides.surface ?? activation.surface,\n slices: overrides.slices ?? activation.slices,\n });\n const result = runtime.present({ ...rest, activation: resolvedActivation });\n // The opener's scope becomes the new overlay's parent (P3-30, plan ruling 3): closing\n // the opener asks about this overlay's forms too, and closes it with the opener.\n if (result.ok && dismissRegistry !== null && openerScope !== null) {\n dismissRegistry.recordParent(result.instance.id, openerScope.id);\n }\n return result;\n },\n [runtime, activation, mount, dismissRegistry, openerScope],\n );\n}\n","import { useCallback, useContext, useSyncExternalStore } from 'react';\nimport { ResolverContext } from '../context.js';\n\nexport function useCtx<T>(selector: (s: never) => T): T {\n const resolver = useContext(ResolverContext);\n if (!resolver) throw new Error('[useCtx] must be used within a BuroProvider');\n\n const subscribe = useCallback((onChange: () => void) => resolver.subscribe(onChange), [resolver]);\n // ⚠️ The THIRD argument is not optional in practice. Omit it and React throws\n // \"Missing getServerSnapshot, which is required for server-rendered content.\n // Will revert to client rendering.\" the moment a component calling this is\n // rendered on the server — and its own wording names the consequence: the\n // boundary silently degrades to client-only instead of failing loudly.\n //\n // This was missing here, and only here: `use-t.ts:77` and\n // `use-doc-panel.tsx:166,377` all pass three. It went unnoticed because\n // nothing in this repository had ever server-rendered a component that reads\n // context — every consumer sits under a provider whose bootstrap returns\n // `null` during SSR, so this body never ran there. The reach is not small:\n // `useCtx` feeds `useAvailability`, `useCapability` and `usePermissions`, and\n // through them every list and every form in `@burojs/ui-shadcn`.\n //\n // The server snapshot is the SAME function as the client one, which is correct\n // rather than a shortcut: the resolver's snapshot is synchronously available\n // and identical on both sides, so there is nothing for a separate server\n // implementation to do differently.\n const getSnapshot = useCallback(\n () => selector(resolver.snapshot() as never),\n [resolver, selector],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","'use client';\nimport {\n type AppContext,\n type UIPresentHost,\n recordEntries,\n resolveAvailability,\n ruleContextFor,\n} from '@burojs/core';\nimport { useCallback } from 'react';\nimport { useApp } from '../hooks/use-app.js';\nimport { useCtx } from '../hooks/use-ctx.js';\nimport { useOptionalPresentationMount } from '../ui/mount.js';\n\n/** Which entry an opener asks for: a quick entry's mode, or the peek. */\nexport type EntryKind = 'show' | 'edit' | 'create' | 'peek';\n\n/**\n * The entry gate's answer (spec 4.4). `open` names the host and the resolved target (a resource\n * delegating its show through `routesTo.show` opens the delegate's entry). `undecided` while the\n * user's permission map loads: the opener renders plain text and sends nothing. `absent`, `hidden`\n * and `disabled` open nothing, and say why.\n */\nexport type EntryAnswer =\n | { readonly state: 'open'; readonly host: UIPresentHost; readonly target: string }\n | { readonly state: 'undecided' }\n | { readonly state: 'absent' | 'hidden' | 'disabled'; readonly why: string };\n\nconst UNDECIDED: EntryAnswer = Object.freeze({ state: 'undecided' });\n\nfunction closed(state: 'absent' | 'hidden' | 'disabled', why: string): EntryAnswer {\n return Object.freeze({ state, why });\n}\n\n/** Missing members already reported, per provider (keyed by its outlet registry). */\nconst reportedMissing = new WeakMap<object, Set<string>>();\n\nfunction reportMissing(provider: object, member: string): void {\n if (process.env.NODE_ENV === 'production') return;\n let seen = reportedMissing.get(provider);\n if (seen === undefined) {\n seen = new Set();\n reportedMissing.set(provider, seen);\n }\n if (seen.has(member)) return;\n seen.add(member);\n console.error(\n `[burojs] Quick entries need presentationHosts.${member}; spread shadcnPresentationHosts (or its screens) into your hosts.`,\n );\n}\n\n/**\n * @internal The one entry gate every opener asks before any request (spec 4.4, 4.14):\n *\n * 1. static — the target resolves (following `routesTo.show` for `show` and `peek`),\n * `recordEntries` names the entry, and its host and screen are wired in\n * `presentationHosts`; otherwise `absent` (one development error per missing member);\n * 2. decided — `undecided` while the permission map has `status: 'loading'`. No map is\n * decided, and a map in `error` is decided by the rules (a `can()` against it fails closed);\n * 3. dynamic — `resolveAvailability` of the entry's operation (`show` for the peek) with the\n * opener's row when it holds one.\n */\nexport function useEntryGate(): (target: string, entry: EntryKind, row?: unknown) => EntryAnswer {\n const app = useApp();\n const mount = useOptionalPresentationMount();\n const scope = useCtx((c: AppContext) => c.scope);\n const user = useCtx((c: AppContext) => c.user);\n const permissions = useCtx((c: AppContext) => c.permissions);\n\n return useCallback(\n (target: string, entry: EntryKind, row?: unknown): EntryAnswer => {\n const own = app.registry.get(target);\n if (own === undefined) return closed('absent', `${target} is not a registered resource`);\n const delegate = entry === 'show' || entry === 'peek' ? own.routesTo?.show : undefined;\n const name = delegate ?? own.name;\n const def = delegate === undefined ? own : app.registry.get(delegate);\n if (def === undefined) {\n return closed(\n 'absent',\n `${target} delegates its show to ${delegate}, which is not registered`,\n );\n }\n const entries = recordEntries(def);\n const host: UIPresentHost | null =\n entry === 'peek' ? (entries.peek ? 'popover' : null) : entries.quick[entry];\n if (host === null) return closed('absent', `${name}'s ${entry} entry is switched off`);\n if (mount === null) return closed('absent', 'no BuroProvider is mounted');\n if (mount.hosts[host] === undefined) {\n reportMissing(mount.registry, host);\n return closed('absent', `presentationHosts.${host} is missing`);\n }\n const screen = entry === 'peek' ? mount.hosts.screens?.peek : mount.hosts.screens?.quick;\n if (screen === undefined) {\n const member = entry === 'peek' ? 'screens.peek' : 'screens.quick';\n reportMissing(mount.registry, member);\n return closed('absent', `presentationHosts.${member} is missing`);\n }\n // Decided only once the permission map is: loading is never \"allowed\" (Known finding 12).\n if (permissions?.status === 'loading') return UNDECIDED;\n const operation = entry === 'peek' ? 'show' : entry;\n const ctx = ruleContextFor({\n user,\n scope,\n permissions,\n record: row,\n mode: operation,\n resource: name,\n });\n const availability = resolveAvailability(app.ruleSource, app.registry, name, operation, ctx);\n if (availability.state === 'available')\n return Object.freeze({ state: 'open', host, target: name });\n return closed(\n availability.state,\n availability.state === 'disabled' && availability.reason !== undefined\n ? availability.reason\n : `${operation} on ${name} is ${availability.state} for this user`,\n );\n },\n [app.registry, app.ruleSource, mount, scope, user, permissions],\n );\n}\n","'use client';\nimport type { QuickHost } from '@burojs/core';\nimport { type Context, createContext, useContext, useMemo } from 'react';\nimport { DismissScopeContext, type DismissScopeValue } from '../navigation/dismiss-scope.js';\nimport { useUIInstance, useUIPresentationRuntime } from '../ui/context.js';\nimport type { QuickStack } from './quick-stack.js';\n\n/** What a component inside a quick overlay knows about it. */\nexport interface QuickEntryValue {\n readonly stack: QuickStack;\n readonly host: QuickHost;\n /** The overlay's presentation id in the runtime. */\n readonly presentationId: string;\n /** The overlay's dismiss scope: a push or a close inside it asks through it. */\n readonly scope: DismissScopeValue;\n}\n\n/** @internal Provided by the UI kit's quick screen around the entry it renders. */\nexport const QuickEntryContext: Context<QuickEntryValue | null> =\n createContext<QuickEntryValue | null>(null);\n\n/** The quick overlay the caller renders in, or `null` outside one. */\nexport function useQuickEntry(): QuickEntryValue | null {\n return useContext(QuickEntryContext);\n}\n\nconst NO_SCOPE: DismissScopeValue = Object.freeze({\n id: '',\n request: (onLeave: () => void) => onLeave(),\n isLocked: () => false,\n});\n\n/**\n * @internal What the UI kit's quick screen provides as `QuickEntryContext`: its stack, the host it\n * was presented in (read off its descriptor), its presentation id and the presentation's dismiss\n * scope. Called by the quick screen, which renders inside its presentation instance.\n */\nexport function useQuickEntryValue(stack: QuickStack): QuickEntryValue {\n const instance = useUIInstance();\n const runtime = useUIPresentationRuntime();\n const scope = useContext(DismissScopeContext) ?? NO_SCOPE;\n const descriptorHost = runtime.getSnapshot().find((d) => d.id === instance.id)?.host;\n const host: QuickHost = descriptorHost === 'dialog' ? 'dialog' : 'sheet';\n return useMemo<QuickEntryValue>(\n () => ({ stack, host, presentationId: instance.id, scope }),\n [stack, host, instance.id, scope],\n );\n}\n","/** One entry of a quick overlay: a record's quick screen in a mode. */\nexport interface QuickEntry {\n readonly resource: string;\n readonly mode: 'show' | 'edit' | 'create';\n /** The record of `show` and `edit`; absent on `create`. */\n readonly recordId?: string;\n /** `create`'s trusted defaults (the caller's tier, P1b+P1c decision 7). */\n readonly defaults?: Readonly<Record<string, unknown>>;\n /**\n * `create`'s user input (a search text typed into a relation select): form values the user can\n * see and change, applied once to the fields the plan holds `active`, never a trusted default\n * (P6 plan ruling 7).\n */\n readonly input?: Readonly<Record<string, unknown>>;\n /** The entry's record title once its screen has read it: what \"Back to …\" names. */\n readonly title?: string;\n}\n\n/** A created row, or `null`: what `useQuick().create` resolves with. */\nexport type QuickSettledRow = Readonly<Record<string, unknown>> | null;\n\n/**\n * The history of one quick overlay (spec 4.9): a stack of entries of which only the top is\n * mounted. A relation inside a sheet pushes; Back pops; Edit in `quick.show` replaces the top.\n * The history is never in the URL. An external store: `subscribe` / `getSnapshot` for\n * `useSyncExternalStore`, and `getSnapshot()` changes identity on every change.\n *\n * `settled` resolves once, with the row a `quick.create` saved or `null` when the overlay closed\n * without one.\n */\nexport class QuickStack {\n private stack: readonly QuickEntry[];\n private readonly listeners = new Set<() => void>();\n private resolveSettled: (row: QuickSettledRow) => void = () => undefined;\n private isSettled = false;\n readonly settled: Promise<QuickSettledRow>;\n\n constructor(first: QuickEntry) {\n this.stack = Object.freeze([Object.freeze({ ...first })]);\n this.settled = new Promise<QuickSettledRow>((resolve) => {\n this.resolveSettled = resolve;\n });\n }\n\n get entries(): readonly QuickEntry[] {\n return this.stack;\n }\n\n get top(): QuickEntry {\n return this.stack[this.stack.length - 1] as QuickEntry;\n }\n\n push(entry: QuickEntry): void {\n this.publish([...this.stack, Object.freeze({ ...entry })]);\n }\n\n /** Back: drops the top entry. A stack of one is never emptied (closing is the overlay's). */\n pop(): void {\n if (this.stack.length <= 1) return;\n this.publish(this.stack.slice(0, -1));\n }\n\n /** Switches the top entry in place (Edit ↔ show), keeping the depth. */\n replaceTop(entry: QuickEntry): void {\n this.publish([...this.stack.slice(0, -1), Object.freeze({ ...entry })]);\n }\n\n /** Records the top entry's title once its record is read. */\n nameTop(title: string): void {\n if (this.top.title === title) return;\n this.publish([...this.stack.slice(0, -1), Object.freeze({ ...this.top, title })]);\n }\n\n /** Resolve `settled`, once: later calls change nothing. */\n settle(row: QuickSettledRow): void {\n if (this.isSettled) return;\n this.isSettled = true;\n this.resolveSettled(row);\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getSnapshot = (): readonly QuickEntry[] => this.stack;\n\n private publish(next: readonly QuickEntry[]): void {\n this.stack = Object.freeze(next);\n for (const listener of [...this.listeners]) listener();\n }\n}\n","'use client';\nimport type {\n QuickHost,\n ResourceRefInput,\n UIActivationContext,\n UIPresentationRuntime,\n} from '@burojs/core';\nimport { useCallback, useContext, useMemo } from 'react';\nimport { relationKeyString } from '../hooks/relation-aggregator.js';\nimport { useApp } from '../hooks/use-app.js';\nimport {\n type DismissRegistry,\n DismissRegistryContext,\n DismissScopeContext,\n} from '../navigation/dismiss-scope.js';\nimport { useUIPresentationRuntime } from '../ui/context.js';\nimport { type PresentationMount, useOptionalPresentationMount } from '../ui/mount.js';\nimport { QUICK_COMPONENT } from '../ui/ui-presentations.js';\nimport { useCurrentUIActivation } from '../ui/use-ui-present.js';\nimport { type EntryAnswer, useEntryGate } from './entry-gate.js';\nimport { useQuickEntry } from './quick-entry-context.js';\nimport { type QuickEntry, type QuickSettledRow, QuickStack } from './quick-stack.js';\n\n/** What a quick open did: opened, opened nothing (with a development error), or waited for access. */\nexport type QuickOpen = 'opened' | 'absent' | 'undecided';\n\n/**\n * Opening a record in an overlay from code (spec 3.5). Every call runs the same entry gate as the\n * framework's openers; `'absent'` and `'undecided'` open nothing, and an undecided call is never\n * queued.\n */\nexport interface QuickApi {\n show(resource: ResourceRefInput, id: string | number): QuickOpen;\n edit(resource: ResourceRefInput, id: string | number): QuickOpen;\n /**\n * Opens `quick.create`; resolves with the created row, or `null` when the gate refused it or\n * the overlay closed without one. `defaults` are the caller's trusted tier; `input` is user\n * input (a search text the user typed): it fills the fields the create form holds active and\n * editable for this user, makes the form dirty, and is dropped for any other field.\n */\n create(\n resource: ResourceRefInput,\n opts?: {\n readonly defaults?: Readonly<Record<string, unknown>>;\n readonly input?: Readonly<Record<string, unknown>>;\n },\n ): Promise<QuickSettledRow>;\n}\n\ninterface PresentQuickInput {\n readonly runtime: UIPresentationRuntime;\n readonly mount: PresentationMount | null;\n readonly registry: DismissRegistry | null;\n readonly activation: UIActivationContext;\n readonly entry: QuickEntry;\n readonly host: QuickHost;\n /** The scope the overlay is opened from: closing it asks about this overlay too. */\n readonly parentScope: string | null;\n}\n\n/**\n * @internal Present a quick overlay through the runtime: the `buro:quick` screen over a fresh\n * stack. The framework presents directly, not through `useUIPresent`, so a host's options schema\n * is not consulted (plan ruling 2); the outlet-missing refusal still applies. Returns the stack\n * and the presentation id, or `null` when nothing was presented.\n */\nexport function presentQuick(\n input: PresentQuickInput,\n): { readonly id: string; readonly stack: QuickStack } | null {\n const { runtime, mount, registry, activation, entry, host, parentScope } = input;\n if (mount !== null && mount.mode === 'app' && !mount.registry.isMounted()) {\n console.error(\n `[burojs] A quick ${entry.mode} of ${entry.resource} was refused: BuroProvider is in presentations=\"app\" mode but no <BuroPresentationOutlet/> is mounted.`,\n );\n return null;\n }\n const stack = new QuickStack(entry);\n const result = runtime.present({\n component: QUICK_COMPONENT,\n host,\n props: { stack },\n options: { ownTitle: true, wrapper: false },\n activation,\n });\n if (!result.ok) {\n stack.settle(null);\n return null;\n }\n if (registry !== null && parentScope !== null) {\n registry.recordParent(result.instance.id, parentScope);\n }\n return { id: result.instance.id, stack };\n}\n\nfunction developmentError(message: string): void {\n if (process.env.NODE_ENV !== 'production') console.error(`[burojs] ${message}`);\n}\n\n/** The stack of the topmost quick sheet, if any. */\nfunction topmostSheetStack(runtime: UIPresentationRuntime): QuickStack | null {\n const sheets = runtime\n .getSnapshot()\n .filter(\n (descriptor) => descriptor.component === QUICK_COMPONENT && descriptor.host === 'sheet',\n );\n const stack = sheets[sheets.length - 1]?.props.stack;\n return stack instanceof QuickStack ? stack : null;\n}\n\n/** The shared parts every quick opener needs. */\nfunction useQuickPresenter() {\n const runtime = useUIPresentationRuntime();\n const mount = useOptionalPresentationMount();\n const registry = useContext(DismissRegistryContext);\n const enclosing = useContext(DismissScopeContext);\n const activation = useCurrentUIActivation();\n const gate = useEntryGate();\n return { runtime, mount, registry, enclosing, activation, gate };\n}\n\n/**\n * The one way to open a record in an overlay from code. `show` / `edit` with an id that is no\n * key (`null`, `''`, `NaN`, an object, a boolean) open nothing and log a development error, as\n * does a refused entry; `'undecided'` (the permission map is loading) opens nothing and is never\n * queued. A `show` of the record already on top of the topmost quick sheet opens nothing more.\n */\nexport function useQuick(): QuickApi {\n const app = useApp();\n const { runtime, mount, registry, enclosing, activation, gate } = useQuickPresenter();\n\n return useMemo<QuickApi>(() => {\n const nameOf = (resource: ResourceRefInput): string =>\n typeof resource === 'string' ? resource : (app.registry.get(resource)?.name ?? '');\n const refused = (answer: EntryAnswer, what: string): QuickOpen => {\n if (answer.state === 'undecided') return 'undecided';\n if (answer.state !== 'open') developmentError(`${what} opened nothing: ${answer.why}.`);\n return 'absent';\n };\n const open = (mode: 'show' | 'edit', resource: ResourceRefInput, id: unknown): QuickOpen => {\n const name = nameOf(resource);\n const key = relationKeyString(id);\n if (key === null) {\n developmentError(\n `useQuick().${mode}(${name}, ${JSON.stringify(id) ?? String(id)}) opened nothing: the id is not a record key.`,\n );\n return 'absent';\n }\n const answer = gate(name, mode);\n if (answer.state !== 'open') return refused(answer, `useQuick().${mode}(${name})`);\n if (mode === 'show') {\n const top = topmostSheetStack(runtime)?.top;\n if (top?.resource === answer.target && top.mode === 'show' && top.recordId === key) {\n return 'opened';\n }\n }\n const presented = presentQuick({\n runtime,\n mount,\n registry,\n activation,\n entry: { resource: answer.target, mode, recordId: key },\n host: answer.host as QuickHost,\n parentScope: enclosing?.id ?? null,\n });\n return presented === null ? 'absent' : 'opened';\n };\n return {\n show: (resource, id) => open('show', resource, id),\n edit: (resource, id) => open('edit', resource, id),\n create: (resource, opts = {}) => {\n const name = nameOf(resource);\n const answer = gate(name, 'create');\n // Plan ruling 10: a refusal resolves `null`, with the development error for `absent`.\n if (answer.state !== 'open') {\n refused(answer, `useQuick().create(${name})`);\n return Promise.resolve(null);\n }\n const presented = presentQuick({\n runtime,\n mount,\n registry,\n activation,\n entry: {\n resource: answer.target,\n mode: 'create',\n ...(opts.defaults === undefined ? {} : { defaults: opts.defaults }),\n ...(opts.input === undefined ? {} : { input: opts.input }),\n },\n host: answer.host as QuickHost,\n parentScope: enclosing?.id ?? null,\n });\n return presented === null ? Promise.resolve(null) : presented.stack.settled;\n },\n };\n }, [app.registry, gate, runtime, mount, registry, enclosing, activation]);\n}\n\n/**\n * @internal The framework openers' path to `quick.show` (a relation display, a related-list\n * row): the gate with the opener's row, then — inside a quick sheet, a push through the sheet's\n * scope (it asks when the sheet holds a dirty form); inside a quick dialog, the dialog closes\n * (through its scope) and the target opens as a new overlay beside it; elsewhere a new overlay\n * whose parent is the enclosing scope.\n */\nexport function useQuickOpener(): (\n target: string,\n id: string,\n opts?: { readonly row?: unknown },\n) => QuickOpen {\n const { runtime, mount, registry, enclosing, activation, gate } = useQuickPresenter();\n const entry = useQuickEntry();\n return useCallback(\n (target, id, opts = {}) => {\n const key = relationKeyString(id);\n if (key === null) return 'absent';\n const answer = gate(target, 'show', opts.row);\n if (answer.state === 'undecided') return 'undecided';\n if (answer.state !== 'open') return 'absent';\n const next: QuickEntry = { resource: answer.target, mode: 'show', recordId: key };\n const host = answer.host as QuickHost;\n if (entry !== null && entry.host === 'sheet') {\n // The record already on top of this sheet: nothing more opens (spec 4.9).\n const top = entry.stack.top;\n if (top.mode === 'show' && top.resource === next.resource && top.recordId === key)\n return 'opened';\n entry.scope.request(() => entry.stack.push(next));\n return 'opened';\n }\n if (entry !== null && entry.host === 'dialog') {\n const parentScope = registry?.parentOf(entry.presentationId) ?? null;\n entry.scope.request(() => {\n // The dialog and every overlay opened from it: none is left orphaned.\n if (registry === null) runtime.dismiss(entry.presentationId);\n else registry.closeSubtree(entry.presentationId);\n presentQuick({ runtime, mount, registry, activation, entry: next, host, parentScope });\n });\n return 'opened';\n }\n const presented = presentQuick({\n runtime,\n mount,\n registry,\n activation,\n entry: next,\n host,\n parentScope: enclosing?.id ?? null,\n });\n return presented === null ? 'absent' : 'opened';\n },\n [gate, entry, runtime, mount, registry, enclosing, activation],\n );\n}\n","'use client';\nimport type { DispatcherEffects, NotifyDescriptor } from '@burojs/core';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { useContext, useRef } from 'react';\nimport { AppContext } from '../context.js';\nimport { useOptionalDataRuntime } from '../data/context.js';\nimport { useOptionalRouterAdapter } from '../hooks/router/router-adapter.js';\nimport { resolveRoute, routePathname } from '../navigation/resolve-route.js';\nimport { useRouteNavigate } from '../navigation/use-route-navigate.js';\nimport {\n type NotificationSinkMessage,\n useNotificationSinkRegistry,\n} from '../notifications/notification-sink.js';\nimport { useQuickOpener } from '../quick/use-quick.js';\nimport { useUIPresent } from '../ui/use-ui-present.js';\n\n/** A handler's `notify` as a sink message: a string is a success; a descriptor keeps its type. */\nexport function toSinkMessage(notification: NotifyDescriptor): NotificationSinkMessage {\n if (typeof notification === 'string') return { type: 'success', message: notification };\n return { type: notification.type, message: notification.message };\n}\n\nfunction isBuroDataKey(key: readonly unknown[]): boolean {\n return key[0] === 'buro-data' && key[1] === 1;\n}\n\n/** Every name a query descriptor answers to: its provider resource, its ref id and its qualified ref. */\nfunction descriptorNames(descriptor: unknown): string[] {\n if (descriptor === null || typeof descriptor !== 'object' || Array.isArray(descriptor)) return [];\n const { resource, ref } = descriptor as { readonly resource?: unknown; readonly ref?: unknown };\n const names: string[] = [];\n if (typeof resource === 'string') names.push(resource);\n if (ref !== null && typeof ref === 'object') {\n const { namespace, id } = ref as { readonly namespace?: unknown; readonly id?: unknown };\n if (typeof id === 'string') {\n names.push(id);\n if (typeof namespace === 'string') names.push(`${namespace}:${id}`);\n }\n }\n return names;\n}\n\n/**\n * Invalidate the framework's data queries: `true` invalidates every\n * `buro-data` query, a list only those whose descriptor names one of the\n * resources, `false` nothing.\n */\nexport async function invalidateBuroData(\n queryClient: QueryClient,\n resources: boolean | readonly string[],\n): Promise<void> {\n if (resources === false) return;\n if (resources === true) {\n await queryClient.invalidateQueries({ predicate: (query) => isBuroDataKey(query.queryKey) });\n return;\n }\n const requested = new Set(resources);\n await queryClient.invalidateQueries({\n predicate: (query) =>\n isBuroDataKey(query.queryKey) &&\n descriptorNames(query.queryKey[2]).some((name) => requested.has(name)),\n });\n}\n\n/**\n * Click a transient download anchor: the URL itself, or an object URL for a\n * blob, revoked once the click has been handed to the browser.\n */\nexport function downloadPayload(\n payload: { url: string; filename?: string } | { blob: Blob; filename: string },\n): void {\n if (typeof document === 'undefined') return;\n let href: string;\n let objectUrl: string | undefined;\n if ('blob' in payload) {\n objectUrl = URL.createObjectURL(payload.blob);\n href = objectUrl;\n } else {\n href = payload.url;\n }\n const anchor = document.createElement('a');\n anchor.href = href;\n anchor.download = payload.filename ?? '';\n anchor.rel = 'noopener';\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n if (objectUrl !== undefined) {\n const revoke = objectUrl;\n setTimeout(() => URL.revokeObjectURL(revoke), 0);\n }\n}\n\n/**\n * The default for every `DispatcherEffects` key but `clearSelection` (the\n * caller owns the selection and reads `clearSelection` off the returned\n * result). Built per render from the current contexts; `RootDispatcherProvider`\n * reads it through a ref at call time. Browser globals are touched only when\n * an effect runs, so server rendering is unaffected.\n */\nexport function useDefaultDispatcherEffects(): DispatcherEffects {\n const app = useContext(AppContext);\n const runtime = useOptionalDataRuntime();\n const adapter = useOptionalRouterAdapter();\n const sinks = useNotificationSinkRegistry();\n const present = useUIPresent();\n const navigate = useRouteNavigate();\n const openQuick = useQuickOpener();\n const warnedNoSink = useRef(false);\n return {\n refetch: (resources) =>\n runtime === null ? undefined : invalidateBuroData(runtime.queryClient, resources),\n notify: (notification) => {\n const sink = sinks?.current();\n if (sink !== undefined) {\n sink.open(toSinkMessage(notification));\n return;\n }\n // Without a sink every notification — a thrown handler's error included —\n // is dropped. Say so once, in development, instead of failing silently.\n if (process.env.NODE_ENV !== 'production' && !warnedNoSink.current) {\n warnedNoSink.current = true;\n console.warn(\n '[burojs] An action notification was dropped: there is no notification sink. ' +\n 'Mount <Toaster> from @burojs/ui-shadcn inside <BuroProvider>, or register ' +\n 'your own with useRegisterNotificationSink. Later notifications are dropped silently.',\n );\n }\n },\n // `navigate` is `useRouteNavigate`, so a redirect asks the navigation guard:\n // a redirect from a dirty form prompts before it leaves (P1b+P1c decision 30).\n redirect: (to) => {\n const href = resolveRoute(to, app?.registry);\n const here =\n adapter?.pathname ?? (typeof window === 'undefined' ? '' : window.location.pathname);\n // The built-in delete redirects to the list unconditionally, also when\n // fired from that list: navigating to where you already are only throws\n // away the filters, page and sort the current URL carries. A target with\n // a query of its own (a page, filters) is a real navigation and goes.\n const ownQuery = (href.split('#')[0] ?? href).includes('?');\n if (!ownQuery && routePathname(href) === here) return;\n navigate(href);\n },\n setClipboard: async (text) => {\n if (typeof navigator === 'undefined' || navigator.clipboard === undefined) return;\n await navigator.clipboard.writeText(text);\n },\n download: (payload) => downloadPayload(payload),\n // A flow's `then.open` (P4 spec 4.13): a quick record through the P3 entry gate, falling back\n // to the guarded record route when the entry is absent or undecided; a block is the flow\n // host's to render, never this default's.\n open: (target) => {\n if (target.kind !== 'record') return;\n if (target.quick && target.mode === 'show') {\n const opened = openQuick(target.resource, target.id);\n if (opened === 'opened') return;\n }\n navigate(\n resolveRoute(\n { resource: target.resource, action: target.mode, params: { id: target.id } },\n app?.registry,\n ),\n );\n },\n modal: (modal) => {\n // `Action.modal` defaults its surface to 'dialog'; an ActionResult modal\n // names no host, so it gets the same default. The activation surface is\n // the root's (`{ type: 'global' }`): a dispatch inside a\n // `UIActivationSurfaceProvider` does not carry its surface yet.\n present({\n component: modal.component,\n host: 'dialog',\n ...(modal.props === undefined ? {} : { props: modal.props }),\n ...(modal.options === undefined ? {} : { options: modal.options }),\n });\n },\n };\n}\n","'use client';\nimport { createDispatcher, type Dispatcher, type DispatcherEffects } from '@burojs/core';\nimport {\n type ReactElement,\n type ReactNode,\n createContext,\n useContext,\n useMemo,\n useRef,\n} from 'react';\nimport { AppContext } from '../context.js';\nimport { useDefaultDispatcherEffects } from './default-effects.js';\n\ninterface DispatcherScope {\n readonly dispatcher: Dispatcher;\n /** The effect set this scope resolves to, read at call time. */\n readonly resolveEffects: () => DispatcherEffects;\n}\n\nconst DispatcherContext = createContext<DispatcherScope | null>(null);\n\n/** Every `DispatcherEffects` key, checked against the interface at compile time. */\nconst EFFECT_KEYS = Object.keys({\n setClipboard: true,\n download: true,\n modal: true,\n notify: true,\n clearSelection: true,\n refetch: true,\n redirect: true,\n open: true,\n} satisfies Record<keyof DispatcherEffects, true>) as (keyof DispatcherEffects)[];\n\n/** `overrides` merged per key over `base`; an `undefined` override keeps the base effect. */\nexport function mergeEffects(\n base: DispatcherEffects,\n overrides: Partial<DispatcherEffects> | undefined,\n): DispatcherEffects {\n if (overrides === undefined) return base;\n const merged: Record<keyof DispatcherEffects, unknown> = { ...base } as Record<\n keyof DispatcherEffects,\n unknown\n >;\n for (const key of EFFECT_KEYS) {\n const effect = overrides[key];\n if (effect !== undefined) merged[key] = effect;\n }\n return merged as DispatcherEffects;\n}\n\n/** A stable effect object whose every key delegates to the scope's current effects. */\nfunction delegatingEffects(resolve: () => DispatcherEffects): DispatcherEffects {\n return {\n setClipboard: (text) => resolve().setClipboard?.(text),\n download: (payload) => resolve().download?.(payload),\n modal: (modal) => resolve().modal?.(modal),\n notify: (notification) => resolve().notify?.(notification),\n clearSelection: () => resolve().clearSelection?.(),\n refetch: (resources) => resolve().refetch?.(resources),\n redirect: (to) => resolve().redirect?.(to),\n open: (target) => resolve().open?.(target),\n };\n}\n\nexport interface DispatcherProviderProps {\n /** Merged per key over the enclosing dispatcher's effects (over the defaults at the root). */\n readonly effects?: Partial<DispatcherEffects>;\n readonly children: ReactNode;\n}\n\n/**\n * @internal Mounted by `BuroProvider`: the root dispatcher, with a default for\n * every effect and `effects` merged per key over them. Built once per app; the\n * effects are read through refs, so an inline `effects` object neither\n * rebuilds the dispatcher nor goes stale.\n */\nexport function RootDispatcherProvider({\n effects,\n children,\n}: DispatcherProviderProps): ReactElement {\n const app = useContext(AppContext);\n const defaults = useDefaultDispatcherEffects();\n const defaultsRef = useRef(defaults);\n defaultsRef.current = defaults;\n const overridesRef = useRef(effects);\n overridesRef.current = effects;\n const scope = useMemo<DispatcherScope>(() => {\n const resolveEffects = (): DispatcherEffects =>\n mergeEffects(defaultsRef.current, overridesRef.current);\n return {\n dispatcher: createDispatcher(delegatingEffects(resolveEffects)),\n resolveEffects,\n };\n }, [app]);\n return <DispatcherContext.Provider value={scope}>{children}</DispatcherContext.Provider>;\n}\n\n/**\n * A nested dispatcher scope: `effects` merged per key over the enclosing\n * dispatcher's. For a subtree that needs a different effect, and for tests that\n * spy on effects. Must be rendered inside a `BuroProvider`.\n */\nexport function DispatcherProvider({ effects, children }: DispatcherProviderProps): ReactElement {\n const parent = useContext(DispatcherContext);\n const app = useContext(AppContext);\n const parentRef = useRef(parent);\n parentRef.current = parent;\n const overridesRef = useRef(effects);\n overridesRef.current = effects;\n const scope = useMemo<DispatcherScope>(() => {\n const resolveEffects = (): DispatcherEffects =>\n mergeEffects(parentRef.current?.resolveEffects() ?? {}, overridesRef.current);\n return {\n dispatcher: createDispatcher(delegatingEffects(resolveEffects)),\n resolveEffects,\n };\n }, [app]);\n if (parent === null) {\n throw new Error('<DispatcherProvider> must be rendered inside a BuroProvider.');\n }\n return <DispatcherContext.Provider value={scope}>{children}</DispatcherContext.Provider>;\n}\n\n/** The nearest dispatcher. `BuroProvider` always mounts one. */\nexport function useDispatcher(): Dispatcher {\n const scope = useContext(DispatcherContext);\n if (scope === null) throw new Error('useDispatcher must be used within a BuroProvider.');\n return scope.dispatcher;\n}\n\n/**\n * @internal The effects the nearest dispatcher scope resolves to, read at call time: a nested\n * scope that replaces one effect (a quick entry's `redirect`) passes what it does not handle to\n * its parent's.\n */\nexport function useDispatcherEffects(): () => DispatcherEffects {\n const scope = useContext(DispatcherContext);\n const scopeRef = useRef(scope);\n scopeRef.current = scope;\n return useMemo(() => () => scopeRef.current?.resolveEffects() ?? {}, []);\n}\n","import { LAYOUT_SIZES, type LayoutSize, isStandardSchema } from '@burojs/core';\nimport type { FieldImplementation, FieldImplementationLayout } from './types.js';\n\n/**\n * Trusted React handles for one provider tree. The keys are deliberately the\n * portable field `format` or `type` values; components themselves never enter\n * a declaration, runtime snapshot, or serialized manifest.\n */\nexport type FieldImplementationCatalog = Readonly<Record<string, FieldImplementation<any, any>>>;\n\nexport type FieldImplementationMap = FieldImplementationCatalog;\n\nexport const EMPTY_FIELD_IMPLEMENTATIONS: FieldImplementationCatalog = Object.freeze({});\n\nfunction assertId(id: string): void {\n if (typeof id !== 'string' || id.trim().length === 0) {\n throw new TypeError('A field implementation ID must be a non-empty string.');\n }\n}\n\nfunction copyLayout(value: unknown, id: string): FieldImplementationLayout | undefined {\n if (value === undefined) return undefined;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`Field implementation '${id}' layout must be an object.`);\n }\n const layout = value as { readonly size?: unknown };\n if (\n Object.keys(layout).some((key) => key !== 'size') ||\n (layout.size !== undefined && !(LAYOUT_SIZES as readonly unknown[]).includes(layout.size))\n ) {\n throw new TypeError(\n `Field implementation '${id}' layout must contain only an optional size (${LAYOUT_SIZES.join(', ')}).`,\n );\n }\n return Object.freeze({\n ...(layout.size === undefined ? {} : { size: layout.size as LayoutSize }),\n });\n}\n\nfunction copyImplementation(id: string, value: unknown): FieldImplementation<any, any> {\n assertId(id);\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`Field implementation '${id}' must be an object.`);\n }\n const implementation = value as FieldImplementation<any, any>;\n const keys = ['Input', 'Display', 'CollectionInput', 'CollectionDisplay', 'layout', 'meta'];\n if (Object.keys(implementation).some((key) => !keys.includes(key))) {\n throw new TypeError(`Field implementation '${id}' contains an unsupported key.`);\n }\n const renderers = {\n Input: implementation.Input,\n Display: implementation.Display,\n CollectionInput: implementation.CollectionInput,\n CollectionDisplay: implementation.CollectionDisplay,\n };\n for (const [name, renderer] of Object.entries(renderers)) {\n if (renderer !== undefined && typeof renderer !== 'function') {\n throw new TypeError(`Field implementation '${id}' ${name} must be a React component.`);\n }\n }\n if (implementation.meta !== undefined && !isStandardSchema(implementation.meta)) {\n throw new TypeError(`Field implementation '${id}' meta must be a Standard Schema.`);\n }\n if (Object.values(renderers).every((renderer) => renderer === undefined)) {\n throw new TypeError(`Field implementation '${id}' must define at least one render surface.`);\n }\n return Object.freeze({\n ...(implementation.Input === undefined ? {} : { Input: implementation.Input }),\n ...(implementation.Display === undefined ? {} : { Display: implementation.Display }),\n ...(implementation.CollectionInput === undefined\n ? {}\n : { CollectionInput: implementation.CollectionInput }),\n ...(implementation.CollectionDisplay === undefined\n ? {}\n : { CollectionDisplay: implementation.CollectionDisplay }),\n ...(implementation.layout === undefined\n ? {}\n : { layout: copyLayout(implementation.layout, id) }),\n ...(implementation.meta === undefined ? {} : { meta: implementation.meta }),\n });\n}\n\n/**\n * Compose immutable host catalogs. Later catalogs intentionally override\n * earlier ones, so an application can layer a local implementation over a\n * shared package catalog without mutating either input.\n */\nexport function composeFieldImplementations(\n ...catalogs: readonly FieldImplementationCatalog[]\n): FieldImplementationCatalog {\n const output: Record<string, FieldImplementation<any, any>> = {};\n for (const catalog of catalogs) {\n if (catalog === null || typeof catalog !== 'object' || Array.isArray(catalog)) {\n throw new TypeError('Field implementations must be a record keyed by implementation ID.');\n }\n for (const [id, implementation] of Object.entries(catalog)) {\n output[id] = copyImplementation(id, implementation);\n }\n }\n return Object.freeze(output);\n}\n","import { createContext, useContext, useMemo, type ReactElement, type ReactNode } from 'react';\nimport {\n EMPTY_FIELD_IMPLEMENTATIONS,\n composeFieldImplementations,\n type FieldImplementationCatalog,\n} from './definitions.js';\n\nconst FieldImplementationCatalogContext = createContext<FieldImplementationCatalog | null>(null);\n\nexport interface FieldImplementationProviderProps {\n readonly fieldImplementations?: FieldImplementationCatalog;\n readonly children: ReactNode;\n}\n\n/**\n * A host-local implementation boundary. Unlike the retired attachment path,\n * this never subscribes to or mutates an AppRuntime; one SSR tree cannot\n * publish code into another tree.\n */\nexport function FieldImplementationProvider({\n fieldImplementations = EMPTY_FIELD_IMPLEMENTATIONS,\n children,\n}: FieldImplementationProviderProps): ReactElement {\n const catalog = useMemo(\n () => composeFieldImplementations(fieldImplementations),\n [fieldImplementations],\n );\n return (\n <FieldImplementationCatalogContext.Provider value={catalog}>\n {children}\n </FieldImplementationCatalogContext.Provider>\n );\n}\n\nexport function useFieldImplementationCatalog(): FieldImplementationCatalog {\n const catalog = useContext(FieldImplementationCatalogContext);\n if (catalog === null) {\n throw new Error(\n 'useFieldImplementation must be used within a BuroProvider or FieldImplementationProvider.',\n );\n }\n return catalog;\n}\n\n/**\n * The catalogue, or `null` outside a provider. A form controller reads it to decide a field's\n * `meta` schema outcome for the plan; a tree without a catalogue has no schema to apply.\n *\n * @internal\n */\nexport function useOptionalFieldImplementationCatalog(): FieldImplementationCatalog | null {\n return useContext(FieldImplementationCatalogContext);\n}\n","import type {\n DataSessionController,\n DataSessionSnapshot,\n DataSessionTransitionParticipant,\n SessionRotationReason,\n} from '@burojs/core';\nimport { useEffect, useRef } from 'react';\nimport { useOptionalDataRuntime } from './context.js';\n\n/** What a session participant does on a transition (a rotation or a scope change). */\nexport type SessionTransitionListener = (\n next: DataSessionSnapshot,\n previous: DataSessionSnapshot,\n reason: SessionRotationReason | undefined,\n) => void | Promise<void>;\n\n/**\n * Registers `participant` with `session` while ready: a session in transition accepts no new\n * participant, so the registration waits for the next ready state. Returns the unregistration.\n */\nfunction registerWhenReady(\n session: DataSessionController,\n participant: DataSessionTransitionParticipant,\n): () => void {\n let unregister: (() => void) | undefined;\n let unsubscribe: (() => void) | undefined;\n let closed = false;\n const attempt = (): boolean => {\n if (closed || session.getState().status !== 'ready') return false;\n try {\n unregister = session.registerParticipant(participant);\n return true;\n } catch {\n return false;\n }\n };\n if (!attempt()) {\n try {\n unsubscribe = session.subscribe(() => {\n if (unregister === undefined && attempt()) unsubscribe?.();\n });\n } catch {\n // A disposed session has no transitions to take part in.\n }\n }\n return () => {\n closed = true;\n unsubscribe?.();\n try {\n unregister?.();\n } catch {\n // A session mid-transition or disposed: the participant goes with it.\n }\n };\n}\n\n/**\n * Takes part in the mounted data session's transitions with `listener` (it reads the latest one).\n * Registered in an effect, so a React StrictMode remount registers again (Known finding 20). A\n * tree without a native data runtime has no session: nothing is registered.\n * @internal\n */\nexport function useSessionParticipant(listener: SessionTransitionListener): void {\n const runtime = useOptionalDataRuntime();\n const session = runtime?.dataSession;\n const latest = useRef(listener);\n latest.current = listener;\n useEffect(() => {\n if (session === undefined) return;\n return registerWhenReady(session, {\n abort() {},\n transition(next, previous, reason) {\n return latest.current(next, previous, reason);\n },\n dispose() {},\n });\n }, [session]);\n}\n","'use client';\nimport {\n type CompiledFlow,\n compileFlow,\n dtoFields,\n type FlowControlState,\n type PortableFieldCondition,\n type Row,\n resolveFlowGate,\n ruleContextFor,\n} from '@burojs/core';\nimport {\n conditionRefs,\n evaluateCondition,\n flowCheckList,\n interpolateParams,\n isPreClickCheck,\n isUndecided,\n} from '@burojs/core/internal';\nimport {\n createContext,\n createElement,\n type ReactElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react';\nimport { useOptionalDataRuntime } from '../data/context.js';\nimport {\n isErrorSlot,\n isSignedOut,\n readPermissions,\n useContextSnapshot,\n} from '../forms/controller/use-source-resolver.js';\nimport { useCurrentUserId } from '../hooks/use-current-user-id.js';\nimport { useFlowAttemptsStore } from './attempts-binding.js';\nimport { useMany } from '../hooks/data/use-many.js';\nimport { useApp } from '../hooks/use-app.js';\nimport { useOptionalT } from '../hooks/use-t.js';\n\n/**\n * One row's record as the flows of a list page see it (plan ruling 15): `covered` — every ref the\n * row flows' `when` and pre-click checks read is a field of the list DTO, so the list row is\n * the record; `ready` — the page's one batched read returned this row (`row`); `pending` — that\n * read has not answered for this id (or the id is not in the page's batch, Known finding 21).\n */\nexport interface FlowRowState {\n readonly status: 'covered' | 'pending' | 'ready';\n readonly row?: Row;\n}\n\nconst COVERED: FlowRowState = Object.freeze({ status: 'covered' });\nconst PENDING: FlowRowState = Object.freeze({ status: 'pending' });\n\n/** The sources a row's pre-click decision may read without a request. */\nconst ROW_SOURCES = new Set(['record', 'scope', 'args', 'values']);\n\n/** The refs a flow's row decision reads: its `when` and its pre-click checks. */\nfunction rowRefs(flow: CompiledFlow, checks: ReturnType<typeof flowCheckList>) {\n const refs = [...conditionRefs(flow.flow.when)];\n for (const check of checks)\n if (isPreClickCheck(check)) refs.push(...conditionRefs(check.when as PortableFieldCondition));\n return refs;\n}\n\n/** An id a read may address (Known finding 1). */\nfunction validId(value: unknown): string | undefined {\n if (typeof value === 'string') return value === '' ? undefined : value;\n if (typeof value === 'number' && Number.isFinite(value)) return String(value);\n return undefined;\n}\n\n/** Whether a page's row flows read past the list DTO in `when` or a pre-click check. */\nfunction useNeedsBatch(resource: string, flows: readonly CompiledFlow[]): boolean {\n const app = useApp();\n const context = useContextSnapshot();\n const permissions = readPermissions(context);\n const def = app.registry.get(resource);\n return useMemo(() => {\n if (def === undefined || flows.length === 0) return false;\n // Decided before anything is read (4.17, P4-C review I2): nothing while the permission map\n // loads, and only for the row flows the user may run at all.\n if (permissions?.status === 'loading') return false;\n const list = new Set(dtoFields(def as never, 'list'));\n return flows.some((flow) => {\n const gate = resolveFlowGate({\n app,\n resource: flow.resource,\n flow,\n ctx: ruleContextFor({\n ...(flow.resource === null ? {} : { resource: flow.resource }),\n mode: 'list',\n user: context.user as never,\n scope: context.scope as never,\n ...(permissions === undefined ? {} : { permissions }),\n }),\n permissionsStatus: permissions?.status as 'loading' | 'ready' | 'error' | undefined,\n });\n if (gate.state !== 'available' && gate.state !== 'disabled') return false;\n return rowRefs(flow, flowCheckList(flow, app.checkSource)).some(\n (ref) => ref.source === 'record' && !list.has(String(ref.path[0] ?? '')),\n );\n });\n }, [def, flows, app, permissions, context.user, context.scope]);\n}\n\n/** The page's batch as it answered: the ids it was asked for and the rows it returned. */\ninterface BatchAnswer {\n readonly key: string;\n readonly rows: readonly Row[];\n}\n\n/** One native `many` over the page's ids; reports its rows once it answered. Renders nothing. */\nfunction BatchRead({\n resource,\n ids,\n batchKey,\n onAnswer,\n}: {\n readonly resource: string;\n readonly ids: readonly string[];\n readonly batchKey: string;\n readonly onAnswer: (answer: BatchAnswer) => void;\n}): null {\n const query = useMany(resource, { ids, enabled: ids.length > 0, retry: false }) as {\n readonly data?: { readonly data?: readonly Row[] };\n };\n const rows = query.data?.data;\n useEffect(() => {\n if (rows !== undefined) onAnswer(Object.freeze({ key: batchKey, rows }));\n }, [rows, batchKey, onAnswer]);\n return null;\n}\n\n/**\n * The per-page batched pre-click read of a list (P4 spec 4.17, I8; plan ruling 15): one per\n * list page, around its rows. When every ref the page's row flows read in `when` and their\n * pre-click checks is a field of the list DTO, nothing is read and every row is `covered`;\n * otherwise the page's ids are read in ONE `many` (the runtime's query key holds the session,\n * the scope, the resource and the ids) and a row is `pending` until the read made for THIS page's\n * ids answered for it (Known finding 21: another page's answer never decides a row). A `with`\n * source is never read here: it loads at the click, or when a row menu opens.\n */\nexport function useFlowRowBatch(\n resource: string,\n ids: readonly string[],\n flows: readonly CompiledFlow[],\n): { readonly state: (id: string) => FlowRowState; readonly reader: ReactElement | null } {\n const app = useApp();\n const runtime = useOptionalDataRuntime();\n const needsBatch = useNeedsBatch(resource, flows);\n const pageIds = useMemo(\n () => [...new Set(ids.map(validId).filter((id): id is string => id !== undefined))].sort(),\n [ids],\n );\n const batchKey = pageIds.join('\\u0000');\n const [answer, setAnswer] = useState<BatchAnswer | null>(null);\n const def = app.registry.get(resource);\n const idField = (def?.data as { readonly idField?: string } | undefined)?.idField ?? 'id';\n const byId = useMemo(() => {\n const out = new Map<string, Row>();\n if (answer === null || answer.key !== batchKey) return out;\n // Only the ids this page asked for: a row of another id is never applied (Known finding 13).\n for (const row of answer.rows) {\n const id = validId(row[idField] ?? row.id);\n if (id !== undefined && pageIds.includes(id)) out.set(id, row);\n }\n return out;\n }, [answer, batchKey, idField, pageIds]);\n const state = useCallback(\n (id: string): FlowRowState => {\n if (!needsBatch) return COVERED;\n const row = byId.get(id);\n return row === undefined ? PENDING : Object.freeze({ status: 'ready', row });\n },\n [needsBatch, byId],\n );\n const reader =\n needsBatch && runtime !== null && pageIds.length > 0\n ? createElement(BatchRead, {\n key: batchKey,\n resource,\n ids: pageIds,\n batchKey,\n onAnswer: setAnswer,\n })\n : null;\n return { state, reader };\n}\n\n/** @internal The list page's batch, for the row flows below it. */\nexport interface FlowRowBatchValue {\n readonly resource: string;\n readonly state: (id: string) => FlowRowState;\n}\n\n/** @internal Provided by the list page (`ResourceList`) around its rows. */\nexport const FlowRowBatchContext = createContext<FlowRowBatchValue | null>(null);\n\n/** What a row (or a record surface without a run) shows for one flow, before any click. */\nexport interface FlowRowControl {\n readonly state: FlowControlState;\n readonly reason?: string;\n /** The record the flow runs on: the batch's row when it read one, else the given row. */\n readonly record?: Row;\n /**\n * Why an `absent` control is absent: the flow's gate (no oracle: indistinguishable from a flow\n * that does not exist) or its own `when` over this record. A page-hosted flow's route answers\n * the first with not-found and the second with \"not available\" (P6).\n */\n readonly cause?: 'gate' | 'when';\n}\n\nconst ABSENT: FlowRowControl = Object.freeze({ state: 'absent' });\nconst ABSENT_BY_WHEN: FlowRowControl = Object.freeze({ state: 'absent', cause: 'when' });\n\n/**\n * @internal What a flow's control shows on a row, decided without a run and without a request\n * (4.17, I8): the gate (undecided while permissions load), then the row's batch state (pending\n * until the page's one read answered), then `when` and the pre-click checks over the row. A\n * condition reading a `with` name is decided at click, when the run reads it.\n */\nexport function useFlowRowResolver(\n resource: string,\n): (name: string, record: Row | undefined) => FlowRowControl {\n const app = useApp();\n const context = useContextSnapshot();\n const batch = useContext(FlowRowBatchContext);\n const hasRuntime = useOptionalDataRuntime() !== null;\n const userId = useCurrentUserId();\n const store = useFlowAttemptsStore();\n // The run's own condition (`useFlowRun`): signed out for certain, or the user's store is up.\n const userKnown =\n userId === null ? isSignedOut(context) : store !== null && store.user === userId;\n // The user lookup failed: no run can be built, and the control says so (not busy forever).\n const userFailed = userId === null && isErrorSlot(context.user);\n const t = useOptionalT();\n const permissions = readPermissions(context);\n // No resource (an app flow asking through `useAction`): nothing to resolve a row against.\n const def = resource === '' ? undefined : app.registry.get(resource);\n const compiledByName = useMemo(() => {\n const out = new Map<string, CompiledFlow | null>();\n return (name: string): CompiledFlow | null => {\n if (!out.has(name)) {\n let compiled: CompiledFlow | null = null;\n try {\n compiled = def === undefined ? null : compileFlow(def as never, name);\n } catch {\n compiled = null;\n }\n out.set(name, compiled);\n }\n return out.get(name) ?? null;\n };\n }, [def]);\n return useCallback(\n (name: string, record: Row | undefined): FlowRowControl => {\n const compiled = compiledByName(name);\n if (compiled === null) return ABSENT;\n // A run can only be built over a data runtime, and over the attempts store of a known\n // user (P4-C review M2): without one, the control says so rather than spin after a click.\n if (!hasRuntime)\n return Object.freeze({\n state: 'disabled',\n reason:\n t('flow.unavailable') === 'flow.unavailable' ? 'Not allowed.' : t('flow.unavailable'),\n });\n if (!userKnown)\n return userFailed\n ? Object.freeze({\n state: 'disabled',\n reason:\n t('flow.couldNotCheck') === 'flow.couldNotCheck'\n ? \"Couldn't check\"\n : t('flow.couldNotCheck'),\n })\n : Object.freeze({ state: 'undecided' });\n const gate = resolveFlowGate({\n app,\n resource: compiled.resource,\n flow: compiled,\n ctx: ruleContextFor({\n ...(record === undefined ? {} : { record }),\n ...(compiled.resource === null ? {} : { resource: compiled.resource }),\n mode: record === undefined ? 'list' : 'show',\n user: context.user as never,\n scope: context.scope as never,\n ...(permissions === undefined ? {} : { permissions }),\n }),\n permissionsStatus: permissions?.status as 'loading' | 'ready' | 'error' | undefined,\n });\n if (gate.state === 'undecided') return Object.freeze({ state: 'undecided' });\n if (gate.state === 'absent' || gate.state === 'hidden') return ABSENT;\n if (gate.state === 'disabled')\n return Object.freeze({\n state: 'disabled',\n ...(gate.reason === undefined ? {} : { reason: gate.reason }),\n });\n let row = record;\n if (record !== undefined && batch !== null && batch.resource === resource) {\n const id = validId(record[compiled.idField] ?? record.id);\n const answer = id === undefined ? PENDING : batch.state(id);\n if (answer.status === 'pending') return Object.freeze({ state: 'pending' });\n if (answer.status === 'ready') row = answer.row;\n }\n const ready = (value: unknown) =>\n Object.freeze({ status: 'ready', value, refreshing: false });\n const sources = {\n record: ready(row),\n values: ready({}),\n scope: ready(context.scope ?? {}),\n args: ready({}),\n } as const;\n const decidable = (condition: PortableFieldCondition) =>\n conditionRefs(condition).every((ref) => ROW_SOURCES.has(ref.source));\n const when = compiled.flow.when;\n if (when !== undefined && decidable(when)) {\n const shown = evaluateCondition(when, sources as never, { mode: 'edit' });\n if (isUndecided(shown)) return Object.freeze({ state: 'pending' });\n if (shown !== true) return ABSENT_BY_WHEN;\n }\n for (const check of flowCheckList(compiled, app.checkSource)) {\n if (!isPreClickCheck(check)) continue;\n const condition = check.when as PortableFieldCondition;\n if (!decidable(condition)) continue;\n const fired = evaluateCondition(condition, sources as never, { mode: 'edit' });\n if (isUndecided(fired)) return Object.freeze({ state: 'pending' });\n if (fired === true) {\n const key = `checks.${check.id}`;\n const translated = t(key);\n const message = translated === key ? check.message : translated;\n return Object.freeze({\n state: 'disabled',\n reason: interpolateParams(String(message), check.params, {\n record: row,\n scope: context.scope,\n args: {},\n }),\n ...(row === undefined ? {} : { record: row }),\n });\n }\n }\n return Object.freeze({ state: 'ready', ...(row === undefined ? {} : { record: row }) });\n },\n [\n app,\n compiledByName,\n context.user,\n context.scope,\n permissions,\n batch,\n resource,\n t,\n hasRuntime,\n userKnown,\n userFailed,\n ],\n );\n}\n","import {\n type AnyBlockHandle,\n type ApplicationSnapshot,\n type CompiledScreen,\n type EntityRef,\n type EntryRowsRead,\n type NodeState,\n type PortableBlockDeclaration,\n type PropValidation,\n type QuerySource,\n type SourceState,\n type TrustedAttachmentCatalog,\n formatEntityRef,\n hydrateBlock,\n resolveEntries,\n resolvePlacementProps,\n snapshotBlockLookup,\n validatePlacementProps,\n} from '@burojs/core';\n\n/** What the resolver knows of one placement at mount (spec 8.1, decision 35). */\nexport interface PlacementRuntime {\n readonly key: string;\n readonly block: EntityRef;\n /** Over props, validation and `data` entries: absent > pending > failed > ready. */\n readonly state: NodeState;\n /**\n * `'access'`: absent because a required prop reads a field its user may not view (P5 spec\n * 3.6.3) — no view mounts, no block `data` is read, and the plan's reason is `access`.\n */\n readonly reason?: 'access';\n readonly error?: unknown;\n /** Whether Retry can help: a failed read, never a refused prop or a missing definition. */\n readonly retryable: boolean;\n /** The validated props (each schema's output), once ready. */\n readonly props?: Readonly<Record<string, unknown>>;\n /** The ready `data` entry values. */\n readonly data: Readonly<Record<string, unknown>>;\n /** A development error to report once (`block.prop-invalid`, `block.data-order`). */\n readonly problem?: { readonly code: string; readonly message: string };\n /** The block handle (the view's `t` and a test read its definition). */\n readonly definition?: AnyBlockHandle;\n}\n\n/** Reads the resolver's sources and queries on behalf of a placement. */\nexport interface PlacementReads {\n read(source: string, path: readonly string[], owner: string): SourceState;\n /** `peek`: read the cache without requesting (a placement outside `blockDemand`). */\n query(owner: string, source: QuerySource, peek: boolean): SourceState;\n /** A `source.one` a `data` entry returned, read as a `with` source reads it (spec 4.4). */\n one(owner: string, source: Extract<EntryRowsRead, { kind: 'one' }>, peek: boolean): SourceState;\n /** A `source.list` a `data` entry returned. */\n list(owner: string, source: Extract<EntryRowsRead, { kind: 'list' }>, peek: boolean): SourceState;\n}\n\n/** Async prop validations, kept across renders by placement key. */\nexport type ValidationCache = Map<\n string,\n { readonly input: string; result: PropValidation; readonly settled?: Promise<unknown> }\n>;\n\nconst NO_DATA: Readonly<Record<string, unknown>> = Object.freeze({});\n\nconst handles = new WeakMap<ApplicationSnapshot, Map<string, AnyBlockHandle | null>>();\n\n/** A placed block's trusted definition, hydrated once per snapshot. */\nfunction hydrated(\n snapshot: ApplicationSnapshot,\n attachments: TrustedAttachmentCatalog,\n ref: EntityRef,\n): AnyBlockHandle | undefined {\n let bySnapshot = handles.get(snapshot);\n if (bySnapshot === undefined) {\n bySnapshot = new Map();\n handles.set(snapshot, bySnapshot);\n }\n const id = formatEntityRef(ref);\n if (!bySnapshot.has(id)) bySnapshot.set(id, hydrateBlock(snapshot, attachments, ref) ?? null);\n return bySnapshot.get(id) ?? undefined;\n}\n\n/** A stable text of a resolved prop map, for the validation cache. */\nfunction inputKey(value: unknown): string {\n try {\n return JSON.stringify(value) ?? '';\n } catch {\n return String(Math.random());\n }\n}\n\n/**\n * Every placement of a compiled screen at mount (spec 8.1): its block definition (fail closed\n * when the snapshot cannot hydrate it), its props read and validated (decision 35), and — only\n * for a placement `blockDemand` lists — its `data` entries resolved through the resolver's pool.\n * `onSettled` re-renders when an asynchronous validation settles.\n */\nexport function resolvePlacements(args: {\n readonly compiled: CompiledScreen;\n readonly snapshot: ApplicationSnapshot;\n readonly attachments: TrustedAttachmentCatalog;\n readonly reads: PlacementReads;\n readonly demanded: ReadonlySet<string>;\n readonly validations: ValidationCache;\n readonly onSettled: () => void;\n /** A source's whole-row DTO fields (decision 41); `undefined` passes a row unprojected. */\n readonly project: (source: string) => readonly string[] | undefined;\n}): Readonly<Record<string, PlacementRuntime>> {\n const { compiled, snapshot, reads, demanded, validations } = args;\n const lookup = snapshotBlockLookup(snapshot);\n const out: Record<string, PlacementRuntime> = Object.create(null);\n for (const node of compiled.nodes) {\n if (node.kind !== 'place' || node.key === undefined || node.placement === undefined) continue;\n const key = node.key;\n const block = node.placement.block;\n const owner = `block:${key}`;\n const fail = (\n error: unknown,\n retryable: boolean,\n problem?: PlacementRuntime['problem'],\n ): PlacementRuntime =>\n Object.freeze({\n key,\n block,\n state: 'failed' as const,\n error,\n retryable,\n data: NO_DATA,\n ...(problem === undefined ? {} : { problem }),\n });\n let declaration: PortableBlockDeclaration | undefined;\n try {\n declaration = lookup(block);\n } catch {\n declaration = undefined;\n }\n const definition =\n declaration === undefined ? undefined : hydrated(snapshot, args.attachments, block);\n if (declaration === undefined || definition === undefined) {\n out[key] = fail(new Error(`The block ${formatEntityRef(block)} is not available.`), false);\n continue;\n }\n // An item placement (or one nested in it) is drawn once per row by the list that owns it:\n // its props read the `item` source, which only that list binds. Here it only holds its\n // definition; the row's props are resolved and validated where the row is (P6 3.13).\n if (node.placement.host?.itemOf !== undefined) {\n out[key] = Object.freeze({\n key,\n block,\n state: 'ready',\n retryable: false,\n props: Object.freeze({}),\n data: NO_DATA,\n definition,\n });\n continue;\n }\n const resolved = resolvePlacementProps(\n declaration,\n node.placement.props,\n (source, path) => reads.read(source, path, owner),\n compiled.mode,\n args.project,\n );\n if (resolved.status === 'pending') {\n out[key] = Object.freeze({\n key,\n block,\n state: 'pending',\n retryable: false,\n data: NO_DATA,\n definition,\n });\n continue;\n }\n if (resolved.status === 'failed') {\n out[key] = fail(resolved.error, true);\n continue;\n }\n // A required prop reads a field its user may not view (P5 spec 3.6.3): absent, never failed.\n if (resolved.status === 'absent') {\n out[key] = Object.freeze({\n key,\n block,\n state: 'absent',\n reason: 'access',\n retryable: false,\n data: NO_DATA,\n definition,\n });\n continue;\n }\n // Props are validated at mount, literals and resolved refs alike (decision 35).\n const text = inputKey(resolved.value);\n let cached = validations.get(key);\n if (cached === undefined || cached.input !== text) {\n const result = validatePlacementProps(definition, resolved.value);\n const entry: { input: string; result: PropValidation; settled?: Promise<unknown> } = {\n input: text,\n result,\n };\n if (result.status === 'pending')\n entry.settled = result.settled.then((settled) => {\n if (validations.get(key) !== entry) return;\n entry.result = settled;\n args.onSettled();\n });\n validations.set(key, entry);\n cached = entry;\n }\n const validation = cached.result;\n if (validation.status === 'pending') {\n out[key] = Object.freeze({\n key,\n block,\n state: 'pending',\n retryable: false,\n data: NO_DATA,\n definition,\n });\n continue;\n }\n if (validation.status === 'failed') {\n const message = `block.prop-invalid: the placement ${key} of ${formatEntityRef(block)} sets ${validation.prop}, which its schema refuses: ${validation.reason}.`;\n out[key] = fail(Object.assign(new Error(message), { code: 'block.prop-invalid' }), false, {\n code: 'block.prop-invalid',\n message,\n });\n continue;\n }\n const props = validation.props;\n if (definition.data.length === 0) {\n out[key] = Object.freeze({\n key,\n block,\n state: 'ready',\n retryable: false,\n props,\n data: NO_DATA,\n definition,\n });\n continue;\n }\n // A placement outside `blockDemand` (a closed tab, a denied or pending panel) requests\n // nothing: it reads only what the cache already holds.\n const peek = !demanded.has(key);\n let entries: ReturnType<typeof resolveEntries>;\n let firstError: unknown;\n try {\n entries = resolveEntries(definition.data, props, {\n read: (source) => {\n const state =\n source.kind === 'query'\n ? reads.query(owner, source, peek)\n : source.kind === 'one'\n ? reads.one(owner, source, peek)\n : reads.list(owner, source, peek);\n if (state.status === 'failed' && firstError === undefined) firstError = state.error;\n return state;\n },\n });\n } catch (error) {\n const code = (error as { readonly code?: unknown }).code;\n const message = error instanceof Error ? error.message : String(error);\n out[key] = fail(\n error,\n false,\n typeof code === 'string' ? { code, message: `${code}: ${message}` } : undefined,\n );\n continue;\n }\n out[key] = Object.freeze({\n key,\n block,\n state: entries.state,\n retryable: entries.failed.length > 0,\n ...(entries.state === 'failed' ? { error: firstError } : {}),\n props,\n data: entries.data,\n definition,\n });\n }\n return Object.freeze(out);\n}\n\n/** The state of each placement for `planScreen`'s `blockData`. */\nexport function blockDataOf(\n placements: Readonly<Record<string, PlacementRuntime>>,\n): Readonly<Record<string, NodeState>> {\n const out: Record<string, NodeState> = Object.create(null);\n for (const [key, placement] of Object.entries(placements)) out[key] = placement.state;\n return Object.freeze(out);\n}\n","import {\n type DataError,\n type ErasedQueryDescriptor,\n normalizeDataError,\n queryKeyFor,\n} from '@burojs/core';\nimport { type QueryClient, useQueries } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { useDataRuntime } from '../../data/context.js';\nimport { type LiveQueryRetention, sessionGenerationOf } from '../../data/live/live-queries.js';\nimport { retryRecordRead } from '../../hooks/data/retry-record-read.js';\n\n/** One request of a screen's resolver: a descriptor, keyed by `queryKeyFor`. */\nexport interface PoolRequest {\n /** `JSON.stringify(queryKeyFor(descriptor))`. */\n readonly key: string;\n readonly descriptor: ErasedQueryDescriptor;\n}\n\n/** What a request holds in the cache right now. */\nexport type PoolState =\n | { readonly status: 'pending' }\n | {\n readonly status: 'ready';\n readonly data: unknown;\n readonly fetching: boolean;\n readonly error?: DataError;\n }\n | { readonly status: 'failed'; readonly error: DataError };\n\nconst PENDING: PoolState = Object.freeze({ status: 'pending' });\n\n/**\n * The requests one render of the resolver reads, deduplicated by query key: every `record`,\n * `with` hop and block `data` entry with an equal descriptor is one request (spec §7).\n */\nexport class PoolCollector {\n readonly #client: QueryClient;\n readonly #requests = new Map<string, PoolRequest>();\n\n constructor(client: QueryClient) {\n this.#client = client;\n }\n\n /** Registers `descriptor` as requested and returns the state its query holds now. */\n read(descriptor: ErasedQueryDescriptor): { readonly key: string; readonly state: PoolState } {\n return this.#state(descriptor, true);\n }\n\n /**\n * The state `descriptor`'s query holds now, without requesting it: what a placement outside\n * `blockDemand` may still show from the cache (its `absent()` answer stays absent), never a fetch.\n */\n peek(descriptor: ErasedQueryDescriptor): { readonly key: string; readonly state: PoolState } {\n return this.#state(descriptor, false);\n }\n\n #state(\n descriptor: ErasedQueryDescriptor,\n request: boolean,\n ): { readonly key: string; readonly state: PoolState } {\n const queryKey = queryKeyFor(descriptor);\n const key = JSON.stringify(queryKey);\n if (request && !this.#requests.has(key))\n this.#requests.set(key, Object.freeze({ key, descriptor }));\n const state = this.#client.getQueryState(queryKey);\n if (state === undefined) return { key, state: PENDING };\n if (state.data !== undefined)\n return {\n key,\n state: Object.freeze({\n status: 'ready',\n data: state.data,\n fetching: state.fetchStatus === 'fetching',\n ...(state.error === null ? {} : { error: normalizeDataError(state.error) }),\n }),\n };\n if (state.status === 'error' && state.fetchStatus !== 'fetching')\n return {\n key,\n state: Object.freeze({ status: 'failed', error: normalizeDataError(state.error) }),\n };\n return { key, state: PENDING };\n }\n\n get requests(): readonly PoolRequest[] {\n return [...this.#requests.values()];\n }\n}\n\nconst NO_UNSUBSCRIBE = () => undefined;\n\n/**\n * Mounts one observer per request (spec §7, the resolver's pool): each retains the runtime's\n * shared live observer of its descriptor (`runtime.liveQueries`) and runs through TanStack under\n * its `queryKeyFor` key, so a `useOne` of the same record elsewhere is the same request. Every\n * request retries as a record read does (`retryRecordRead`). Returns `refetch(keys)`.\n */\nexport function useQueryPool(requests: readonly PoolRequest[]): (keys: readonly string[]) => void {\n const runtime = useDataRuntime();\n const generation = useSyncExternalStore(\n runtime.dataSession.subscribe,\n () => sessionGenerationOf(runtime.dataSession),\n () => sessionGenerationOf(runtime.dataSession),\n );\n const held = useRef(new Map<string, LiveQueryRetention>());\n const [version, setVersion] = useState(0);\n const keys = requests.map((request) => request.key).join('\\n');\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the request keys and the session generation\n useEffect(() => {\n const map = held.current;\n const wanted = new Map(requests.map((request) => [`${generation}:${request.key}`, request]));\n let changed = false;\n for (const [key, retention] of map)\n if (!wanted.has(key)) {\n retention.release();\n map.delete(key);\n changed = true;\n }\n for (const [key, request] of wanted)\n if (!map.has(key)) {\n map.set(key, runtime.liveQueries.retain(request.descriptor));\n changed = true;\n }\n if (changed) setVersion((value) => value + 1);\n }, [keys, generation, runtime]);\n useEffect(\n () => () => {\n for (const retention of held.current.values()) retention.release();\n held.current.clear();\n },\n [],\n );\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-subscribes when the held set changes\n const subscribe = useCallback(\n (onChange: () => void) => {\n const offs = [...held.current.values()].map((retention) =>\n retention.observer.subscribe(onChange),\n );\n return offs.length === 0\n ? NO_UNSUBSCRIBE\n : () => {\n for (const off of offs) off();\n };\n },\n [version],\n );\n const enabledOf = (key: string) =>\n held.current.get(`${generation}:${key}`)?.observer.queryEnabled === true;\n const flags = useSyncExternalStore(\n subscribe,\n () => requests.map((request) => (enabledOf(request.key) ? '1' : '0')).join(''),\n () => '',\n );\n useQueries({\n queries: requests.map((request, index) => ({\n queryKey: queryKeyFor(request.descriptor),\n queryFn: runtime.liveQueries.queryFn(request.descriptor) as (context: {\n readonly signal: AbortSignal;\n }) => Promise<unknown>,\n retry: retryRecordRead as (failureCount: number, error: unknown) => boolean,\n enabled: flags[index] === '1',\n })),\n });\n const { queryClient } = runtime;\n return useCallback(\n (refetchKeys: readonly string[]) => {\n for (const key of refetchKeys)\n void queryClient.refetchQueries({ queryKey: JSON.parse(key) as unknown[], exact: true });\n },\n [queryClient],\n );\n}\n","import { useSyncExternalStore } from 'react';\nimport type { InlineFlowHolder } from '../../flows/inline-holder.js';\nimport { useDismissPending } from '../../navigation/dismiss-scope.js';\nimport { useNavigationBlocker, useNavigationHold } from '../../navigation/navigation-guard.js';\n\n/** One label for the guard: the hidden inline flows' names, joined (P6 3.12, ruling 16). */\nfunction labelOf(labels: readonly string[]): string | undefined {\n return labels.length === 0 ? undefined : [...new Set(labels)].join(', ');\n}\n\n/**\n * The screen's guard for the inline flows whose node is not on screen (a placement a `when`\n * hid, a tab panel switched away): their unsaved input still blocks leaving, labelled so the\n * prompt names the action; their write in flight still locks the enclosing dismiss scope and\n * holds every route change. Held by the screen, not by the node (Known finding 20: registered\n * in effects, so a StrictMode remount registers them again).\n * @internal\n */\nexport function InlineBlockers({ holder }: { readonly holder: InlineFlowHolder }): null {\n useSyncExternalStore(holder.subscribe, holder.version, holder.version);\n const { labels, locked } = holder.guarded();\n const label = labelOf(labels);\n useNavigationBlocker(label !== undefined, label === undefined ? {} : { label });\n useDismissPending(locked);\n useNavigationHold(locked);\n return null;\n}\n","import type { FlowRun } from '@burojs/core';\n\n/**\n * What an inline flow placement keeps beyond the lifetime of its node (P6 3.12): the run, so that\n * switching a tab away and back, or a re-render of the tree, neither loses what was typed nor\n * starts a second attempt. `useFlowRun` fills `run` and `deps` through its `lease` option.\n * @internal\n */\nexport interface InlineLease {\n /** The placement's key on its screen. */\n readonly key: string;\n readonly flowId: string;\n readonly record: string;\n /** The run the lease holds; created by the first `useFlowRun` that takes the lease. */\n run: FlowRun | null;\n /** What the run was built for; a change builds a new run in the lease. */\n deps: string | null;\n /** Whether the run was opened (its gate asked) already. */\n opened: boolean;\n /** The run's values when it opened, as JSON: what \"dirty\" is measured against. */\n initial?: string;\n /** The flow's label, for the guard's text when the node is not on screen. */\n label: string;\n /** Unsaved input, or an unresolved attempt: set by the host from the run's snapshots. */\n dirty: boolean;\n /** A write is in flight. */\n locked: boolean;\n /** How many nodes currently show this lease. */\n mounted: number;\n}\n\n/**\n * The screen-held state of inline flows (P6 3.12): one lease per placement key, and the registry of\n * which flow-and-record slot a mounted screen holds, so a second screen showing the same record\n * (a quick sheet over the page) draws the flow's button instead of a second form. A slot is the\n * attempt slot of P4: `(user, flow, record)`.\n * @internal\n */\nexport interface InlineFlowHolder {\n /**\n * The placement's lease, created on the first call and kept; or `'held-elsewhere'` when another\n * mounted holder already holds the slot. `user` is the signed-in user's id (`''` without one).\n */\n acquire(\n key: string,\n flowId: string,\n record: string,\n user?: string,\n ): InlineLease | 'held-elsewhere';\n /** Whether the screen places `flowId` inline: the flow's own button is not drawn on it. */\n suppressed(flowId: string): boolean;\n /** The lease of `key` if the screen holds one (no acquisition). */\n get(key: string): InlineLease | undefined;\n /** Replaces the set of flows the screen places inline (by flow name). */\n declare(flowNames: Iterable<string>): void;\n /** Frees the lease of `key`; a run with a write in flight is disposed once that write settles (the attempt store adopts it). */\n release(key: string): void;\n /**\n * Marks the holder mounted. The returned function marks it unmounted: the leases are released\n * after the commit, unless the holder was attached again (StrictMode's simulated unmount).\n */\n attach(): () => void;\n /** Tells the screen's blockers that a lease changed (dirty, locked, mounted). */\n touch(): void;\n subscribe(listener: () => void): () => void;\n /** Counts every change `touch` announced: the external store's version. */\n version(): number;\n /**\n * What the screen must guard for the leases whose node is not on screen: the labels of those\n * holding unsaved input, and whether any write is in flight.\n */\n guarded(): { readonly labels: readonly string[]; readonly locked: boolean };\n}\n\n/** The slot of each held lease, by the holder that holds it. Module-level: it spans screens. */\nconst slots = new Map<string, object>();\n\n/** @internal */\nexport function disposeWhenIdle(run: FlowRun): void {\n if (run.getSnapshot().control !== 'running') {\n run.dispose();\n return;\n }\n const stop = run.subscribe(() => {\n if (run.getSnapshot().control === 'running') return;\n stop();\n run.dispose();\n });\n}\n\n/** A fresh holder, one per screen instance. */\nexport function createInlineFlowHolder(): InlineFlowHolder {\n const self = {};\n const leases = new Map<string, InlineLease & { slot: string }>();\n let declared: ReadonlySet<string> = new Set();\n let attached = 0;\n let changes = 0;\n const listeners = new Set<() => void>();\n const touch = () => {\n changes += 1;\n for (const listener of [...listeners]) listener();\n };\n\n const release = (key: string) => {\n const lease = leases.get(key);\n if (lease === undefined) return;\n leases.delete(key);\n if (slots.get(lease.slot) === self) slots.delete(lease.slot);\n if (lease.run !== null) disposeWhenIdle(lease.run);\n touch();\n };\n\n return {\n acquire(key, flowId, record, user = '') {\n const known = leases.get(key);\n if (known !== undefined && known.flowId === flowId && known.record === record) return known;\n if (known !== undefined) release(key);\n const slot = `${user}\\u0000${flowId}\\u0000${record}`;\n const holder = slots.get(slot);\n if (holder !== undefined && holder !== self) return 'held-elsewhere';\n const lease = {\n key,\n flowId,\n record,\n slot,\n run: null,\n deps: null,\n opened: false,\n label: '',\n dirty: false,\n locked: false,\n mounted: 0,\n };\n slots.set(slot, self);\n leases.set(key, lease);\n return lease;\n },\n get: (key) => leases.get(key),\n suppressed: (flowId) => declared.has(flowId),\n declare(flowNames) {\n declared = new Set(flowNames);\n },\n release,\n touch,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n version: () => changes,\n guarded() {\n const labels: string[] = [];\n let locked = false;\n for (const lease of leases.values()) {\n if (lease.locked) locked = true;\n if (lease.dirty && lease.mounted === 0) labels.push(lease.label);\n }\n return { labels, locked };\n },\n attach() {\n attached += 1;\n return () => {\n attached -= 1;\n setTimeout(() => {\n if (attached > 0) return;\n for (const key of [...leases.keys()]) release(key);\n }, 0);\n };\n },\n };\n}\n","import type { PlanScreenInput } from '@burojs/core';\nimport { InlineBlockers } from './inline-blockers.js';\nimport { createInlineFlowHolder, type InlineFlowHolder } from '../../flows/inline-holder.js';\nimport {\n createContext,\n type ReactElement,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\n/**\n * Which panels of a screen are open: the `open` input of `planScreen` (P1b+P1c\n * decision 13), plus `expanded`: the `collapse: 'closed'` panels a user opened.\n * A host holds no screen, so it cannot list the panels a screen starts\n * collapsed; the controller adds every `collapse: 'closed'` panel that is not\n * in `expanded` to `collapsed` before it plans.\n */\nexport type ScreenOpenState = NonNullable<PlanScreenInput['open']> & {\n readonly expanded?: readonly string[];\n};\n\nexport interface ScreenStateValue {\n readonly open: ScreenOpenState;\n openPanel(containerId: string, panelKey: string): void;\n setCollapsed(containerId: string, collapsed: boolean): void;\n /** The inline flows this screen instance holds (P6 3.12); released when the screen unmounts. */\n readonly inline: InlineFlowHolder;\n}\n\nexport interface ScreenStateProviderProps {\n /** The uncontrolled start value. */\n readonly initialOpen?: ScreenOpenState;\n /**\n * Controlled: when given, the provider holds no state of its own and plans\n * this value, so a host can drive it after mount (URL tab state reaching\n * the plan).\n */\n readonly open?: ScreenOpenState;\n /** Called by `openPanel` and `setCollapsed`, controlled or not. */\n readonly onOpenChange?: (next: ScreenOpenState) => void;\n readonly children: ReactNode;\n}\n\nconst ScreenStateContext = createContext<ScreenStateValue | null>(null);\n\nconst CLOSED: ScreenOpenState = Object.freeze({\n containers: Object.freeze({}),\n collapsed: Object.freeze([]),\n});\n\nfunction withPanel(open: ScreenOpenState, containerId: string, panelKey: string): ScreenOpenState {\n return Object.freeze({\n ...open,\n containers: Object.freeze({ ...open.containers, [containerId]: panelKey }),\n });\n}\n\nfunction withCollapsed(\n open: ScreenOpenState,\n containerId: string,\n collapsed: boolean,\n): ScreenOpenState {\n const others = open.collapsed.filter((id) => id !== containerId);\n const expanded = (open.expanded ?? []).filter((id) => id !== containerId);\n return Object.freeze({\n containers: open.containers,\n collapsed: Object.freeze(collapsed ? [...others, containerId] : others),\n expanded: Object.freeze(collapsed ? expanded : [...expanded, containerId]),\n });\n}\n\n/**\n * Holds what is open on a screen (tabs, steps, collapsed panels) for the form\n * controller and the renderer below it. Controlled through `open` /\n * `onOpenChange`, or uncontrolled from `initialOpen`.\n */\nexport function ScreenStateProvider({\n initialOpen,\n open,\n onOpenChange,\n children,\n}: ScreenStateProviderProps): ReactElement {\n const [own, setOwn] = useState<ScreenOpenState>(() => initialOpen ?? CLOSED);\n const controlled = open !== undefined;\n const current = open ?? own;\n // The latest value, so two calls in one event compose.\n const latest = useRef(current);\n latest.current = current;\n const change = useCallback(\n (next: ScreenOpenState) => {\n latest.current = next;\n if (!controlled) setOwn(next);\n onOpenChange?.(next);\n },\n [controlled, onOpenChange],\n );\n const openPanel = useCallback(\n (containerId: string, panelKey: string) =>\n change(withPanel(latest.current, containerId, panelKey)),\n [change],\n );\n const setCollapsed = useCallback(\n (containerId: string, collapsed: boolean) =>\n change(withCollapsed(latest.current, containerId, collapsed)),\n [change],\n );\n const [inline] = useState(createInlineFlowHolder);\n useEffect(() => inline.attach(), [inline]);\n const value = useMemo(\n () => ({ open: current, openPanel, setCollapsed, inline }),\n [current, openPanel, setCollapsed, inline],\n );\n return (\n <ScreenStateContext.Provider value={value}>\n {children}\n <InlineBlockers holder={inline} />\n </ScreenStateContext.Provider>\n );\n}\n\n/** The screen state, or `null` outside a provider: the controller then plans without `open`. */\nexport function useScreenState(): ScreenStateValue | null {\n return useContext(ScreenStateContext);\n}\n","import {\n type CompiledScreen,\n type DataError,\n type EntityRef,\n type ErasedQueryDescriptor,\n type FieldAccessMap,\n type FieldReach,\n type PermissionMap,\n type Rule,\n type NodeState,\n type PortableFieldValueSource,\n type PortableValue,\n type ScreenSource,\n type ScreenSources,\n type SourceState,\n createCustomQueryDescriptor,\n LIST_SOURCE_DEFAULT_LIMIT,\n addressesCapability,\n canonicalEntityNodeKey,\n dtoFields,\n formatEntityRef,\n isDataError,\n lowerVia,\n normalizeDataError,\n normalizeEntityRef,\n projectSource,\n readProjected,\n relationAmbiguousError,\n resolveFieldAccess,\n ruleContextFor,\n relationPathVisible,\n snapshotResourceFields,\n} from '@burojs/core';\nimport {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { ResolverContext } from '../../context.js';\nimport { useDataRuntime } from '../../data/context.js';\nimport { useFlowRowResolver } from '../../flows/row-batch.js';\nimport {\n buildStandardQueryDescriptor,\n useDescriptorSession,\n} from '../../hooks/data/use-standard-query-descriptor.js';\nimport { resolveCountExecution } from '../../data/count-policy.js';\nimport { useLocale } from '../../hooks/use-t.js';\nimport { useApplicationSnapshot, useLayerRuntime } from '../../runtime.js';\nimport {\n type PlacementRuntime,\n type ValidationCache,\n blockDataOf,\n resolvePlacements,\n} from './placements.js';\nimport { PoolCollector, type PoolState, useQueryPool } from './query-pool.js';\nimport { useScreenState } from './screen-state.js';\n\nexport interface SourceResolverInput {\n /** `null`: a failure marker, resolve nothing. */\n readonly compiled: CompiledScreen | null;\n /** The resource's canonical name. */\n readonly resource: string;\n readonly recordId?: string;\n /** A caller-supplied row: `record` is ready, nothing is read. */\n readonly record?: Record<string, unknown>;\n readonly values: Record<string, unknown>;\n /**\n * The `route` source (spec 4.5): what the record route or the page host parsed; `''` reads\n * `null`. Absent: `{}`.\n */\n readonly route?: Readonly<Record<string, unknown>>;\n /**\n * What the controller's last plan demands: the `with` sources it loads (`demand.active` and\n * `demand.shown`, spec 10.1). A `with` source outside it stays pending with no request, so an\n * unvisited tab does not fetch. Absent: none.\n */\n readonly demand?: ResolverDemand;\n /**\n * A custom page's body (`usePageScreen`): there is no record, so `record` is ready with `null`\n * and nothing is read for it (a page body cannot reference it).\n */\n readonly page?: boolean;\n}\n\n/** The part of a plan the resolver loads by (spec 10.1). */\nexport interface ResolverDemand {\n /** The loadable sources: `demand.active` then `demand.shown`. */\n readonly sources: readonly string[];\n /**\n * `blockDemand`: the placements whose block `data` may be requested now. A placement in a\n * pending or denied panel is never here, whatever the URL opens (S4a.5).\n */\n readonly blocks: readonly string[];\n}\n\nexport const NO_DEMAND: ResolverDemand = Object.freeze({\n sources: Object.freeze([]),\n blocks: Object.freeze([]),\n});\n\nconst sameList = (left: readonly string[], right: readonly string[]) =>\n left.length === right.length && left.every((name, index) => right[index] === name);\n\n/** Whether two demands load the same sources and placements. */\nexport function sameDemand(left: ResolverDemand, right: ResolverDemand): boolean {\n return sameList(left.sources, right.sources) && sameList(left.blocks, right.blocks);\n}\n\nexport interface SourceResolution {\n /** `record`, `values`, `scope`, `user`, `route` and every `with` name. */\n readonly sources: ScreenSources;\n /**\n * Refetches only the failed requests under these source names: for a `via` chain, the failed\n * hop (a failed record behind it included); `block:<key>` refetches that placement's failed\n * `data` requests.\n */\n retry(sources: readonly string[]): void;\n /** Each placement's state for `planScreen`'s `blockData`, by placement key. */\n readonly blockData: Readonly<Record<string, NodeState>>;\n /** Each placement at mount, by placement key (`usePlacement` reads it). */\n readonly placements: Readonly<Record<string, PlacementRuntime>>;\n /**\n * The screen resource's field decisions in record reach (P5 spec 3.5), as the resolver projected\n * `record` and `values` with them: `planScreen`'s `fieldAccess`. Outside create, a field a\n * `field/view` rule addresses is `pending` until the record is ready (`failed` when it failed).\n */\n readonly fieldAccess: FieldAccessMap;\n /**\n * The placements absent for access (P5 spec 3.6.3): a required prop reads a field its user may\n * not view. `planScreen`'s `blockAccess`.\n */\n readonly blockAccess: readonly string[];\n /**\n * The record as read, before the projection: what rules see (decision P5-12, they are policy).\n * `undefined` until it is ready, and in create. Never view code's.\n */\n readonly policyRecord: unknown;\n}\n\nconst PENDING: SourceState = Object.freeze({ status: 'pending' });\nconst READY_EMPTY: SourceState = Object.freeze({ status: 'ready', value: {}, refreshing: false });\nconst READY_NULL: SourceState = Object.freeze({ status: 'ready', value: null, refreshing: false });\n/** A one-row read its user may not make (P5 decision P5-17): `null`, flagged hidden. */\nconst HIDDEN_NULL: SourceState = Object.freeze({\n status: 'ready',\n value: null,\n refreshing: false,\n hidden: true,\n});\nconst EMPTY_SNAPSHOT: Readonly<Record<string, unknown>> = Object.freeze({});\nconst NO_UNSUBSCRIBE = () => undefined;\n\nfunction ready(value: unknown, refreshing = false, error?: DataError): SourceState {\n return Object.freeze({\n status: 'ready',\n value,\n refreshing,\n ...(error === undefined ? {} : { error }),\n });\n}\n\nfunction failed(error: unknown): SourceState {\n return Object.freeze({ status: 'failed', error: normalizeDataError(error) });\n}\n\n/**\n * The permission map in a context snapshot; `undefined` when none is mounted (field decisions\n * then fail closed).\n * @internal Also read by the form controller and `usePageScreen`.\n */\nexport function readPermissions(\n snapshot: Readonly<Record<string, unknown>>,\n): PermissionMap | undefined {\n const value = snapshot.permissions;\n return value !== null && typeof value === 'object' ? (value as PermissionMap) : undefined;\n}\n\n/** @internal A context slot that failed to resolve. */\nexport function isErrorSlot(value: unknown): value is { readonly __error: unknown } {\n return value !== null && typeof value === 'object' && '__error' in value;\n}\n\n/**\n * `scope` as a source state: pending while the resolver holds a `scope` slot\n * whose value is `undefined`, failed when it holds `{ __error }`, ready with\n * its value otherwise, and ready `{}` when no slot is wired.\n */\nexport function scopeSourceState(snapshot: Readonly<Record<string, unknown>>): SourceState {\n if (!Object.hasOwn(snapshot, 'scope')) return READY_EMPTY;\n const scope = snapshot.scope;\n if (scope === undefined) return PENDING;\n if (isErrorSlot(scope)) return failed(scope.__error);\n return ready(scope);\n}\n\nfunction ownData(value: unknown, key: string): unknown {\n if (value === null || typeof value !== 'object') return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor !== undefined && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nconst NO_ROUTE: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/** A route as the `route` source reads it: an empty value reads `null` (spec 4.5). */\nfunction normalizeRoute(\n route: Readonly<Record<string, unknown>> | undefined,\n): Readonly<Record<string, unknown>> {\n if (route === undefined) return NO_ROUTE;\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(route))\n out[name] = value === '' || value === undefined ? null : value;\n return Object.freeze(out);\n}\n\n/**\n * Whether the context says the user is signed out for certain (P4-B review C1): no `user` slot\n * is wired, or a wired slot holds no id. A slot still pending (`undefined`) or failed\n * (`{ __error }`) says nothing: the user may be signed in.\n */\nexport function isSignedOut(snapshot: Readonly<Record<string, unknown>>): boolean {\n if (!Object.hasOwn(snapshot, 'user')) return true;\n const user = snapshot.user;\n if (user === undefined || isErrorSlot(user)) return false;\n return userIdOf(user) === null;\n}\n\n/** A user id as the framework reads it: a non-empty string, or a finite number as a string. */\nexport function userIdOf(user: unknown): string | null {\n const id = ownData(user, 'id');\n if (typeof id === 'string') return id === '' ? null : id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return null;\n}\n\n/**\n * `user` as a source state: `{ id, name, locale }` only — never roles or\n * permissions (access is a rule). Pending while a wired slot holds `undefined`.\n */\nexport function userSourceState(\n snapshot: Readonly<Record<string, unknown>>,\n locale: string,\n): SourceState {\n const wired = Object.hasOwn(snapshot, 'user');\n const user = wired ? snapshot.user : null;\n if (wired && user === undefined) return PENDING;\n if (isErrorSlot(user)) return failed(user.__error);\n const name = ownData(user, 'name');\n const own = ownData(user, 'locale');\n return ready(\n Object.freeze({\n id: userIdOf(user) ?? '',\n name: typeof name === 'string' ? name : null,\n locale: typeof own === 'string' && own !== '' ? own : locale,\n }),\n );\n}\n\n/** The resolver's context snapshot, `{}` outside a provider. */\nexport function useContextSnapshot(): Readonly<Record<string, unknown>> {\n const resolver = useContext(ResolverContext);\n const subscribe = useCallback(\n (onChange: () => void) => (resolver === null ? NO_UNSUBSCRIBE : resolver.subscribe(onChange)),\n [resolver],\n );\n const read = useCallback(\n () =>\n resolver === null\n ? EMPTY_SNAPSHOT\n : (resolver.snapshot() as unknown as Readonly<Record<string, unknown>>),\n [resolver],\n );\n return useSyncExternalStore(subscribe, read, read);\n}\n\n/** A configuration failure of a source that issues no request (a `via` it cannot lower, a query it cannot bind). */\nfunction configurationFailure(code: string, message: string): SourceState {\n return failed(\n normalizeDataError(Object.assign(new Error(message), { kind: 'configuration' as const, code })),\n );\n}\n\n/** Whether two source states read the same: same status, value, refresh, error and projection. */\nfunction sameState(left: SourceState | undefined, right: SourceState | undefined): boolean {\n if (left === right) return true;\n if (left === undefined || right === undefined || left.status !== right.status) return false;\n if (left.status === 'ready' && right.status === 'ready')\n return (\n Object.is(left.value, right.value) &&\n left.refreshing === right.refreshing &&\n Object.is(left.error, right.error) &&\n Object.is(left.withheld, right.withheld) &&\n left.hidden === right.hidden\n );\n if (left.status === 'failed' && right.status === 'failed')\n return Object.is(left.error, right.error);\n return true;\n}\n\n/** The value at `path` inside a ready value (own data properties only). */\nfunction valueAt(value: unknown, path: readonly string[]): unknown {\n let current = value;\n for (const segment of path) {\n current = ownData(current, segment);\n if (current === undefined) return undefined;\n }\n return current;\n}\n\n/** A relation key as a hop reads it: `null` for no key (spec 6.1), else the id. */\n/** @internal Shared with the flow source reader. */\nexport function hopId(value: unknown): string | number | null {\n if (value === null || value === undefined || value === '') return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n return null;\n}\n\n/** Whether a row read answered `not-found` or `forbidden`: both read `null` (spec 4.1). */\nfunction isMissingRow(state: PoolState): boolean {\n return (\n state.status === 'failed' &&\n (state.error.kind === 'not-found' || state.error.kind === 'forbidden')\n );\n}\n\n/** The `(screen, source, hop)` triples whose `forbidden` answer was already logged. */\nconst FORBIDDEN_NOTICED = new WeakMap<object, Set<string>>();\n/** The `(screen, source, key)` triples whose ambiguous `by` key was already logged. */\nconst AMBIGUOUS_NOTICED = new WeakMap<object, Set<string>>();\n\n/** Whether `key` is new under `screen` in `seen` (and records it). */\nfunction firstNotice(seen: WeakMap<object, Set<string>>, screen: object, key: string): boolean {\n let own = seen.get(screen);\n if (own === undefined) {\n own = new Set();\n seen.set(screen, own);\n }\n if (own.has(key)) return false;\n own.add(key);\n return true;\n}\n\n/** A `source.one` as the resolver reads it: a `with` entry, or a block `data` entry's result. */\nexport type OneRead = Pick<Extract<ScreenSource, { kind: 'one' }>, 'target' | 'key' | 'by'>;\n/** A `source.list` as the resolver reads it. */\nexport type ListRead = Pick<\n Extract<ScreenSource, { kind: 'list' }>,\n 'target' | 'where' | 'sort' | 'limit' | 'count'\n>;\n/** A `source.list`'s filter: one condition, or an `and` of several. */\nexport type ListFilter =\n | { readonly field: string; readonly op: string; readonly value: PortableValue }\n | {\n readonly and: readonly {\n readonly field: string;\n readonly op: string;\n readonly value: PortableValue;\n }[];\n };\n\n/** `source.list`'s value with no rows to read (spec 4.4). */\nexport const EMPTY_ROWS = Object.freeze({ rows: Object.freeze([]) });\nexport const EMPTY_COUNTED = Object.freeze({ rows: Object.freeze([]), total: 0 });\n\n/**\n * Whether a resolved `where` value can be sent (spec 4.1, 4.4): a non-empty string, a finite\n * number, a boolean only against a boolean field, or a non-empty array of those (`in`). Anything\n * else — `null`, `undefined`, `''`, `NaN`, an object — reads no rows and sends nothing.\n */\n/** @internal Shared with the flow source reader. */\nexport function whereValueUsable(value: unknown, kind: string | undefined): boolean {\n if (typeof value === 'string') return value !== '';\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value === 'boolean') return kind === 'boolean';\n if (Array.isArray(value))\n return (\n value.length > 0 &&\n value.every((entry) => !Array.isArray(entry) && whereValueUsable(entry, kind))\n );\n return false;\n}\n\n/** Each raw rows array's projection, by field list, so an unchanged result keeps one identity. */\nconst PROJECTED_ROWS = new WeakMap<object, Map<string, readonly unknown[]>>();\n\n/** List rows as their target's list DTO (spec 4.4); a non-array reads as no rows. */\n/** @internal Shared with the flow source reader. */\nexport function projectRows(\n rows: unknown,\n fields: readonly string[] | undefined,\n): readonly unknown[] {\n if (!Array.isArray(rows)) return EMPTY_ROWS.rows;\n const key = fields === undefined ? '' : fields.join('\\u0000');\n let own = PROJECTED_ROWS.get(rows);\n const known = own?.get(key);\n if (known !== undefined) return known;\n const out = Object.freeze(rows.map((row) => projectRow(row, fields)));\n if (own === undefined) {\n own = new Map();\n PROJECTED_ROWS.set(rows, own);\n }\n own.set(key, out);\n return out;\n}\n\n/** `{ rows }`, or `{ rows, total }`: one frozen object per rows array and total. */\nconst LIST_VALUES = new WeakMap<object, Map<string, unknown>>();\n/** @internal Shared with the flow source reader. */\nexport function listValue(rows: readonly unknown[], total?: number): unknown {\n const key = total === undefined ? '' : String(total);\n let own = LIST_VALUES.get(rows);\n const known = own?.get(key);\n if (known !== undefined) return known;\n const value = Object.freeze(total === undefined ? { rows } : { rows, total });\n if (own === undefined) {\n own = new Map();\n LIST_VALUES.set(rows, own);\n }\n own.set(key, value);\n return value;\n}\n\n/** Each raw row's projections, by field list, so an unchanged row keeps one identity. */\nconst PROJECTED = new WeakMap<object, Map<string, Readonly<Record<string, unknown>>>>();\n\n/**\n * A row as its target's DTO (decision 41, spec 4.1): only the declared fields of `fields`, so a\n * column the provider sent beyond the projection (a list-only field, an undeclared column) never\n * reaches a ref or a view. `undefined` fields leave the row as it is.\n */\n/** `row` with `idField` set to `key` when the provider's row left it out (an id read). */\n/** @internal Shared with the flow source reader. */\nexport function withRowId(row: unknown, idField: string, key: unknown): unknown {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) return row;\n if (ownData(row, idField) !== undefined) return row;\n if (typeof key !== 'string' && typeof key !== 'number') return row;\n let own = WITH_ID.get(row);\n if (own === undefined) {\n own = Object.freeze({ ...(row as Record<string, unknown>), [idField]: key });\n WITH_ID.set(row, own);\n }\n return own;\n}\nconst WITH_ID = new WeakMap<object, object>();\n\n/** @internal Shared with the flow source reader. */\nexport function projectRow(row: unknown, fields: readonly string[] | undefined): unknown {\n if (fields === undefined || row === null || typeof row !== 'object' || Array.isArray(row))\n return row;\n const key = fields.join('\\u0000');\n let own = PROJECTED.get(row);\n const known = own?.get(key);\n if (known !== undefined) return known;\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n const value = ownData(row, field);\n if (value !== undefined) out[field] = value;\n }\n const frozen = Object.freeze(out);\n if (own === undefined) {\n own = new Map();\n PROJECTED.set(row, own);\n }\n own.set(key, frozen);\n return frozen;\n}\n\n/** A decision set as a cache key: each field's view, in the map's order. */\nfunction accessKey(access: FieldAccessMap): string {\n let key = '';\n for (const [field, decision] of Object.entries(access))\n key += `${field}\\u0000${decision.view}\\u0001`;\n return key;\n}\n\n/** A raw value's own entries as they were projected, to tell a value mutated in place. */\ntype Shallow = readonly (readonly [string, unknown])[];\n\nfunction shallowOf(value: object): Shallow {\n return Object.entries(value);\n}\n\nfunction sameShallow(value: object, seen: Shallow): boolean {\n const now = Object.keys(value);\n if (now.length !== seen.length) return false;\n return seen.every(\n ([key, entry]) => Object.hasOwn(value, key) && Object.is((value as never)[key], entry),\n );\n}\n\n/** Each raw value's projections, by shape, id field and decision set: one identity per answer. */\nconst PROJECTED_STATES = new WeakMap<\n object,\n Map<string, { readonly state: SourceState; readonly seen: Shallow }>\n>();\n\n/**\n * `projectSource` over a ready state (P5 spec 3.6), memoised per raw value and decision set so an\n * unchanged read keeps one projected identity (a plan is not recomputed for nothing); a raw value\n * mutated in place since (an in-memory provider) is projected again. The state's own\n * `refreshing` and `error` are carried over; the projected value (and with it what\n * `readProjected` knows was removed) is the cached one.\n */\nfunction projectCached(\n state: SourceState,\n access: FieldAccessMap,\n shape: 'row' | 'rows',\n idField: string,\n): SourceState {\n if (state.status !== 'ready') return state;\n const value = state.value;\n if (value === null || typeof value !== 'object') return state;\n const key = `${shape}\\u0002${idField}\\u0002${accessKey(access)}`;\n let own = PROJECTED_STATES.get(value);\n if (own === undefined) {\n own = new Map();\n PROJECTED_STATES.set(value, own);\n }\n let entry = own.get(key);\n if (entry === undefined || !sameShallow(value, entry.seen)) {\n entry = {\n state: Object.freeze(projectSource(ready(value), access, shape, idField)),\n seen: shallowOf(value),\n };\n own.set(key, entry);\n }\n const known = entry.state;\n if (known.status !== 'ready') return known;\n if (known.refreshing === state.refreshing && known.error === state.error) return known;\n const { error: _error, ...rest } = known;\n return Object.freeze({\n ...rest,\n refreshing: state.refreshing,\n ...(state.error === undefined ? {} : { error: state.error }),\n });\n}\n\n/** `state` marked refreshing, its projection (value, `withheld`) kept. */\nfunction refreshed(state: SourceState, refreshing: boolean): SourceState {\n if (!refreshing || state.status !== 'ready' || state.refreshing) return state;\n return Object.freeze({ ...state, refreshing: true });\n}\n\n/** A pool state as a source state; `value` reads the request's result. */\nfunction fromPool(state: PoolState, value: (data: unknown) => unknown): SourceState {\n if (state.status === 'pending') return PENDING;\n if (state.status === 'failed') return failed(state.error);\n return ready(value(state.data), state.fetching, state.error);\n}\n\n/**\n * Resolves one render's sources: the built-ins handed in, and every demanded `with` entry\n * through the pool (`collector`). Records the failed request keys under each source name, and\n * the request keys a source read (its inputs' included), for `retry`.\n */\nclass SourceReader {\n readonly states = new Map<string, SourceState>();\n /** The request keys behind each source, its inputs' included, and whether each failed. */\n readonly keys = new Map<string, Map<string, boolean>>();\n readonly #reading = new Set<string>();\n\n constructor(\n private readonly options: {\n readonly compiled: CompiledScreen;\n readonly owner: EntityRef;\n readonly base: Readonly<Record<string, SourceState | undefined>>;\n readonly recordKey?: { readonly key: string; readonly failed: boolean };\n readonly demanded: ReadonlySet<string>;\n readonly collector: PoolCollector;\n readonly fieldsOf: ReturnType<typeof snapshotResourceFields>;\n readonly idFieldOf: (ref: EntityRef) => string | undefined;\n /** A target's record DTO fields; `undefined` for a resource the registry lacks. */\n readonly recordDto: (ref: EntityRef) => readonly string[] | undefined;\n readonly one: (target: EntityRef, id: string | number) => ErasedQueryDescriptor | DataError;\n /** A target's list DTO fields; `undefined` for a resource the registry lacks. */\n readonly listDto: (ref: EntityRef) => readonly string[] | undefined;\n /** A field's kind on a target (`undefined` when undeclared), for a `where` value's check. */\n readonly fieldKindOf: (ref: EntityRef, field: string) => string | undefined;\n /** A `source.list` read: the list descriptor and, for `count`, the count descriptor. */\n readonly list: (target: EntityRef, read: ListRead) => ErasedQueryDescriptor | DataError;\n readonly count: (\n target: EntityRef,\n filter: ListFilter | undefined,\n ) => ErasedQueryDescriptor | DataError;\n /** One row of `target` by a non-id key: `where <by> eq <key>`, two rows, the record DTO. */\n readonly byRow: (\n target: EntityRef,\n by: string,\n key: string | number,\n ) => ErasedQueryDescriptor | DataError;\n readonly custom: (ref: EntityRef, input: PortableValue) => ErasedQueryDescriptor | DataError;\n /**\n * A target's ready row or rows projected by its field view (P5 spec 3.6.2): a row in record\n * reach with that row, rows in any-record reach. Not ready: as is.\n */\n readonly project: (target: EntityRef, state: SourceState, reach: FieldReach) => SourceState;\n /**\n * Whether an author predicate (`where`, `sort`, `by`) may name `field` of `target`: its view\n * in any-record reach (P5 spec 3.7). `'pending'` while undecided.\n */\n readonly predicateVisible: (target: EntityRef, field: string) => boolean | 'pending';\n },\n ) {\n if (options.recordKey !== undefined)\n this.keys.set('record', new Map([[options.recordKey.key, options.recordKey.failed]]));\n }\n\n #note(name: string, key: string, isFailed: boolean): void {\n const own = this.keys.get(name) ?? new Map<string, boolean>();\n own.set(key, (own.get(key) ?? false) || isFailed);\n this.keys.set(name, own);\n }\n\n #inherit(name: string, from: string): void {\n for (const [key, isFailed] of this.keys.get(from) ?? []) this.#note(name, key, isFailed);\n }\n\n /** The state of a source by name; `values` in show is the record (spec 6.1). */\n state(name: string): SourceState {\n const { base, compiled } = this.options;\n const alias = name === 'values' && compiled.mode === 'show' ? 'record' : name;\n if (Object.hasOwn(base, alias)) return base[alias] ?? PENDING;\n const known = this.states.get(alias);\n if (known !== undefined) return known;\n const entry = Object.hasOwn(compiled.with, alias) ? compiled.with[alias] : undefined;\n if (entry === undefined)\n return configurationFailure('source-unknown', `The source '${alias}' is not declared.`);\n if (!this.options.demanded.has(alias)) return PENDING;\n if (this.#reading.has(alias))\n return configurationFailure('source-cycle', `The source '${alias}' reads itself.`);\n this.#reading.add(alias);\n const state =\n entry.kind === 'via'\n ? this.#via(alias, entry)\n : entry.kind === 'query'\n ? this.#query(alias, entry)\n : entry.kind === 'one'\n ? this.one(alias, entry)\n : this.list(alias, entry);\n this.#reading.delete(alias);\n this.states.set(alias, state);\n return state;\n }\n\n /** The value at `path` of a source, as a state; `from` inherits its request keys. */\n read(name: string, path: readonly string[], from?: string): SourceState {\n const state = this.state(name);\n if (from !== undefined)\n this.#inherit(\n from,\n name === 'values' && this.options.compiled.mode === 'show' ? 'record' : name,\n );\n if (state.status !== 'ready') return state;\n // Through the one projected read (P5 spec 3.6): an undecided field waits, a removed one reads\n // `null` flagged `hidden`; any other read as before (a missing key reads `undefined`).\n const projected = readProjected(state, path);\n if (projected.status !== 'ready' || projected.hidden === true) return projected;\n return ready(valueAt(state.value, path), state.refreshing);\n }\n\n #via(name: string, entry: Extract<ScreenSource, { kind: 'via' }>): SourceState {\n let hops: ReturnType<typeof lowerVia>;\n try {\n hops = lowerVia(\n this.options.owner,\n {\n path: entry.path,\n ...(entry.to === undefined ? {} : { to: entry.to }),\n ...(entry.by === undefined ? {} : { by: entry.by }),\n },\n this.options.fieldsOf,\n this.options.idFieldOf,\n );\n } catch (error) {\n const code = (error as { readonly code?: unknown }).code;\n return configurationFailure(\n typeof code === 'string' ? code : 'via-invalid',\n error instanceof Error ? error.message : String(error),\n );\n }\n this.#inherit(name, 'record');\n // Each row is projected (the record by the screen's decisions, every hop row by its target's),\n // so a hop key its user may not view reads `null` and the hop sends nothing (P5 spec 3.6.2);\n // an undecided key waits.\n let row: SourceState = this.state('record');\n let refreshing = false;\n for (const [index, hop] of hops.entries()) {\n if (row.status !== 'ready') return row;\n refreshing ||= row.refreshing;\n const read = readProjected(row, [hop.field]);\n if (read.status !== 'ready') return read;\n const key = read.hidden === true ? null : hopId(ownData(row.value, hop.field));\n // No key: nothing to read, and no request for this hop or any later one (spec 4.1).\n if (key === null) return ready(null, refreshing);\n const next = this.#row(name, hop.target, key, hop.by, `hop ${index}`);\n if (next.status !== 'ready') return next;\n // A missing or denied row reads `null` and stops the chain (spec 4.1).\n if (next.value === null) return ready(null, refreshing || next.refreshing);\n row = next;\n }\n return refreshed(row, refreshing);\n }\n\n /**\n * One row of `target` keyed by `key` on behalf of `name` (a hop, or a `source.one`): by id, or\n * by its `by` field as a two-row list read that fails closed on a duplicate (spec 4.2). A row\n * answered `not-found` or `forbidden` reads `null`, so a read is no existence oracle (spec 4.1);\n * a `forbidden` answer logs one development notice per `(source, hop)`. `hop` names the hop in\n * that notice.\n */\n #row(\n name: string,\n target: EntityRef,\n key: string | number,\n by: string | undefined,\n hop: string,\n peek = false,\n ): SourceState {\n const { compiled } = this.options;\n // A `by` on a field its user may not view forbids the read (decision P5-17): `null`, no\n // request — never a row found by matching a hidden value.\n if (by !== undefined) {\n const allowed = this.options.predicateVisible(target, by);\n if (allowed === 'pending') return PENDING;\n if (!allowed) return HIDDEN_NULL;\n }\n const descriptor =\n by === undefined ? this.options.one(target, key) : this.options.byRow(target, by, key);\n if (isDataError(descriptor)) return failed(descriptor);\n const read = this.#read(descriptor, peek);\n const missing = isMissingRow(read.state);\n // A missing or denied row is an answer, not a failure: Retry does not refetch it.\n if (!peek) this.#note(name, read.key, read.state.status === 'failed' && !missing);\n if (missing) {\n if (\n read.state.status === 'failed' &&\n read.state.error.kind === 'forbidden' &&\n process.env.NODE_ENV !== 'production' &&\n firstNotice(FORBIDDEN_NOTICED, compiled, `${name}\\u0000${hop}`)\n )\n console.warn(\n `[buro] The source '${name}' read ${formatEntityRef(target)} (${hop}), which the user may not read: the source reads null.`,\n );\n return READY_NULL;\n }\n // A hop row keeps its id field (`data.idField ?? 'id'`) whether or not the target declares it,\n // as the `record` base does: `l.ref('<source>', 'id')` reads the row's id (an id read's own key\n // when the provider's projection left it out).\n const idField = this.options.idFieldOf(target) ?? 'id';\n const declared = this.options.recordDto(target);\n const dto =\n declared === undefined || declared.includes(idField) ? declared : [...declared, idField];\n if (by === undefined)\n return this.options.project(\n target,\n fromPool(read.state, (data) =>\n withRowId(\n projectRow((data as { readonly data?: unknown } | null)?.data ?? null, dto),\n idField,\n key,\n ),\n ),\n 'record',\n );\n const state = fromPool(read.state, (data) => {\n const rows = (data as { readonly data?: unknown } | null)?.data;\n return Array.isArray(rows) ? rows : [];\n });\n if (state.status !== 'ready') return state;\n const rows = state.value as readonly unknown[];\n if (rows.length === 0) return ready(null, state.refreshing);\n if (rows.length === 1)\n return this.options.project(\n target,\n ready(projectRow(rows[0], dto), state.refreshing, state.error),\n 'record',\n );\n // Two rows share the key: never pick one (fail closed, spec 4.2).\n const error = relationAmbiguousError(formatEntityRef(target), by, String(key));\n if (\n process.env.NODE_ENV !== 'production' &&\n firstNotice(AMBIGUOUS_NOTICED, compiled, `${name}\\u0000${hop}\\u0000${String(key)}`)\n )\n console.error(`[buro] The source '${name}': ${error.message}`);\n return failed(error);\n }\n\n /** Requests `descriptor` (or, with `peek`, reads what the cache holds without requesting it). */\n #read(descriptor: ErasedQueryDescriptor, peek: boolean) {\n return peek ? this.options.collector.peek(descriptor) : this.options.collector.read(descriptor);\n }\n\n /** A key or `where` value: a literal, or a ref read on behalf of `name` (pending sends nothing). */\n #operand(name: string, value: PortableFieldValueSource): SourceState {\n if (value.kind !== 'ref') return ready(value.value);\n return this.read(value.source, value.path, name);\n }\n\n /**\n * A `source.one` (spec 4.4) on behalf of `name` (a `with` name, or `block:<key>`): its key read\n * first (pending sends nothing), an empty key `ready(null)` with no request, then one row as a\n * hop reads it — by id or by `by`, `not-found` and `forbidden` as `null`, the record DTO.\n */\n one(name: string, entry: OneRead, peek = false): SourceState {\n const input = this.#operand(name, entry.key);\n if (input.status !== 'ready') return input;\n const key = hopId(input.value);\n if (key === null) return ready(null, input.refreshing);\n const row = this.#row(name, entry.target, key, entry.by, 'its key', peek);\n return refreshed(row, input.refreshing);\n }\n\n /**\n * A `source.list` (spec 4.4) on behalf of `name`: every `where` value read first (pending sends\n * nothing); a value that cannot key its field (`null`, `''`, an object, …) reads no rows and\n * sends nothing — never `field eq null`. Else one list read (`where`, `sort`, `limit`, the list\n * DTO) and, with `count`, the total: the list's own when the provider returns one, else a count\n * read with the same filter; a provider that cannot count fails the source (`capability`).\n */\n list(name: string, entry: ListRead, peek = false): SourceState {\n // A `where` or `sort` on a field its user may not view forbids the read (decision P5-17): no\n // rows, no total, no request — never dropped, which would widen what an author narrowed.\n for (const field of [\n ...(entry.where ?? []).map((condition) => condition.field),\n ...(entry.sort ?? []).map((sort) => sort.field),\n ]) {\n const allowed = this.options.predicateVisible(entry.target, field);\n if (allowed === 'pending') return PENDING;\n if (!allowed) return ready(EMPTY_ROWS);\n }\n const conditions: { field: string; op: string; value: PortableValue }[] = [];\n let refreshing = false;\n for (const condition of entry.where) {\n const input = this.#operand(name, condition.value);\n if (input.status !== 'ready') return input;\n refreshing ||= input.refreshing;\n if (!whereValueUsable(input.value, this.options.fieldKindOf(entry.target, condition.field)))\n return ready(entry.count === true ? EMPTY_COUNTED : EMPTY_ROWS, refreshing);\n conditions.push({\n field: condition.field,\n op: condition.op,\n value: input.value as PortableValue,\n });\n }\n const filter: ListFilter | undefined =\n conditions.length === 0\n ? undefined\n : conditions.length === 1\n ? conditions[0]\n : { and: conditions };\n const descriptor = this.options.list(entry.target, {\n ...entry,\n ...(filter === undefined ? {} : { filter }),\n } as never);\n if (isDataError(descriptor)) return failed(descriptor);\n const read = this.#read(descriptor, peek);\n if (!peek) this.#note(name, read.key, read.state.status === 'failed');\n if (read.state.status === 'pending') return PENDING;\n if (read.state.status === 'failed') return failed(read.state.error);\n refreshing ||= read.state.fetching;\n const data = read.state.data as { readonly data?: unknown; readonly total?: unknown } | null;\n const rows = projectRows(data?.data, this.options.listDto(entry.target));\n // The rows a ref or a view reads: the target's field view in any-record reach (P5 spec 3.6.2).\n const project = (state: SourceState) => this.options.project(entry.target, state, 'every');\n if (entry.count !== true) return project(ready(listValue(rows), refreshing, read.state.error));\n const inline = typeof data?.total === 'number' ? data.total : undefined;\n const execution = resolveCountExecution('auto', inline, { query: true, live: false });\n if (isDataError(execution)) return failed(execution);\n if (execution.kind === 'inline')\n return project(ready(listValue(rows, execution.total), refreshing));\n const countDescriptor = this.options.count(entry.target, filter);\n if (isDataError(countDescriptor)) return failed(countDescriptor);\n const counted = this.#read(countDescriptor, peek);\n if (!peek) this.#note(name, counted.key, counted.state.status === 'failed');\n if (counted.state.status === 'pending') return PENDING;\n if (counted.state.status === 'failed') return failed(counted.state.error);\n const total = (counted.state.data as { readonly total?: unknown } | null)?.total;\n if (typeof total !== 'number')\n return failed(\n normalizeDataError(\n Object.assign(new Error('The count read returned no total.'), {\n kind: 'protocol' as const,\n code: 'count-missing',\n }),\n ),\n );\n return project(ready(listValue(rows, total), refreshing || counted.state.fetching));\n }\n\n /**\n * A `source.query` read on behalf of `name` (a `with` name, or `block:<key>` for a block's\n * `data` entry): its ref inputs read first (a pending input sends no request), then the query.\n */\n query(\n name: string,\n entry: Pick<Extract<ScreenSource, { kind: 'query' }>, 'query' | 'input'>,\n peek = false,\n ): SourceState {\n return this.#query(name, entry, peek);\n }\n\n #query(\n name: string,\n entry: Pick<Extract<ScreenSource, { kind: 'query' }>, 'query' | 'input'>,\n peek = false,\n ): SourceState {\n const input: Record<string, unknown> = {};\n let refreshing = false;\n for (const [key, value] of Object.entries(entry.input)) {\n if (value.kind !== 'ref') {\n input[key] = value.value;\n continue;\n }\n // A pending input sends no request (Review Focus 2's rule, for queries).\n const read = this.read(value.source, value.path, name);\n if (read.status !== 'ready') return read;\n refreshing ||= read.refreshing;\n input[key] = read.value === undefined ? null : read.value;\n }\n const descriptor = this.options.custom(entry.query, input as PortableValue);\n if (isDataError(descriptor)) return failed(descriptor);\n const { key, state } = peek\n ? this.options.collector.peek(descriptor)\n : this.options.collector.read(descriptor);\n if (!peek) this.#note(name, key, state.status === 'failed');\n const out = fromPool(state, (data) => data);\n return out.status === 'ready' && refreshing ? ready(out.value, true, out.error) : out;\n }\n}\n\n/**\n * The built-in `SourceResolver` (P1b+P1c decision 9): the record, the form values, the app\n * scope, the user, the route params and the screen's `with` sources (`via`, `source.query`) of\n * one record form. Every request runs through one observer pool keyed by `queryKeyFor`, so equal\n * reads are one request, and the record shares the record page's request (same descriptor and\n * retry policy). Only the demanded `with` sources load.\n */\nexport function useSourceResolver(input: SourceResolverInput): SourceResolution {\n const { compiled } = input;\n const runtime = useDataRuntime();\n const snapshot = useApplicationSnapshot();\n const session = useDescriptorSession(runtime);\n const contextSnapshot = useContextSnapshot();\n const locale = useLocale();\n const scopeSlot = contextSnapshot.scope;\n const userSlot = contextSnapshot.user;\n const hasScope = Object.hasOwn(contextSnapshot, 'scope');\n const hasUser = Object.hasOwn(contextSnapshot, 'user');\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the two slots, not the whole snapshot\n const scope = useMemo(() => scopeSourceState(contextSnapshot), [hasScope, scopeSlot]);\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the user slot and the locale\n const user = useMemo(() => userSourceState(contextSnapshot, locale), [hasUser, userSlot, locale]);\n const permissions = readPermissions(contextSnapshot);\n const route = useMemo(() => ready(normalizeRoute(input.route)), [input.route]);\n\n const layerRuntime = useLayerRuntime();\n const validations = useRef<ValidationCache>(new Map());\n const [, setSettled] = useState(0);\n const collector = new PoolCollector(runtime.queryClient);\n const context = { runtime, snapshot, session, locale };\n // Every record read asks for its target's record DTO (decision 41): the record page passes the\n // same projection, so a page and its form share one request.\n const one = (target: string | EntityRef, id: string | number) => {\n const handle = (\n typeof target === 'string' ? target : { kind: 'resource', ref: target }\n ) as never;\n const def = runtime.app.registry.get(handle);\n return buildStandardQueryDescriptor<never, ErasedQueryDescriptor>(context, handle, {\n kind: 'one',\n id,\n ...(def === undefined ? {} : { projection: dtoFields(def, 'record') }),\n });\n };\n\n /** The id field of a target (`data.idField`), `undefined` for the default `id`. */\n const idFieldOf = (target: EntityRef): string | undefined => {\n const def = runtime.app.registry.get({ kind: 'resource', ref: target } as never) as\n | { readonly data?: { readonly idField?: unknown } }\n | undefined;\n const idField = def?.data?.idField;\n return typeof idField === 'string' && idField !== '' ? idField : undefined;\n };\n /** A target's record DTO fields (decision 41), `undefined` for a resource the registry lacks. */\n const recordDto = (target: EntityRef) => {\n const def = runtime.app.registry.get({ kind: 'resource', ref: target } as never);\n return def === undefined ? undefined : dtoFields(def, 'record');\n };\n /** A target's list DTO fields (spec 4.4), `undefined` for a resource the registry lacks. */\n const listDto = (target: EntityRef) => {\n const def = runtime.app.registry.get({ kind: 'resource', ref: target } as never);\n return def === undefined ? undefined : dtoFields(def, 'list');\n };\n const fieldsOfSnapshot = snapshotResourceFields(snapshot);\n const fieldKindOf = (target: EntityRef, field: string) => {\n const entry = fieldsOfSnapshot(target)?.find((candidate) => candidate.name === field) as\n | { readonly kind?: unknown }\n | undefined;\n return typeof entry?.kind === 'string' ? entry.kind : undefined;\n };\n // A `source.list` read (spec 4.4): `where`, `sort`, `limit` (25 when absent), the list DTO.\n const list = (target: EntityRef, read: ListRead & { readonly filter?: ListFilter }) => {\n const handle = { kind: 'resource', ref: target } as never;\n const projection = listDto(target);\n return buildStandardQueryDescriptor<never, ErasedQueryDescriptor>(context, handle, {\n kind: 'list',\n ...(read.filter === undefined ? {} : { filter: read.filter }),\n ...(read.sort === undefined ? {} : { sort: read.sort }),\n pagination: { kind: 'offset', page: 1, pageSize: read.limit ?? LIST_SOURCE_DEFAULT_LIMIT },\n ...(projection === undefined ? {} : { projection }),\n });\n };\n // Its total, when the list read returns none: the same filter (Known finding 10).\n const count = (target: EntityRef, filter: ListFilter | undefined) =>\n buildStandardQueryDescriptor<never, ErasedQueryDescriptor>(\n context,\n { kind: 'resource', ref: target } as never,\n { kind: 'count', ...(filter === undefined ? {} : { filter }) },\n );\n // A row by a non-id key (spec 4.2): `where <by> eq <key>`, at most two rows so a duplicate is\n // seen, with the record DTO projection a by-id read asks for.\n const byRow = (target: EntityRef, by: string, key: string | number) => {\n const handle = { kind: 'resource', ref: target } as never;\n const def = runtime.app.registry.get(handle);\n return buildStandardQueryDescriptor<never, ErasedQueryDescriptor>(context, handle, {\n kind: 'list',\n filter: { field: by, op: 'eq', value: key },\n pagination: { kind: 'offset', page: 1, pageSize: 2 },\n ...(def === undefined ? {} : { projection: dtoFields(def, 'record') }),\n });\n };\n\n // Field access (P5 spec 3.4–3.6): decided before the plan, over the row as read, and every\n // source projected by it — view code and conditions read only what their user may view.\n const ruleSource = runtime.app.ruleSource;\n const keyOf = (target: EntityRef) => canonicalEntityNodeKey({ name: target.id, ref: target });\n /** A resource's decisions over every declared field (list DTO: the union over types). */\n const decide = (\n resourceKey: string,\n extraRules: readonly Rule[],\n record: unknown,\n reach: FieldReach,\n ): FieldAccessMap | undefined => {\n const def = runtime.app.registry.get(resourceKey as never);\n if (def === undefined) return undefined;\n return resolveFieldAccess({\n rules: [...extraRules, ...ruleSource.rules(resourceKey)],\n fields: dtoFields(def, 'list'),\n context: ruleContextFor({\n user: userSlot as never,\n scope: scopeSlot,\n ...(permissions === undefined ? {} : { permissions }),\n ...(record === undefined ? {} : { record }),\n mode: compiled?.mode ?? 'show',\n resource: resourceKey,\n }),\n permissions,\n reach,\n });\n };\n const projectTarget = (target: EntityRef, state: SourceState, reach: FieldReach) => {\n if (state.status !== 'ready' || state.value === null || typeof state.value !== 'object')\n return state;\n const access = decide(\n keyOf(target),\n NO_RULES,\n reach === 'record' ? state.value : undefined,\n reach,\n );\n // A target the registry lacks has no declared field to decide: nothing is known to show.\n if (access === undefined) return reach === 'record' ? READY_NULL : ready(EMPTY_ROWS);\n return projectCached(\n state,\n access,\n reach === 'record' ? 'row' : 'rows',\n idFieldOf(target) ?? 'id',\n );\n };\n\n // The record: read as the record page reads it, so the two share one request.\n let record: SourceState | undefined;\n let recordKey: { readonly key: string; readonly failed: boolean } | undefined;\n if (compiled !== null && compiled.mode !== 'create') {\n if (input.page === true) record = READY_NULL;\n else if (input.record !== undefined) record = ready(input.record);\n else if (input.recordId === undefined) record = PENDING;\n else {\n const descriptor = one(input.resource, input.recordId);\n if (isDataError(descriptor)) record = failed(descriptor);\n else {\n const read = collector.read(descriptor);\n recordKey = { key: read.key, failed: read.state.status === 'failed' };\n record = fromPool(read.state, (data) => (data as { readonly data?: unknown }).data);\n }\n }\n }\n\n // The screen resource's decisions in record reach, over the record as read; in create with no\n // record (decided before the first plan). Outside create a guarded field waits on the record.\n const policyRecord =\n compiled !== null && compiled.mode !== 'create' && record?.status === 'ready'\n ? record.value\n : undefined;\n const screenRules = compiled?.rules ?? NO_RULES;\n const decided =\n compiled === null || input.page === true\n ? undefined\n : decide(input.resource, screenRules, policyRecord ?? undefined, 'record');\n const screenIdField = idFieldOf(normalizeEntityRef(input.resource)) ?? 'id';\n const fieldAccess = useStableAccess(\n decided === undefined\n ? NO_ACCESS\n : compiled !== null && compiled.mode !== 'create' && record?.status !== 'ready'\n ? undecidedUntil(decided, [...screenRules, ...ruleSource.rules(input.resource)], record)\n : decided,\n );\n if (record !== undefined && decided !== undefined)\n record = projectCached(record, fieldAccess, 'row', screenIdField);\n // In edit, form state holds only the fields its user may edit (P5 decision 23): a read of any\n // other field falls back to the record, projected like it (`ref('values', f)` of a read-only\n // field reads the record's value; of a hidden one `null`).\n const editRecord =\n compiled?.mode === 'edit' && policyRecord !== null && typeof policyRecord === 'object'\n ? policyRecord\n : undefined;\n const rawValues = useMemo(\n () => ready(editRecord === undefined ? input.values : { ...editRecord, ...input.values }),\n [input.values, editRecord],\n );\n const values =\n decided === undefined ? rawValues : projectCached(rawValues, fieldAccess, 'row', screenIdField);\n\n const resolved: Record<string, SourceState> = {};\n const failedKeys = new Map<string, readonly string[]>();\n if (recordKey?.failed === true) failedKeys.set('record', [recordKey.key]);\n let placements: Readonly<Record<string, PlacementRuntime>> = NO_PLACEMENTS;\n if (compiled !== null) {\n const everyAccess = new Map<string, FieldAccessMap>();\n const reader = new SourceReader({\n compiled,\n owner: normalizeEntityRef(input.resource),\n base: { record, values, scope, user, route },\n ...(recordKey === undefined ? {} : { recordKey }),\n demanded: new Set(input.demand?.sources ?? []),\n collector,\n fieldsOf: fieldsOfSnapshot,\n idFieldOf,\n recordDto,\n listDto,\n fieldKindOf,\n list,\n count,\n one: (target, id) => one(target, id),\n byRow,\n custom: (ref, queryInput) =>\n createCustomQueryDescriptor({ snapshot, session, locale, ref, input: queryInput }) as\n | ErasedQueryDescriptor\n | DataError,\n project: projectTarget,\n predicateVisible: (target, field) => {\n const viewOf = (ref: EntityRef, name: string): boolean | 'pending' => {\n const key = keyOf(ref);\n let access = everyAccess.get(key);\n if (access === undefined) {\n access = decide(key, NO_RULES, undefined, 'every') ?? NO_ACCESS;\n everyAccess.set(key, access);\n }\n const decision = Object.hasOwn(access, name) ? access[name] : undefined;\n // A name the target does not declare carries no field rule.\n if (decision === undefined) return true;\n if (decision.view === 'pending') return 'pending';\n return decision.view === 'visible';\n };\n const head = viewOf(target, field.split('.')[0]!);\n if (head !== true) return head;\n // A relation path is decided on every resource it crosses (P5 spec 3.7).\n return relationPathVisible(target, field, { fieldsOf: fieldsOfSnapshot, viewOf });\n },\n });\n for (const name of Object.keys(compiled.with)) resolved[name] = reader.state(name);\n const owner = normalizeEntityRef(input.resource);\n /** Decision 41: the declared fields a whole row of `name` reaches a view with. */\n const projectionOf = (name: string): readonly string[] | undefined => {\n if (name === 'record' || name === 'values') return recordDto(owner);\n const entry = Object.hasOwn(compiled.with, name) ? compiled.with[name] : undefined;\n if (entry === undefined) return undefined;\n if (entry.kind === 'query') {\n const value = snapshot.getProjection({ kind: 'custom-query', ref: entry.query })?.value as\n | { readonly fields?: readonly { readonly name: string }[] }\n | undefined;\n return value?.fields?.map((field) => field.name);\n }\n // A `source.one` row is its target's record DTO; a list value is `{ rows, total? }`, whose\n // rows are already projected to the list DTO.\n if (entry.kind === 'one') return recordDto(entry.target);\n if (entry.kind !== 'via') return undefined;\n try {\n const hops = lowerVia(\n owner,\n {\n path: entry.path,\n ...(entry.to === undefined ? {} : { to: entry.to }),\n ...(entry.by === undefined ? {} : { by: entry.by }),\n },\n fieldsOfSnapshot,\n idFieldOf,\n );\n const last = hops.at(-1);\n return last === undefined ? undefined : recordDto(last.target);\n } catch {\n return undefined;\n }\n };\n if (compiled.nodes.some((node) => node.kind === 'place'))\n placements = resolvePlacements({\n compiled,\n snapshot,\n attachments: layerRuntime.getAttachmentCatalog(),\n reads: {\n read: (name, path, owner) => reader.read(name, path, owner),\n query: (owner, query, peek) => reader.query(owner, query, peek),\n one: (owner, one, peek) => reader.one(owner, one, peek),\n list: (owner, list, peek) => reader.list(owner, list, peek),\n },\n demanded: new Set(input.demand?.blocks ?? []),\n validations: validations.current,\n onSettled: () => setSettled((value) => value + 1),\n project: (name) => projectionOf(name),\n });\n for (const [name, keys] of reader.keys) {\n if (name === 'record') continue;\n failedKeys.set(\n name,\n [...keys].filter(([, isFailed]) => isFailed).map(([key]) => key),\n );\n }\n }\n\n const refetch = useQueryPool(collector.requests);\n // An inline-flow placement is gated by its flow too (3.12): a flow that is not there for this\n // record leaves no panel title over nothing. The planner reads these like block data.\n const flowGate = useFlowRowResolver(input.resource);\n const inlineHolder = useScreenState()?.inline;\n useSyncExternalStore(\n inlineHolder?.subscribe ?? NO_SUBSCRIBE,\n inlineHolder?.version ?? ZERO,\n inlineHolder?.version ?? ZERO,\n );\n // The flow's gate reads the record as read (P4 4.24 C2), not the projected one.\n const inlineFlowStates = inlineFlowNodeStates(\n compiled,\n record?.status === 'ready' && policyRecord !== undefined ? ready(policyRecord) : record,\n input.recordId,\n flowGate,\n (key) => inlineHolder?.get(key)?.dirty === true,\n );\n const blockData = useStableBlockData(placements, inlineFlowStates);\n // A gone flow's node is no longer mounted to release its own lease (fail closed, 3.12).\n const goneKeys = Object.keys(inlineFlowStates)\n .filter((key) => inlineFlowStates[key] === 'absent')\n .join('\\u0000');\n useEffect(() => {\n if (goneKeys === '' || inlineHolder === undefined) return;\n for (const key of goneKeys.split('\\u0000')) inlineHolder.release(key);\n }, [goneKeys, inlineHolder]);\n const blockAccess = useStableKeys(\n Object.values(placements)\n .filter((placement) => placement.reason === 'access')\n .map((placement) => placement.key),\n );\n\n // One stable object while every state reads the same, so the plan is not recomputed for nothing.\n const previous = useRef<ScreenSources | null>(null);\n const next: Record<string, SourceState> = {\n ...resolved,\n ...(record === undefined ? {} : { record }),\n values,\n scope,\n user,\n route,\n };\n const prior = previous.current;\n const sources =\n prior !== null &&\n Object.keys(prior).length === Object.keys(next).length &&\n Object.keys(next).every((name) => sameState(prior[name], next[name]))\n ? prior\n : (Object.freeze(next) as ScreenSources);\n previous.current = sources;\n\n const failing = useRef(failedKeys);\n failing.current = failedKeys;\n const retry = useCallback(\n (names: readonly string[]) => {\n const keys = new Set<string>();\n for (const name of names) for (const key of failing.current.get(name) ?? []) keys.add(key);\n if (keys.size > 0) refetch([...keys]);\n },\n [refetch],\n );\n return { sources, retry, blockData, placements, fieldAccess, blockAccess, policyRecord };\n}\n\nconst NO_RULES: readonly Rule[] = Object.freeze([]);\nconst NO_ACCESS: FieldAccessMap = Object.freeze({});\nconst NO_KEYS: readonly string[] = Object.freeze([]);\n\n/**\n * Decisions outside create while the record is not ready: a field a `field/view` rule addresses\n * reads the record, so it is `pending` (`failed` when the read failed) until the row is in hand.\n */\nfunction undecidedUntil(\n decided: FieldAccessMap,\n rules: readonly Rule[],\n record: SourceState | undefined,\n): FieldAccessMap {\n const view = record?.status === 'failed' ? 'failed' : 'pending';\n const out: Record<string, FieldAccessMap[string]> = {};\n for (const [field, decision] of Object.entries(decided))\n out[field] = addressesCapability(rules as Rule[], 'view', { kind: 'field', name: field })\n ? Object.freeze({ view, edit: view === 'failed' ? 'readonly' : 'pending' })\n : decision;\n return Object.freeze(out);\n}\n\n/** One identity per decision set (views and edits), so the plan is not recomputed for nothing. */\n/** @internal Also read by the resource-less form controller. */\nexport function useStableAccess(next: FieldAccessMap): FieldAccessMap {\n const previous = useRef<{ key: string; value: FieldAccessMap } | null>(null);\n let key = '';\n for (const [field, decision] of Object.entries(next))\n key += `${field}\\u0000${decision.view}\\u0000${decision.edit}\\u0000${decision.reason ?? ''}\\u0001`;\n if (previous.current !== null && previous.current.key === key) return previous.current.value;\n previous.current = { key, value: next };\n return next;\n}\n\n/** One identity per list of keys. */\nfunction useStableKeys(next: readonly string[]): readonly string[] {\n const previous = useRef<readonly string[]>(NO_KEYS);\n if (sameList(previous.current, next)) return previous.current;\n previous.current = next.length === 0 ? NO_KEYS : Object.freeze(next);\n return previous.current;\n}\n\nconst NO_SUBSCRIBE = () => () => undefined;\nconst ZERO = () => 0;\n\n/**\n * The state of each `buro:inline-flow` placement from its flow's gate over the record: `absent`\n * when the flow is not there for this user and record, `pending` while it is undecided. A flow\n * whose `when` turned false keeps its node while its lease holds unsaved input (the view shows\n * the \"no longer applies\" notice). Only placements with an entry are touched.\n */\nfunction inlineFlowNodeStates(\n compiled: CompiledScreen | null,\n record: SourceState | undefined,\n recordId: string | undefined,\n gate: ReturnType<typeof useFlowRowResolver>,\n dirty: (key: string) => boolean,\n): Readonly<Record<string, NodeState>> {\n const out: Record<string, NodeState> = Object.create(null);\n if (compiled === null || compiled.mode !== 'show') return out;\n const row =\n record?.status === 'ready' && record.value !== null && typeof record.value === 'object'\n ? ({ ...(record.value as Record<string, unknown>), id: recordId } as { id: string })\n : undefined;\n for (const node of compiled.nodes) {\n const placement = node.placement;\n if (node.kind !== 'place' || placement === undefined || node.key === undefined) continue;\n if (placement.block.namespace !== 'buro' || placement.block.id !== 'inline-flow') continue;\n const flow = (placement.props as { readonly flow?: unknown }).flow;\n if (typeof flow !== 'string') continue;\n if (row === undefined) continue;\n const control = gate(flow, row as never);\n if (control.state === 'undecided' || control.state === 'pending') out[node.key] = 'pending';\n else if (control.state === 'absent') {\n if (control.cause === 'when' && dirty(node.key)) continue;\n out[node.key] = 'absent';\n }\n }\n return out;\n}\n\nconst NO_PLACEMENTS: Readonly<Record<string, PlacementRuntime>> = Object.freeze({});\n\n/** `blockData`, one stable object while every placement keeps its state. */\nfunction useStableBlockData(\n placements: Readonly<Record<string, PlacementRuntime>>,\n extra: Readonly<Record<string, NodeState>>,\n): Readonly<Record<string, NodeState>> {\n const previous = useRef<Readonly<Record<string, NodeState>> | null>(null);\n const next = Object.freeze({ ...blockDataOf(placements), ...extra });\n const prior = previous.current;\n const same =\n prior !== null &&\n Object.keys(prior).length === Object.keys(next).length &&\n Object.keys(next).every((key) => prior[key] === next[key]);\n const value = same ? prior : next;\n previous.current = value;\n return value;\n}\n","import { userIdOf, useContextSnapshot } from '../forms/controller/use-source-resolver.js';\n\n/**\n * The signed-in user's id from the `user` context slot: a non-empty string,\n * or a finite number as a string; `null` without a slot, while the slot is\n * pending and for an empty id. The one user-id read of the framework (drafts,\n * sign-out, recent records).\n */\nexport function useCurrentUserId(): string | null {\n return userIdOf(useContextSnapshot().user);\n}\n","import type { StoredAttempt } from '@burojs/core';\n\n/** The `BroadcastChannel` the attempts store talks over (4.10). */\nexport const ATTEMPTS_CHANNEL = 'buro:attempts';\n\n/** The part of `BroadcastChannel` the store uses: a test passes an in-memory one. */\nexport interface BroadcastChannelLike {\n postMessage(message: unknown): void;\n addEventListener(type: 'message', listener: (event: { readonly data: unknown }) => void): void;\n removeEventListener(type: 'message', listener: (event: { readonly data: unknown }) => void): void;\n close?(): void;\n}\n\n/** The part of the Web Locks `LockManager` the store uses. */\nexport interface LockManagerLike {\n request<T>(\n name: string,\n options: { readonly ifAvailable: true },\n callback: (lock: unknown) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * The query/reply protocol between tabs (4.10, B2). Every message names the user, so a tab\n * signed in as someone else ignores it; it carries only the stored attempt's own fields, never a\n * value, an input, `args` or a `result`.\n *\n * - `ask`: a tab opening a flow, or about to write ahead inside the lock, asks for the slot.\n * - `reply`: every tab holding a `pending` or `unknown` entry for that slot answers with it.\n * - `settled`: a tab persisted an outcome (removed, or unknown) or dropped an entry.\n */\nexport type AttemptsMessage =\n | {\n readonly kind: 'ask';\n readonly user: string;\n readonly ask: { readonly attempt: string };\n }\n | { readonly kind: 'reply'; readonly user: string; readonly attempt: StoredAttempt }\n | {\n readonly kind: 'settled';\n readonly user: string;\n readonly settled: {\n /** `attemptKey({ user, flow, slot })`. */\n readonly attempt: string;\n readonly key: string;\n readonly to: 'remove' | 'unknown';\n };\n };\n\nconst ATTEMPT_FIELDS = [\n 'at',\n 'bodyHash',\n 'flow',\n 'key',\n 'mutation',\n 'slot',\n 'state',\n 'user',\n 'v',\n] as const;\n\n/** A stored attempt as exactly its own fields (what storage and the channel may hold). */\nexport function attemptFields(entry: StoredAttempt): StoredAttempt {\n return Object.freeze({\n v: 1,\n user: entry.user,\n flow: entry.flow,\n slot: entry.slot,\n mutation: entry.mutation,\n key: entry.key,\n bodyHash: entry.bodyHash,\n state: entry.state,\n at: entry.at,\n });\n}\n\n/** Whether a value is a well-formed stored attempt (storage and messages are untrusted). */\nexport function isStoredAttempt(value: unknown): value is StoredAttempt {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;\n const entry = value as Record<string, unknown>;\n if (Object.keys(entry).length !== ATTEMPT_FIELDS.length) return false;\n return (\n entry.v === 1 &&\n typeof entry.user === 'string' &&\n typeof entry.flow === 'string' &&\n typeof entry.slot === 'string' &&\n typeof entry.mutation === 'string' &&\n typeof entry.key === 'string' &&\n typeof entry.bodyHash === 'string' &&\n (entry.state === 'pending' || entry.state === 'unknown') &&\n typeof entry.at === 'number' &&\n Number.isFinite(entry.at)\n );\n}\n\n/** Whether a channel message is one of the protocol's (anything else is ignored). */\nexport function isAttemptsMessage(value: unknown): value is AttemptsMessage {\n if (value === null || typeof value !== 'object') return false;\n const message = value as Record<string, unknown>;\n if (typeof message.user !== 'string') return false;\n if (message.kind === 'ask') {\n const ask = message.ask as Record<string, unknown> | null;\n return ask !== null && typeof ask === 'object' && typeof ask.attempt === 'string';\n }\n if (message.kind === 'reply') return isStoredAttempt(message.attempt);\n if (message.kind === 'settled') {\n const settled = message.settled as Record<string, unknown> | null;\n return (\n settled !== null &&\n typeof settled === 'object' &&\n typeof settled.attempt === 'string' &&\n typeof settled.key === 'string' &&\n (settled.to === 'remove' || settled.to === 'unknown')\n );\n }\n return false;\n}\n","import {\n ATTEMPT_MAX_AGE_MS,\n ATTEMPT_REPLY_WINDOW_MS,\n ATTEMPT_SIGN_OUT_WAIT_MS,\n type FlowAttemptsPort,\n type SessionRotationReason,\n type StoredAttempt,\n attemptKey,\n} from '@burojs/core';\nimport {\n ATTEMPTS_CHANNEL,\n type AttemptsMessage,\n type BroadcastChannelLike,\n type LockManagerLike,\n attemptFields,\n isAttemptsMessage,\n isStoredAttempt,\n} from './attempts-channel.js';\n\nexport type { BroadcastChannelLike, LockManagerLike } from './attempts-channel.js';\n\nconst PREFIX = 'buro:attempt:v1:';\n\n/** A lock refused: another holder (another tab, or another run of this one) has the slot. */\nconst BUSY = 'busy' as const;\n\nexport interface CreateAttemptsStoreOptions {\n /** The signed-in user; every key, lock and message is theirs. */\n readonly user: string;\n /** Default: `window.sessionStorage` (the tab's lifetime, surviving a reload). */\n readonly storage?: Storage;\n /** Default: a `BroadcastChannel('buro:attempts')` when the platform has one. */\n readonly channel?: BroadcastChannelLike;\n /** Default: `navigator.locks` when the platform has it. */\n readonly locks?: LockManagerLike;\n readonly clock: {\n now(): number;\n wait(ms: number): Promise<void>;\n };\n}\n\n/**\n * The attempts store of one tab for one user (spec 4.10): write-ahead entries in\n * `sessionStorage` under `buro:attempt:v1:` and the URI-encoded `attemptKey`\n * (`<user>:<flow>:<slot>`), a Web Lock per attempt key, and the query/reply protocol over `BroadcastChannel` so a tab opened\n * late, or one already open, learns of another tab's attempt before it writes. Every entry is\n * keyed by its flow: two flows on one record never share, overwrite or clear each other's\n * attempt. The machine reaches it through {@link AttemptsStore.port}.\n */\nexport interface AttemptsStore {\n readonly user: string;\n /** The machine's port: every method takes `attemptKey({ user, flow, slot })`. */\n readonly port: FlowAttemptsPort;\n /**\n * A session rotation (4.10, I4): `sign-out` and `user-change` wait for `settled` (the tab's\n * in-flight send persisting its outcome) at most `ATTEMPT_SIGN_OUT_WAIT_MS` — past it, a\n * write still in flight keeps its attempt as `unknown` — then remove every other attempt of\n * this user;\n * `forced-sign-out`, `sign-in` and a rotation without a reason keep them.\n */\n onRotation(reason: SessionRotationReason | undefined, settled: Promise<void>): Promise<void>;\n /** Settles when every send this store wrote ahead has persisted its outcome. */\n idle(): Promise<void>;\n /** Re-reads storage after a back/forward-cache restore (M9) and tells the listeners. */\n resync(): void;\n /** Called when an entry this tab sees changed (another tab settled, a resync). */\n subscribe(listener: () => void): () => void;\n dispose(): void;\n}\n\nlet warnedDegraded = false;\n\n// Core-free React package code may read `process.env.NODE_ENV`; bundlers fold it.\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } };\n\nfunction defaultStorage(): Storage | undefined {\n try {\n return typeof window === 'undefined' ? undefined : window.sessionStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction defaultChannel(): BroadcastChannelLike | undefined {\n try {\n const Channel = (\n globalThis as { BroadcastChannel?: new (name: string) => BroadcastChannelLike }\n ).BroadcastChannel;\n return Channel === undefined ? undefined : new Channel(ATTEMPTS_CHANNEL);\n } catch {\n return undefined;\n }\n}\n\nfunction defaultLocks(): LockManagerLike | undefined {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n return locks !== undefined && typeof locks.request === 'function' ? locks : undefined;\n}\n\nconst segment = (value: string) => encodeURIComponent(value);\n\n/** Creates the tab's attempts store for `user` (plan Names: B.3). */\nexport function createAttemptsStore(options: CreateAttemptsStoreOptions): AttemptsStore {\n const { user, clock } = options;\n const storage = options.storage ?? defaultStorage();\n const ownChannel = options.channel === undefined;\n const channel = options.channel ?? defaultChannel();\n const locks = options.locks ?? defaultLocks();\n if (\n (channel === undefined || locks === undefined) &&\n !warnedDegraded &&\n process.env.NODE_ENV !== 'production'\n ) {\n warnedDegraded = true;\n console.warn(\n `[burojs] Flow attempts are protected per tab only: this browser has no ${\n locks === undefined ? 'Web Locks' : 'BroadcastChannel'\n }, so another tab cannot learn of an attempt this one sent.`,\n );\n }\n /** The entry's storage key: the prefix and its `attemptKey` (`<user>:<flow>:<slot>`), encoded. */\n const storageKey = (attempt: string) => `${PREFIX}${segment(attempt)}`;\n const lockName = (attempt: string) => `buro:attempt:${segment(attempt)}`;\n /** The keys of the entries this store wrote `pending` and has not settled: truly in flight. */\n const live = new Map<string, { readonly done: Promise<void>; readonly resolve: () => void }>();\n /** In-tab locks when the platform has no Web Locks. */\n const held = new Set<string>();\n const listeners = new Set<() => void>();\n let disposed = false;\n\n const notify = () => {\n for (const listener of [...listeners]) listener();\n };\n const post = (message: AttemptsMessage) => {\n if (disposed) return;\n try {\n channel?.postMessage(message);\n } catch {\n // A closed channel: the protection is per tab.\n }\n };\n\n const write = (entry: StoredAttempt) => {\n try {\n storage?.setItem(storageKey(attemptKey(entry)), JSON.stringify(attemptFields(entry)));\n } catch {\n // A full or blocked storage: the lock and the in-memory run still hold the intent.\n }\n };\n const remove = (attempt: string) => {\n try {\n storage?.removeItem(storageKey(attempt));\n } catch {\n // Nothing to remove.\n }\n };\n /** The raw entry under `attempt`, validated (its own key, this user), unexpired; else `null`. */\n const raw = (attempt: string): StoredAttempt | null => {\n let parsed: unknown;\n try {\n const text = storage?.getItem(storageKey(attempt));\n if (text === null || text === undefined) return null;\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (!isStoredAttempt(parsed) || parsed.user !== user || attemptKey(parsed) !== attempt)\n return null;\n if (parsed.at < clock.now() - ATTEMPT_MAX_AGE_MS) {\n remove(attempt);\n return null;\n }\n return parsed;\n };\n /**\n * An entry as the machine reads it (write-ahead, 4.10): a `pending` entry this store did not\n * write in this page load belongs to a tab that died mid-flight, so it reads `unknown`.\n */\n const read = (attempt: string): StoredAttempt | null => {\n const entry = raw(attempt);\n if (entry === null) return null;\n if (entry.state === 'pending' && !live.has(attempt))\n return Object.freeze({ ...entry, state: 'unknown' });\n return entry;\n };\n const release = (attempt: string) => {\n const entry = live.get(attempt);\n live.delete(attempt);\n entry?.resolve();\n };\n\n const onMessage = (event: { readonly data: unknown }) => {\n const message = event.data;\n if (disposed || !isAttemptsMessage(message) || message.user !== user) return;\n if (message.kind === 'ask') {\n const entry = read(message.ask.attempt);\n if (entry !== null) post({ kind: 'reply', user, attempt: attemptFields(entry) });\n return;\n }\n if (message.kind === 'settled') {\n const { attempt, key, to } = message.settled;\n const entry = raw(attempt);\n if (entry === null || entry.key !== key) return;\n if (to === 'remove') remove(attempt);\n else write({ ...entry, state: 'unknown' });\n notify();\n }\n // Replies are collected by the asking `ask` only.\n };\n channel?.addEventListener('message', onMessage);\n\n /** Asks the other tabs for `attempt`; a reply is kept as a local `unknown` entry. */\n const askOthers = async (attempt: string): Promise<StoredAttempt | null> => {\n if (channel === undefined || disposed) return null;\n let answer: StoredAttempt | null = null;\n const collect = (event: { readonly data: unknown }) => {\n const message = event.data;\n if (\n answer === null &&\n isAttemptsMessage(message) &&\n message.kind === 'reply' &&\n message.user === user &&\n message.attempt.user === user &&\n attemptKey(message.attempt) === attempt\n )\n answer = message.attempt;\n };\n channel.addEventListener('message', collect);\n try {\n post({ kind: 'ask', user, ask: { attempt } });\n await clock.wait(ATTEMPT_REPLY_WINDOW_MS);\n } finally {\n channel.removeEventListener('message', collect);\n }\n const found = answer as StoredAttempt | null;\n if (found === null) return null;\n // Another tab holds it: here it is unknown (this tab holds no body and no request).\n const local = Object.freeze({ ...attemptFields(found), state: 'unknown' as const });\n if (raw(attempt) === null) write(local);\n return local;\n };\n\n /** The in-tab lock: what a platform without Web Locks (or a refusing one) falls back to. */\n const tabLock = async <T>(name: string, fn: () => Promise<T>): Promise<T | 'busy'> => {\n if (held.has(name)) return BUSY;\n held.add(name);\n try {\n return await fn();\n } finally {\n held.delete(name);\n }\n };\n let warnedLockRefused = false;\n const lock = async <T>(attempt: string, fn: () => Promise<T>): Promise<T | 'busy'> => {\n const name = lockName(attempt);\n if (locks === undefined) return tabLock(name, fn);\n let entered = false;\n try {\n return await locks.request(name, { ifAvailable: true }, async (granted) => {\n if (granted === null) return BUSY;\n entered = true;\n return fn();\n });\n } catch (error) {\n // The send itself failed inside the lock: its own error, as it came.\n if (entered) throw error;\n // The platform refused the lock (a `SecurityError` in an opaque-origin frame): the run\n // falls back to the in-tab lock rather than staying `running` (P4-B review M1).\n if (!warnedLockRefused && process.env.NODE_ENV !== 'production') {\n warnedLockRefused = true;\n console.warn(\n '[burojs] Web Locks refused a flow lock; this tab falls back to its own lock.',\n error,\n );\n }\n return tabLock(name, fn);\n }\n };\n\n const port: FlowAttemptsPort = Object.freeze({\n lock,\n read,\n async ask(attempt: string) {\n return read(attempt) ?? (await askOthers(attempt));\n },\n writePending(entry: StoredAttempt) {\n if (entry.user !== user) throw new TypeError(\"An attempt is written under its user's store.\");\n const attempt = attemptKey(entry);\n let resolve!: () => void;\n const done = new Promise<void>((settle) => {\n resolve = settle;\n });\n release(attempt);\n live.set(attempt, { done, resolve });\n write(Object.freeze({ ...entry, state: 'pending' }));\n },\n settle(attempt: string, key: string, to: 'remove' | 'unknown') {\n const entry = raw(attempt);\n if (entry !== null && entry.key === key) {\n if (to === 'remove') remove(attempt);\n else write({ ...entry, state: 'unknown' });\n }\n release(attempt);\n post({ kind: 'settled', user, settled: { attempt, key, to } });\n },\n drop(attempt: string) {\n const entry = raw(attempt);\n remove(attempt);\n release(attempt);\n if (entry !== null)\n post({ kind: 'settled', user, settled: { attempt, key: entry.key, to: 'remove' } });\n },\n });\n\n return {\n user,\n port,\n async onRotation(reason, settled) {\n if (reason !== 'sign-out' && reason !== 'user-change') return;\n // Bounded (review I4): a write held behind an auth recovery that itself waits for this\n // sign-out would otherwise wait forever. Past the bound, what is still in flight stays.\n let timedOut = false;\n await Promise.race([\n settled,\n clock.wait(ATTEMPT_SIGN_OUT_WAIT_MS).then(() => {\n timedOut = true;\n }),\n ]);\n const kept = new Set<string>();\n if (timedOut)\n for (const attempt of live.keys()) {\n const entry = raw(attempt);\n if (entry === null) continue;\n write({ ...entry, state: 'unknown' });\n kept.add(storageKey(attempt));\n }\n removeAttempts(storage, (owner) => owner === user, kept);\n notify();\n },\n idle() {\n return Promise.all([...live.values()].map((entry) => entry.done)).then(() => undefined);\n },\n resync() {\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n channel?.removeEventListener('message', onMessage);\n if (ownChannel) channel?.close?.();\n listeners.clear();\n },\n };\n}\n\n/** The user an attempt entry belongs to; `null` for an unreadable entry. */\nfunction ownerOf(storage: Storage, key: string): string | null {\n try {\n const parsed: unknown = JSON.parse(storage.getItem(key) ?? 'null');\n return isStoredAttempt(parsed) ? parsed.user : null;\n } catch {\n return null;\n }\n}\n\n/** Removes every attempt entry whose owner `doomed` picks (an unreadable one included); how many. */\nfunction removeAttempts(\n storage: Storage | undefined,\n doomed: (owner: string | null) => boolean,\n keep: ReadonlySet<string> = new Set(),\n): number {\n if (storage === undefined) return 0;\n try {\n const keys: string[] = [];\n for (let index = 0; index < storage.length; index += 1) {\n const key = storage.key(index);\n if (key?.startsWith(PREFIX) && !keep.has(key) && doomed(ownerOf(storage, key)))\n keys.push(key);\n }\n for (const key of keys) storage.removeItem(key);\n return keys.length;\n } catch {\n return 0;\n }\n}\n\n/**\n * Removes every attempt in `storage` whose user is not `user` (a different user signed in in\n * this tab, I4); how many were removed.\n * @internal\n */\nexport function clearOtherUsersAttempts(\n user: string,\n storage: Storage | undefined = defaultStorage(),\n): number {\n return removeAttempts(storage, (owner) => owner !== user);\n}\n\n/**\n * Whether the tab's store holds an unresolved attempt under `attempt` (`attemptKey`): a draft of\n * that flow survives a forced sign-out (P4-B review M5).\n * @internal\n */\nexport function hasStoredAttempt(\n attempt: string,\n storage: Storage | undefined = defaultStorage(),\n): boolean {\n try {\n const parsed: unknown = JSON.parse(storage?.getItem(`${PREFIX}${segment(attempt)}`) ?? 'null');\n return isStoredAttempt(parsed) && attemptKey(parsed) === attempt;\n } catch {\n return false;\n }\n}\n","import {\n createContext,\n type ReactElement,\n type ReactNode,\n useContext,\n useEffect,\n useState,\n} from 'react';\nimport { useSessionParticipant } from '../data/use-session-participant.js';\nimport { useCurrentUserId } from '../hooks/use-current-user-id.js';\nimport {\n type AttemptsStore,\n type CreateAttemptsStoreOptions,\n clearOtherUsersAttempts,\n createAttemptsStore,\n} from './attempts-store.js';\n\n/**\n * What the tab's store is built over: the platform's `sessionStorage`, `BroadcastChannel`, Web\n * Locks and timers by default. A test supplies an in-memory world from outside the provider.\n * @internal\n */\nexport type FlowAttemptsEnvironment = Omit<CreateAttemptsStoreOptions, 'user'>;\nexport const FlowAttemptsEnvironmentContext = createContext<FlowAttemptsEnvironment | null>(null);\n\n/** The tab's attempts store for the signed-in user; `null` without one (ruling 13). */\nconst FlowAttemptsContext = createContext<AttemptsStore | null>(null);\n\n/** @internal The tab's attempts store for the signed-in user, once it is created. */\nexport function useFlowAttemptsStore(): AttemptsStore | null {\n return useContext(FlowAttemptsContext);\n}\n\nconst wait = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n\n/**\n * Mounts the tab's attempts store (spec 4.10) for the signed-in user, for the provider's\n * lifetime, so the tab answers other tabs' queries even when no flow is open. It takes part in\n * the data session's rotations: a sign-out (and a user change) waits for this tab's in-flight\n * send to persist, then clears the user's attempts; a forced sign-out and a sign-in keep them.\n * When another user signs in in this tab, the previous users' attempts are removed. On a\n * back/forward-cache restore (`pageshow` with `persisted`) the store re-reads storage and every\n * open flow re-syncs from it (M9). Re-created under StrictMode (Known finding 20).\n * @internal\n */\nexport function FlowAttemptsProvider({ children }: { readonly children: ReactNode }): ReactElement {\n const userId = useCurrentUserId();\n const environment = useContext(FlowAttemptsEnvironmentContext);\n const [store, setStore] = useState<AttemptsStore | null>(null);\n useEffect(() => {\n if (userId === null) {\n setStore(null);\n return;\n }\n clearOtherUsersAttempts(userId, environment?.storage);\n const created = createAttemptsStore({\n clock: { now: () => Date.now(), wait },\n ...environment,\n user: userId,\n });\n setStore(created);\n return () => {\n created.dispose();\n };\n }, [userId, environment]);\n useSessionParticipant((_next, _previous, reason) =>\n store === null ? undefined : store.onRotation(reason, store.idle()),\n );\n useEffect(() => {\n if (store === null || typeof window === 'undefined') return;\n const onPageShow = (event: Event) => {\n if ((event as PageTransitionEvent).persisted === true) store.resync();\n };\n window.addEventListener('pageshow', onPageShow);\n return () => window.removeEventListener('pageshow', onPageShow);\n }, [store]);\n return <FlowAttemptsContext.Provider value={store}>{children}</FlowAttemptsContext.Provider>;\n}\n","import {\n type CompiledScreen,\n addressesCapability,\n fieldSensitivity,\n type ResourceFieldMap,\n type Rule,\n type ScreenPlan,\n} from '@burojs/core';\nimport type { FormValues } from '../types.js';\n\nexport type { FormDraftState } from './types.js';\n\n/** How often a dirty form's draft is stored. */\nexport const DRAFT_INTERVAL_MS = 1000;\n\n/** A `localStorage` draft older than this is dropped on read, not offered (the old form's rule). */\nexport const DRAFT_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** Where a draft lives (spec 4.11): the tab's `sessionStorage` by default, or `localStorage`. */\nexport type DraftStore = 'session' | 'local';\n\nexport interface DraftKeyInput {\n readonly userId: string;\n readonly formId: string;\n /** `flow`: a flow's form (its `formId` is `<resource>/actions/<name>` or `app/<name>`). */\n readonly mode: 'create' | 'edit' | 'flow';\n readonly recordId?: string;\n readonly type?: string;\n /** A flow started with `args`: an FNV hash of them (the attempt slot's segment, 4.10). */\n readonly argsHash?: string;\n /** A single-mutation bulk flow: a hash of its selection. */\n readonly selectionHash?: string;\n /**\n * A hash of the data session's scope (the tenant): a draft typed in one scope is never offered\n * in another (P4-B review M4). Absent without a data runtime.\n */\n readonly scopeHash?: string;\n}\n\n/** The prefix of every draft key, any version. */\nconst DRAFT_PREFIX = 'buro:draft:';\nconst V2_PREFIX = 'buro:draft:v2:';\nconst V3_PREFIX = 'buro:draft:v3:';\n\n/**\n * The storage key of a form's draft (spec 4.11):\n * `buro:draft:v3:<user>:<formId>:<mode>:<id|create|_>[:t=<type>][:a=<argsHash>][:s=<selectionHash>][:sc=<scopeHash>]`.\n * A create's id segment is `create`, a flow's the record's id or `_`. Each segment is URI-component\n * encoded, so a `:` in one cannot shift the segments of another key. Keyed by the user, so one\n * browser never offers one user's draft to another.\n */\nexport function draftKey(input: DraftKeyInput): string {\n const id =\n input.mode === 'create'\n ? 'create'\n : input.recordId === undefined\n ? input.mode === 'flow'\n ? '_'\n : 'create'\n : segment(input.recordId);\n return `${V3_PREFIX}${segment(input.userId)}:${segment(input.formId)}:${input.mode}:${id}${\n input.type === undefined ? '' : `:t=${segment(input.type)}`\n }${input.argsHash === undefined ? '' : `:a=${segment(input.argsHash)}`}${\n input.selectionHash === undefined ? '' : `:s=${segment(input.selectionHash)}`\n }${input.scopeHash === undefined ? '' : `:sc=${segment(input.scopeHash)}`}`;\n}\n\n/** One key segment, escaped: a `:` in an id can never shift the segments of another key. */\nfunction segment(value: string): string {\n return encodeURIComponent(value);\n}\n\n/** What is stored under a draft key. */\nexport interface StoredDraft {\n readonly version: 3;\n readonly savedAt: string;\n readonly values: FormValues;\n /** Edit only: the version of the record the draft was made over ({@link recordVersionOf}). */\n readonly recordVersion?: string;\n /**\n * A flow's form only: the attempt key of its run. While that attempt is unresolved, a forced\n * sign-out of the same user keeps the draft (P4-B review M5).\n */\n readonly attempt?: string;\n}\n\n/** The store's `Storage`, or `undefined` where it is absent or blocked. */\nexport function draftStorage(store: DraftStore): Storage | undefined {\n try {\n if (typeof window === 'undefined') return undefined;\n return store === 'local' ? window.localStorage : window.sessionStorage;\n } catch {\n return undefined;\n }\n}\n\n/** The store a `draft` option names: `'local'` only when it says so (spec 4.11). */\nexport function draftStoreOf(option: unknown): DraftStore {\n return option !== null &&\n typeof option === 'object' &&\n (option as { readonly store?: unknown }).store === 'local'\n ? 'local'\n : 'session';\n}\n\n/** The draft stored under `key`, or `null` (none, unreadable, or not a v3 draft). */\nexport function readDraft(key: string, store: DraftStore = 'session'): StoredDraft | null {\n const storage = draftStorage(store);\n try {\n const raw = storage?.getItem(key);\n if (raw === null || raw === undefined) return null;\n const parsed = JSON.parse(raw) as Partial<StoredDraft> | null;\n if (\n parsed === null ||\n typeof parsed !== 'object' ||\n parsed.version !== 3 ||\n typeof parsed.savedAt !== 'string' ||\n parsed.values === null ||\n typeof parsed.values !== 'object' ||\n Array.isArray(parsed.values) ||\n (parsed.recordVersion !== undefined && typeof parsed.recordVersion !== 'string') ||\n (parsed.attempt !== undefined && typeof parsed.attempt !== 'string')\n )\n return null;\n // The 24-hour expiry is `localStorage`'s: a session draft dies with its tab.\n if (store === 'local') {\n const age = Date.now() - new Date(parsed.savedAt).getTime();\n if (!Number.isFinite(age) || age > DRAFT_MAX_AGE_MS) {\n storage?.removeItem(key);\n return null;\n }\n }\n return parsed as StoredDraft;\n } catch {\n return null;\n }\n}\n\nexport function writeDraft(\n key: string,\n values: FormValues,\n recordVersion?: string,\n now: Date = new Date(),\n store: DraftStore = 'session',\n attempt?: string,\n): void {\n try {\n const draft: StoredDraft = {\n version: 3,\n savedAt: now.toISOString(),\n values,\n ...(recordVersion === undefined ? {} : { recordVersion }),\n ...(attempt === undefined ? {} : { attempt }),\n };\n draftStorage(store)?.setItem(key, JSON.stringify(draft));\n } catch {\n // A full or blocked storage loses the draft, never the form.\n }\n}\n\n/** Removes the draft under `key` from both stores (a changed `store` option leaves no orphan). */\nexport function clearDraft(key: string): void {\n for (const store of ['session', 'local'] as const) {\n try {\n draftStorage(store)?.removeItem(key);\n } catch {\n // Nothing to clear.\n }\n }\n}\n\n/** Removes every key starting with `prefix` (that `keep` does not keep); how many were removed. */\nfunction removePrefixed(\n storage: Storage | undefined,\n prefix: string,\n keep: (raw: string | null) => boolean = () => false,\n): number {\n if (storage === undefined) return 0;\n try {\n const doomed: string[] = [];\n for (let index = 0; index < storage.length; index += 1) {\n const key = storage.key(index);\n if (key?.startsWith(prefix) && !keep(storage.getItem(key))) doomed.push(key);\n }\n for (const key of doomed) storage.removeItem(key);\n return doomed.length;\n } catch {\n return 0;\n }\n}\n\n/**\n * Removes every draft (`buro:draft:…`, any version, any user) from both stores; how many were\n * removed. Drafts are session-bound (spec 4.11): the data session calls it on every rotation.\n */\nexport function clearAllDrafts(keep?: (draft: StoredDraft) => boolean): number {\n const kept = (raw: string | null): boolean => {\n if (keep === undefined || raw === null) return false;\n try {\n const parsed = JSON.parse(raw) as StoredDraft;\n return parsed !== null && typeof parsed === 'object' && keep(parsed);\n } catch {\n return false;\n }\n };\n return (\n removePrefixed(draftStorage('session'), DRAFT_PREFIX, kept) +\n removePrefixed(draftStorage('local'), DRAFT_PREFIX, kept)\n );\n}\n\n/** Deletes every v2 draft (`buro:draft:v2:…`) once at boot (spec 4.11); how many. */\nexport function migrateDraftsV2(): number {\n return (\n removePrefixed(draftStorage('local'), V2_PREFIX) +\n removePrefixed(draftStorage('session'), V2_PREFIX)\n );\n}\n\n/**\n * The part of a stored draft a restore may apply: only the fields `active` in\n * the current plan, never the discriminator — a draft is a user tier, so a\n * tampered or stale draft reaches no `readonly`, rule-denied, inactive or\n * undeclared field.\n */\nexport function restorableValues(\n stored: Record<string, unknown>,\n plan: ScreenPlan,\n discriminator?: string,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(stored)) {\n if (name === discriminator) continue;\n if (!Object.hasOwn(plan.fields, name) || plan.fields[name] !== 'active') continue;\n out[name] = value;\n }\n return out;\n}\n\n/**\n * Whether a field is `sensitive`, in either form (`true` or a mask function),\n * read off the compiled declaration and the live definition: a compiled\n * declaration carries a mask function as a trusted-attachment descriptor,\n * which `fieldSensitivity` does not read.\n */\nfunction isSensitive(declaration: unknown, definition: unknown): boolean {\n if (fieldSensitivity(declaration) !== undefined || fieldSensitivity(definition) !== undefined)\n return true;\n for (const source of [declaration, definition]) {\n if (source === null || typeof source !== 'object') continue;\n const opts = (source as { readonly opts?: unknown }).opts;\n const marked =\n opts !== null && typeof opts === 'object'\n ? (opts as { readonly sensitive?: unknown }).sensitive\n : undefined;\n if (marked !== undefined && marked !== false) return true;\n }\n return false;\n}\n\n/**\n * What a draft stores (P1b+P1c decision 25): the fields `active` in the\n * current plan, never a `sensitive` one (either form) and never one the\n * resource's `draft.exclude` names. An undeclared key is never stored.\n */\nexport function snapshotValues(\n values: FormValues,\n plan: ScreenPlan,\n compiled: CompiledScreen,\n exclude: readonly string[] = [],\n fieldMap?: ResourceFieldMap,\n /**\n * The form's rules, lowered `requires` included: a field any `field/view` rule addresses is\n * never stored, whether or not this user may view it today (P5 decision 24) — browser storage\n * outlives a permission change.\n */\n rules: readonly Rule[] = [],\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const field of compiled.fields) {\n const name = field.name;\n if (plan.fields[name] !== 'active') continue;\n if (exclude.includes(name)) continue;\n if (isSensitive(field.declaration, fieldMap?.[name])) continue;\n if (addressesCapability(rules as Rule[], 'view', { kind: 'field', name })) continue;\n if (!Object.hasOwn(values, name)) continue;\n out[name] = values[name];\n }\n return out;\n}\n\n/** FNV-1a over a string, as 8 hex digits: a stable, dependency-free fingerprint. */\nfunction fingerprint(text: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < text.length; index += 1) {\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n}\n\nfunction stableJson(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n const entries = Object.keys(value as Record<string, unknown>)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableJson((value as Record<string, unknown>)[key])}`);\n return `{${entries.join(',')}}`;\n}\n\n/**\n * The version of the record an edit draft is made over: its `updated_at`\n * when the resource declares that field and the record holds a string or a\n * number there, else a stable hash of the record's declared-field values.\n */\nexport function recordVersionOf(record: FormValues, compiled: CompiledScreen): string {\n const declared = compiled.fields.map((field) => field.name);\n if (declared.includes('updated_at')) {\n const stamp = record.updated_at;\n if (typeof stamp === 'string' || typeof stamp === 'number') return String(stamp);\n }\n const picked: Record<string, unknown> = {};\n for (const name of declared) if (Object.hasOwn(record, name)) picked[name] = record[name];\n return `h:${fingerprint(stableJson(picked))}`;\n}\n\n/** An id a draft key can carry: a non-empty string or a finite number. */\nexport function draftRecordId(value: unknown): string | undefined {\n if (typeof value === 'string' && value !== '') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return String(value);\n return undefined;\n}\n\n/**\n * Removes every draft of `userId` (`buro:draft:v3:<userId>:…`) from both stores and returns how\n * many were removed. `BuroProvider` calls it when the signed-in user signs out or changes, so a\n * shared browser keeps no one's drafts for the next user.\n */\nexport function clearUserDrafts(userId: string): number {\n const prefix = `${V3_PREFIX}${segment(userId)}:`;\n return (\n removePrefixed(draftStorage('session'), prefix) + removePrefixed(draftStorage('local'), prefix)\n );\n}\n","import { type DataSessionController, fnv1a } from '@burojs/core';\nimport { useContext, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { FlowAttemptsEnvironmentContext } from '../../flows/attempts-binding.js';\nimport { useOptionalDataRuntime } from '../../data/context.js';\nimport { useSessionParticipant } from '../../data/use-session-participant.js';\nimport { useCurrentUserId } from '../../hooks/use-current-user-id.js';\nimport { hasStoredAttempt } from '../../flows/attempts-store.js';\nimport { clearAllDrafts, clearUserDrafts, migrateDraftsV2 } from './draft.js';\n\n/** The recent-records list `@burojs/ui-shadcn`'s record page writes for a user (its `recent-records.ts`). */\nfunction clearUserRecentRecords(userId: string): void {\n try {\n globalThis.localStorage?.removeItem(`buro:recent:v2:${userId}`);\n } catch {\n // Unavailable storage holds nothing to clear.\n }\n}\n\n/**\n * Binds drafts to the data session (spec 4.11, P4-28): every session rotation — a sign-in, a\n * sign-out, a forced sign-out — clears every draft in both stores; a user who signs out or is\n * replaced by another also loses the recent records the record page wrote for them; and the\n * previous version's drafts (`buro:draft:v2:`) are discarded once at mount. A scope change keeps\n * the session key and clears nothing. `BuroProvider` renders it below its context providers,\n * since the provider cannot read its own resolver from its body.\n * @internal\n */\nexport function DraftSessionBinding(): null {\n const userId = useCurrentUserId();\n const attemptsEnvironment = useContext(FlowAttemptsEnvironmentContext);\n const previous = useRef<string | null>(userId);\n useEffect(() => {\n migrateDraftsV2();\n }, []);\n useSessionParticipant((next, before, reason) => {\n if (next.sessionKey === before.sessionKey) return;\n // A forced sign-out (session expiry) keeps a flow's draft while its attempt is unresolved:\n // the user signs back in to the unknown screen with what they typed (P4-B review M5). A\n // user change clears it below; every other rotation clears every draft.\n clearAllDrafts(\n reason === 'forced-sign-out'\n ? (draft) =>\n typeof draft.attempt === 'string' &&\n draft.attempt.startsWith(`${userId ?? ''}:`) &&\n hasStoredAttempt(draft.attempt, attemptsEnvironment?.storage)\n : undefined,\n );\n });\n useEffect(() => {\n const before = previous.current;\n previous.current = userId;\n if (before !== null && before !== userId) {\n clearUserDrafts(before);\n clearUserRecentRecords(before);\n }\n }, [userId]);\n return null;\n}\n\nconst NO_SCOPE = () => () => {};\n\n/**\n * A hash of the data session's scope (the tenant), for the draft key (P4-B review M4): a scope\n * change keeps the session, so the drafts stay, but a draft typed in one scope is never offered\n * in another. `undefined` without a data runtime.\n * @internal\n */\nexport function useDraftScopeHash(): string | undefined {\n const runtime = useOptionalDataRuntime();\n const session = runtime?.dataSession;\n const scopeKey = useSyncExternalStore(\n session === undefined ? NO_SCOPE : session.subscribe,\n () => scopeOf(session),\n () => scopeOf(session),\n );\n return scopeKey === undefined ? undefined : fnv1a(scopeKey);\n}\n\nfunction scopeOf(session: DataSessionController | undefined): unknown {\n if (session === undefined) return undefined;\n const state = session.getState();\n return state.status === 'ready' ? state.snapshot.scopeKey : state.target.scopeKey;\n}\n","import {\n createMutationDescriptor,\n createQueryDescriptor,\n type ActionDataAccess,\n type CustomMutationHandle,\n type CustomQueryHandle,\n type EntityRef,\n type ErasedMutationDescriptor,\n type InferCreateInput,\n type InferCustomInput,\n type InferCustomOutput,\n type InferId,\n type InferUpdateInput,\n type Pagination,\n type ResourceHandle,\n} from '@burojs/core';\n\nimport { executeMutation } from './mutation-options.js';\nimport { executeQuery } from './query-execution.js';\nimport type { DataRuntimeContextValue } from './runtime.js';\n\ntype AnyResource = ResourceHandle<any, any, any, any>;\n\n/**\n * The descriptor fields of a resource read or write under the current lease: the binding, the\n * session and the record's id field.\n * @internal\n */\nexport async function resourceDescriptorBase(\n runtime: DataRuntimeContextValue,\n resource: Pick<AnyResource, 'ref'>,\n) {\n const session = await runtime.waitUntilReady();\n const projection = runtime.app.registry.get(resource as AnyResource);\n if (projection === undefined)\n throw {\n kind: 'configuration',\n code: 'action-data-resource-unavailable',\n message: `Resource '${resource.ref.namespace}:${resource.ref.id}' is unavailable.`,\n };\n const binding = runtime.app.resolveDataBinding(resource as AnyResource);\n return {\n providerId: binding.providerId,\n ref: binding.ref,\n resource: binding.resource,\n sessionKey: session.sessionKey,\n scopeKey: session.scopeKey,\n bindingRevision: runtime.app.runtime.getSnapshot().manifest.snapshotId,\n idField: projection.data?.idField ?? 'id',\n ...(projection.data?.providerOptions === undefined\n ? {}\n : { providerOptions: projection.data.providerOptions }),\n };\n}\n\n/**\n * A custom mutation's descriptor under the current lease, its replay policy resolved from the\n * projection's attachment.\n * @internal\n */\nexport async function customMutationDescriptor(\n runtime: DataRuntimeContextValue,\n ref: EntityRef,\n input: unknown,\n): Promise<ErasedMutationDescriptor> {\n const session = await runtime.waitUntilReady();\n const snapshot = runtime.app.runtime.getSnapshot();\n const projection = snapshot.getProjection({ kind: 'custom-mutation', ref } as never);\n if (projection === undefined || projection.kind !== 'custom-mutation')\n throw {\n kind: 'configuration',\n code: 'action-data-custom-mutation-unavailable',\n message: 'Custom mutation handle is unavailable.',\n };\n const value = projection.value as {\n binding?: {\n provider?: string;\n resource?: string;\n operation?: string;\n providerOptions?: unknown;\n };\n replay?: unknown;\n };\n const binding = value.binding;\n if (!binding?.provider || !binding.operation)\n throw {\n kind: 'configuration',\n code: 'action-data-custom-binding-invalid',\n message: 'Custom mutation binding is invalid.',\n };\n // The projection holds an attachment ({ capability, id }); the descriptor takes the policy string.\n const replay = value.replay as Readonly<Record<string, unknown>> | undefined;\n const policy =\n replay?.capability === 'mutation-replay-policy' && typeof replay.id === 'string'\n ? runtime.app.getPluginCapability('mutation-replay-policy', replay.id)\n : undefined;\n return createMutationDescriptor({\n kind: 'custom',\n providerId: binding.provider,\n ref,\n resource: binding.resource ?? ref.id,\n operation: binding.operation,\n input,\n sessionKey: session.sessionKey,\n scopeKey: session.scopeKey,\n bindingRevision: snapshot.manifest.snapshotId,\n ...(binding.providerOptions === undefined ? {} : { providerOptions: binding.providerOptions }),\n ...(policy === undefined ? {} : { replay: policy }),\n } as never) as ErasedMutationDescriptor;\n}\n\n/** Runtime-owned action DI. Descriptor identity always comes from the current lease. */\nexport function createRuntimeActionDataAccess(runtime: DataRuntimeContextValue): ActionDataAccess {\n const resourceBase = (resource: AnyResource) => resourceDescriptorBase(runtime, resource);\n async function resourceQuery(resource: AnyResource, input: Record<string, unknown>) {\n return executeQuery({\n descriptor: createQueryDescriptor({ ...(await resourceBase(resource)), ...input } as never),\n runtime,\n signal: new AbortController().signal,\n });\n }\n async function resourceMutation(resource: AnyResource, input: Record<string, unknown>) {\n return executeMutation({\n descriptor: createMutationDescriptor({\n ...(await resourceBase(resource)),\n ...input,\n } as never),\n runtime,\n });\n }\n async function customQuery(handle: CustomQueryHandle<unknown, unknown>, input: unknown) {\n const session = await runtime.waitUntilReady();\n const snapshot = runtime.app.runtime.getSnapshot();\n const projection = snapshot.getProjection(handle);\n if (projection === undefined || projection.kind !== 'custom-query')\n throw {\n kind: 'configuration',\n code: 'action-data-custom-query-unavailable',\n message: 'Custom query handle is unavailable.',\n };\n const binding = (\n projection.value as {\n binding?: {\n provider?: string;\n resource?: string;\n operation?: string;\n providerOptions?: unknown;\n };\n }\n ).binding;\n if (!binding?.provider || !binding.operation)\n throw {\n kind: 'configuration',\n code: 'action-data-custom-binding-invalid',\n message: 'Custom query binding is invalid.',\n };\n return executeQuery({\n descriptor: createQueryDescriptor({\n kind: 'custom',\n providerId: binding.provider,\n ref: handle.ref,\n resource: binding.resource ?? handle.ref.id,\n operation: binding.operation,\n input,\n sessionKey: session.sessionKey,\n scopeKey: session.scopeKey,\n bindingRevision: snapshot.manifest.snapshotId,\n ...(binding.providerOptions === undefined\n ? {}\n : { providerOptions: binding.providerOptions }),\n } as never),\n runtime,\n signal: new AbortController().signal,\n });\n }\n async function customMutation(handle: CustomMutationHandle<unknown, unknown>, input: unknown) {\n return executeMutation({\n descriptor: await customMutationDescriptor(runtime, handle.ref, input),\n runtime,\n });\n }\n return Object.freeze({\n one: <R extends AnyResource>(resource: R, { id }: { id: InferId<R> }) =>\n resourceQuery(resource, { kind: 'one', id }),\n list: <R extends AnyResource>(\n resource: R,\n args: { pagination?: Pagination; filter?: unknown; sort?: unknown } = {},\n ) => resourceQuery(resource, { kind: 'list', ...args }),\n many: <R extends AnyResource>(resource: R, { ids }: { ids: readonly InferId<R>[] }) =>\n resourceQuery(resource, { kind: 'many', ids }),\n createOne: <R extends AnyResource>(resource: R, { input }: { input: InferCreateInput<R> }) =>\n resourceMutation(resource, { kind: 'createOne', input }),\n updateOne: <R extends AnyResource>(\n resource: R,\n { id, input }: { id: InferId<R>; input: InferUpdateInput<R> },\n ) => resourceMutation(resource, { kind: 'updateOne', id, input }),\n deleteOne: <R extends AnyResource>(resource: R, { id }: { id: InferId<R> }) =>\n resourceMutation(resource, { kind: 'deleteOne', id }),\n query: <H extends CustomQueryHandle<unknown, unknown>>(handle: H, input: InferCustomInput<H>) =>\n customQuery(handle, input) as Promise<InferCustomOutput<H>>,\n mutate: <H extends CustomMutationHandle<unknown, unknown>>(\n handle: H,\n input: InferCustomInput<H>,\n ) => customMutation(handle, input) as Promise<InferCustomOutput<H>>,\n } as ActionDataAccess);\n}\n\n/**\n * Stand-in `ActionDataAccess` for a DI consumer (`useChecks`/`useCheckGate`)\n * mounted with no native data runtime (`useOptionalDataRuntime()` returned\n * `null` — see `../data/context.tsx`). Every method rejects with `reason`\n * rather than being unavailable outright: a check/rule that never touches\n * `di.data` must keep working normally, and one that DOES gets a clear,\n * named diagnostic instead of a generic \"cannot read properties of null\"\n * crash. `evaluateChecks` already treats a throwing/rejecting predicate as a\n * `check.exception` warning issue (`@burojs/core`'s `evaluate.ts`), so this\n * degrades to a visible, non-blocking \"check failed to run\" rather than\n * silently vanishing or crashing the host form.\n */\nexport function createUnavailableActionDataAccess(reason: string): ActionDataAccess {\n // Typed `() => Promise<never>` (not cast away) so the object literal below\n // is actually checked structurally against `ActionDataAccess` — a fewer-\n // parameter function is assignable to each of the interface's specific\n // (more-parameter) method signatures, and `Promise<never>` is assignable\n // to every method's own `Promise<...>` return type, so this catches a\n // shape drift (a renamed/added/removed method) at compile time instead of\n // silently no-op'ing behind a cast.\n const fail = (): Promise<never> => Promise.reject(new Error(reason));\n return Object.freeze({\n one: fail,\n list: fail,\n many: fail,\n createOne: fail,\n updateOne: fail,\n deleteOne: fail,\n query: fail,\n mutate: fail,\n });\n}\n","import { createContext, useContext } from 'react';\n\n/**\n * The `route` source of the screen below (spec 4.5): `{ id }` from the record route on show and\n * edit, `{}` on its create, a page's declared params from the page host. Only those routes\n * provide it; any other mount — a `<RecordScreen>` outside the record route, a nested screen —\n * reads `{}`. Values are what the route parsed (a page param's schema may coerce); `''` reads\n * `null` (the resolver normalises it).\n *\n * @internal Provided by `@burojs/ui-shadcn`'s record route and page host.\n */\nexport const RouteSourceContext = createContext<Readonly<Record<string, unknown>> | null>(null);\n\n/** The `route` the nearest record route or page host provides; `null` when none does. */\nexport function useRouteSource(): Readonly<Record<string, unknown>> | null {\n return useContext(RouteSourceContext);\n}\n\n/** `route` where no route provides one. */\nexport const EMPTY_ROUTE: Readonly<Record<string, unknown>> = Object.freeze({});\n","'use client';\nimport type { Audit } from '@burojs/core';\nimport { useContext } from 'react';\nimport { AuditContext } from './context.js';\n\n/**\n * The framework's own audit emitter (`form.submit`, `flow.submit`): the whole `Audit`, which\n * `useAudit()` narrows to `app.*` events for applications. Not exported from the package.\n * @internal\n */\nexport function useFrameworkAudit(): Audit | null {\n return useContext(AuditContext);\n}\n","'use client';\nimport { type AuditFieldDiff, buildFormDiff } from '@burojs/core';\nimport { useCallback, useMemo } from 'react';\nimport { useFrameworkAudit } from './internal.js';\n\n/**\n * `errorCode` on a degraded `form.submit` event — `buildFormDiff` itself\n * threw (e.g. malformed `fields`/`before`/`after` from a caller) rather than\n * one field's own redaction failing. `outcome` still reflects what the host\n * reported about the actual submit; this code only says the audit machinery\n * could not describe what changed.\n */\nconst DIFF_BUILD_FAILED = 'audit-diff-build-failed';\n\nexport interface FormSubmitAuditArgs {\n /** Values as the form opened — captured BEFORE the write, since a host may re-baseline after it. */\n readonly before: Readonly<Record<string, unknown>>;\n readonly after: Readonly<Record<string, unknown>>;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly outcome: 'success' | 'error' | 'invalid';\n readonly resource?: string;\n readonly recordId?: string;\n readonly view?: 'create' | 'edit';\n /**\n * A backend-reported error code (e.g. `'backend-500'`, design doc §4.1) —\n * plumbing for a host to report WHY an `'error'` outcome happened, distinct\n * from `audit-diff-build-failed` below (which means the audit machinery\n * itself, not the submit, failed). Ignored on any other outcome.\n */\n readonly errorCode?: string;\n}\n\nexport interface FormSubmitAudit {\n /**\n * False when the app configured no sink. Hosts check it before copying their\n * values — that check is what makes an unaudited app pay nothing.\n */\n readonly enabled: boolean;\n readonly emit: (args: FormSubmitAuditArgs) => void;\n}\n\n/**\n * The single place a `form.submit` event is constructed.\n *\n * Its host is `useFormController`. A second form host shares this hook rather\n * than a copied block, so the redaction branch cannot drift between them.\n */\nexport function useFormSubmitAudit(): FormSubmitAudit {\n const audit = useFrameworkAudit();\n\n const emit = useCallback(\n (args: FormSubmitAuditArgs): void => {\n if (!audit) return;\n\n // `buildFormDiff` guards every FIELD-level failure internally (a\n // throwing mask redacts, an unknown field redacts), but it can still\n // throw as a whole on a malformed call — e.g. a host passing a nullish\n // `fields`/`before`/`after`. `buildFormDiff` is itself a public\n // `@burojs/react` export an adopter's own code can call directly, so\n // this construction site cannot assume a well-formed call reached it.\n // `createAudit` already guards every app-supplied callback (the sink,\n // the actor getter) on the same principle — observability must never\n // break the UI — and this is the one step of `emit` that was left\n // unguarded. On failure the event still goes out, with an empty diff\n // and `errorCode` marking it degraded, rather than silently dropping\n // the action or falling back to raw values.\n // The caller's own `errorCode` (a backend diagnostic) is the default;\n // a `buildFormDiff` crash overrides it below rather than the reverse,\n // because at that point the event ALSO cannot honestly describe what\n // changed — that is the more urgent fact for whoever reads this event,\n // and it must not be silently dropped in favour of the backend code.\n let diff: Readonly<Record<string, AuditFieldDiff>>;\n let errorCode: string | undefined = args.errorCode;\n try {\n diff = buildFormDiff({\n before: args.before,\n after: args.after,\n fields: args.fields,\n });\n } catch {\n diff = {};\n errorCode = DIFF_BUILD_FAILED;\n }\n\n audit.emit(\n {\n type: 'form.submit',\n outcome: args.outcome,\n resource: args.resource,\n recordId: args.recordId,\n view: args.view,\n diff,\n errorCode,\n },\n { initiates: true },\n );\n },\n [audit],\n );\n\n // Memoized: this return value lands in `handleSubmit`'s dependency array in\n // both form hosts, so a fresh object identity on every render would\n // invalidate that `useCallback` every render too — defeating the point of\n // memoizing `handleSubmit` at all.\n return useMemo(() => ({ enabled: audit !== null, emit }), [audit, emit]);\n}\n","import type { AppContext, PermissionMap } from '@burojs/core';\nimport { useCallback, useContext, useSyncExternalStore } from 'react';\nimport { ResolverContext } from '../context.js';\nimport { useCtx } from './use-ctx.js';\n\n/**\n * Read the current `permissions` slice from AppContext.\n *\n * Returns `undefined` when no `permissions` slice has been wired (default —\n * adopters opt INTO permissions by registering a slice that emits a\n * PermissionMap value). Callers MUST handle the undefined case; the\n * convention is fail-closed (treat missing permissions as \"deny\" inside\n * `visible(ctx)` predicates) — see `evaluateVisible` in `@burojs/core`.\n */\nexport function usePermissions(): PermissionMap | undefined {\n return useCtx((ctx: AppContext) => ctx.permissions);\n}\n\n/**\n * Read the current `scope` slice from AppContext.\n *\n * Returns `undefined` when no `scope` slice has been wired (default — the\n * scope slot is opt-in). The slot is intentionally typed as\n * `Record<string, unknown>` so adopters define the shape (PG, location,\n * warehouse, tenant…) and read keys with `ctx.scope?.<key>` inside their\n * `visible(ctx)` predicates.\n */\nexport function useScopeCtx(): Record<string, unknown> | undefined {\n return useCtx((ctx: AppContext) => ctx.scope);\n}\n\n/**\n * Build a snapshot of the AppContext suitable for passing to `evaluateVisible`.\n *\n * Aggregates every built-in slot the framework consumes for visibility\n * predicates: `{ permissions, scope, user }`.\n *\n * ⚠️ `user` was MISSING here, and the omission was silent and unsafe. It is a\n * documented built-in slot (`AppContext.user`, \"consumed by the\n * capability-rules engine so predicates can gate on `ctx.user.roles`\"), and\n * `useCapabilityResolver` reads all three — so the same predicate behaved\n * differently depending on whether it was written as a `rules:` entry (worked)\n * or as a field/resource/action `visible` (saw `undefined`).\n *\n * The failure mode is data exposure, because the natural phrasing fails OPEN:\n *\n * visible: (ctx) => !ctx.user?.roles.includes('external_auditor')\n * // ctx.user === undefined → !undefined → TRUE → shown to the auditor\n *\n * and the mirror phrasing (`?? false`) hides the field from everyone including\n * the users who should see it. Both compile, neither warns.\n *\n * This docblock previously claimed call sites \"pick up new built-in slots\n * automatically when they are added\" — which is exactly what did not happen.\n */\nexport function useVisibilityCtx(): AppContext {\n const permissions = usePermissions();\n const scope = useScopeCtx();\n const user = useCtx((c: AppContext) => c.user);\n return { permissions, scope, user };\n}\n\nconst EMPTY_APP_CONTEXT: AppContext = Object.freeze({});\n\n/**\n * Like `useVisibilityCtx`, but tolerant of a missing `BuroProvider` —\n * returns `{}` instead of throwing outside one.\n *\n * Mirrors `useCurrentUIActivation`'s (`../ui/use-ui-present.ts`) \"works\n * standalone\" precedent: a headless hook meant to be instantiable via a bare\n * `renderHook(() => useX(...))`, with no wrapper, needs graceful\n * degradation rather than `useCtx`'s hard `must be used within a\n * BuroProvider` throw. The form controller (`useFormController`) is the\n * consumer: a form with no predicate `required`/`disabled` fields must not\n * need a full app `BuroProvider` tree just to mount and be unit-tested —\n * `renderHook(() => useFormController(...))` tests (no wrapper) keep passing\n * while the controller reads a visibility ctx.\n *\n * Inside a real `BuroProvider`, this reads the same live resolver snapshot\n * `useVisibilityCtx` does (including reactivity to slice updates), just\n * without narrowing it down to `{ permissions, scope, user }` first — the\n * one behavioral difference is that other app-defined slices ride along\n * too, which is harmless for a predicate `ctx` argument that only ever\n * reads `ctx.permissions`/`ctx.scope`/`ctx.user`.\n */\nexport function useOptionalVisibilityCtx(): AppContext {\n const resolver = useContext(ResolverContext);\n const subscribe = useCallback(\n (onChange: () => void) => (resolver === null ? () => undefined : resolver.subscribe(onChange)),\n [resolver],\n );\n const getSnapshot = useCallback(\n () => (resolver === null ? EMPTY_APP_CONTEXT : (resolver.snapshot() as AppContext)),\n [resolver],\n );\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","import {\n evaluateChecks,\n type CheckOutcome,\n type CheckSurface,\n type SourceState,\n type ValidationIssues,\n} from '@burojs/core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { scopeSourceState, useContextSnapshot } from '../forms/controller/use-source-resolver.js';\nimport {\n createRuntimeActionDataAccess,\n createUnavailableActionDataAccess,\n} from '../data/action-data-access.js';\nimport { useOptionalDataRuntime } from '../data/context.js';\nimport { useApp } from '../hooks/use-app.js';\nimport { useVisibilityCtx } from '../hooks/use-permissions.js';\nimport { useT } from '../hooks/use-t.js';\n\nexport interface CheckGateRequest {\n readonly surface: CheckSurface;\n readonly values?: Record<string, unknown>;\n readonly saved?: Record<string, unknown>;\n readonly record?: Record<string, unknown>;\n readonly actionName?: string;\n /** The screen's `with` sources the checks read, by name (P2 4.10). */\n readonly sources?: Readonly<Record<string, SourceState>>;\n /** An existing `action.confirm` message; becomes the dialog header. */\n readonly header?: string | null;\n}\n\nexport interface CheckGateState {\n /**\n * The resource whose checks this gate evaluates. Carried in the state so the\n * dialog rendering it can bind its translations to the same resource the\n * rules came from: a check message's i18n key is `checks.<id>`, which only\n * reaches the per-resource entry `resources.<name>.checks.<id>` when a\n * resource is bound.\n *\n * It must travel WITH the state rather than being passed to the dialog\n * separately — the ambient `ResourceContext` is not a substitute. Only\n * `<RecordScreen>` and `<DeclarativeForm>` mount one, so an action gated from a\n * LIST ROW has no ambient resource at all, and the same check would render\n * translated on a show page and untranslated in the list. (Exactly the bug\n * `useResolvedLabel` in `action-button.tsx` carries a comment about.)\n *\n * Optional because a resource-less host — `<DeclarativeForm>` builds this\n * shape by hand — genuinely has no resource to name.\n */\n readonly resource?: string;\n readonly open: boolean;\n readonly busy: boolean;\n readonly header: string | null;\n readonly blockers: ValidationIssues;\n readonly confirmable: ValidationIssues;\n readonly proceed: () => void;\n readonly cancel: () => void;\n}\n\nexport interface UseCheckGateResult {\n readonly run: (request: CheckGateRequest) => Promise<'proceed' | 'cancel'>;\n readonly state: CheckGateState;\n}\n\nconst EMPTY: ValidationIssues = Object.freeze([]);\n\n/**\n * Imperative pre-flight gate. `run()` evaluates the resource's checks for the\n * surface, and resolves immediately with 'proceed' when there is nothing to say.\n * Otherwise it opens (the host renders the dialog off `state`) and resolves once\n * the user decides. One dialog: an existing `action.confirm` becomes its header\n * rather than a second prompt.\n */\nexport function useCheckGate(resource: string): UseCheckGateResult {\n const app = useApp();\n // Tolerant of a missing native data runtime — see `useChecks` (`./use-\n // checks.js`) for the full rationale. `run()` must still evaluate and open\n // for a `data`-free check with no runtime mounted; a check that DOES touch\n // `di.data` degrades to a `check.exception` warning instead of throwing.\n const runtime = useOptionalDataRuntime();\n const data = useMemo(\n () =>\n runtime === null\n ? createUnavailableActionDataAccess(\n `Check evaluation for \"${resource}\" needs a data runtime; none is mounted.`,\n )\n : createRuntimeActionDataAccess(runtime),\n [runtime, resource],\n );\n const ctx = useVisibilityCtx();\n const translate = useT();\n // Same wrapping as `useChecks`: `CheckDI.t` is `(key, params?) => string`;\n // `useT`'s translator takes `(key, { resource?, params? })`.\n const t = useCallback(\n (key: string, params?: Record<string, unknown>) => translate(key, { params }),\n [translate],\n );\n\n const [open, setOpen] = useState(false);\n const [busy, setBusy] = useState(false);\n const [header, setHeader] = useState<string | null>(null);\n const [blockers, setBlockers] = useState<ValidationIssues>(EMPTY);\n const [confirmable, setConfirmable] = useState<ValidationIssues>(EMPTY);\n const decide = useRef<((decision: 'proceed' | 'cancel') => void) | null>(null);\n const controller = useRef<AbortController | null>(null);\n const mounted = useRef(true);\n\n // Read off a ref inside the async callback — captured ONCE before the first\n // `await` — same technique `use-checks.ts` uses: `ctx`/`t` are fresh\n // identities every render (`useVisibilityCtx`/`useT` return new object\n // literals / closures each call). `run` is imperative (called on click, not\n // driven by an effect), so there is no debounce loop to break here, but\n // putting `ctx`/`t` straight in `run`'s own dependency array would still\n // recreate `run` itself on every render — this ref keeps `run`'s identity\n // stable while every invocation still reads the LATEST ctx/t/data.\n // The scope as a source state: a portable check over a pending scope waits.\n const snapshot = useContextSnapshot();\n const latest = useRef({ ctx, t, data, snapshot });\n latest.current = { ctx, t, data, snapshot };\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n controller.current?.abort();\n decide.current?.('cancel');\n decide.current = null;\n };\n }, []);\n\n const close = useCallback((decision: 'proceed' | 'cancel') => {\n setOpen(false);\n setBlockers(EMPTY);\n setConfirmable(EMPTY);\n setHeader(null);\n const resolve = decide.current;\n decide.current = null;\n resolve?.(decision);\n }, []);\n\n const run = useCallback(\n async (request: CheckGateRequest): Promise<'proceed' | 'cancel'> => {\n // A second `run()` while one is open supersedes the first: abort its\n // evaluation and resolve its promise so it never dangles. `close()`\n // both resolves the pending decision AND resets `open`/`header`/\n // `blockers`/`confirmable` — without the reset, a superseding run that\n // ends up with nothing to confirm (the early return below) would leave\n // the dialog visually open showing the FIRST, already-cancelled call's\n // stale content, wired to a null `decide.current`.\n controller.current?.abort();\n close('cancel');\n const own = new AbortController();\n controller.current = own;\n const current = latest.current;\n setBusy(true);\n let outcome: CheckOutcome;\n try {\n outcome = await evaluateChecks({\n checks: app.checkSource.checks(resource),\n surface: request.surface,\n resource,\n values: request.values ?? {},\n saved: request.saved ?? {},\n record: request.record,\n ctx: current.ctx,\n scope: scopeSourceState(current.snapshot),\n t: current.t,\n data: current.data,\n signal: own.signal,\n ...(request.actionName === undefined ? {} : { actionName: request.actionName }),\n ...(request.sources === undefined ? {} : { sources: request.sources }),\n });\n } catch (error) {\n // `evaluateChecks` itself never rejects — a throwing check predicate\n // becomes a `check.exception` warning issue (see `evaluate.ts`) — but\n // `checkSource.checks(resource)` is caller-supplied (app + resource\n // merged; `source.ts` anticipates a future backend-pulled source) and\n // CAN throw. `run()`'s contract is `Promise<'proceed' | 'cancel'>`,\n // never a rejection: a Task 8/9/10 caller awaiting it must always see\n // it settle. A check engine that cannot run must not silently wave\n // the user through, so this resolves 'cancel' rather than 'proceed'.\n console.error(\n `[buro] useCheckGate(\"${resource}\") failed to evaluate checks; treating as cancel.`,\n error,\n );\n return 'cancel';\n } finally {\n if (mounted.current && controller.current === own) setBusy(false);\n }\n // ABORTED means this run never reached a verdict — it is NOT a verdict\n // of \"nothing to confirm\".\n //\n // `evaluateChecks` answers an aborted signal with an empty outcome\n // (flagged `aborted`, precisely so this is decidable). The two guards\n // below — still mounted, still the current controller — do NOT catch\n // the case that matters, because React StrictMode tears this hook down\n // and re-mounts it synchronously: by the time the aborted evaluation\n // resolves, `mounted.current` has been set back to `true` by the second\n // mount effect and `controller.current` is still THIS run's own\n // controller (nothing else started one). Both guards pass, the empty\n // lists read as \"no blockers, no confirmable\", and `run()` answered\n // 'proceed' — dispatching a check-gated action with no dialog at all.\n // Development builds only, which is where every adopter works.\n //\n // A gate whose evaluation did not complete must never wave the caller\n // through. Re-RUNNING is the caller's job (it owns the click that\n // started this); refusing to proceed is ours.\n if (own.signal.aborted || outcome.aborted === true) return 'cancel';\n // Unmounted, or superseded by a later `run()`: don't paint state or\n // resolve — either the unmount cleanup already resolved 'cancel', or\n // the newer `run()` owns `decide.current` now.\n if (!mounted.current || controller.current !== own) return 'cancel';\n const requestHeader = request.header ?? null;\n if (\n outcome.blockers.length === 0 &&\n outcome.confirmable.length === 0 &&\n requestHeader === null\n ) {\n return 'proceed';\n }\n setHeader(requestHeader);\n setBlockers(outcome.blockers);\n setConfirmable(outcome.confirmable);\n setOpen(true);\n return new Promise<'proceed' | 'cancel'>((resolve) => {\n decide.current = resolve;\n });\n },\n [app, resource, close],\n );\n\n return {\n run,\n state: {\n resource,\n open,\n busy,\n header,\n blockers,\n confirmable,\n // `blockers.length > 0` means an 'error'-severity check fired: Task 7's\n // dialog is expected to omit the proceed button in that case, but this\n // guard means a mis-wired host cannot bypass a blocking check by\n // calling `proceed()` directly — a no-op (dialog stays open) rather\n // than resolving 'proceed' OR silently resolving 'cancel' out from\n // under the caller.\n proceed: () => {\n if (blockers.length > 0) return;\n close('proceed');\n },\n cancel: () => close('cancel'),\n },\n };\n}\n","import {\n evaluateChecks,\n filterInlineIssues,\n type CheckOutcome,\n type CheckSurface,\n type SourceState,\n type ValidationIssues,\n} from '@burojs/core';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { scopeSourceState, useContextSnapshot } from '../forms/controller/use-source-resolver.js';\nimport {\n createRuntimeActionDataAccess,\n createUnavailableActionDataAccess,\n} from '../data/action-data-access.js';\nimport { useOptionalDataRuntime } from '../data/context.js';\nimport { useApp } from '../hooks/use-app.js';\nimport { useVisibilityCtx } from '../hooks/use-permissions.js';\nimport { useLocale, useT } from '../hooks/use-t.js';\n\nexport interface UseChecksOptions {\n readonly resource: string;\n readonly surface: CheckSurface;\n readonly values: Record<string, unknown>;\n readonly saved?: Record<string, unknown>;\n readonly record?: Record<string, unknown>;\n readonly touched?: Record<string, boolean>;\n readonly submitAttempted?: boolean;\n /** Default 300ms, matching `def.validate`. 0 disables debouncing. */\n readonly debounceMs?: number;\n readonly enabled?: boolean;\n readonly actionName?: string;\n /**\n * The screen's `with` sources the checks read, by name (P2 4.10). Pass a stable object: a\n * new one re-runs the inline pass.\n */\n readonly sources?: Readonly<Record<string, SourceState>>;\n}\n\n/** The values one authoritative pass evaluates, when they are not the render's. */\nexport interface CheckPassValues {\n readonly values: Record<string, unknown>;\n readonly saved?: Record<string, unknown>;\n}\n\nexport interface UseChecksResult {\n readonly inlineIssues: ValidationIssues;\n readonly outcome: CheckOutcome | null;\n readonly isChecking: boolean;\n /**\n * Un-debounced authoritative pass. Call at submit / before dispatch.\n *\n * ⚠️ Can resolve with an outcome flagged `aborted: true` (the host unmounted,\n * or a second `runNow()` superseded this one). Its three issue lists are then\n * empty because nothing was evaluated — a caller MUST NOT read that as\n * \"nothing fired\" and proceed. Check `outcome.aborted` before\n * `outcome.blockers`.\n *\n * `over` evaluates the given values (and saved record) instead of the ones\n * this render passed: a submit decides on exactly the values it submits.\n */\n readonly runNow: (over?: CheckPassValues) => Promise<CheckOutcome>;\n}\n\nconst EMPTY: ValidationIssues = Object.freeze([]);\nconst EMPTY_OUTCOME: CheckOutcome = Object.freeze({\n issues: EMPTY,\n blockers: EMPTY,\n confirmable: EMPTY,\n});\n\nexport function useChecks(options: UseChecksOptions): UseChecksResult {\n const app = useApp();\n // Tolerant of a missing native data runtime (`useOptionalDataRuntime`,\n // `../data/context.js`) — unlike `useAction`, a check that never touches\n // `di.data` must still evaluate normally with no runtime mounted (the\n // common case: most form hosts in tests, and any adopter that\n // hasn't wired the native runtime, render checkless resources through the\n // exact same code path). A check whose predicate DOES call `di.data.*`\n // gets a rejecting stub instead — `evaluateChecks` turns that into a\n // visible `check.exception` warning rather than crashing the form.\n const runtime = useOptionalDataRuntime();\n const data = useMemo(\n () =>\n runtime === null\n ? createUnavailableActionDataAccess(\n `Check evaluation for \"${options.resource}\" needs a data runtime; none is mounted.`,\n )\n : createRuntimeActionDataAccess(runtime),\n [runtime, options.resource],\n );\n const ctx = useVisibilityCtx();\n const translate = useT();\n const locale = useLocale();\n // `CheckDI.t` is `(key, params?: Record<string, unknown>) => string`; `useT`'s\n // translator takes `(key, { resource?, params? })`. Wrap so predicate/message\n // interpolation params land under `.params` correctly — unlike `useAction`\n // (which stubs `t: (k) => k`), checks get the REAL translator: check messages\n // are adopter-authored and localizable, not internal plumbing.\n const t = useCallback(\n (key: string, params?: Record<string, unknown>) => translate(key, { params }),\n [translate],\n );\n // `ctx` is a fresh `{ permissions, scope, user }` object literal every render\n // (see the `latest` ref comment below) — but a check predicate CAN legitimately\n // read `di.ctx.permissions`/`di.ctx.user`, and a genuine change to either (a\n // permission grant landing, the session's user rotating) must re-evaluate.\n // Fingerprint its CONTENT — same technique as `valuesKey` below — so the\n // debounce effect reacts to what changed, not to the literal's identity.\n const ctxKey = useMemo(() => JSON.stringify(ctx), [ctx]);\n\n const [outcome, setOutcome] = useState<CheckOutcome | null>(null);\n const [isChecking, setIsChecking] = useState(false);\n\n // Monotonic seq + live controllers: the same race discipline `def.validate`\n // uses. Only the newest run may paint; older ones of the SAME kind are\n // aborted and dropped.\n const seq = useRef(0);\n // TWO controller slots, deliberately. The debounced inline pass and the\n // authoritative `runNow()` pass are different jobs with different consumers,\n // and sharing one slot let the cheap one kill the important one:\n //\n // 1. a host awaits `runNow()` and gates its WRITE on the result\n // (the record form: `if (outcome.blockers.length > 0) return;`);\n // 2. anything in the debounce effect's dependency list changes while that\n // pass is still in flight (see below for what actually can);\n // 3. the effect re-arms, its timer fires, and `evaluate()` aborted the\n // single shared `controller.current` — the SUBMIT's controller;\n // 4. `evaluateChecks` returned early, so `runNow()` handed its caller an\n // outcome with no blockers in it;\n // 5. the host read `blockers.length === 0` as permission and wrote the\n // record — past a `severity: 'error'` check, which then painted inline\n // moments later, AFTER the write.\n //\n // WHAT CAN ACTUALLY RE-ARM THE EFFECT MID-PASS. Not a keystroke into\n // the record form: its `handleSubmit` calls `setIsSubmitting(true)` on its\n // FIRST line (the double-submit guard, `resource-form.tsx`), and its fields\n // render `disabled={!editable || isSubmitting}` — verified, `userEvent.type`\n // is correctly refused for the whole duration of the pass. The reachable\n // triggers are the effect's other dependencies:\n // - `valuesKey` — a CUSTOM field renderer that ignores `disabled`, or an\n // async default / picker / relation resolving into `setFieldValue`;\n // - `ctxKey` — a permission slice landing, or the session's user rotating;\n // - `locale` — a live language switch (this framework ships one).\n // And `useChecks` is public API: a host that does NOT disable its inputs\n // during submit has the plain keystroke version of this.\n //\n // No StrictMode needed — this is a production path, and the window is\n // `debounceMs` (300ms by default) against check latency. A best-effort\n // inline pass has no business cancelling the authoritative one, so it no\n // longer can: each kind supersedes only its own. `seq` stays shared because\n // it governs PAINTING (newest values win), which is genuinely one job.\n const controller = useRef<AbortController | null>(null);\n const authoritativeController = useRef<AbortController | null>(null);\n const mounted = useRef(true);\n // `ctx` (useVisibilityCtx) and `t` (wrapped useT) are fresh identities EVERY\n // render, even when their content hasn't changed: useVisibilityCtx returns a\n // new `{ permissions, scope, user }` object literal each call, and useT\n // returns a new closure each call. Reading them off a ref updated every\n // render — rather than putting them in `evaluate`'s dependency array — keeps\n // `evaluate` (and therefore the debounce effect below) stable across renders\n // that don't touch values/surface/resource. Depending on the raw `ctx`/`t`\n // identities directly would re-fire the debounce effect on every render\n // `evaluate` itself causes (via setOutcome/setIsChecking), which re-fires\n // `evaluate`, which re-renders — an infinite loop. `data` is already stable\n // (memoized on `runtime`), and `options` uses the same ref technique for the\n // same reason. This ref only prevents TEARING inside the async callback —\n // it does not drive re-evaluation. Liveness to a genuine ctx/locale change is\n // `ctxKey`/`locale` below, in the debounce effect's own dependency array.\n // The scope as a source state: a portable check over a pending scope waits.\n const snapshot = useContextSnapshot();\n const latest = useRef({ options, ctx, t, data, snapshot });\n latest.current = { options, ctx, t, data, snapshot };\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n controller.current?.abort();\n authoritativeController.current?.abort();\n };\n }, []);\n\n const evaluate = useCallback(\n async (kind: 'debounced' | 'authoritative', over?: CheckPassValues): Promise<CheckOutcome> => {\n const current = latest.current;\n const mySeq = seq.current + 1;\n seq.current = mySeq;\n // Supersede only the same KIND — see the two-slot note above.\n const slot = kind === 'authoritative' ? authoritativeController : controller;\n slot.current?.abort();\n const ownController = new AbortController();\n slot.current = ownController;\n if (mounted.current) setIsChecking(true);\n try {\n // Inside the `try`: a `CheckSource` is caller-supplied (app + resource\n // merged) and can throw. Looking it up outside this block would skip the\n // `finally` below entirely, leaving `isChecking` stuck `true` forever.\n const checks = app.checkSource.checks(current.options.resource);\n const next = await evaluateChecks({\n checks,\n surface: current.options.surface,\n resource: current.options.resource,\n values: over?.values ?? current.options.values,\n saved: over?.saved ?? current.options.saved ?? {},\n record: current.options.record,\n ctx: current.ctx,\n scope: scopeSourceState(current.snapshot),\n t: current.t,\n data: current.data,\n signal: ownController.signal,\n ...(current.options.actionName === undefined\n ? {}\n : { actionName: current.options.actionName }),\n ...(current.options.sources === undefined ? {} : { sources: current.options.sources }),\n });\n // An ABORTED pass evaluated nothing, so it must never be painted NOR\n // handed back as if it were a verdict. `runNow()`'s return value is\n // authoritative for the record form's submit gate, so an unflagged\n // empty outcome here is a straight bypass of every `severity: 'error'`\n // check. `evaluateChecks` flags this itself (`CheckOutcome.aborted`,\n // `@burojs/core`); pass the flag through untouched rather than\n // laundering it into a clean-looking empty result.\n if (next.aborted === true) return next;\n // Complete, but a newer pass owns the paint (or we unmounted): the\n // VERDICT is still honest — this pass ran every applicable check\n // against the values it was given — so the caller gets it. Only the\n // state write is skipped.\n if (seq.current !== mySeq || !mounted.current) return next;\n setOutcome(next);\n return next;\n } finally {\n if (seq.current === mySeq && mounted.current) setIsChecking(false);\n }\n },\n [app],\n );\n\n const debounceMs = options.debounceMs ?? 300;\n const enabled = options.enabled ?? true;\n // Memoized on the values OBJECT, not recomputed every render: a host that\n // mounts this hook unconditionally (the record form does) would otherwise\n // pay a full `JSON.stringify` of the record on every single render,\n // including the renders this hook's own `setIsChecking`/`setOutcome`\n // cause. Skipped entirely while disabled — a resource with no checks has\n // no reason to serialize anything.\n //\n // Two caveats a caller has to know about, one pre-existing and one\n // introduced by the memo:\n //\n // 1. (pre-existing) `JSON.stringify` collapses a `File` to `{}`, so\n // swapping one file for another in a file field produces the same key\n // and does not retrigger the pass. True before the memo and after it —\n // memoizing changes WHEN the call runs, not what it produces.\n //\n // 2. (new, and a real narrowing of this hook's public contract)\n // `options.values` is now compared by IDENTITY. Before the memo the\n // stringify ran every render, so a host that MUTATED its values object\n // in place — `values.amount = 5` rather than `setValues({ ...values,\n // amount: 5 })` — still produced a changed key and still retriggered\n // the debounced pass. It no longer does: an in-place mutation keeps\n // the same object reference, the memo does not recompute, and the pass\n // does not re-run. Pass a NEW object on every change (which every\n // React state update already does, and which the old record form — whose\n // `values` is state — has always done). Recorded in the changeset.\n const valuesKey = useMemo(\n () => (enabled ? JSON.stringify(options.values) : ''),\n [enabled, options.values],\n );\n // The pending debounced timer, so `runNow()` can cancel it (see below) —\n // without this a submit-time `runNow()` call would leave the old timer alive\n // to fire a redundant, already-superseded evaluation afterwards.\n const pendingTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-arms on what the pass reads through `latest` (values, surface, resource, context, locale, sources), not only on what the body names\n useEffect(() => {\n if (!enabled) return;\n if (debounceMs === 0) {\n void evaluate('debounced');\n return;\n }\n const timer = setTimeout(() => {\n pendingTimer.current = null;\n void evaluate('debounced');\n }, debounceMs);\n pendingTimer.current = timer;\n return () => {\n clearTimeout(timer);\n if (pendingTimer.current === timer) pendingTimer.current = null;\n };\n }, [\n enabled,\n debounceMs,\n evaluate,\n valuesKey,\n options.surface,\n options.resource,\n ctxKey,\n locale,\n options.sources,\n ]);\n\n // Same signature as `evaluate` (`() => Promise<CheckOutcome>`); wrapped\n // rather than exposing `evaluate` directly so a submit-time call also\n // cancels a still-pending debounced run instead of leaving it to fire a\n // redundant evaluation afterwards. `evaluate` itself is untouched — the\n // debounce effect above still calls it directly.\n const runNow = useCallback(\n (over?: CheckPassValues): Promise<CheckOutcome> => {\n if (pendingTimer.current !== null) {\n clearTimeout(pendingTimer.current);\n pendingTimer.current = null;\n }\n // `enabled: false` means \"this host has nothing to evaluate\" (typically\n // a resource that declares no checks at all), so the authoritative\n // submit-time pass has nothing to do either — running it would reinstate\n // exactly the work `enabled` exists to avoid. Resolves with the same\n // shape a real empty pass produces, so a caller reading\n // `.blockers`/`.confirmable` needs no special case.\n if (!enabled) return Promise.resolve(EMPTY_OUTCOME);\n return evaluate('authoritative', over);\n },\n [evaluate, enabled],\n );\n\n const inlineIssues = useMemo(\n () =>\n outcome === null\n ? EMPTY\n : filterInlineIssues(outcome.issues, {\n touched: options.touched ?? {},\n submitAttempted: options.submitAttempted ?? false,\n }),\n [outcome, options.touched, options.submitAttempted],\n );\n\n return { inlineIssues, outcome, isChecking, runNow };\n}\n","import {\n type CompiledScreen,\n type CompileFormScreenOptions,\n type FormBody,\n type ResourceFieldMap,\n type ScreenFailure,\n compileFormScreen,\n} from '@burojs/core';\n\n/**\n * The compiled screen of a resource-less form: the one `compileFormScreen`\n * call of `@burojs/react` and `@burojs/ui-shadcn` (P1b+P1c decision 21).\n * `compileFormScreen` memoises by `fields`, `body` and the options.\n */\nexport function useFormScreen<F extends ResourceFieldMap>(\n fields: F,\n body: FormBody<F> | undefined,\n options: CompileFormScreenOptions,\n): CompiledScreen | ScreenFailure {\n return compileFormScreen(fields, body, options);\n}\n","import type { ErasedResourceHandle, FilterExpression } from '@burojs/core';\nimport type { FormValues, RelationFilterOpt } from './types.js';\n\n/**\n * A field-level `required` / `disabled` predicate: a static boolean, or a\n * function evaluated against the current ctx + form values. `values` is\n * optional in the function form's signature because the field-types builder\n * types `required` as `(d: unknown) => boolean`; at the call site it is always\n * the live values map. Local to `@burojs/react`, not re-exported.\n */\nexport type ConditionalFieldPredicate = boolean | ((ctx: unknown, values?: FormValues) => boolean);\n\n/**\n * Resolve a `required`/`disabled` predicate to a boolean.\n * - `undefined` → `fallback` (the field never declared this predicate).\n * - `boolean` → itself (static form).\n * - function → called `(ctx, values)`; a throw is caught and ALSO resolves\n * to `fallback` — \"a broken predicate behaves as if it were never\n * declared\".\n */\nexport function resolvePredicate(\n p: ConditionalFieldPredicate | undefined,\n ctx: unknown,\n values: FormValues,\n fallback: boolean,\n): boolean {\n if (p === undefined) return fallback;\n if (typeof p === 'boolean') return p;\n try {\n return p(ctx, values);\n } catch {\n return fallback;\n }\n}\n\n/** The field-def keys this module resolves off a field, uniformly across shapes. */\nexport type ConditionalFieldKey = 'required' | 'disabled';\n\n/**\n * Read a field def's raw `required` / `disabled` value — boolean, predicate\n * function, or `undefined` — checking top-level first (raw declarations),\n * then `.opts` (the `@burojs/field-types` `f` builder's shape), the same\n * fallback chain `resolveFieldStatic` (`@burojs/core`) uses for the static\n * `required` boolean. `disabled` has no typed builder channel; it is reachable\n * by spreading a builder field (`{ ...f.string({}), disabled: true }`).\n */\nexport function readFieldOpt(\n fieldDef: unknown,\n key: ConditionalFieldKey,\n): ConditionalFieldPredicate | undefined {\n if (fieldDef === null || typeof fieldDef !== 'object') return undefined;\n const record = fieldDef as Record<string, unknown> & { readonly opts?: Record<string, unknown> };\n const value = record[key] !== undefined ? record[key] : record.opts?.[key];\n if (typeof value === 'boolean' || typeof value === 'function')\n return value as ConditionalFieldPredicate;\n return undefined;\n}\n\n/**\n * A field's `required(fn)` / `disabled(fn)` evaluated against a ctx + values\n * snapshot (the form controller's own reading; whether a field is shown is the\n * plan's: a leaf's `when`, the field's `in`, a panel's `requires`). Undeclared\n * or throwing → `false` — \"no predicate declared → behave exactly as before\".\n */\nexport function fieldPredicateFlags(\n fieldDef: unknown,\n ctx: unknown,\n values: FormValues,\n): { readonly required: boolean; readonly disabled: boolean } {\n return {\n required: resolvePredicate(readFieldOpt(fieldDef, 'required'), ctx, values, false),\n disabled: resolvePredicate(readFieldOpt(fieldDef, 'disabled'), ctx, values, false),\n };\n}\n\n/**\n * Read a field def's `filter` function (top-level first, then `.opts`, the fallback chain\n * `readFieldOpt` uses): code that returns extra filters from the current form values. A static\n * array is not a `filter` any more — that is `candidates`, data in the field's `meta` — so\n * anything but a function reads as no filter.\n */\nexport function readFieldFilterOpt(fieldDef: unknown): RelationFilterOpt | undefined {\n if (fieldDef === null || typeof fieldDef !== 'object') return undefined;\n const record = fieldDef as Record<string, unknown> & { readonly opts?: Record<string, unknown> };\n const value = record.filter !== undefined ? record.filter : record.opts?.filter;\n return typeof value === 'function' ? (value as RelationFilterOpt) : undefined;\n}\n\n/**\n * Resolve a field's `filter` function against the current values snapshot — the value\n * `FieldBinding.fixedFilters` carries, applied on top of the field's resolved `candidates`.\n * - no function declared → `undefined`.\n * - a throw, OR a non-array return, resolves to `undefined` — \"a broken filter behaves as if it\n * were never declared\", the same fail-open convention `resolvePredicate` uses for\n * `required`/`disabled`. A THROW specifically also emits a dev-only `console.warn`, so a\n * broken filter is discoverable in dev instead of silently showing unscoped options.\n *\n * `name` is the field name, used only for the dev warning's message.\n */\nexport function resolveFieldFilter(\n fieldDef: unknown,\n values: FormValues,\n name: string,\n): readonly FilterExpression<ErasedResourceHandle>[] | undefined {\n const raw = readFieldFilterOpt(fieldDef);\n if (raw === undefined) return undefined;\n try {\n const result = raw(values);\n return Array.isArray(result) ? result : undefined;\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn(\n `[buro] relation filter for field \"${name}\" threw; showing unscoped options`,\n err,\n );\n }\n return undefined;\n }\n}\n","import { resourceKey, type AppRuntime } from '@burojs/core';\n\n/**\n * What a relation select needs to know about its target to seed a create (P6-31): the target's\n * fields with whether its create form can hold them, and the type discriminator.\n */\nexport interface SeedTarget {\n readonly fields: readonly { readonly name: string; readonly creatable: boolean }[];\n readonly discriminator?: string;\n}\n\nconst NO_SEEDS: Readonly<Record<string, unknown>> = Object.freeze(Object.create(null));\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** A field map (code) or an entry list (a type's lowered fields), as `[name, definition]` pairs. */\nfunction fieldPairs(fields: unknown): readonly (readonly [string, Record<string, unknown>])[] {\n if (Array.isArray(fields))\n return fields.flatMap((entry) => {\n const def = record(entry);\n return def !== undefined && typeof def.name === 'string' ? [[def.name, def] as const] : [];\n });\n const map = record(fields);\n if (map === undefined) return [];\n return Object.entries(map).flatMap(([name, def]) => {\n const field = record(def);\n return field === undefined ? [] : [[name, field] as const];\n });\n}\n\nfunction creatableField(def: Record<string, unknown>): boolean {\n const opts = record(def.opts);\n const declared = record(def.__static);\n const modes = def.in;\n if (Array.isArray(modes) && !modes.includes('create')) return false;\n const write = def.write ?? declared?.write ?? opts?.write;\n return write !== 'update' && write !== 'never';\n}\n\n/**\n * The target resource as the seeds read it, from the code registry's definition (Known finding 2:\n * a type's fields live under `types.items`, not the base map).\n */\nexport function seedTargetOf(def: unknown): SeedTarget {\n const value = record(def);\n const types = record(value?.types);\n const items = Array.isArray(types?.items) ? types.items : [];\n const fields = [\n ...fieldPairs(value?.fields),\n ...items.flatMap((item) => fieldPairs(record(item)?.fields)),\n ].map(([name, field]) => ({ name, creatable: creatableField(field) }));\n return Object.freeze({\n fields: Object.freeze(fields),\n ...(typeof types?.by === 'string' ? { discriminator: types.by } : {}),\n });\n}\n\nfunction isLiteral(value: unknown): boolean {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\n/**\n * The trusted `defaults` of a create opened from a relation select (P6-31, P7 3.4): the top-level\n * `eq` literals of the field's `meta.candidates`, read from the CODE registry's field only. A ref\n * of any source, a list or other operator, a dotted path, a field the create form cannot hold and\n * the type discriminator contribute nothing, and neither does a function `filter`. A `marked`\n * field — one whose candidates a granted layer chose — seeds nothing at all. The result is frozen\n * with a null prototype.\n */\nexport function selectSeeds(\n target: SeedTarget,\n fieldDef: unknown,\n marked: boolean,\n): Readonly<Record<string, unknown>> {\n if (marked) return NO_SEEDS;\n const candidates = record(record(fieldDef)?.meta)?.candidates;\n if (!Array.isArray(candidates)) return NO_SEEDS;\n const out: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n let any = false;\n for (const raw of candidates) {\n const entry = record(raw);\n if (entry === undefined || entry.op !== 'eq' || !isLiteral(entry.value)) continue;\n const field = entry.field;\n if (typeof field !== 'string' || field.includes('.') || field === target.discriminator)\n continue;\n if (!target.fields.some((f) => f.name === field && f.creatable)) continue;\n out[field] = entry.value;\n any = true;\n }\n return any ? Object.freeze(out) : NO_SEEDS;\n}\n\n/**\n * The seeds of one relation field, from its CODE definition and its target in the code registry.\n * Anything missing (not a relation, no static target, an unregistered target) seeds nothing.\n */\nexport function relationSeedsFor(\n app: AppRuntime | null,\n codeField: unknown,\n marked: boolean,\n): Readonly<Record<string, unknown>> {\n const field = record(codeField);\n if (app === null || field === undefined || field.kind !== 'relation') return NO_SEEDS;\n const to = record(field.meta)?.to ?? record(field.opts)?.to;\n if (to === undefined) return NO_SEEDS;\n let key: string;\n try {\n key = resourceKey(to as Parameters<typeof resourceKey>[0]);\n } catch {\n return NO_SEEDS;\n }\n const target = app.registry.get(key as never);\n return target === undefined ? NO_SEEDS : selectSeeds(seedTargetOf(target), codeField, marked);\n}\n","import type { FlowRun } from '@burojs/core';\n\n/**\n * The runs `useFlowRun` created, each with its flow's form id: the only claims a form controller\n * takes, and only for that form (P4-B review M6).\n */\nconst runs = new WeakMap<object, string>();\n\n/** @internal Records a run `useFlowRun` created for the flow whose form is `formId`. */\nexport function registerFlowRun(run: FlowRun, formId: string): void {\n runs.set(run, formId);\n}\n\n/**\n * @internal Whether `value` is a run `useFlowRun` created for the form `formId` (Known finding\n * 24: a claim, not a flag — and a claim on its own form only).\n */\nexport function isFrameworkFlowRun(value: unknown, formId: string | undefined): value is FlowRun {\n return (\n value !== null &&\n typeof value === 'object' &&\n formId !== undefined &&\n runs.get(value) === formId\n );\n}\n","import { type CompiledScreen, type ScreenFieldInfo, fieldDefaults } from '@burojs/core';\n\n/** Where a create value came from: a trusted seed tier, or the user. */\nexport type SeedTier = 'trusted' | 'user';\n\nexport interface CreateSeeds {\n readonly values: Readonly<Record<string, unknown>>;\n readonly provenance: Readonly<Record<string, SeedTier>>;\n /** The value each trusted tier gave a field at mount; read back only from here. */\n readonly trusted: Readonly<Record<string, unknown>>;\n}\n\nexport interface CreateSeedsInput {\n /** Its fields, discriminator and type defaults. */\n readonly compiled: CompiledScreen;\n /** The accepted type. */\n readonly type?: string;\n readonly callerDefaults?: Readonly<Record<string, unknown>>;\n /** The `?prefill.<field>=` params. */\n readonly prefill: URLSearchParams;\n /** `ResourceConfig.prefill.fromQuery`. */\n readonly fromQuery: readonly string[];\n}\n\n/** A field's `generated` policy, from either representation's static metadata. */\nexport function generationOf(field: ScreenFieldInfo): 'create' | 'always' | undefined {\n const declaration = field.declaration as {\n readonly __static?: { readonly generated?: unknown };\n readonly opts?: { readonly generated?: unknown };\n };\n const generated = declaration.__static?.generated ?? declaration.opts?.generated;\n return generated === 'create' || generated === 'always' ? generated : undefined;\n}\n\n/**\n * Whether a create could ever write the field from the form: not `system`,\n * no `write: 'never' | 'update'`, not `generated`. A field that fails this is\n * never `active` in create, so the user tier never seeds it.\n */\nexport function createWritable(field: ScreenFieldInfo): boolean {\n if (field.system) return false;\n if (field.write === 'never' || field.write === 'update') return false;\n return generationOf(field) === undefined;\n}\n\n/**\n * The create seeds with their provenance (P1b+P1c decisions 7 and 24), low to\n * high: each field's static default (`fieldDefaults`) and the accepted type's\n * `defaults` (trusted), the URL prefill (the user tier, which fills only the\n * `fromQuery` fields a create may write), then the caller's `defaults`\n * (trusted), merged over all of them. The discriminator is taken from no tier: it is the accepted `type`.\n * Undeclared names are dropped from every tier.\n */\nexport function createSeeds(input: CreateSeedsInput): CreateSeeds {\n const { compiled } = input;\n const discriminator = compiled.discriminator;\n const fields = new Map(compiled.fields.map((field) => [field.name, field]));\n const values: Record<string, unknown> = {};\n const provenance: Record<string, SeedTier> = {};\n const trusted: Record<string, unknown> = {};\n const apply = (tier: Readonly<Record<string, unknown>> | undefined, from: SeedTier) => {\n for (const [name, value] of Object.entries(tier ?? {})) {\n if (!fields.has(name) || name === discriminator || value === undefined) continue;\n values[name] = value;\n provenance[name] = from;\n if (from === 'trusted') trusted[name] = value;\n }\n };\n apply(\n fieldDefaults(\n {\n fields: Object.fromEntries(\n compiled.fields.map((field) => [field.name, field.declaration]),\n ) as never,\n },\n 'create',\n ),\n 'trusted',\n );\n if (input.type !== undefined && Object.hasOwn(compiled.typeDefaults, input.type))\n apply(compiled.typeDefaults[input.type], 'trusted');\n const prefill: Record<string, unknown> = {};\n for (const name of input.fromQuery) {\n const field = fields.get(name);\n if (field === undefined || !createWritable(field)) continue;\n const value = input.prefill.get(`prefill.${name}`);\n if (value !== null) prefill[name] = value;\n }\n apply(prefill, 'user');\n // The caller's `defaults` is merged over the URL prefill (spec section 10.3).\n apply(input.callerDefaults, 'trusted');\n if (discriminator !== undefined && input.type !== undefined) {\n values[discriminator] = input.type;\n provenance[discriminator] = 'trusted';\n trusted[discriminator] = input.type;\n }\n return Object.freeze({\n values: Object.freeze(values),\n provenance: Object.freeze(provenance),\n trusted: Object.freeze(trusted),\n });\n}\n","import {\n type CompiledScreen,\n type FieldAccessMap,\n type PlanAccess,\n type PlanNode,\n type RuleContext,\n type ScreenPlan,\n addressesCapability,\n loweredFieldPairs,\n resolveCapability,\n} from '@burojs/core';\nimport { type CreateSeeds, generationOf } from './seeds.js';\n\nexport interface BuildPayloadInput {\n readonly plan: ScreenPlan;\n readonly compiled: CompiledScreen;\n readonly values: Readonly<Record<string, unknown>>;\n /** Create only. */\n readonly seeds?: CreateSeeds;\n /** Create only: the accepted type. */\n readonly type?: string;\n /**\n * The fields a rule denies `edit` ({@link ruleDeniedFields}). A `system`\n * field is not editable before any rule is read, so the plan carries no\n * `lockReason` for it; this set is what keeps its trusted seed out.\n */\n readonly denied?: ReadonlySet<string>;\n /**\n * The screen resource's field decisions (P5 spec 3.9): a field whose view is not `visible` or\n * whose edit is not `editable` never reaches a payload from user input — the edit branch and a\n * create's form values. A create's trusted `system` seed is governed by `denied` alone (P1b+P1c\n * decision 7): a lowered `requires` does not exclude it.\n */\n readonly access: FieldAccessMap;\n}\n\n/** The fields its user may not type into: not visible, or not editable. */\nfunction accessDenied(access: FieldAccessMap): ReadonlySet<string> {\n const out = new Set<string>();\n for (const [name, decision] of Object.entries(access))\n if (decision.view !== 'visible' || decision.edit !== 'editable') out.add(name);\n return out;\n}\n\n/** Every field leaf in a plan tree that carries a `lockReason`. */\nfunction lockedLeaves(nodes: readonly PlanNode[], out: Set<string>): Set<string> {\n for (const node of nodes) {\n if (node.field !== undefined && node.lockReason !== undefined) out.add(node.field);\n lockedLeaves(node.children, out);\n }\n return out;\n}\n\n/**\n * The fields whose `edit` an authored rule denies, read as the planner reads them: the\n * resource's rules and the screen's, over the plan's rule context. A\n * permission map that is loading or failed fails closed. The rules a field's `requires` lowers to\n * are not read here (P5 spec 3.9): they are user-tier access, which `BuildPayloadInput.access`\n * decides, and never exclude a trusted `system` seed.\n */\nexport function ruleDeniedFields(\n compiled: CompiledScreen,\n access: PlanAccess,\n record: unknown,\n): ReadonlySet<string> {\n const rules = [...compiled.rules, ...access.rules].filter(\n (rule) => loweredFieldPairs(rule) === undefined,\n );\n const denied = new Set<string>();\n if (rules.length === 0) return denied;\n const { record: _record, permissions: _permissions, ...rest } = access.context;\n const context: RuleContext = {\n ...rest,\n ...(access.permissions === undefined ? {} : { permissions: access.permissions }),\n ...(compiled.mode === 'create' || record === undefined ? {} : { record }),\n };\n const unsettled = access.permissions !== undefined && access.permissions.status !== 'ready';\n for (const field of compiled.fields) {\n const target = { kind: 'field', name: field.name };\n if (!addressesCapability(rules, 'edit', target)) continue;\n if (unsettled || !resolveCapability(rules, 'edit', target, context, true).allowed)\n denied.add(field.name);\n }\n return denied;\n}\n\n/**\n * The payload allow-list (P1b+P1c decisions 7, 19 and 24): the `active`\n * declared values; in create, a `system` field's trusted seed (placed as a\n * display or not placed at all) and\n * the discriminator from the accepted type. A key the screen does not declare\n * is never read; a field with `write: 'never' | 'update'` or `generated` never\n * reaches a create; a rule-denied field never reaches any payload; `undefined`\n * values are omitted.\n */\nexport function buildPayload(input: BuildPayloadInput): Record<string, unknown> {\n const { plan, compiled, values, seeds } = input;\n const mode = plan.mode;\n const discriminator = compiled.discriminator;\n const denied = lockedLeaves(plan.slots.body, new Set(input.denied ?? []));\n const userDenied = accessDenied(input.access);\n const payload: Record<string, unknown> = {};\n if (mode === 'show') return payload;\n for (const field of compiled.fields) {\n const name = field.name;\n if (mode === 'create' && name === discriminator) continue;\n if (denied.has(name)) continue;\n const status = plan.fields[name];\n const generated = generationOf(field);\n if (mode === 'create') {\n if (field.write === 'never' || field.write === 'update' || generated !== undefined) continue;\n if (status === 'active') {\n if (userDenied.has(name)) continue;\n if (Object.hasOwn(values, name) && values[name] !== undefined) payload[name] = values[name];\n } else if (\n // A `system` field's trusted seed is sent whatever its render status (decision 7):\n // the generic create leaves the field out, and a seed is never lost to hiding.\n field.system &&\n // Only a base field or one of the accepted type's: another type's field is not on\n // this record, whatever a shared `defaults` names (final review I1).\n (field.typeName === undefined || field.typeName === input.type) &&\n (field.in === undefined || field.in.includes('create')) &&\n seeds?.provenance[name] === 'trusted' &&\n Object.hasOwn(seeds.trusted, name) &&\n seeds.trusted[name] !== undefined\n ) {\n payload[name] = seeds.trusted[name];\n }\n continue;\n }\n if (status !== 'active' || generated === 'always' || userDenied.has(name)) continue;\n if (Object.hasOwn(values, name) && values[name] !== undefined) payload[name] = values[name];\n }\n if (mode === 'create' && discriminator !== undefined && input.type !== undefined)\n payload[discriminator] = input.type;\n return payload;\n}\n","import {\n type CompiledScreen,\n type FieldIssue,\n type ResourceFieldMap,\n type ScreenPlan,\n type StandardSchemaV1,\n type ValidationContext,\n type ValidationIssue,\n type ValidatorImplementation,\n isStandardSchema,\n normalizeFieldIssues,\n resolveFieldStatic,\n validateFieldValue,\n} from '@burojs/core';\nimport { fieldPredicateFlags } from '../conditional.js';\nimport type { FormValidate, FormValues, ResolvedIssue } from '../types.js';\n\n/**\n * One field's dirty rule (the form's, `resource-form.tsx`): `''` and\n * `null`/`undefined` are the same \"nothing entered\", so a nullable column\n * hydrated as `null` and an empty input reporting `''` are not a change.\n */\nexport function isFieldDirty(current: unknown, initial: unknown): boolean {\n const currentEmpty = current == null || current === '';\n const initialEmpty = initial == null || initial === '';\n if (currentEmpty && initialEmpty) return false;\n return current !== initial;\n}\n\n/** Whether any value diverges from the baseline, under {@link isFieldDirty}. */\nexport function isFormDirty(values: FormValues, baseline: FormValues): boolean {\n for (const key of Object.keys(values)) if (isFieldDirty(values[key], baseline[key])) return true;\n for (const key of Object.keys(baseline))\n if (!(key in values) && isFieldDirty(undefined, baseline[key])) return true;\n return false;\n}\n\n/** The field a validation issue lands on, or `undefined` for a form-level one. */\nexport function issueField(issue: ValidationIssue): string | undefined {\n const head = issue.path[0];\n return typeof head === 'string' || typeof head === 'number' ? String(head) : undefined;\n}\n\n/** An issue as a form shows it: one field, one message. */\nexport function toResolvedIssue(issue: ValidationIssue): ResolvedIssue {\n return {\n field: issueField(issue) ?? '_form',\n code: issue.code,\n severity: issue.severity,\n message: issue.message,\n ...(issue.params === undefined ? {} : { params: issue.params }),\n };\n}\n\nfunction pathHead(path: readonly unknown[] | undefined): string | undefined {\n const head = path?.[0];\n if (typeof head === 'string' || typeof head === 'number') return String(head);\n if (head !== null && typeof head === 'object' && 'key' in (head as Record<string, unknown>)) {\n const key = (head as { readonly key?: unknown }).key;\n if (typeof key === 'string' || typeof key === 'number') return String(key);\n }\n return undefined;\n}\n\n/** One whole-form Standard Schema, its issues normalized onto their first path segment. */\nasync function runFormSchema(schema: StandardSchemaV1, values: FormValues) {\n const result = await schema['~standard'].validate(values);\n if (!('issues' in result) || result.issues === undefined) return [];\n const friendly: FieldIssue[] = result.issues.map((entry) => ({\n message: typeof entry.message === 'string' ? entry.message : 'Invalid',\n field: pathHead(entry.path) ?? '_form',\n }));\n return normalizeFieldIssues(friendly, { defaultField: '_form' });\n}\n\nexport interface RunValidationInput {\n readonly compiled: CompiledScreen;\n readonly plan: ScreenPlan;\n readonly values: FormValues;\n /** The live field definitions: their `required` (static or a predicate) and validators. */\n readonly fieldMap: ResourceFieldMap;\n /** What a `required(fn)` predicate reads as its context. */\n readonly ctx?: unknown;\n readonly schema?: StandardSchemaV1;\n readonly validate?: FormValidate;\n}\n\n/**\n * Validates the `active` fields only (section 10.3: a `readonly`, `inactive`\n * or `pending` field is never validated): core's runner over each field's\n * `required` and validators, then the form schema, then `validate`. A\n * form-level issue keyed to a field that is not active is dropped.\n */\n/**\n * A field validator may return the `FieldIssue` shorthand (`{ message,\n * severity?, code? }`, as `normalizeFieldIssues` reads it) as well as a string\n * or a full issue; the core runner reads an object without a `path` as a nested\n * map, so the shorthand is lowered here first, its severity kept.\n */\nfunction shorthandAware(validator: ValidatorImplementation): ValidatorImplementation {\n if (isStandardSchema(validator)) return validator;\n const run = validator as (value: unknown, ctx: unknown) => unknown;\n return (async (value: unknown, ctx: unknown) => {\n const outcome = await run(value, ctx);\n const lower = (entry: unknown): unknown => {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return entry;\n const candidate = entry as { readonly path?: unknown; readonly message?: unknown };\n if (Array.isArray(candidate.path) || candidate.message === undefined) return entry;\n const [normalized] = normalizeFieldIssues(entry as FieldIssue, { defaultField: '' });\n return { ...normalized!, path: [] };\n };\n return Array.isArray(outcome) ? outcome.map(lower) : lower(outcome);\n }) as ValidatorImplementation;\n}\n\nexport async function runValidation(\n input: RunValidationInput,\n): Promise<readonly ValidationIssue[]> {\n const { compiled, plan, values, fieldMap } = input;\n const active = new Set(\n compiled.fields.map((field) => field.name).filter((name) => plan.fields[name] === 'active'),\n );\n const out: ValidationIssue[] = [];\n for (const name of active) {\n const definition = fieldMap[name];\n if (definition === undefined) continue;\n const { required } = fieldPredicateFlags(definition, input.ctx ?? {}, values);\n const { validators } = resolveFieldStatic(definition);\n const outcome = await validateFieldValue({\n // The runner's structural half: presence and the declared validators. A field's type and\n // constraints are its input's concern until the declaration carries them.\n field: { type: 'unknown', ...(required ? { required: true } : {}) },\n fieldName: name,\n value: values[name],\n values,\n fieldValidators: (validators as readonly ValidatorImplementation[]).map(shorthandAware),\n allowSchemaMessageFallback: true,\n runValidatorsOnEmpty: true,\n });\n // A validator that threw answers nothing: the issue says so to the user, and the\n // development console says which field's validator to read.\n if (\n outcome.issues.some((issue) => issue.code.endsWith('.exception')) &&\n process.env.NODE_ENV !== 'production'\n )\n console.error(`[useFormController] The validator of \"${name}\" threw; see its issue.`);\n out.push(...outcome.issues);\n }\n if (input.schema !== undefined) out.push(...(await runFormSchema(input.schema, values)));\n if (input.validate !== undefined) {\n const ctx: ValidationContext = { values };\n out.push(...normalizeFieldIssues(await input.validate(values, ctx), { defaultField: '_form' }));\n }\n return out.filter((issue) => {\n const field = issueField(issue);\n return field === undefined || field === '_form' || active.has(field);\n });\n}\n\n/** The context a resource's form-level `validate` reads (`ResourceValidationContext`). */\nexport interface ResourceValidateContext {\n readonly values: FormValues;\n readonly resource: string;\n readonly view: 'create' | 'edit' | 'show';\n readonly signal: AbortSignal;\n readonly dirty: Record<string, boolean>;\n readonly initialValues: FormValues;\n}\n\n/** A resource's form-level validator, as `ResourceConfig.validate` declares it. */\nexport type ResourceValidate = (\n values: FormValues,\n ctx: ResourceValidateContext,\n) => unknown | Promise<unknown>;\n\nfunction isCanonicalIssueList(\n result: unknown,\n): result is ValidationIssue | readonly ValidationIssue[] {\n const candidates = Array.isArray(result) ? result : [result];\n return (\n candidates.length > 0 &&\n candidates.every(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n typeof (entry as ValidationIssue).code === 'string' &&\n Array.isArray((entry as ValidationIssue).path) &&\n typeof (entry as ValidationIssue).message?.key === 'string',\n )\n );\n}\n\n/** The issue a form shows when its form-level validator throws: nothing checked the values. */\nconst VALIDATOR_FAILED: ValidationIssue = Object.freeze({\n code: 'validator.exception',\n message: Object.freeze({ key: 'errors.validatorFailed' }),\n path: Object.freeze([]),\n source: 'resource',\n severity: 'error',\n});\n\n/**\n * Runs a resource's form-level `validate` (the old engine's contract): a\n * returned map of field → `string | string[] | null` becomes one\n * `resource.invalid` issue per declared field with a message (an array's\n * first entry), canonical `ValidationIssue`s pass through, and a throw that is\n * not an abort becomes one form-level `errors.validatorFailed` error — the\n * absence of an answer is not evidence of validity.\n */\nexport async function runResourceValidate(\n validate: ResourceValidate,\n ctx: ResourceValidateContext,\n fieldMap: ResourceFieldMap,\n): Promise<readonly ValidationIssue[]> {\n let returned: unknown;\n try {\n returned = await validate(ctx.values, ctx);\n } catch (error) {\n const aborted =\n ctx.signal.aborted ||\n (error !== null &&\n typeof error === 'object' &&\n (error as { readonly name?: unknown }).name === 'AbortError');\n if (aborted) return [];\n console.error('[useFormController] The form-level validator threw:', error);\n return [VALIDATOR_FAILED];\n }\n if (isCanonicalIssueList(returned))\n return Array.isArray(returned)\n ? (returned as readonly ValidationIssue[])\n : [returned as ValidationIssue];\n if (returned === null || typeof returned !== 'object') return [];\n const out: ValidationIssue[] = [];\n for (const [name, entry] of Object.entries(returned as Record<string, unknown>)) {\n if (entry == null || !Object.hasOwn(fieldMap, name)) continue;\n const text =\n typeof entry === 'string'\n ? entry\n : Array.isArray(entry) && typeof entry[0] === 'string'\n ? entry[0]\n : undefined;\n if (text === undefined) {\n console.warn(`[burojs] form validate returned a non-string error for \"${name}\":`, entry);\n continue;\n }\n out.push(\n Object.freeze({\n code: 'resource.invalid',\n message: Object.freeze({ key: 'validation.resource.invalid', default: text }),\n path: Object.freeze([name]),\n source: 'resource',\n severity: 'error',\n }),\n );\n }\n return out;\n}\n","import {\n type ScreenSources,\n type StandardSchemaResult,\n type StandardSchemaV1,\n resolveFieldMeta,\n} from '@burojs/core';\nimport { type DependencyList, useEffect } from 'react';\nimport type { FieldMetaState } from './use-field-meta.js';\n\ntype Meta = Readonly<Record<string, unknown>>;\n\ninterface Entry {\n state: FieldMetaState;\n /** Set while an asynchronous schema runs; settled once `state` is no longer pending. */\n promise?: Promise<void>;\n}\n\n/** The last outcome per schema and per resolved meta object: equal inputs are validated once. */\nconst CACHE = new WeakMap<object, WeakMap<object, Entry>>();\n\nconst PENDING: FieldMetaState = Object.freeze({ status: 'pending' });\n\nfunction describeIssues(\n issues: readonly { readonly message?: unknown; readonly path?: readonly unknown[] }[],\n): string {\n return issues\n .map((issue) => {\n const path = (issue.path ?? [])\n .map((segment) =>\n String(\n segment !== null && typeof segment === 'object'\n ? (segment as { readonly key?: unknown }).key\n : segment,\n ),\n )\n .join('.');\n const message = String(issue.message ?? 'invalid');\n return path === '' ? message : `${path}: ${message}`;\n })\n .join('; ');\n}\n\nfunction settle(entry: Entry, result: StandardSchemaResult<unknown>): void {\n if (result.issues !== undefined)\n entry.state = Object.freeze({ status: 'failed', reason: describeIssues(result.issues) });\n else entry.state = Object.freeze({ status: 'ready', meta: result.value as Meta });\n}\n\n/**\n * The schema's verdict on a resolved `meta` (P7 3.3), memoised per schema and meta object. A\n * synchronous schema answers at once; an asynchronous one is `pending` until it settles, then\n * answers from the cache. A throw is a refusal. The returned entry's `promise` resolves when a\n * pending answer settles, so a hook can render again.\n */\nexport function validateFieldMeta(\n schema: StandardSchemaV1,\n meta: Meta,\n): { readonly state: FieldMetaState; readonly settled?: Promise<void> } {\n let perSchema = CACHE.get(schema);\n if (perSchema === undefined) {\n perSchema = new WeakMap();\n CACHE.set(schema, perSchema);\n }\n const cached = perSchema.get(meta);\n if (cached !== undefined) return { state: cached.state, settled: cached.promise };\n const entry: Entry = { state: PENDING };\n perSchema.set(meta, entry);\n try {\n const result = schema['~standard'].validate(meta);\n if (result instanceof Promise) {\n entry.promise = result.then(\n (value) => {\n settle(entry, value);\n },\n (error: unknown) => {\n entry.state = Object.freeze({\n status: 'failed',\n reason: error instanceof Error ? error.message : String(error),\n });\n },\n );\n } else settle(entry, result);\n } catch (error) {\n entry.state = Object.freeze({\n status: 'failed',\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n return { state: entry.state, settled: entry.promise };\n}\n\nfunction reasonOf(path: readonly string[]): string {\n return `meta.${path.join('.')} reads a source that failed`;\n}\n\n/**\n * A field's `meta` as its implementation receives it (P7 3.2, 3.3): the refs read from `sources`,\n * then `schema` (when the implementation declares one) applied to the result. `settled` resolves\n * when a pending asynchronous schema answers.\n */\nexport function fieldMetaStateFor(\n meta: Meta | undefined,\n schema: StandardSchemaV1 | undefined,\n sources: ScreenSources,\n): { readonly state: FieldMetaState; readonly settled?: Promise<void> } {\n const resolution = resolveFieldMeta(meta, sources);\n if (resolution.status === 'pending') return { state: PENDING };\n if (resolution.status === 'failed')\n return { state: Object.freeze({ status: 'failed', reason: reasonOf(resolution.path) }) };\n if (schema === undefined)\n return { state: Object.freeze({ status: 'ready', meta: resolution.meta }) };\n return validateFieldMeta(schema, resolution.meta);\n}\n\n/** Runs `rerender` once every promise in `waiting` has settled; a change of `deps` starts over. */\nexport function useRerenderOnSettle(\n waiting: readonly Promise<void>[],\n rerender: () => void,\n deps: DependencyList,\n): void {\n // biome-ignore lint/correctness/useExhaustiveDependencies: the caller names what restarts it\n useEffect(() => {\n if (waiting.length === 0) return;\n let live = true;\n void Promise.all(waiting).then(() => {\n if (live) rerender();\n });\n return () => {\n live = false;\n };\n }, deps);\n}\n","import type {\n FieldDeclaration,\n FieldOption,\n ValidationIssue,\n ValidationIssues,\n} from '@burojs/core';\nimport { createElement, type ComponentType, type ReactElement, useMemo } from 'react';\nimport { useFieldImplementationCatalog } from './provider.js';\nimport type { FieldImplementationCatalog } from './definitions.js';\nimport type {\n CollectionDisplayProps,\n CollectionInputProps,\n FieldAccessibilityIds,\n FieldImplementationAttempt,\n FieldImplementationComponent,\n FieldImplementation,\n FieldImplementationLayout,\n FieldRenderSurface,\n FieldTestIds,\n FieldUiHints,\n ResolvedFieldImplementation,\n ScalarDisplayProps,\n ScalarInputProps,\n UseFieldImplementationArgs,\n} from './types.js';\n\nconst EMPTY_LAYOUT: FieldImplementationLayout = Object.freeze({});\nconst EMPTY_META = Object.freeze({});\nconst EMPTY_UI = Object.freeze({});\nconst EMPTY_OPTIONS = Object.freeze([]);\n\ntype RuntimeField = {\n readonly type: string;\n readonly format?: string;\n readonly items?: FieldDeclaration;\n readonly meta?: Readonly<Record<string, unknown>>;\n readonly ui?: FieldUiHints;\n readonly options?: readonly FieldOption[];\n};\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction ui(value: unknown): FieldUiHints | undefined {\n return isRecord(value) ? (value as FieldUiHints) : undefined;\n}\n\n/** Accept a raw declaration or a native FieldDefBase that carries one. */\nfunction canonicalField(input: UseFieldImplementationArgs['field']): RuntimeField {\n if (!isRecord(input)) throw new TypeError('A field implementation requires a field declaration.');\n const nested = isRecord(input.declaration) ? input.declaration : undefined;\n const type = typeof input.type === 'string' ? input.type : nested?.type;\n if (typeof type !== 'string' || type.length === 0) {\n throw new TypeError('A field implementation requires a canonical field type.');\n }\n const format =\n typeof input.format === 'string'\n ? input.format\n : typeof nested?.format === 'string'\n ? nested.format\n : undefined;\n const items = isRecord(input.items)\n ? (input.items as unknown as FieldDeclaration)\n : isRecord(nested?.items)\n ? (nested.items as unknown as FieldDeclaration)\n : undefined;\n const meta = isRecord(input.meta) ? input.meta : isRecord(nested?.meta) ? nested.meta : undefined;\n const fieldUi = ui(input.ui) ?? ui(nested?.ui);\n return Object.freeze({\n type,\n ...(format === undefined ? {} : { format }),\n ...(items === undefined ? {} : { items }),\n ...(meta === undefined ? {} : { meta }),\n ...(fieldUi === undefined ? {} : { ui: fieldUi }),\n ...(Array.isArray(input.options)\n ? { options: input.options as readonly FieldOption[] }\n : Array.isArray(nested?.options)\n ? { options: nested.options as readonly FieldOption[] }\n : {}),\n });\n}\n\nfunction component(\n catalog: FieldImplementationCatalog,\n id: string | undefined,\n surface: FieldRenderSurface,\n collection: boolean,\n): FieldImplementationComponent | undefined {\n if (id === undefined) return undefined;\n const implementation = catalog[id];\n if (implementation === undefined) return undefined;\n const value = collection\n ? surface === 'input'\n ? implementation.CollectionInput\n : implementation.CollectionDisplay\n : surface === 'input'\n ? implementation.Input\n : implementation.Display;\n return value as FieldImplementationComponent | undefined;\n}\n\n/** The catalogue entry an id names, for `ResolvedFieldImplementation.implementation`. */\nfunction implementationOf(\n catalog: FieldImplementationCatalog,\n id: string | undefined,\n): { readonly implementation: FieldImplementation<any, any> } | Record<string, never> {\n const found = id === undefined ? undefined : catalog[id];\n return found === undefined ? {} : { implementation: found };\n}\n\nfunction layout(\n catalog: FieldImplementationCatalog,\n id: string | undefined,\n): FieldImplementationLayout {\n return id === undefined ? EMPTY_LAYOUT : (catalog[id]?.layout ?? EMPTY_LAYOUT);\n}\n\nfunction explicitId(field: RuntimeField, surface: FieldRenderSurface): string | undefined {\n const candidate = surface === 'input' ? field.ui?.input : field.ui?.display;\n return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined;\n}\n\nfunction trace(field: RuntimeField, attempts: readonly FieldImplementationAttempt[]) {\n return Object.freeze({\n ...(field.format === undefined\n ? {}\n : { rawFormat: field.format, resolvedFormat: field.format }),\n attempts: Object.freeze([...attempts]),\n });\n}\n\nfunction missing(\n field: RuntimeField,\n surface: FieldRenderSurface,\n multiple: boolean,\n attempts: readonly FieldImplementationAttempt[],\n): ResolvedFieldImplementation {\n const resolution = trace(field, attempts);\n return Object.freeze({\n multiple,\n source: 'fallback',\n layout: EMPTY_LAYOUT,\n trace: resolution,\n diagnostic: Object.freeze({\n code: 'missing-field-implementation',\n fieldType: field.type,\n ...(field.format === undefined ? {} : { format: field.format, resolvedFormat: field.format }),\n surface,\n attempts: resolution.attempts,\n }),\n });\n}\n\nfunction lookup(\n catalog: FieldImplementationCatalog,\n attempts: FieldImplementationAttempt[],\n stage: FieldImplementationAttempt['stage'],\n id: string | undefined,\n surface: FieldRenderSurface,\n collection: boolean,\n): FieldImplementationComponent | undefined {\n attempts.push(\n Object.freeze({\n stage,\n capability: collection ? `collection-${surface}` : surface,\n ...(id === undefined ? {} : { id }),\n }),\n );\n return component(catalog, id, surface, collection);\n}\n\nfunction scalar(\n catalog: FieldImplementationCatalog,\n field: RuntimeField,\n surface: FieldRenderSurface,\n): ResolvedFieldImplementation {\n const attempts: FieldImplementationAttempt[] = [];\n const explicit = explicitId(field, surface);\n const explicitComponent = lookup(catalog, attempts, 'explicit', explicit, surface, false);\n if (explicitComponent !== undefined)\n return Object.freeze({\n Component: explicitComponent,\n ...implementationOf(catalog, explicit),\n multiple: false,\n source: 'explicit',\n layout: layout(catalog, explicit),\n trace: trace(field, attempts),\n });\n const formatComponent = lookup(catalog, attempts, 'format', field.format, surface, false);\n if (formatComponent !== undefined)\n return Object.freeze({\n Component: formatComponent,\n ...implementationOf(catalog, field.format),\n multiple: false,\n source: 'format',\n layout: layout(catalog, field.format),\n trace: trace(field, attempts),\n });\n const base = lookup(catalog, attempts, 'base', field.type, surface, false);\n if (base !== undefined)\n return Object.freeze({\n Component: base,\n ...implementationOf(catalog, field.type),\n multiple: false,\n source: 'base',\n layout: layout(catalog, field.type),\n trace: trace(field, attempts),\n });\n return missing(field, surface, false, attempts);\n}\n\nfunction collection(\n catalog: FieldImplementationCatalog,\n field: RuntimeField,\n surface: FieldRenderSurface,\n): ResolvedFieldImplementation {\n const attempts: FieldImplementationAttempt[] = [];\n const explicit = explicitId(field, surface);\n const explicitComponent = lookup(catalog, attempts, 'explicit', explicit, surface, true);\n if (explicitComponent !== undefined)\n return Object.freeze({\n Component: explicitComponent,\n ...implementationOf(catalog, explicit),\n multiple: true,\n source: 'explicit',\n layout: layout(catalog, explicit),\n trace: trace(field, attempts),\n });\n const ownFormat = lookup(catalog, attempts, 'own-collection-format', field.format, surface, true);\n if (ownFormat !== undefined)\n return Object.freeze({\n Component: ownFormat,\n ...implementationOf(catalog, field.format),\n multiple: true,\n source: 'collection-format',\n layout: layout(catalog, field.format),\n trace: trace(field, attempts),\n });\n const item = canonicalField(field.items!);\n const itemFormat = lookup(\n catalog,\n attempts,\n 'item-collection-format',\n item.format,\n surface,\n true,\n );\n if (itemFormat !== undefined)\n return Object.freeze({\n Component: itemFormat,\n ...implementationOf(catalog, item.format),\n multiple: true,\n source: 'collection-format',\n layout: layout(catalog, item.format),\n trace: trace(field, attempts),\n });\n const itemResolved = scalar(catalog, item, surface);\n attempts.push(\n ...itemResolved.trace.attempts.map((attempt) =>\n Object.freeze({ ...attempt, stage: 'item-scalar' as const }),\n ),\n );\n if (itemResolved.Component !== undefined)\n return Object.freeze({\n Component: (surface === 'input'\n ? GenericArrayInput\n : GenericArrayDisplay) as FieldImplementationComponent,\n multiple: true,\n source: 'array-shell',\n layout: itemResolved.layout,\n item: itemResolved,\n trace: trace(field, attempts),\n });\n const base = lookup(catalog, attempts, 'base', field.type, surface, true);\n if (base !== undefined)\n return Object.freeze({\n Component: base,\n ...implementationOf(catalog, field.type),\n multiple: true,\n source: 'base',\n layout: layout(catalog, field.type),\n trace: trace(field, attempts),\n });\n return missing(field, surface, true, attempts);\n}\n\n/** Resolve host-provided code without consulting an app runtime or module global. */\nexport function resolveFieldImplementation(\n catalog: FieldImplementationCatalog,\n input: UseFieldImplementationArgs,\n): ResolvedFieldImplementation {\n const field = canonicalField(input.field);\n if (field.type === 'array') {\n if (field.items === undefined)\n throw new TypeError('An array field implementation requires an items declaration.');\n return collection(catalog, field, input.surface);\n }\n return scalar(catalog, field, input.surface);\n}\n\nexport function useFieldImplementation(\n input: UseFieldImplementationArgs,\n): ResolvedFieldImplementation {\n const catalog = useFieldImplementationCatalog();\n return useMemo(() => resolveFieldImplementation(catalog, input), [catalog, input]);\n}\n\nfunction indexedIds<T extends FieldAccessibilityIds | FieldTestIds>(input: T, index: number): T {\n return Object.freeze(\n Object.fromEntries(\n Object.entries(input).map(([key, value]) => [\n key,\n typeof value === 'string' && value.length > 0 ? `${value}-${index}` : value,\n ]),\n ),\n ) as T;\n}\n\nfunction itemIssues(issues: ValidationIssues, index: number): ValidationIssues {\n return Object.freeze(\n issues\n .filter((issue) => issue.path[0] === index)\n .map((issue) =>\n Object.freeze({ ...issue, path: Object.freeze(issue.path.slice(1)) }),\n ) as ValidationIssue[],\n );\n}\n\nfunction itemContext<T extends CollectionInputProps<unknown> | CollectionDisplayProps<unknown>>(\n parent: T,\n field: FieldDeclaration,\n index: number,\n) {\n const item = canonicalField(field);\n return Object.freeze({\n ...parent,\n field,\n path: Object.freeze([...parent.path, index]),\n meta: item.meta ?? EMPTY_META,\n ui: item.ui ?? EMPTY_UI,\n options: item.options ?? EMPTY_OPTIONS,\n issues: itemIssues(parent.issues, index),\n accessibility: indexedIds(parent.accessibility, index),\n testIds: indexedIds(parent.testIds, index),\n });\n}\n\nfunction GenericArrayInput(props: CollectionInputProps<unknown>): ReactElement | null {\n const field = canonicalField(props.field);\n if (field.type !== 'array' || field.items === undefined) return null;\n return createElement(\n 'div',\n { 'data-buro-array-shell': 'input' },\n props.value.map((value, index) =>\n createElement(GenericArrayItemInput, {\n key: index,\n field: field.items!,\n parent: props,\n value,\n index,\n }),\n ),\n );\n}\n\nfunction GenericArrayItemInput({\n field,\n parent,\n value,\n index,\n}: {\n readonly field: FieldDeclaration;\n readonly parent: CollectionInputProps<unknown>;\n readonly value: unknown;\n readonly index: number;\n}): ReactElement | null {\n const resolved = useFieldImplementation({ field, surface: 'input' });\n if (resolved.Component === undefined) return null;\n const Component = resolved.Component as ComponentType<ScalarInputProps<unknown>>;\n return createElement(Component, {\n ...itemContext(parent, field, index),\n multiple: false,\n value,\n onChange: (next: unknown) =>\n parent.onChange?.(\n parent.value.map((entry, itemIndex) => (itemIndex === index ? next : entry)),\n ),\n } as ScalarInputProps<unknown>);\n}\n\nfunction GenericArrayDisplay(props: CollectionDisplayProps<unknown>): ReactElement | null {\n const field = canonicalField(props.field);\n if (field.type !== 'array' || field.items === undefined) return null;\n return createElement(\n 'div',\n { 'data-buro-array-shell': 'display' },\n props.value.map((value, index) =>\n createElement(GenericArrayItemDisplay, {\n key: index,\n field: field.items!,\n parent: props,\n value,\n index,\n }),\n ),\n );\n}\n\nfunction GenericArrayItemDisplay({\n field,\n parent,\n value,\n index,\n}: {\n readonly field: FieldDeclaration;\n readonly parent: CollectionDisplayProps<unknown>;\n readonly value: unknown;\n readonly index: number;\n}): ReactElement | null {\n const resolved = useFieldImplementation({ field, surface: 'display' });\n if (resolved.Component === undefined) return null;\n const Component = resolved.Component as ComponentType<ScalarDisplayProps<unknown>>;\n return createElement(Component, {\n ...itemContext(parent, field, index),\n multiple: false,\n value,\n } as ScalarDisplayProps<unknown>);\n}\n","import type { FieldDeclaration, NodeState, ScreenSources, SourceState } from '@burojs/core';\nimport { useReducer, useRef } from 'react';\nimport type { FieldImplementationCatalog } from './definitions.js';\nimport { fieldMetaStateFor, useRerenderOnSettle } from './meta-validation.js';\nimport { resolveFieldImplementation } from './use-field-implementation.js';\n\nconst READY_NULL = Object.freeze({\n status: 'ready',\n value: null,\n refreshing: false,\n}) as SourceState;\nconst NONE: Readonly<Record<string, NodeState>> = Object.freeze({});\n\n/**\n * What the planner folds in for each field of a screen whose `meta` is not ready (P7 3.2, 3.3,\n * `PlanScreenInput.fieldMeta`): `pending` while a ref's source (or one field of a projected row,\n * P5) is undecided or an asynchronous schema runs, `failed` once a source failed or the field's\n * implementation refused the resolved meta. A field whose meta is ready has no entry. The same\n * object is returned while the outcomes are the same, so a plan memoised on it holds.\n *\n * @internal\n */\nexport function useFieldMetaOutcomes(\n fields: readonly { readonly name: string; readonly declaration: unknown }[],\n sources: ScreenSources,\n mode: 'create' | 'edit' | 'show',\n catalog: FieldImplementationCatalog | null,\n): Readonly<Record<string, NodeState>> {\n const previous = useRef<Readonly<Record<string, NodeState>>>(NONE);\n const [tick, rerender] = useReducer((count: number) => count + 1, 0);\n const next: Record<string, NodeState> = {};\n const waiting: Promise<void>[] = [];\n // A create has no record: a `record` ref reads `null` there, as the field's own render reads it.\n const readable: ScreenSources =\n mode === 'create' && !Object.hasOwn(sources, 'record')\n ? { ...sources, record: READY_NULL }\n : sources;\n for (const { name, declaration } of fields) {\n const field = declaration as FieldDeclaration;\n let schema: ReturnType<typeof schemaOf>;\n try {\n schema = schemaOf(catalog, field, mode === 'show' ? 'display' : 'input');\n } catch {\n schema = undefined;\n }\n if (field.meta === undefined && schema === undefined) continue;\n const answer = fieldMetaStateFor(field.meta, schema, readable);\n if (answer.state.status === 'pending') {\n next[name] = 'pending';\n if (answer.settled !== undefined) waiting.push(answer.settled);\n } else if (answer.state.status === 'failed') next[name] = 'failed';\n }\n useRerenderOnSettle(waiting, rerender, [tick, waiting.length === 0 ? 0 : outcomeKey(next)]);\n const keys = Object.keys(next);\n const held = previous.current;\n if (\n keys.length === Object.keys(held).length &&\n keys.every((key) => Object.hasOwn(held, key) && held[key] === next[key])\n )\n return held;\n previous.current = keys.length === 0 ? NONE : Object.freeze(next);\n return previous.current;\n}\n\nfunction outcomeKey(outcomes: Readonly<Record<string, NodeState>>): string {\n return JSON.stringify(outcomes);\n}\n\nfunction schemaOf(\n catalog: FieldImplementationCatalog | null,\n field: FieldDeclaration,\n surface: 'input' | 'display',\n) {\n if (catalog === null) return undefined;\n return resolveFieldImplementation(catalog, { field, surface }).implementation?.meta;\n}\n","/**\n * What policy reads beside what view code reads (P5 spec 3.6, P4 4.24 C2): the raw record of a\n * form controller and the raw rows of a list controller. They hang off the controller object in\n * a side table, not on its public type: a consumer of `useFormController` or `useResourceList`\n * sees only the projected values, and `@burojs/ui-shadcn` reads these for item-action gates,\n * selection and the flows a record page starts.\n */\n\nconst records = new WeakMap<object, Readonly<Record<string, unknown>>>();\nconst rows = new WeakMap<object, readonly Record<string, unknown>[]>();\n\n/** Records `controller`'s record as read (before field view projected it). */\nexport function attachPolicyRecord<T extends object>(\n controller: T,\n record: Readonly<Record<string, unknown>> | undefined,\n): T {\n if (record !== undefined) records.set(controller, record);\n return controller;\n}\n\n/** Records `controller`'s rows as read. */\nexport function attachPolicyRows<T extends object>(\n controller: T,\n policyRows: readonly Record<string, unknown>[],\n): T {\n rows.set(controller, policyRows);\n return controller;\n}\n\n/**\n * The record as read, for policy: item-action gates and the flows a record page starts.\n * `fallback` (the controller's own projected `record`) when none was attached.\n *\n * @internal `@burojs/ui-shadcn` reads it; view code never does.\n */\nexport function policyRecordOf(\n controller: object,\n fallback?: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> | undefined {\n return records.get(controller) ?? fallback;\n}\n\n/**\n * The rows as read, for policy: selection, bulk and item-action gates. `fallback` (the\n * controller's own `rows`) when none was attached, as for a hand-written controller.\n *\n * @internal `@burojs/ui-shadcn` reads it; view code never does.\n */\nexport function policyRowsOf<T extends Record<string, unknown>>(\n controller: object,\n fallback: T[],\n): T[] {\n return (rows.get(controller) as T[] | undefined) ?? fallback;\n}\n","import type { CompiledScreen, NodeState, ScreenSources, SourceState } from '@burojs/core';\nimport { useMemo, useRef, useState } from 'react';\nimport { useOptionalApplicationSnapshot, useOptionalLayerRuntime } from '../../runtime.js';\nimport {\n blockDataOf,\n type PlacementReads,\n type PlacementRuntime,\n resolvePlacements,\n type ValidationCache,\n} from './placements.js';\n\nconst NONE: { readonly placements?: undefined; readonly blockData?: undefined } = Object.freeze({});\n\nconst unavailable = (what: string): SourceState =>\n Object.freeze({\n status: 'ready',\n value: undefined,\n refreshing: false,\n error: Object.freeze({\n kind: 'capability',\n code: 'resource-less-read',\n message: `A resource-less form reads no ${what}: a block it places reads its props.`,\n }),\n }) as SourceState;\n\n/**\n * The placements of a resource-less form whose tree places blocks (P4-D: a flow's form and its\n * review place the app's blocks, spec 3.6): each placement's props validated and resolved over\n * the form's own sources — a prop defaulting to a `values` ref reads what the user filled in. A\n * resource-less form reads no data: a block's `data` entry (`source.one`, `source.list`, a\n * query) answers unavailable. Only with `enabled` (a form given the app's block catalogue);\n * otherwise nothing is resolved, as before.\n */\nexport function useResourceLessPlacements(input: {\n readonly enabled: boolean;\n readonly screen: CompiledScreen | null;\n readonly sources: ScreenSources;\n}): {\n readonly placements?: Readonly<Record<string, PlacementRuntime>>;\n readonly blockData?: Readonly<Record<string, NodeState>>;\n} {\n const snapshot = useOptionalApplicationSnapshot();\n const layerRuntime = useOptionalLayerRuntime();\n const validations = useRef<ValidationCache>(new Map());\n const [settled, setSettled] = useState(0);\n const { enabled, screen, sources } = input;\n // biome-ignore lint/correctness/useExhaustiveDependencies: `settled` re-resolves after an async prop validation\n return useMemo(() => {\n if (\n !enabled ||\n snapshot === null ||\n layerRuntime === null ||\n screen === null ||\n !screen.nodes.some((node) => node.kind === 'place')\n )\n return NONE;\n const reads: PlacementReads = {\n read: (source, path) => {\n const state = Object.hasOwn(sources, source) ? sources[source] : undefined;\n if (state === undefined) return unavailable(source);\n if (state.status !== 'ready') return state;\n let value: unknown = state.value;\n for (const segment of path)\n value =\n value !== null && typeof value === 'object'\n ? (value as Record<string, unknown>)[segment]\n : undefined;\n return Object.freeze({ ...state, value });\n },\n query: () => unavailable('query'),\n one: () => unavailable('record'),\n list: () => unavailable('list'),\n };\n const placements = resolvePlacements({\n compiled: screen,\n snapshot,\n attachments: layerRuntime.getAttachmentCatalog(),\n reads,\n demanded: new Set(),\n validations: validations.current,\n onSettled: () => setSettled((value) => value + 1),\n project: () => undefined,\n });\n return Object.freeze({ placements, blockData: blockDataOf(placements) });\n }, [enabled, screen, sources, snapshot, layerRuntime, settled]);\n}\n","import {\n type CheckOutcome,\n type CheckSurface,\n type CompiledScreen,\n type EntityRef,\n type LayerRuntime,\n type PlanNode,\n type PlanOpen,\n type FieldAccessMap,\n type PlanAccess,\n type Rule,\n type SourceState,\n type Check,\n type DraftOption,\n type ResourceFieldMap,\n type NodeState,\n type ScreenPlan,\n type ScreenSources,\n type StandardSchemaV1,\n type TypeOfferState,\n type ValidationIssue,\n type ValidationIssues,\n canonicalEntityNodeKey,\n checkSourceNames,\n compiledScreenFor,\n dtoFields,\n evaluateChecks,\n filterInlineIssues,\n i18nPrefixToRef,\n isScreenFailure,\n normalizeEntityRef,\n planScreen,\n projectSource,\n resolveAvailability,\n resolveFieldAccess,\n ruleContextFor,\n typeOffer,\n} from '@burojs/core';\nimport {\n type Dispatch,\n type SetStateAction,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { inheritFileMapperBaseline } from '@burojs/file-storage';\nimport { useFormSubmitAudit } from '../../audit/use-form-submit-audit.js';\nimport { type CheckGateState, useCheckGate } from '../../checks/use-check-gate.js';\nimport {\n createRuntimeActionDataAccess,\n createUnavailableActionDataAccess,\n} from '../../data/action-data-access.js';\nimport { useOptionalDataRuntime } from '../../data/context.js';\nimport { useChecks } from '../../checks/use-checks.js';\nimport { useCreateOne } from '../../hooks/data/use-create.js';\nimport { useUpdateOne } from '../../hooks/data/use-update.js';\nimport { AppContext } from '../../context.js';\nimport { useApp } from '../../hooks/use-app.js';\nimport { useOptionalRouterAdapter } from '../../hooks/router/router-adapter.js';\nimport { EMPTY_ROUTE, useRouteSource } from './route-source.js';\nimport { useRuntimeSelection } from '../../runtime.js';\nimport { useCurrentUserId } from '../../hooks/use-current-user-id.js';\nimport { useOptionalVisibilityCtx } from '../../hooks/use-permissions.js';\nimport { useLocale, useTranslate } from '../../hooks/use-t.js';\nimport { useDismissPending } from '../../navigation/dismiss-scope.js';\nimport { useNavigationBlocker } from '../../navigation/navigation-guard.js';\nimport { useFormScreen } from '../use-form-screen.js';\nimport type { FieldBinding, FormValidate, FormValues, SubmitEventLike } from '../types.js';\nimport { resolveFieldFilter, fieldPredicateFlags } from '../conditional.js';\nimport { relationSeedsFor } from '../select-seeds.js';\nimport {\n DRAFT_INTERVAL_MS,\n type DraftStore,\n type StoredDraft,\n clearDraft,\n draftKey,\n draftStoreOf,\n draftRecordId,\n readDraft,\n recordVersionOf,\n restorableValues,\n snapshotValues,\n writeDraft,\n} from './draft.js';\nimport { isFrameworkFlowRun } from '../../flows/run-registry.js';\nimport { useDraftScopeHash } from './draft-session-binding.js';\nimport { buildPayload, ruleDeniedFields } from './payload.js';\nimport {\n type ResourceValidate,\n isFieldDirty,\n isFormDirty,\n issueField,\n runResourceValidate,\n runValidation,\n toResolvedIssue,\n} from './pipeline.js';\nimport { type ScreenOpenState, useScreenState } from './screen-state.js';\nimport { type CreateSeeds, createSeeds } from './seeds.js';\nimport type {\n FormController,\n FormControllerFailure,\n FormDraftState,\n FormSteps,\n FormSubmitResult,\n UseFormControllerFormOptions,\n UseFormControllerRecordOptions,\n} from './types.js';\nimport {\n readPermissions,\n scopeSourceState,\n useContextSnapshot,\n userSourceState,\n NO_DEMAND,\n type ResolverDemand,\n sameDemand,\n useSourceResolver,\n useStableAccess,\n} from './use-source-resolver.js';\nimport { grantedCandidateFields } from '@burojs/core';\nimport { useOptionalFieldImplementationCatalog } from '../../fields/provider.js';\nimport { useFieldMetaOutcomes } from '../../fields/use-field-meta-outcomes.js';\nimport { attachPolicyRecord } from '../../policy-side-channel.js';\nimport type { PlacementRuntime } from './placements.js';\nimport { useResourceLessPlacements } from './resource-less-placements.js';\n\nconst EMPTY_VALUES: FormValues = Object.freeze({});\nconst NO_VALIDATION: readonly ValidationIssue[] = Object.freeze([]);\nconst REFUSED: FormSubmitResult = Object.freeze({ status: 'refused' });\nconst BLOCKED: FormSubmitResult = Object.freeze({ status: 'blocked' });\nconst INVALID: FormSubmitResult = Object.freeze({ status: 'invalid' });\nconst CANCELLED: FormSubmitResult = Object.freeze({ status: 'cancelled' });\n\n/** A controller's form state: its values, the baseline `isDirty` reads, and what seeded them. */\ninterface FormState {\n readonly values: FormValues;\n readonly baseline: FormValues;\n /** Create only. */\n readonly seeds?: CreateSeeds;\n /** What the values were seeded from: the type in create, the record id elsewhere. */\n readonly key: string;\n /** Edit and show: whether the record has seeded the values yet. */\n readonly seeded: boolean;\n /** The fields blurred since the last reset: `trigger: 'touched'` checks read it. */\n readonly touched: Readonly<Record<string, boolean>>;\n /** Whether a submit was attempted since the last reset. */\n readonly submitAttempted: boolean;\n /**\n * A resource-less form with `access`: the baseline as given, before a field its user may not\n * view left it. Rules read it, so they answer the same before and after the first render; view\n * code never does.\n */\n readonly policy?: FormValues;\n}\n\nconst UNTOUCHED: Readonly<Record<string, boolean>> = Object.freeze({});\n\n/** How the engine runs checks: the resource's (`useChecks` / `useCheckGate`) or a plain list. */\ninterface ChecksPort {\n /** The check issues a form shows inline now. */\n inline(outcome: CheckOutcome | null, state: FormState): ValidationIssues;\n /** The authoritative pass at submit; `null` when there are no checks. */\n runNow(values: FormValues, saved: FormValues): Promise<CheckOutcome | null>;\n /** The dialog state a host renders (a record form's check gate). */\n readonly gate?: CheckGateState;\n /** Asks about the confirmable issues. */\n confirm(\n outcome: CheckOutcome,\n values: FormValues,\n saved: FormValues,\n ): Promise<'proceed' | 'cancel'>;\n}\n\n/** What one controller shape hands the shared engine. */\ninterface EngineInput {\n readonly screen: CompiledScreen | null;\n readonly failure: FormControllerFailure | null;\n readonly mode: 'create' | 'edit' | 'show';\n readonly state: FormState;\n readonly setState: Dispatch<SetStateAction<FormState>>;\n readonly sources: ScreenSources;\n /** Refetches failed sources by name. */\n readonly retry: (sources: readonly string[]) => void;\n /**\n * Told every plan during render: the record controller hands the plan's demand back to its\n * source resolver (spec 10.1), which loads only what the plan asks for.\n */\n readonly onPlan?: (plan: ScreenPlan) => void;\n /** Each placement's block data state, for `planScreen` (the record controller's resolver). */\n readonly blockData?: Readonly<Record<string, NodeState>>;\n /**\n * The `with` sources the form's checks read, demanded active while the form can submit\n * (P2 4.10): merged into the plan's `demand.active`, which the resolver loads.\n */\n readonly checkSources?: readonly string[];\n /** Each placement at mount, by key. */\n readonly placements?: Readonly<Record<string, PlacementRuntime>>;\n /** The resource name a development message names. */\n readonly label: string;\n readonly access: PlanAccess;\n /** The record view code sees (edit, show): projected by field view (P5 spec 3.6.1). */\n readonly record: unknown;\n /**\n * The record as read, before the projection (edit, show): what rules, the payload's denied set\n * and the file baseline read (decision P5-12). Absent: `record`.\n */\n readonly policyRecord?: unknown;\n /** The screen resource's field decisions the resolver projected with (`planScreen`'s `fieldAccess`). */\n readonly fieldAccess?: FieldAccessMap;\n /** The placements absent for access (`planScreen`'s `blockAccess`). */\n readonly blockAccess?: readonly string[];\n readonly fieldMap: ResourceFieldMap;\n /** The fields as the code declared them (the registry's, or the resource-less form's own): the seeds' only source. */\n readonly codeFields: ResourceFieldMap;\n /**\n * The registry definition the fields belong to: its marker names the fields whose candidates a\n * granted layer chose (they seed nothing). Absent for a resource-less form, whose fields are\n * the caller's own code.\n */\n readonly candidateOwner?: object;\n readonly resourceRef: EntityRef;\n readonly type?: string;\n /** A typed create's offer; absent otherwise. */\n readonly typeOffer?: TypeOfferState;\n /** Writes the payload; `null` in show. */\n readonly write: ((payload: Record<string, unknown>) => unknown | Promise<unknown>) | null;\n readonly onChange?: (values: FormValues) => void;\n /** The state `reset()` returns to when given no values. */\n readonly initial: () => FormState;\n readonly checks: ChecksPort;\n /** What `required(fn)` and `disabled(fn)` read as their context. */\n readonly ctx: unknown;\n readonly schema?: StandardSchemaV1;\n readonly validate?: FormValidate;\n /** The draft's storage key; `null` when drafts are off. */\n readonly draftKey: string | null;\n /** Where the draft lives (`draft.store`; default the tab's `sessionStorage`, spec 4.11). */\n readonly draftStore: DraftStore;\n /** A flow's form: its run's attempt key, stored with the draft (P4-B review M5). */\n readonly draftAttempt?: string;\n /** The fields a draft never stores (`draft.exclude`). */\n readonly draftExclude: readonly string[];\n /** `false` (a resource's `dirtyWarning: false`): the form registers no navigation blocker. */\n readonly dirtyWarning: boolean;\n /** A flow's form (a verified run claim): the run emits `flow.submit`, the form nothing. */\n readonly flowForm?: boolean;\n /**\n * A flow's form: the issues its run decided (a check's error on a field, a server's validation\n * refusal, M14), shown beside the form's own and brought into view when they arrive.\n */\n readonly externalIssues?: readonly ValidationIssue[];\n /** What a `form.submit` audit event names: the resource, the record, the view. */\n readonly audit: {\n readonly resource?: string;\n readonly recordId?: string;\n readonly view: 'create' | 'edit';\n };\n /**\n * A record edit: carry the record's file-mapper baseline onto the payload\n * (`inheritFileMapperBaseline`), so a file field it did not touch keeps its\n * stored value.\n */\n readonly fileBaseline: boolean;\n /**\n * A record form's resource-level `validate` (`ResourceConfig.validate`): run\n * after `debounceMs` on every change and at submit, the older run aborted.\n */\n readonly resourceValidate?: {\n readonly run: ResourceValidate;\n readonly resource: string;\n readonly debounceMs: number;\n };\n}\n\n/** How long a reveal step waits for the next node to mount: ticks of `REVEAL_TICK_MS`. */\nconst REVEAL_WAIT_TICKS = 20;\nconst REVEAL_TICK_MS = 16;\n\n/** How many times a submit re-runs an aborted or superseded check pass before it blocks. */\nconst MAX_CHECK_PASSES = 3;\n\n/** `ResourceConfig.validateDebounceMs`' default. */\nconst VALIDATE_DEBOUNCE_MS = 300;\n\nfunction screenOf(compiled: ReturnType<typeof compiledScreenFor>): {\n screen: CompiledScreen | null;\n failure: FormControllerFailure | null;\n} {\n if (compiled === undefined) return { screen: null, failure: null };\n if (isScreenFailure(compiled))\n return { screen: null, failure: { kind: 'screen', failure: compiled } };\n return { screen: compiled, failure: null };\n}\n\nconst NO_NAMES: readonly string[] = Object.freeze([]);\n\n/** Whether a granted layer chose the candidates of `field` on `owner` (fail closed when unknown). */\nfunction candidatesMarked(owner: object | undefined, field: string): boolean {\n if (owner === undefined) return false;\n const marker = grantedCandidateFields(owner);\n return marker === 'unknown' || marker.has(field);\n}\nconst NO_FIELDS: readonly { readonly name: string; readonly declaration: unknown }[] =\n Object.freeze([]);\n\n/** A plan whose active demand also holds the check sources (P2 4.10). */\nfunction withCheckDemand(plan: ScreenPlan, names: readonly string[]): ScreenPlan {\n const missing = names.filter((name) => !plan.demand.active.includes(name));\n if (missing.length === 0) return plan;\n return Object.freeze({\n ...plan,\n demand: Object.freeze({\n ...plan.demand,\n active: Object.freeze([...plan.demand.active, ...missing]),\n }),\n });\n}\n\n/** The engine both controller shapes run: the one `planScreen` call, values, bindings and submit. */\nfunction useControllerEngine(input: EngineInput): FormController {\n const { screen, failure, mode, state, sources, access, fieldMap, codeFields } = input;\n const seedApp = useContext(AppContext);\n const host = useScreenState();\n const hostOpen = host?.open;\n // Without a host, the controller keeps the open step of a create wizard itself.\n const [ownContainers, setOwnContainers] = useState<Readonly<Record<string, string>>>(NO_OPEN);\n // The host cannot list the panels a screen starts collapsed: every `collapse: 'closed'`\n // panel the user has not expanded is collapsed.\n const open = useMemo(\n () => planOpenOf(hostOpen, screen, ownContainers),\n [hostOpen, screen, ownContainers],\n );\n const checkSources = input.checkSources ?? NO_NAMES;\n // The fields whose `meta` reads a source still undecided or failed (P7 3.2): pending leaves.\n const fieldMeta = useFieldMetaOutcomes(\n screen?.fields ?? NO_FIELDS,\n sources,\n mode,\n useOptionalFieldImplementationCatalog(),\n );\n const plan: ScreenPlan | null = useMemo(\n () =>\n screen === null || failure !== null\n ? null\n : withCheckDemand(\n planScreen(screen, {\n sources,\n access,\n ...(open === undefined ? {} : { open }),\n baseline: state.baseline,\n ...(input.blockData === undefined ? {} : { blockData: input.blockData }),\n fieldMeta,\n ...(input.fieldAccess === undefined ? {} : { fieldAccess: input.fieldAccess }),\n ...(input.blockAccess === undefined ? {} : { blockAccess: input.blockAccess }),\n ...(input.policyRecord === undefined ? {} : { policyRecord: input.policyRecord }),\n }),\n checkSources,\n ),\n [\n screen,\n failure,\n sources,\n access,\n open,\n state.baseline,\n input.blockData,\n fieldMeta,\n input.fieldAccess,\n input.blockAccess,\n input.policyRecord,\n checkSources,\n ],\n );\n if (plan !== null) input.onPlan?.(plan);\n // What brings a node into view, by compiled node id (guarantee 3).\n const reveals = useRef(new Map<string, () => void>());\n const registerReveal = useCallback((nodeId: string, reveal: () => void) => {\n reveals.current.set(nodeId, reveal);\n return () => {\n if (reveals.current.get(nodeId) === reveal) reveals.current.delete(nodeId);\n };\n }, []);\n /** Opens every container holding the first failing field, outermost first, then focuses it. */\n const revealFirst = useCallback((failing: ReadonlySet<string>) => {\n const { plan: current, input: engine } = latest.current;\n if (current === null || engine.screen === null || failing.size === 0) return;\n const leaf = firstLeaf(current.slots.body, (node) => failing.has(node.field!));\n if (leaf === undefined) return;\n const chain: string[] = [];\n for (\n let index = engine.screen.nodes[leaf.index]?.parent ?? -1;\n index >= 0;\n index = engine.screen.nodes[index]!.parent\n )\n chain.unshift(engine.screen.nodes[index]!.id);\n chain.push(leaf.id);\n // One step per tick: a container opened by the step before mounts the next one's reveal.\n // One step per tick, after the submit settles (its inputs are inert while it runs): a\n // container opened by the step before mounts the next node, whose reveal registers\n // on mount, so a step waits a few frames for it.\n const step = (at: number, waited: number) => {\n if (at >= chain.length) return;\n const reveal = reveals.current.get(chain[at]!);\n if (reveal === undefined && waited < REVEAL_WAIT_TICKS) {\n setTimeout(() => step(at, waited + 1), REVEAL_TICK_MS);\n return;\n }\n reveal?.();\n setTimeout(() => step(at + 1, 0), 0);\n };\n setTimeout(() => step(0, 0), 0);\n }, []);\n const submitAudit = useFormSubmitAudit();\n const [issues, setIssues] = useState<readonly ValidationIssue[]>(NO_VALIDATION);\n const [checkOutcome, setCheckOutcome] = useState<CheckOutcome | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n // The steps of a create wizard the user has completed with Next.\n const [completed, setCompleted] = useState<readonly string[]>(NO_STEPS);\n const submitting = useRef(false);\n const latest = useRef({ plan, state, input });\n latest.current = { plan, state, input };\n\n // The stored draft offered for restore, read again whenever the key changes.\n const key = input.draftKey;\n const [stored, setStored] = useState<{ key: string | null; draft: StoredDraft | null }>(() => ({\n key,\n draft: key === null ? null : readDraft(key, input.draftStore),\n }));\n if (stored.key !== key)\n setStored({ key, draft: key === null ? null : readDraft(key, input.draftStore) });\n\n /** Validates and replaces the issues of `only` (every field when absent). */\n // Every validation run takes a number; a whole-form run (a submit) owns the issues it\n // decides, so an older partial run (a slow blur, a step's Next) that settles after it\n // writes nothing.\n const validationRuns = useRef({ next: 0, lastWhole: 0 });\n const validateNow = useCallback(async (values: FormValues, only?: ReadonlySet<string>) => {\n const { plan: current, input: engine } = latest.current;\n if (current === null || engine.screen === null) return NO_VALIDATION;\n const runs = validationRuns.current;\n runs.next += 1;\n const run = runs.next;\n if (only === undefined) runs.lastWhole = run;\n const fresh = await runValidation({\n compiled: engine.screen,\n plan: current,\n values,\n fieldMap: engine.fieldMap,\n ctx: engine.ctx,\n ...(engine.schema === undefined ? {} : { schema: engine.schema }),\n ...(engine.validate === undefined ? {} : { validate: engine.validate }),\n });\n if (only === undefined) {\n if (runs.lastWhole === run) setIssues(fresh);\n } else if (runs.lastWhole < run)\n setIssues((previous) => [\n ...previous.filter((issue) => !only.has(issueField(issue) ?? '')),\n ...fresh.filter((issue) => only.has(issueField(issue) ?? '')),\n ]);\n return only === undefined ? fresh : fresh.filter((issue) => only.has(issueField(issue) ?? ''));\n }, []);\n\n // The resource-level validator's own issues, replaced by each run that is not superseded.\n const [crossIssues, setCrossIssues] = useState<readonly ValidationIssue[]>(NO_VALIDATION);\n const cross = useRef<{\n seq: number;\n controller: AbortController | null;\n timer: ReturnType<typeof setTimeout> | null;\n mounted: boolean;\n }>({ seq: 0, controller: null, timer: null, mounted: true });\n useEffect(() => {\n const runs = cross.current;\n runs.mounted = true;\n return () => {\n runs.mounted = false;\n if (runs.timer !== null) clearTimeout(runs.timer);\n runs.timer = null;\n runs.controller?.abort();\n };\n }, []);\n\n /** Runs the resource-level validator now; `null` when a newer run superseded this one. */\n // A background run of the resource-level validator is in flight (a submit's own run is\n // covered by `isSubmitting`).\n const [isValidating, setIsValidating] = useState(false);\n const runCross = useCallback(\n async (values: FormValues, background = false): Promise<readonly ValidationIssue[] | null> => {\n const { input: engine, state: now, plan: current } = latest.current;\n const declared = engine.resourceValidate;\n if (declared === undefined) return NO_VALIDATION;\n const runs = cross.current;\n if (runs.timer !== null) clearTimeout(runs.timer);\n runs.timer = null;\n runs.controller?.abort();\n const controller = new AbortController();\n runs.controller = controller;\n runs.seq += 1;\n const seq = runs.seq;\n // A submit has visited every field it can write: each is dirty to the validator.\n const dirty: Record<string, boolean> = { ...now.touched };\n if (!background && current !== null)\n for (const [name, status] of Object.entries(current.fields))\n if (status === 'active') dirty[name] = true;\n setIsValidating(background);\n let fresh: readonly ValidationIssue[];\n try {\n fresh = await runResourceValidate(\n declared.run,\n {\n values,\n resource: declared.resource,\n view: engine.mode,\n signal: controller.signal,\n dirty,\n initialValues: now.baseline,\n },\n engine.fieldMap,\n );\n } finally {\n if (runs.seq === seq && runs.mounted) setIsValidating(false);\n }\n if (runs.seq !== seq || !runs.mounted) return null;\n setCrossIssues(fresh);\n return fresh;\n },\n [],\n );\n\n const scheduleCross = useCallback(() => {\n const declared = latest.current.input.resourceValidate;\n if (declared === undefined) return;\n const runs = cross.current;\n if (runs.timer !== null) clearTimeout(runs.timer);\n runs.timer = setTimeout(() => {\n runs.timer = null;\n void runCross(latest.current.state.values, true);\n }, declared.debounceMs);\n }, [runCross]);\n\n const setValue = useCallback(\n (name: string, value: unknown) => {\n const { plan: current, input: engine, state: now } = latest.current;\n if (current === null || current.fields[name] !== 'active') return;\n if (name === engine.screen?.discriminator) return;\n const next = { ...now.values, [name]: value };\n engine.setState((previous) => ({\n ...previous,\n values: { ...previous.values, [name]: value },\n }));\n engine.onChange?.(next);\n // A field the user was told about re-validates as it changes, so its error is no dead end.\n if (now.submitAttempted || now.touched[name] === true)\n void validateNow(next, new Set([name]));\n scheduleCross();\n },\n [validateNow, scheduleCross],\n );\n\n const blur = useCallback(\n (name: string) => {\n const engine = latest.current.input;\n engine.setState((previous) =>\n previous.touched[name] === true\n ? previous\n : { ...previous, touched: { ...previous.touched, [name]: true } },\n );\n void validateNow(latest.current.state.values, new Set([name]));\n },\n [validateNow],\n );\n\n const run = useCallback(\n async (\n writeWith: ((payload: Record<string, unknown>) => unknown | Promise<unknown>) | null,\n ): Promise<FormSubmitResult> => {\n const { plan: current, input: engine } = latest.current;\n if (engine.failure !== null || engine.screen === null || current === null) return REFUSED;\n if (engine.mode === 'show' || writeWith === null) return REFUSED;\n if (submitting.current) return REFUSED;\n if (current.submitBlocked) return BLOCKED;\n submitting.current = true;\n setIsSubmitting(true);\n engine.setState((previous) =>\n previous.submitAttempted ? previous : { ...previous, submitAttempted: true },\n );\n // The audit's `before` is the baseline as the submit starts (a success re-baselines);\n // its `after` is read when each outcome is decided. No sink, no copy.\n const auditBefore =\n submitAudit.enabled && engine.flowForm !== true\n ? { ...latest.current.state.baseline }\n : null;\n const emitSubmit = (outcome: 'success' | 'error' | 'invalid'): void => {\n if (auditBefore === null) return;\n // The diff covers the fields active in the actor's plan only (P5 decision 25): a hidden or\n // read-only field is never recorded, whatever the record did under the form.\n const planned = latest.current.plan ?? current;\n submitAudit.emit({\n before: activeOnly(auditBefore, planned),\n after: activeOnly(latest.current.state.values, planned),\n fields: engine.fieldMap as Record<string, unknown>,\n outcome,\n ...engine.audit,\n });\n };\n try {\n // Validation and checks decide on the values being submitted, in a completed,\n // non-aborted pass (P1b+P1c decision 28): an aborted pass or one an edit superseded\n // decides nothing, so it is run again; one that never completes blocks.\n let decided = false;\n // The values validation and checks decided on: the payload and the new baseline.\n let submitted: FormValues = latest.current.state.values;\n for (let attempt = 0; attempt < MAX_CHECK_PASSES && !decided; attempt += 1) {\n const values = latest.current.state.values;\n submitted = values;\n const saved = latest.current.state.baseline;\n // 1. Validation of the active fields, and the resource-level validator, un-debounced.\n const [fresh, crossFresh] = await Promise.all([validateNow(values), runCross(values)]);\n // A newer run (an edit during this submit) superseded the validator: nothing decided.\n if (crossFresh === null) return REFUSED;\n const planAfter = latest.current.plan ?? current;\n const crossActive = crossFresh.filter((issue) => {\n const field = issueField(issue);\n return field === undefined || field === '_form' || planAfter.fields[field] === 'active';\n });\n const failed = [...fresh, ...crossActive].filter((issue) => issue.severity === 'error');\n if (failed.length > 0) {\n revealFirst(\n new Set(failed.map(issueField).filter((name): name is string => name !== undefined)),\n );\n emitSubmit('invalid');\n return INVALID;\n }\n // 2. Checks over the submitted values.\n const outcome = await engine.checks.runNow(values, saved);\n if (outcome !== null && outcome.aborted === true) continue;\n if (latest.current.state.values !== values) continue;\n if (outcome !== null) {\n setCheckOutcome(outcome);\n if (outcome.blockers.length > 0) {\n emitSubmit('invalid');\n return BLOCKED;\n }\n if (outcome.confirmable.length > 0) {\n const decision = await engine.checks.confirm(outcome, values, saved);\n if (decision === 'cancel') return CANCELLED;\n }\n }\n decided = true;\n }\n if (!decided) return BLOCKED;\n // 3. The payload, then the write.\n // An edit made while the confirm prompt was open is not sent: the payload is the\n // snapshot that was validated and checked; the edit stays in the form, dirty.\n const planNow = latest.current.plan ?? current;\n const now = latest.current.state;\n const policy = engine.policyRecord ?? engine.record;\n const payload = buildPayload({\n plan: planNow,\n compiled: engine.screen,\n values: submitted,\n ...(now.seeds === undefined ? {} : { seeds: now.seeds }),\n ...(engine.type === undefined ? {} : { type: engine.type }),\n denied: ruleDeniedFields(engine.screen, engine.access, policy),\n access: engine.fieldAccess ?? NO_FIELD_ACCESS,\n });\n const sent =\n engine.fileBaseline && policy !== null && typeof policy === 'object'\n ? inheritFileMapperBaseline(policy, payload)\n : payload;\n let result: unknown;\n try {\n result = await writeWith(sent);\n } catch (error) {\n // An aborted write saved nothing and is no reportable failure.\n if (!isAbort(error)) emitSubmit('error');\n return { status: 'failed', error };\n }\n emitSubmit('success');\n // The baseline is the SUBMITTED values (decision 30): an edit typed during the write\n // stays dirty, keeps the guard armed and keeps its draft.\n engine.setState((previous) => ({ ...previous, baseline: submitted }));\n const untouched = latest.current.state.values === submitted;\n if (untouched) {\n // Before the promise resolves: the caller navigates right after `await submit()`.\n blockerRef.current.release();\n if (engine.draftKey !== null) {\n clearDraft(engine.draftKey);\n setStored({ key: engine.draftKey, draft: null });\n }\n }\n return { status: 'submitted', result };\n } finally {\n submitting.current = false;\n setIsSubmitting(false);\n }\n },\n [validateNow, runCross, revealFirst, submitAudit],\n );\n\n const submit = useCallback(() => run(latest.current.input.write), [run]);\n\n const handleSubmit = useCallback(\n (cb?: (values: FormValues) => unknown | Promise<unknown>) =>\n async (event?: SubmitEventLike): Promise<void> => {\n event?.preventDefault?.();\n await run(cb ?? latest.current.input.write);\n },\n [run],\n );\n\n const reset = useCallback((next?: FormValues) => {\n const engine = latest.current.input;\n const fresh = engine.initial();\n const state =\n next === undefined ? fresh : { ...fresh, values: next, baseline: next, seeded: true };\n engine.setState(state);\n setIssues(NO_VALIDATION);\n const runs = cross.current;\n if (runs.timer !== null) clearTimeout(runs.timer);\n runs.timer = null;\n runs.controller?.abort();\n runs.seq += 1;\n setCrossIssues(NO_VALIDATION);\n setCheckOutcome(null);\n setCompleted(NO_STEPS);\n engine.onChange?.(state.values);\n }, []);\n\n const revalidate = useCallback(async () => {\n const { input: engine, state: now } = latest.current;\n const fresh = await validateNow(now.values);\n if (fresh.some((issue) => issue.severity === 'error') || submitting.current) return;\n const outcome = await engine.checks.runNow(now.values, now.baseline);\n if (outcome !== null && outcome.aborted !== true) setCheckOutcome(outcome);\n }, [validateNow]);\n\n // A field that becomes inactive drops its issues (its own and the resource validator's):\n // shown again, it starts clean rather than resurfacing an error about a value the user\n // could not see.\n useEffect(() => {\n if (plan === null) return;\n const inactive = (issue: ValidationIssue): boolean => {\n const name = issueField(issue);\n return name !== undefined && plan.fields[name] === 'inactive';\n };\n setIssues((previous) =>\n previous.some(inactive) ? previous.filter((i) => !inactive(i)) : previous,\n );\n setCrossIssues((previous) =>\n previous.some(inactive) ? previous.filter((i) => !inactive(i)) : previous,\n );\n }, [plan]);\n\n const values = state.values;\n const isActive = useCallback(\n (field: string | undefined) =>\n field === undefined ||\n field === '_form' ||\n plan === null ||\n plan.fields[field] !== 'inactive',\n [plan],\n );\n const inline = input.checks.inline(checkOutcome, state);\n // The resource-level validator runs as the user types: an issue it anchors to a field\n // the user has not reached yet waits for that field's blur or a submit, as a field's\n // own validator does; a record-level one shows at once.\n const { touched, submitAttempted, baseline: shownBaseline } = state;\n const crossShown = useMemo(\n () =>\n crossIssues.filter((issue) => {\n const field = issueField(issue);\n return (\n field === undefined ||\n field === '_form' ||\n submitAttempted ||\n touched[field] === true ||\n isFieldDirty(values[field], shownBaseline[field])\n );\n }),\n [crossIssues, touched, submitAttempted, values, shownBaseline],\n );\n const external = input.externalIssues ?? NO_VALIDATION;\n const visible = useMemo(() => {\n const own = [...issues, ...crossShown, ...inline];\n // An issue the run decided that the form already shows (the same field and code) once.\n const seen = new Set(own.map((issue) => `${issueField(issue) ?? ''}\\u0000${issue.code}`));\n const added = external.filter(\n (issue) => !seen.has(`${issueField(issue) ?? ''}\\u0000${issue.code}`),\n );\n return [...own, ...added].map(toResolvedIssue).filter((issue) => isActive(issue.field));\n }, [issues, crossShown, inline, isActive, external]);\n // The run's issues arrive after its submit: the first failing field comes into view (its step).\n useEffect(() => {\n const failing = new Set(\n external\n .filter((issue) => issue.severity !== 'warning' && issue.severity !== 'info')\n .map(issueField)\n .filter((name): name is string => name !== undefined && name !== '_form'),\n );\n if (failing.size > 0) revealFirst(failing);\n }, [external, revealFirst]);\n const errors = useMemo(() => visible.filter((issue) => issue.severity === 'error'), [visible]);\n const warnings = useMemo(() => visible.filter((issue) => issue.severity !== 'error'), [visible]);\n\n const resourceRef = input.resourceRef;\n const ctx = input.ctx;\n const field = useCallback(\n (name: string): FieldBinding => {\n const fieldDef = fieldMap[name];\n if (fieldDef === undefined) throw new Error(`useFormController: unknown field \"${name}\"`);\n const status = plan?.fields[name];\n const flags = fieldPredicateFlags(fieldDef, ctx ?? {}, values);\n const error = errors.find((issue) => issue.field === name);\n return {\n name,\n value: values[name],\n onChange: (value: unknown) => setValue(name, value),\n onBlur: () => blur(name),\n ...(error === undefined ? {} : { error }),\n warnings: warnings.filter((issue) => issue.field === name),\n required: flags.required,\n disabled: status !== 'active' || flags.disabled,\n hidden: status === 'inactive',\n resource: resourceRef,\n field: fieldDef,\n fixedFilters: resolveFieldFilter(fieldDef, values, name),\n relationSeeds: relationSeedsFor(\n seedApp,\n codeFields[name],\n candidatesMarked(input.candidateOwner, name),\n ),\n };\n },\n [\n fieldMap,\n codeFields,\n input.candidateOwner,\n seedApp,\n plan,\n values,\n setValue,\n blur,\n resourceRef,\n ctx,\n errors,\n warnings,\n ],\n );\n const fields = useMemo(\n () =>\n (screen?.fields ?? [])\n .filter((entry) => fieldMap[entry.name] !== undefined)\n .filter((entry) => plan !== null && plan.fields[entry.name] !== 'inactive')\n .map((entry) => field(entry.name)),\n [screen, fieldMap, plan, field],\n );\n const errorsIn = useCallback(\n (containerKey: string): number => {\n const container = plan?.byKey[containerKey];\n if (plan === null || container === undefined) return 0;\n const names = new Set<string>();\n collectLeaves(container, (node) => {\n if (plan.fields[node.field!] === 'active') names.add(node.field!);\n });\n return errors.filter((issue) => names.has(issue.field)).length;\n },\n [plan, errors],\n );\n const isDirty = useMemo(() => isFormDirty(values, state.baseline), [values, state.baseline]);\n // The unsaved-changes guard: armed while dirty and not submitting, released\n // synchronously by a successful submit (P1b+P1c decision 30).\n const blocker = useNavigationBlocker(input.dirtyWarning && isDirty && !isSubmitting);\n // A submitting form's blocker is inactive, so its overlay counts it as pending instead:\n // Escape, an outside click and ✕ do nothing until the write settles (P3-34).\n useDismissPending(isSubmitting);\n const blockerRef = useRef(blocker);\n blockerRef.current = blocker;\n\n // The key the form became dirty under: values typed under one user's key are never\n // written under another's, so a user change while dirty stops autosave until the next reset.\n const dirtyKey = useRef<string | null | undefined>(undefined);\n // Autosave while dirty: active, non-sensitive, non-excluded fields only, and in edit the\n // version of the record the values are over.\n useEffect(() => {\n if (!isDirty) {\n dirtyKey.current = undefined;\n return;\n }\n if (dirtyKey.current === undefined) dirtyKey.current = key;\n if (key === null || key !== dirtyKey.current) return;\n const timer = setInterval(() => {\n const { plan: current, input: engine, state: now } = latest.current;\n if (current === null || engine.screen === null || engine.draftKey !== key) return;\n writeDraft(\n key,\n snapshotValues(now.values, current, engine.screen, engine.draftExclude, engine.fieldMap, [\n ...engine.screen.rules,\n ...engine.access.rules,\n ]),\n engine.mode === 'edit' ? recordVersionOf(now.baseline, engine.screen) : undefined,\n new Date(),\n engine.draftStore,\n engine.draftAttempt,\n );\n }, DRAFT_INTERVAL_MS);\n return () => clearInterval(timer);\n }, [key, isDirty]);\n\n const pendingDraft = stored.draft;\n // An edit draft made over another version of the record is offered, never restored over it.\n const recordChanged =\n pendingDraft !== null &&\n mode === 'edit' &&\n screen !== null &&\n state.seeded &&\n pendingDraft.recordVersion !== recordVersionOf(state.baseline, screen);\n const draft: FormDraftState = useMemo(\n () => ({\n pending: pendingDraft === null ? null : { savedAt: pendingDraft.savedAt },\n recordChanged,\n restore: () => {\n const { plan: current, input: engine, state: now } = latest.current;\n if (pendingDraft === null || current === null) return;\n if (recordChanged || (engine.mode === 'edit' && !now.seeded)) return;\n // A stored field the form no longer declares is dropped, and said so in development.\n const unknown = Object.keys(pendingDraft.values).filter(\n (name) => !Object.hasOwn(engine.fieldMap, name),\n );\n if (unknown.length > 0 && process.env.NODE_ENV !== 'production')\n console.warn(`[burojs] Restore dropped unknown field(s): ${unknown.join(', ')}`);\n // A draft is a user tier: only the fields active now, never the discriminator.\n const restored = restorableValues(\n pendingDraft.values,\n current,\n engine.screen?.discriminator,\n );\n const next = { ...latest.current.state.values, ...restored };\n engine.setState((previous) => ({\n ...previous,\n values: { ...previous.values, ...restored },\n }));\n engine.onChange?.(next);\n setStored((previous) => ({ ...previous, draft: null }));\n },\n discard: () => {\n if (key !== null) clearDraft(key);\n setStored((previous) => ({ ...previous, draft: null }));\n },\n }),\n [pendingDraft, key, recordChanged],\n );\n // A `requires` with no permission map is planned absent (fail closed): say so once, in\n // development, so a missing permissions slice is not mistaken for a denial.\n const requiresReported = useRef(false);\n const unmappedRequires =\n access.permissions === undefined &&\n screen !== null &&\n screen.nodes.some((node) => node.ruleTarget !== undefined);\n // A field's own `requires` likewise (P5 spec 3.2): hidden everywhere without a map.\n const unmappedFields =\n access.permissions === undefined && screen !== null\n ? screen.fields.flatMap((field) => (field.requires === undefined ? [] : [field.name]))\n : [];\n const unmappedFieldList = unmappedFields.join(', ');\n useEffect(() => {\n if ((!unmappedRequires && unmappedFieldList === '') || requiresReported.current) return;\n requiresReported.current = true;\n if (process.env.NODE_ENV === 'production') return;\n if (unmappedRequires)\n console.error(\n `[burojs] The '${input.label}' screen declares \\`requires\\` on a panel, but no permission map is mounted (the \\`permissions\\` context slice): every such panel stays absent.`,\n );\n if (unmappedFieldList !== '')\n console.error(\n `[burojs] '${input.label}' declares requires on ${unmappedFieldList}, but no permission map is mounted: those fields stay hidden.`,\n );\n }, [unmappedRequires, unmappedFieldList, input.label]);\n const record =\n input.record !== null && typeof input.record === 'object'\n ? (input.record as Readonly<Record<string, unknown>>)\n : undefined;\n const policyRow =\n input.policyRecord !== null && typeof input.policyRecord === 'object'\n ? (input.policyRecord as Readonly<Record<string, unknown>>)\n : record;\n\n // A create's `steps` node is a wizard (P1b+P1c decision 11): its open panel is the current\n // step, a step validates its own active fields, and a step with none is skipped.\n const stepsNode = mode === 'create' && plan !== null ? findSteps(plan.slots.body) : undefined;\n const stepsId = stepsNode?.id;\n const openStep = useCallback(\n (id: string) => {\n if (stepsId === undefined) return;\n if (host !== null) host.openPanel(stepsId, id);\n else setOwnContainers((previous) => ({ ...previous, [stepsId]: id }));\n },\n [host, stepsId],\n );\n const steps = useMemo<FormSteps | null>(() => {\n if (stepsNode === undefined || plan === null) return null;\n const panels = stepsNode.children.filter((child) => child.state !== 'absent');\n const ids = panels.map(stepId);\n const currentPanel = panels.find((child) => child.open === true) ?? panels[0];\n const current = currentPanel === undefined ? undefined : stepId(currentPanel);\n const activeIn = (panel: PlanNode): Set<string> => {\n const names = new Set<string>();\n collectLeaves(panel, (leaf) => {\n if (plan.fields[leaf.field!] === 'active') names.add(leaf.field!);\n });\n return names;\n };\n const at = currentPanel === undefined ? -1 : panels.indexOf(currentPanel);\n /** The nearest step from `from` in `direction` with an active field. */\n const nearest = (from: number, direction: 1 | -1): PlanNode | undefined => {\n for (let index = from + direction; index >= 0 && index < panels.length; index += direction)\n if (activeIn(panels[index]!).size > 0) return panels[index];\n return undefined;\n };\n return {\n ids,\n current,\n completed,\n next: async () => {\n if (currentPanel === undefined) return false;\n const names = activeIn(currentPanel);\n if (names.size > 0) {\n const failed = (await validateNow(latest.current.state.values, names)).filter(\n (issue) => issue.severity === 'error',\n );\n if (failed.length > 0) {\n revealFirst(\n new Set(failed.map(issueField).filter((name): name is string => name !== undefined)),\n );\n return false;\n }\n }\n const target = nearest(at, 1);\n if (target === undefined) return false;\n const id = stepId(currentPanel);\n setCompleted((previous) => (previous.includes(id) ? previous : [...previous, id]));\n openStep(stepId(target));\n return true;\n },\n back: () => {\n const target = nearest(at, -1);\n if (target !== undefined) openStep(stepId(target));\n },\n goTo: (id: string) => {\n if (id === current || !completed.includes(id) || !ids.includes(id)) return;\n openStep(id);\n },\n };\n }, [stepsNode, plan, completed, validateNow, revealFirst, openStep]);\n // A submit's first error in another step reveals it: the steps node and each step register\n // a reveal that opens the step, whatever was completed.\n const stepPanels = stepsNode?.children.filter((child) => child.state !== 'absent');\n const stepPanelIds = stepPanels?.map((panel) => `${panel.id} ${stepId(panel)}`).join('|');\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the step panel ids\n useEffect(() => {\n if (stepsId === undefined || stepPanels === undefined) return;\n const off = [\n registerReveal(stepsId, () => undefined),\n ...stepPanels.map((panel) => registerReveal(panel.id, () => openStep(stepId(panel)))),\n ];\n return () => {\n for (const unregister of off) unregister();\n };\n }, [stepsId, stepPanelIds, registerReveal, openStep]);\n\n const canSubmit =\n mode !== 'show' &&\n input.write !== null &&\n !isSubmitting &&\n errors.length === 0 &&\n failure === null &&\n plan !== null &&\n !plan.submitBlocked;\n\n const controller: FormController = {\n screen: failure === null ? screen : null,\n plan,\n failure,\n field,\n fields,\n values,\n errors,\n warnings,\n canSubmit,\n isDirty,\n isSubmitting,\n checkOutcome,\n handleSubmit,\n setValue,\n reset,\n revalidate,\n submit,\n draft,\n record,\n sources: input.sources,\n retry: input.retry,\n placement: (key: string) =>\n input.placements !== undefined && Object.hasOwn(input.placements, key)\n ? input.placements[key]\n : undefined,\n errorsIn,\n registerReveal,\n checkGate: input.checks.gate ?? null,\n isValidating,\n steps,\n typeOffer: input.typeOffer ?? null,\n };\n return attachPolicyRecord(controller, policyRow);\n}\n\nconst NO_OPEN: Readonly<Record<string, string>> = Object.freeze({});\nconst NO_STEPS: readonly string[] = Object.freeze([]);\n\n/** A step's id: its panel key, else its compiled node id. */\nfunction stepId(panel: PlanNode): string {\n return panel.key ?? panel.id;\n}\n\n/** The first `steps` node of a tree, depth first. */\nfunction findSteps(nodes: readonly PlanNode[]): PlanNode | undefined {\n for (const node of nodes) {\n if (node.kind === 'steps') return node;\n const inner = findSteps(node.children);\n if (inner !== undefined) return inner;\n }\n return undefined;\n}\n\n/** Whether a write was aborted: it saved nothing (`AbortError` by name, any realm). */\nfunction isAbort(error: unknown): boolean {\n if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return false;\n try {\n return (error as { readonly name?: unknown }).name === 'AbortError';\n } catch {\n return false;\n }\n}\n\n/** Every field leaf under `node` (itself included), depth first. */\nfunction collectLeaves(node: PlanNode, visit: (leaf: PlanNode) => void): void {\n if (node.kind === 'field' && node.field !== undefined) visit(node);\n for (const child of node.children) collectLeaves(child, visit);\n}\n\n/** The first field leaf, in config order, that `test` accepts. */\nfunction firstLeaf(\n nodes: readonly PlanNode[],\n test: (leaf: PlanNode) => boolean,\n): PlanNode | undefined {\n for (const node of nodes) {\n let found: PlanNode | undefined;\n collectLeaves(node, (leaf) => {\n if (found === undefined && test(leaf)) found = leaf;\n });\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n/**\n * The plan's `open` from a host's: every `collapse: 'closed'` panel the host\n * has not expanded is collapsed (the host knows no screen); `undefined`\n * without a host.\n */\n/** @internal Also read by `usePageScreen`. */\nexport function planOpenOf(\n open: ScreenOpenState | undefined,\n screen: CompiledScreen | null,\n own: Readonly<Record<string, string>>,\n): PlanOpen | undefined {\n if (open === undefined && Object.keys(own).length === 0) return undefined;\n const expanded = new Set(open?.expanded ?? []);\n const collapsed = new Set(open?.collapsed ?? []);\n for (const node of screen?.nodes ?? [])\n if (node.options.collapse === 'closed' && !expanded.has(node.id)) collapsed.add(node.id);\n return { containers: open?.containers ?? own, collapsed: [...collapsed] };\n}\n\n/** The resource's checks: `useChecks` for the inline pass and `runNow`, `useCheckGate` to confirm. */\nfunction useResourceChecks(\n resource: string,\n mode: 'create' | 'edit' | 'show',\n state: FormState,\n sources?: Readonly<Record<string, SourceState>>,\n /**\n * Whether the form can submit (P2 4.10). When it cannot, its `with` sources are never loaded,\n * so a check that reads one shows no \"could not verify\" inline; the authoritative pass still\n * runs if a submit is attempted.\n */\n submittable = true,\n /** The ids of the checks that read a `with` source: only their unverified issue is held back. */\n withChecks: ReadonlySet<string> = NO_IDS,\n): ChecksPort {\n const surface: CheckSurface = mode === 'create' ? 'create' : 'edit';\n const app = useApp();\n // Read every render: a resource the registry republishes with checks starts its pass\n // then, and a resource with none never serialises its values for one.\n let hasChecks = false;\n try {\n hasChecks = app.checkSource.checks(resource).length > 0;\n } catch {\n // A throwing check source is the pass's to report (it runs the lookup again).\n hasChecks = true;\n }\n const checks = useChecks({\n resource,\n surface,\n values: state.values,\n saved: state.baseline,\n touched: state.touched,\n submitAttempted: state.submitAttempted,\n enabled: mode !== 'show' && hasChecks,\n ...(sources === undefined ? {} : { sources }),\n });\n const gate = useCheckGate(resource);\n const latest = useRef({ checks, gate, sources });\n latest.current = { checks, gate, sources };\n // While a check's `with` source loads, its \"could not verify\" is not news: the inline pass\n // shows it only once the source settled (failed), never as a flash. A submit still blocks.\n const loading =\n sources !== undefined && Object.values(sources).some((state) => state.status === 'pending');\n const allInline = checks.inlineIssues;\n // Only the \"could not verify\" of a check that reads a `with` source is held back; every other\n // check issue shows inline as before.\n const holdBack = !submittable || loading;\n const inlineIssues = useMemo(\n () =>\n !holdBack || withChecks.size === 0\n ? allInline\n : allInline.filter(\n (issue) =>\n issue.code !== 'check.undecided' ||\n !withChecks.has(String((issue.params as { checkId?: unknown } | undefined)?.checkId)),\n ),\n [allInline, holdBack, withChecks],\n );\n const gateState = gate.state;\n return useMemo(\n () => ({\n gate: gateState,\n inline: () => inlineIssues,\n runNow: (values, saved) => latest.current.checks.runNow({ values, saved }),\n confirm: (_outcome, values, saved) =>\n latest.current.gate.run({\n surface,\n values,\n saved,\n ...(latest.current.sources === undefined ? {} : { sources: latest.current.sources }),\n }),\n }),\n [inlineIssues, surface, gateState],\n );\n}\n\nconst NO_IDS: ReadonlySet<string> = new Set();\n\n/** A fresh form state over `values`. */\nfunction fresh(values: FormValues, key: string, seeded: boolean, seeds?: CreateSeeds): FormState {\n return {\n values,\n baseline: values,\n ...(seeds === undefined ? {} : { seeds }),\n key,\n seeded,\n touched: UNTOUCHED,\n submitAttempted: false,\n };\n}\n\n/** `values` restricted to the fields `plan` makes active. */\nfunction activeOnly(values: FormValues, plan: ScreenPlan): FormValues {\n const out: Record<string, unknown> = {};\n for (const [name, status] of Object.entries(plan.fields))\n if (status === 'active' && Object.hasOwn(values, name)) out[name] = values[name];\n return out as FormValues;\n}\n\n/** Whether a field's decision lets its user type into it: visible and editable. */\nfunction editableByAccess(access: FieldAccessMap, name: string): boolean | 'pending' {\n const decision = Object.hasOwn(access, name) ? access[name] : undefined;\n if (decision === undefined) return true;\n if (decision.view === 'pending' || decision.edit === 'pending') return 'pending';\n return decision.view === 'visible' && decision.edit === 'editable';\n}\n\n/** Whether a field's decision lets its user see it. */\nfunction viewableByAccess(access: FieldAccessMap, name: string): boolean | 'pending' {\n const decision = Object.hasOwn(access, name) ? access[name] : undefined;\n if (decision === undefined) return true;\n if (decision.view === 'pending') return 'pending';\n return decision.view === 'visible';\n}\n\n/**\n * Form state against field access (P5 decision 23, spec 3.6.1): values and baseline drop every\n * field whose user may not view or edit it — a user-tier seed, a restored draft or a typed value\n * included — and, in edit, a field decided editable after the seed takes its projected record\n * value (a pending decision changes nothing yet). The same state when nothing changes.\n */\nfunction reconcileAccess(\n state: FormState,\n access: FieldAccessMap,\n record: FormValues | undefined,\n /**\n * A typed form's discriminator stays: its value is the accepted type, written by the offer and\n * never by the user (P1b+P1c decision 24), and the type's own fields are planned on it.\n */\n discriminator?: string,\n /**\n * A resource-less form's state is the host's own data, not a server record: a field its user\n * may view but not edit keeps its value (it is displayed), and only a field not viewable\n * leaves. A record form's state holds only what its user may edit.\n */\n viewOnly = false,\n): FormState {\n let values: Record<string, unknown> | undefined;\n let baseline: Record<string, unknown> | undefined;\n for (const name of Object.keys(access)) {\n if (name === discriminator) continue;\n const allowed = viewOnly ? viewableByAccess(access, name) : editableByAccess(access, name);\n if (allowed === 'pending') continue;\n if (!allowed) {\n if (Object.hasOwn(state.values, name)) {\n values ??= { ...state.values };\n delete values[name];\n }\n if (Object.hasOwn(state.baseline, name)) {\n baseline ??= { ...state.baseline };\n delete baseline[name];\n }\n continue;\n }\n if (\n record !== undefined &&\n Object.hasOwn(record, name) &&\n !Object.hasOwn(state.values, name) &&\n !Object.hasOwn(state.baseline, name)\n ) {\n values ??= { ...state.values };\n baseline ??= { ...state.baseline };\n values[name] = record[name];\n baseline[name] = record[name];\n }\n }\n if (values === undefined && baseline === undefined) return state;\n return {\n ...state,\n values: (values ?? state.values) as FormValues,\n baseline: (baseline ?? state.baseline) as FormValues,\n ...(viewOnly && baseline !== undefined ? { policy: state.policy ?? state.baseline } : {}),\n };\n}\n\n/** The canonical ref of a name or a handle; the handle itself is never read beyond its ref. */\nfunction refOf(resource: UseFormControllerRecordOptions['resource']): EntityRef {\n return normalizeEntityRef(typeof resource === 'string' ? resource : resource.ref);\n}\n\n/** The record shape: a resource's screen, record and mutations. */\nfunction useRecordController(options: UseFormControllerRecordOptions): FormController {\n const app = useApp();\n const refKey = typeof options.resource === 'string' ? options.resource : options.resource.ref;\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the ref, not the handle object\n const ref = useMemo(() => refOf(options.resource), [refKey]);\n const name = canonicalEntityNodeKey({ name: ref.id, ref });\n const { mode, type } = options;\n // The entry the screen is compiled for (P6 3.8, 3.9): a quick host's declared body, a peek's.\n const entry = options.entry ?? 'route';\n const selectClient = useCallback(\n (runtime: LayerRuntime) => compiledScreenFor(runtime.getSnapshot(), ref, mode, entry),\n [ref, mode, entry],\n );\n const selectServer = useCallback(\n (runtime: LayerRuntime) => compiledScreenFor(runtime.getServerSnapshot(), ref, mode, entry),\n [ref, mode, entry],\n );\n const compiled = useRuntimeSelection(selectClient, selectServer);\n const marked = screenOf(compiled);\n const screen = marked.screen;\n\n const def = app.registry.get(name) as\n | {\n readonly fields?: ResourceFieldMap;\n readonly prefill?: { readonly fromQuery?: readonly string[] };\n readonly draft?: DraftOption;\n readonly data?: { readonly idField?: string };\n readonly validate?: ResourceValidate;\n readonly validateDebounceMs?: number;\n readonly dirtyWarning?: boolean;\n }\n | undefined;\n const baseFields = def?.fields ?? (EMPTY_VALUES as ResourceFieldMap);\n // A type's own fields live in its `types` entry, not the base map: the compiled screen\n // carries every field the screen can place (base, then each type's), with its declaration.\n const fieldMap = useMemo<ResourceFieldMap>(() => {\n const extra = (screen?.fields ?? []).filter((entry) => !Object.hasOwn(baseFields, entry.name));\n if (extra.length === 0) return baseFields;\n return {\n ...baseFields,\n ...Object.fromEntries(extra.map((entry) => [entry.name, entry.declaration])),\n } as ResourceFieldMap;\n }, [baseFields, screen]);\n const fromQuery = def?.prefill?.fromQuery ?? [];\n const router = useOptionalRouterAdapter();\n // Without a router adapter the URL is the document's (a host that mounts none still\n // links to a create with `?prefill.`).\n const search =\n router?.searchParams ??\n (typeof window === 'undefined' ? undefined : new URLSearchParams(window.location.search));\n\n const idField = def?.data?.idField ?? 'id';\n // The record an edit or show reads and writes: `recordId`, else the record's id field.\n const editId =\n mode === 'create'\n ? undefined\n : (draftRecordId(options.recordId) ?? draftRecordId(options.record?.[idField]));\n const keyFor = mode === 'create' ? `create:${type ?? ''}` : `record:${editId ?? ''}`;\n const initial = (): FormState => {\n if (mode === 'create') {\n if (screen === null) return fresh(EMPTY_VALUES, keyFor, false);\n const seeds = createSeeds({\n compiled: screen,\n ...(type === undefined ? {} : { type }),\n ...(options.defaults === undefined ? {} : { callerDefaults: options.defaults }),\n prefill: new URLSearchParams(search?.toString() ?? ''),\n fromQuery,\n });\n return fresh(seeds.values, keyFor, true, seeds);\n }\n // A caller's `record` seeds nothing here: the resolver projects it by field access and the\n // projected record seeds the values once it is ready (P5 §3.6), so a hidden value never\n // reaches form state, not even while the permission map loads.\n return fresh(EMPTY_VALUES, keyFor, false);\n };\n const [state, setState] = useState<FormState>(initial);\n // Re-seed when what seeded the values changes (the type in create, the record id elsewhere),\n // and seed a create once its screen is known.\n if (state.key !== keyFor || (mode === 'create' && !state.seeded && screen !== null)) {\n const next = initial();\n if (next.key !== state.key || next.seeded !== state.seeded) setState(next);\n }\n\n // What the last plan demanded: the resolver loads only those sources (spec 10.1).\n const [demand, setDemand] = useState<ResolverDemand>(NO_DEMAND);\n // `route` comes only from the record route (spec 4.5): elsewhere it reads `{}`.\n const routeSource = useRouteSource();\n const { sources, retry, blockData, placements, fieldAccess, blockAccess, policyRecord } =\n useSourceResolver({\n compiled: screen,\n resource: name,\n ...(options.recordId === undefined ? {} : { recordId: options.recordId }),\n ...(options.record === undefined ? {} : { record: options.record }),\n values: state.values,\n route: routeSource ?? EMPTY_ROUTE,\n demand,\n });\n const onPlan = (plan: ScreenPlan) => {\n const next: ResolverDemand = {\n sources: [...plan.demand.active, ...plan.demand.shown],\n blocks: plan.blockDemand,\n };\n if (!sameDemand(next, demand)) setDemand(next);\n };\n // A typed create accepts only a type the offer lists (P1b+P1c decision 24): an undeclared\n // type, one whose `when` does not hold, or any type while the offer is pending is refused,\n // so the form plans nothing, writes nothing, and the host shows the offer.\n const typed = screen !== null && mode === 'create' && screen.discriminator !== undefined;\n const offer = typed ? typeOffer(screen, sources) : undefined;\n const accepted =\n offer === undefined\n ? type\n : offer.status === 'ready' && type !== undefined && offer.types.includes(type)\n ? type\n : undefined;\n const failure: FormControllerFailure | null =\n marked.failure ?? (typed && accepted === undefined ? { kind: 'type-required' } : null);\n // The discriminator is seeded by the offer only: a caller's `defaults` or a `?prefill.` value\n // naming it is ignored (seeds.ts), and said so once, in development.\n const discriminator = typed ? screen.discriminator : undefined;\n const ignoredSeed =\n discriminator !== undefined &&\n ((options.defaults !== undefined && Object.hasOwn(options.defaults, discriminator)) ||\n search?.has(`prefill.${discriminator}`) === true);\n const warnedSeed = useRef(false);\n useEffect(() => {\n if (!ignoredSeed || warnedSeed.current || process.env.NODE_ENV === 'production') return;\n warnedSeed.current = true;\n console.warn(\n `[burojs] \"${name}\": the discriminator \"${discriminator}\" is set by the type offer only; the value in defaults or ?prefill.${discriminator} is ignored. Link to the create with ?type=<value> instead.`,\n );\n }, [ignoredSeed, name, discriminator]);\n const recordState = sources.record;\n const record = recordState?.status === 'ready' ? recordState.value : undefined;\n // Edit and show: the record seeds the values once it is ready.\n if (mode !== 'create' && !state.seeded && record !== null && typeof record === 'object') {\n setState(fresh(record as FormValues, keyFor, true));\n } else if (mode !== 'show' && state.seeded) {\n // Form state holds only what its user may edit (P5 decision 23): the projected record seeded\n // it, and a field its user may not view or edit leaves values and baseline as soon as it is\n // decided; one decided editable after the seed (a map that was loading) is seeded then.\n const next = reconcileAccess(\n state,\n fieldAccess,\n mode === 'edit' && record !== null && typeof record === 'object'\n ? (record as FormValues)\n : undefined,\n screen?.discriminator,\n );\n if (next !== state) setState(next);\n }\n\n const context = useContextSnapshot();\n const permissions = readPermissions(context);\n const rules = useMemo(() => app.ruleSource.rules(name), [app.ruleSource, name]);\n const access: PlanAccess = useMemo(\n () => ({\n rules,\n context: ruleContextFor({\n user: context.user as never,\n scope: context.scope,\n ...(permissions === undefined ? {} : { permissions }),\n ...(policyRecord === undefined ? {} : { record: policyRecord }),\n mode,\n resource: name,\n }),\n permissions,\n }),\n [rules, context.user, context.scope, permissions, policyRecord, mode, name],\n );\n\n const create = useCreateOne(name);\n const update = useUpdateOne(name);\n const { onSubmit } = options;\n // The form's operation (`create` / `edit`) as this user may run it on this record: a rule that\n // hides or disables it, or a resource that turned it off, leaves the framework's own write\n // without a writer, so Save is disabled and `submit()` is refused — a typed URL is not a way\n // past the rule. An `onSubmit` the host passes is its own write, decided by its own code.\n const operationOn =\n mode !== 'show' &&\n resolveAvailability(app.ruleSource, app.registry, name, mode, access.context).state ===\n 'available';\n const write = useMemo(() => {\n if (mode === 'show') return null;\n if (onSubmit !== undefined) return onSubmit;\n if (!operationOn) return null;\n if (mode === 'create')\n return (payload: Record<string, unknown>) => create.mutateAsync({ values: payload });\n // An edit with no record id has nothing to update: no writer, so submit is refused.\n if (editId === undefined) return null;\n return (payload: Record<string, unknown>) =>\n update.mutateAsync({ id: editId, values: payload });\n }, [mode, operationOn, onSubmit, create.mutateAsync, update.mutateAsync, editId]);\n const unsavable = mode === 'edit' && editId === undefined && onSubmit === undefined;\n useEffect(() => {\n if (unsavable && process.env.NODE_ENV !== 'production')\n console.error(\n `[burojs] useFormController: an edit of \"${name}\" has neither recordId nor a record id (${idField}); it cannot be saved.`,\n );\n }, [unsavable, name, idField]);\n\n // The `with` sources the checks read (P2 4.10): handed to every check pass, and demanded active\n // only while the form can submit — a surface whose operation is off, denied or unwritable\n // decides no submit, so it loads nothing for its checks.\n const surface: CheckSurface = mode === 'create' ? 'create' : 'edit';\n let declaredChecks: readonly Check[] = NO_CHECKS;\n try {\n declaredChecks = mode === 'show' ? NO_CHECKS : app.checkSource.checks(name);\n } catch {\n // A throwing check source is the pass's to report.\n }\n const readKey =\n screen === null\n ? ''\n : checkSourceNames(declaredChecks, surface)\n .filter((source) => Object.hasOwn(screen.with, source))\n .join('\\u0000');\n const submittable = failure === null && write !== null;\n const checkReads = useMemo(\n () => (readKey === '' ? NO_NAMES : readKey.split('\\u0000')),\n [readKey],\n );\n const checkStates = useMemo(() => {\n const out: Record<string, SourceState> = {};\n for (const source of checkReads) {\n const own = Object.hasOwn(sources, source) ? sources[source] : undefined;\n if (own !== undefined) out[source] = own;\n }\n return Object.freeze(out);\n }, [checkReads, sources]);\n const withKey =\n screen === null\n ? ''\n : declaredChecks\n .filter((check) =>\n checkSourceNames([check], surface).some((source) => Object.hasOwn(screen.with, source)),\n )\n .map((check) => check.id)\n .join('\\u0000');\n const withChecks = useMemo(\n () => (withKey === '' ? NO_IDS : new Set(withKey.split('\\u0000'))),\n [withKey],\n );\n const checks = useResourceChecks(name, mode, state, checkStates, submittable, withChecks);\n const ctx = useOptionalVisibilityCtx();\n const userId = useCurrentUserId();\n const scopeHash = useDraftScopeHash();\n const draftOption = options.draft ?? def?.draft ?? false;\n const drafts = draftOption !== false;\n // An edit draft is keyed by the record it edits; with no id, drafts are off.\n const key =\n userId === null || mode === 'show' || !drafts || (mode === 'edit' && editId === undefined)\n ? null\n : draftKey({\n userId,\n formId: name,\n mode,\n ...(editId === undefined ? {} : { recordId: editId }),\n ...(mode === 'create' && accepted !== undefined ? { type: accepted } : {}),\n ...(scopeHash === undefined ? {} : { scopeHash }),\n });\n\n return useControllerEngine({\n screen,\n failure,\n mode,\n state,\n setState,\n sources,\n retry,\n onPlan,\n blockData,\n placements,\n checkSources: submittable ? checkReads : NO_NAMES,\n label: name,\n access,\n record,\n policyRecord,\n fieldAccess,\n blockAccess,\n fieldMap,\n codeFields: baseFields,\n ...(def === undefined ? {} : { candidateOwner: def }),\n resourceRef: ref,\n ...(accepted === undefined ? {} : { type: accepted }),\n ...(offer === undefined ? {} : { typeOffer: offer }),\n write,\n initial,\n checks,\n ctx,\n draftKey: key,\n draftStore: draftStoreOf(draftOption),\n draftExclude: draftExcludeOf(draftOption),\n dirtyWarning: def?.dirtyWarning !== false,\n audit: {\n resource: name,\n ...(mode === 'create' ? {} : { recordId: editId ?? '' }),\n view: mode === 'create' ? 'create' : 'edit',\n },\n fileBaseline: mode === 'edit',\n ...(typeof def?.validate === 'function'\n ? {\n resourceValidate: {\n run: def.validate,\n resource: name,\n debounceMs: def.validateDebounceMs ?? VALIDATE_DEBOUNCE_MS,\n },\n }\n : {}),\n });\n}\n\nconst NO_EXCLUDE: readonly string[] = Object.freeze([]);\n\nfunction draftExcludeOf(option: unknown): readonly string[] {\n if (option === null || typeof option !== 'object') return NO_EXCLUDE;\n const exclude = (option as { readonly exclude?: unknown }).exclude;\n return Array.isArray(exclude) ? exclude.filter((name) => typeof name === 'string') : NO_EXCLUDE;\n}\n\nconst NO_CHECKS: readonly Check[] = Object.freeze([]);\n\n/** A plain list of checks, evaluated here: a resource-less form has no registry entry. */\nfunction useListChecks(options: UseFormControllerFormOptions, mode: 'create' | 'edit' | 'show') {\n const runtime = useOptionalDataRuntime();\n const prefix = options.i18nPrefix ?? 'form';\n const data = useMemo(\n () =>\n runtime === null\n ? createUnavailableActionDataAccess(\n `Check evaluation for \"${prefix}\" needs a data runtime; none is mounted.`,\n )\n : createRuntimeActionDataAccess(runtime),\n [runtime, prefix],\n );\n const ctx = useOptionalVisibilityCtx();\n const translate = useTranslate();\n const snapshot = useContextSnapshot();\n const latest = useRef({ options, ctx, translate, data, snapshot });\n latest.current = { options, ctx, translate, data, snapshot };\n const surface: CheckSurface = options.surface ?? (mode === 'edit' ? 'edit' : 'create');\n return useMemo<ChecksPort>(\n () => ({\n inline: (outcome, state) =>\n outcome === null\n ? NO_VALIDATION\n : filterInlineIssues(outcome.issues, {\n touched: state.touched,\n submitAttempted: state.submitAttempted,\n }),\n runNow: async (values, saved) => {\n const now = latest.current;\n const checks = now.options.checks ?? NO_CHECKS;\n if (checks.length === 0) return null;\n return evaluateChecks({\n checks,\n surface,\n resource: now.options.i18nPrefix ?? 'form',\n values,\n saved,\n ctx: now.ctx,\n scope: scopeSourceState(now.snapshot),\n t: (key: string, params?: Record<string, unknown>) => now.translate(key, { params }),\n data: now.data,\n signal: new AbortController().signal,\n });\n },\n confirm: async (outcome) => {\n const confirm = latest.current.options.onConfirmChecks;\n return confirm === undefined ? 'proceed' : confirm(outcome);\n },\n }),\n [surface],\n );\n}\n\nconst RESOURCE_LESS_RULES: readonly Rule[] = Object.freeze([]);\nconst NO_FIELD_ACCESS: FieldAccessMap = Object.freeze({});\n\n/** A resource-less form reads nothing, so it has nothing to refetch. */\nconst NO_RETRY = (): void => undefined;\n\n/** The resource-less shape: a screen compiled from `fields` and `body`, written by `onSubmit`. */\nfunction useResourceLessController(options: UseFormControllerFormOptions): FormController {\n const mode = options.mode ?? 'create';\n const prefix = options.i18nPrefix ?? 'form';\n const compiled = useFormScreen(options.fields, options.body, {\n mode,\n i18nPrefix: prefix,\n // A flow's form (a claim the controller verifies) also reads its host's `record` and `args`.\n fieldMetaOwner: isFrameworkFlowRun(options.flowRun, options.formId) ? 'flow' : 'form',\n ...(options.blocks === undefined ? {} : { blocks: options.blocks }),\n });\n if (isScreenFailure(compiled) && process.env.NODE_ENV !== 'production')\n throw new Error(`[burojs] ${compiled.code} at ${compiled.path.join('.')}: ${compiled.message}`);\n if (options.draft !== undefined && options.draft !== false && options.formId === undefined)\n if (process.env.NODE_ENV !== 'production')\n throw new Error('[burojs] A resource-less form with `draft` needs a `formId`.');\n const failure: FormControllerFailure | null = isScreenFailure(compiled)\n ? { kind: 'screen', failure: compiled }\n : null;\n const screen = isScreenFailure(compiled) ? null : compiled;\n\n const controlled = options.value !== undefined;\n const initial = (): FormState =>\n fresh(options.value ?? options.defaults ?? EMPTY_VALUES, 'form', true);\n const [own, setOwn] = useState<FormState>(initial);\n // Controlled: the values are the host's; an edit reaches them through `onChange`.\n const state: FormState = controlled ? { ...own, values: options.value as FormValues } : own;\n const latestState = useRef(state);\n latestState.current = state;\n const setState = useCallback<Dispatch<SetStateAction<FormState>>>(\n (next) =>\n setOwn((previous) => {\n if (!controlled) return typeof next === 'function' ? next(previous) : next;\n const base = { ...previous, values: latestState.current.values };\n const updated = typeof next === 'function' ? next(base) : next;\n return { ...updated, values: previous.values };\n }),\n [controlled],\n );\n\n const context = useContextSnapshot();\n const locale = useLocale();\n const permissions = readPermissions(context);\n // `access: { resource }` (P5 ruling 6, decision 41): a form field named like a declared field of\n // that resource takes its field rules — lowered `requires` and authored — planned as a record\n // form plans them; any other field has none.\n const app = useContext(AppContext);\n const accessResource = options.access?.resource;\n const fieldNames = Object.keys(options.fields).join('\\u0000');\n const fieldRules = useMemo(() => {\n if (accessResource === undefined || app === null) return RESOURCE_LESS_RULES;\n const def = app.registry.get(accessResource as never);\n if (def === undefined) {\n if (process.env.NODE_ENV !== 'production')\n console.error(\n `[burojs] useFormController({ access: { resource: '${accessResource}' } }): no such resource is registered; its field rules do not apply.`,\n );\n return RESOURCE_LESS_RULES;\n }\n const declared = new Set(dtoFields(def, 'list'));\n const names = new Set(fieldNames.split('\\u0000'));\n return Object.freeze(\n app.ruleSource\n .rules(accessResource)\n .filter(\n (rule) =>\n rule.target.kind === 'field' &&\n typeof rule.target.name === 'string' &&\n names.has(rule.target.name) &&\n declared.has(rule.target.name),\n ),\n );\n }, [app, accessResource, fieldNames]);\n const baseline = state.baseline;\n // Rules read the baseline as given (see `FormState.policy`).\n const policyBaseline = state.policy ?? baseline;\n const decided =\n fieldRules === RESOURCE_LESS_RULES\n ? undefined\n : resolveFieldAccess({\n rules: [\n ...(compiled === null || isScreenFailure(compiled) ? [] : compiled.rules),\n ...fieldRules,\n ],\n fields: Object.keys(options.fields),\n context: ruleContextFor({\n user: context.user as never,\n scope: context.scope,\n ...(permissions === undefined ? {} : { permissions }),\n ...(mode === 'create' ? {} : { record: policyBaseline }),\n mode,\n }),\n permissions,\n reach: 'record',\n });\n const fieldAccess = useStableAccess(decided ?? NO_FIELD_ACCESS);\n // Form state against those decisions, as a record form keeps it (uncontrolled values only:\n // controlled values are the host's, and the payload leaves the field out either way).\n if (decided !== undefined && !controlled) {\n const next = reconcileAccess(own, fieldAccess, undefined, undefined, true);\n if (next !== own) setOwn(next);\n }\n const values = state.values;\n const scopeSlot = context.scope;\n const userSlot = context.user;\n const hasScope = Object.hasOwn(context, 'scope');\n const hasUser = Object.hasOwn(context, 'user');\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the scope slot\n const scope = useMemo(() => scopeSourceState(context), [hasScope, scopeSlot]);\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the user slot and the locale\n const user = useMemo(() => userSourceState(context, locale), [hasUser, userSlot, locale]);\n // A flow's form reads its host's `record` and `args` in a field's `meta`: honoured only for a\n // run `useFlowRun` created, like the flow issues.\n const extraSources = isFrameworkFlowRun(options.flowRun, options.formId)\n ? options.metaSources\n : undefined;\n const sources: ScreenSources = useMemo(\n () =>\n Object.freeze({\n // Edit and show plan over a record: here, the values the form was given — projected by\n // the field access `access` names, like any record (P5 spec 3.6.1).\n ...(mode === 'create'\n ? {}\n : { record: projectSource(readyState(baseline), fieldAccess, 'row') }),\n values: projectSource(readyState(values), fieldAccess, 'row'),\n scope,\n user,\n route: READY_EMPTY_ROUTE,\n ...(extraSources === undefined ? {} : extraSources),\n }),\n [mode, baseline, values, scope, user, fieldAccess, extraSources],\n );\n const access: PlanAccess = useMemo(\n () => ({\n rules: fieldRules,\n context: ruleContextFor({\n user: userSlot as never,\n scope: scopeSlot,\n ...(permissions === undefined ? {} : { permissions }),\n mode,\n }),\n permissions,\n }),\n [userSlot, scopeSlot, permissions, mode, fieldRules],\n );\n const checks = useListChecks(options, mode);\n const ctx = useOptionalVisibilityCtx();\n const userId = useCurrentUserId();\n const scopeHash = useDraftScopeHash();\n const drafts = options.draft !== undefined && options.draft !== false;\n // A flow's form: honoured only for a run `useFlowRun` created (Known finding 24).\n const flowForm = isFrameworkFlowRun(options.flowRun, options.formId);\n // An edit draft is keyed by the id of the values it edits; with none, drafts are off.\n const editId = mode === 'edit' ? draftRecordId(baseline.id) : undefined;\n const flowDraft = options.flowDraft;\n const key =\n userId === null ||\n mode === 'show' ||\n !drafts ||\n options.formId === undefined ||\n (!flowForm && mode === 'edit' && editId === undefined)\n ? null\n : flowForm\n ? draftKey({\n userId,\n formId: options.formId,\n mode: 'flow',\n ...(flowDraft?.recordId === undefined ? {} : { recordId: flowDraft.recordId }),\n ...(flowDraft?.argsHash === undefined ? {} : { argsHash: flowDraft.argsHash }),\n ...(flowDraft?.selectionHash === undefined\n ? {}\n : { selectionHash: flowDraft.selectionHash }),\n ...(scopeHash === undefined ? {} : { scopeHash }),\n })\n : draftKey({\n userId,\n formId: options.formId,\n mode,\n ...(editId === undefined ? {} : { recordId: editId }),\n ...(scopeHash === undefined ? {} : { scopeHash }),\n });\n const resourceRef = useMemo(() => i18nPrefixToRef(prefix), [prefix]);\n const { onSubmit } = options;\n const write = useMemo(\n () => (mode === 'show' ? null : (onSubmit ?? (async () => undefined))),\n [mode, onSubmit],\n );\n\n // A tree given the app's blocks resolves its placements over the form's own sources (P4-D).\n const placed = useResourceLessPlacements({\n enabled: options.blocks !== undefined,\n screen,\n sources,\n });\n\n return useControllerEngine({\n screen,\n failure,\n mode,\n state,\n setState,\n sources,\n ...(placed.placements === undefined ? {} : { placements: placed.placements }),\n ...(placed.blockData === undefined ? {} : { blockData: placed.blockData }),\n retry: NO_RETRY,\n label: prefix,\n access,\n record: mode === 'create' ? undefined : baseline,\n ...(state.policy === undefined ? {} : { policyRecord: state.policy }),\n ...(decided === undefined ? {} : { fieldAccess }),\n fieldMap: options.fields,\n codeFields: options.fields,\n resourceRef,\n write,\n ...(options.onChange === undefined ? {} : { onChange: options.onChange }),\n initial,\n checks,\n ctx,\n ...(options.schema === undefined ? {} : { schema: options.schema }),\n ...(options.validate === undefined ? {} : { validate: options.validate }),\n draftKey: key,\n draftStore: draftStoreOf(options.draft),\n ...(flowForm && flowDraft?.attempt !== undefined ? { draftAttempt: flowDraft.attempt } : {}),\n draftExclude: draftExcludeOf(options.draft),\n // A flow whose write may have been applied (the unknown screen, 4.19) closes without\n // asking: its values are the attempt's, kept by the run and the draft, so nothing typed is\n // lost. Read from the run itself — the claim, never a flag a caller passes (Known finding 24).\n dirtyWarning: !(flowForm && options.flowRun?.getSnapshot().outcome?.outcome === 'unknown'),\n ...(flowForm ? { flowForm: true } : {}),\n ...(flowForm && options.flowIssues !== undefined ? { externalIssues: options.flowIssues } : {}),\n audit: { view: mode === 'create' ? 'create' : 'edit' },\n fileBaseline: false,\n });\n}\n\nfunction readyState(value: unknown): SourceState {\n return Object.freeze({ status: 'ready', value, refreshing: false });\n}\n\nconst READY_EMPTY_ROUTE: SourceState = Object.freeze({\n status: 'ready',\n value: Object.freeze({}),\n refreshing: false,\n});\n\n/**\n * The form controller (P1b+P1c section 10.3): one planned screen, its values\n * with their seed provenance, validation, checks and the payload allow-list.\n * A record form passes `resource` and `mode`, and its screen is read from the\n * compiled snapshot, never from a handle; a resource-less form passes\n * `fields` (and a `body`), and its screen is compiled by `compileFormScreen`.\n */\n// The resource-less overload first: a zero-parameter `body` arrow is typed against the\n// first overload that names it, so its leaves keep their literal field names.\nexport function useFormController<F extends ResourceFieldMap>(\n options: UseFormControllerFormOptions<F>,\n): FormController;\nexport function useFormController(options: UseFormControllerRecordOptions): FormController;\nexport function useFormController(\n options: UseFormControllerRecordOptions | UseFormControllerFormOptions,\n): FormController {\n // The two shapes never change for one mounted controller, so the hook order holds.\n return 'fields' in options ? useResourceLessController(options) : useRecordController(options);\n}\n","import {\n type AppContext,\n type FieldAccessMap,\n type FieldReach,\n type ListAccess,\n dtoFields,\n listAccess,\n type EntityRef,\n normalizeEntityRef,\n projectSource,\n relationPathVisible,\n relationTargets,\n resolveFieldAccess,\n ruleContextFor,\n snapshotResourceFields,\n} from '@burojs/core';\nimport { useMemo } from 'react';\nimport { useApplicationSnapshot } from '../runtime.js';\nimport { useApp } from './use-app.js';\nimport { useCtx } from './use-ctx.js';\n\nconst NO_ACCESS: FieldAccessMap = Object.freeze({});\n\n/** A resource the registry lacks: nothing is known to show (Known finding 15, fail closed). */\nconst CLOSED: ListAccess = Object.freeze({\n status: 'ready' as const,\n fieldVisible: () => false,\n columnVisible: () => false,\n});\n\ninterface ResourceShape {\n readonly views?: {\n readonly list?: {\n readonly columns?: readonly string[];\n readonly optionalColumns?: readonly string[];\n };\n };\n}\n\n/** Rules, the declared fields and the definition of `resource`, as of the committed snapshot. */\nfunction useAccessInputs(resource: string) {\n const app = useApp();\n // A published layer changes rules and fields: the snapshot keys every memo below.\n const snapshot = useApplicationSnapshot();\n const scope = useCtx((c: AppContext) => c.scope);\n const user = useCtx((c: AppContext) => c.user);\n const permissions = useCtx((c: AppContext) => c.permissions);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the snapshot stands for the registry's content\n const declared = useMemo(() => {\n // An empty name is no resource (a flow not yet compiled): it decides nothing.\n const def = resource === '' ? undefined : app.registry.get(resource as never);\n if (def === undefined) return undefined;\n return { def, rules: app.ruleSource.rules(resource), fields: dtoFields(def, 'list') };\n }, [app, resource, snapshot]);\n return { declared, scope, user, permissions };\n}\n\n/**\n * Every declared field's view and edit decision for the signed-in user (P5 spec 3.4) — the one\n * `resolveFieldAccess`, never a second branch. `reach: 'record'` decides over `row` (absent: a\n * create); `'every'` decides for every row at once (the record probe), and ignores `row`.\n * Memoised by the rules, the user, the scope, the permission map and the row (Known finding 19).\n * A loading map makes every guarded field `pending`; a resource the registry lacks decides\n * nothing (`{}`).\n */\nexport function useFieldAccess(resource: string, reach: FieldReach, row?: unknown): FieldAccessMap {\n const { declared, scope, user, permissions } = useAccessInputs(resource);\n const record = reach === 'record' ? row : undefined;\n return useMemo(() => {\n if (declared === undefined) return NO_ACCESS;\n return resolveFieldAccess({\n rules: declared.rules,\n fields: declared.fields,\n context: ruleContextFor({\n user: user as never,\n scope,\n ...(permissions === undefined ? {} : { permissions }),\n ...(record === undefined ? {} : { record }),\n mode: reach === 'every' ? 'list' : 'show',\n resource,\n }),\n permissions,\n reach,\n });\n }, [declared, scope, user, permissions, record, reach, resource]);\n}\n\n/**\n * The one list predicate of a resource (P5 spec 3.7, decision P5-18): field view in any-record\n * reach and `column` rules, both with the record probe. Every list surface — the controller's\n * columns and filter offer, the table, the export dialog, the picker and the palette — reads it.\n * `pending` while the map loads and a decision depends on it; a resource the registry lacks is\n * closed (no field, no column).\n */\nexport function useListAccess(resource: string): ListAccess {\n const { declared, scope, user, permissions } = useAccessInputs(resource);\n return useMemo(() => {\n if (declared === undefined) return CLOSED;\n const list = (declared.def as ResourceShape).views?.list;\n return listAccess({\n rules: declared.rules,\n fields: declared.fields,\n columns: [...declared.fields, ...(list?.columns ?? []), ...(list?.optionalColumns ?? [])],\n context: ruleContextFor({\n user: user as never,\n scope,\n ...(permissions === undefined ? {} : { permissions }),\n mode: 'list',\n resource,\n }),\n permissions,\n });\n }, [declared, scope, user, permissions, resource]);\n}\n\n/** Every list predicate on a relation path, decided hop by hop (P5 spec 3.7). */\nexport interface PathAccess {\n /**\n * Whether `path` names only fields its user may view, each against the resource its hop leads\n * to (the target's `field/view` decides the last segment). A path of one segment, or one that\n * crosses no relation, is `true` here — its own field is the list access's to decide. A target\n * the application lacks, an undeclared segment after a hop and a pending decision are `false`.\n */\n visible(path: string): boolean;\n /** A resource a relation of this one reaches still waits on the permission map. */\n readonly pending: boolean;\n}\n\n/**\n * The one relation-path predicate of a resource: `useResourceList`, the filter offer, the saved\n * views and `fixedFilters` read it, so that they agree. The resolver's `with` sources and block\n * data read the same `relationPathVisible` over their own decisions.\n */\nexport function usePathAccess(resource: string): PathAccess {\n const app = useApp();\n const snapshot = useApplicationSnapshot();\n const scope = useCtx((c: AppContext) => c.scope);\n const user = useCtx((c: AppContext) => c.user);\n const permissions = useCtx((c: AppContext) => c.permissions);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the snapshot stands for the registry's content\n return useMemo(() => {\n const fieldsOf = snapshotResourceFields(snapshot);\n const access = new Map<string, ListAccess>();\n const accessOf = (ref: EntityRef): ListAccess => {\n const key = `${ref.namespace ?? ''}:${ref.id}`;\n let known = access.get(key);\n if (known === undefined) {\n const name = ref.namespace === undefined ? ref.id : `${ref.namespace}:${ref.id}`;\n const def = app.registry.get({ kind: 'resource', ref } as never);\n known =\n def === undefined\n ? CLOSED\n : listAccess({\n rules: app.ruleSource.rules(name),\n fields: dtoFields(def, 'list'),\n columns: dtoFields(def, 'list'),\n context: ruleContextFor({\n user: user as never,\n scope,\n ...(permissions === undefined ? {} : { permissions }),\n mode: 'list',\n resource: name,\n }),\n permissions,\n });\n access.set(key, known);\n }\n return known;\n };\n const owner = normalizeEntityRef(resource);\n const reader = {\n fieldsOf,\n viewOf: (ref: EntityRef, field: string) =>\n accessOf(ref).status === 'pending'\n ? ('pending' as const)\n : accessOf(ref).fieldVisible(field),\n };\n // Pending: some resource a relation of the owner reaches decides on a loading map.\n const pending = relationTargets(owner, fieldsOf).some(\n (ref) => accessOf(ref).status === 'pending',\n );\n return {\n visible: (path: string) => relationPathVisible(owner, path, reader) === true,\n pending,\n };\n }, [app, snapshot, scope, user, permissions, resource]);\n}\n\n/**\n * A list row as view code may read it (P5 spec 3.6.6, plan ruling 9): every field its user may\n * not view for every row left out — the id kept. For `renderCell`, `rowHref`, cell renderers and\n * selection-aware views; rules, item-action gates and action handlers keep the row as read\n * (policy). Memoised per row object while the decisions hold (Known finding 21: a row is never\n * projected with decisions computed for another).\n */\nexport function useViewRow(resource: string): <T extends object>(row: T) => T {\n const access = useFieldAccess(resource, 'every');\n return useMemo(() => {\n const cache = new WeakMap<object, object>();\n return <T extends object>(row: T): T => {\n const known = cache.get(row);\n if (known !== undefined) return known as T;\n const projected = projectSource(\n { status: 'ready', value: row, refreshing: false },\n access,\n 'row',\n );\n const value = (projected.status === 'ready' ? projected.value : row) as T;\n cache.set(row, value);\n return value;\n };\n }, [access]);\n}\n","'use client';\nimport type { RecordTitleContext } from '@burojs/core';\nimport { resolveEnumLabel } from '@burojs/core';\nimport { useApp } from './use-app.js';\nimport { useI18nCaps } from './use-t.js';\n\n/**\n * Resolve a record's human title for breadcrumbs and detail-page headings.\n *\n * Order: `def.recordTitle(record)` → `record[def.displayField]` → `#<id>`.\n *\n * The `#<id>` fallback is deliberate rather than an empty string or a spinner:\n * a detail page knows its id immediately but not its record, so the breadcrumb\n * renders `#53` on first paint and UPGRADES in place to \"Заказ кодов №53\" once\n * the fetch lands — no layout shift, no flash of nothing, and the URL always\n * stays reconcilable with what's on screen.\n *\n * Pass `record` as undefined while loading; the hook is pure and safe to call\n * on every render.\n */\nexport function useRecordTitle(\n resource: string | undefined,\n id: unknown,\n record?: unknown,\n): string {\n const app = useApp();\n const normalizedResource = resource?.trim() ? resource : undefined;\n // Bind i18n caps to this resource so a composed `recordTitle` can translate\n // embedded enum labels (e.g. the document type) — and re-resolve on a language\n // switch (`useI18nCaps` recomputes on locale change, re-rendering this hook).\n // Keep this hook call unconditional on non-resource routes; only the registry\n // lookup is skipped when breadcrumbs have no resource identity.\n const caps = useI18nCaps(normalizedResource);\n const def = normalizedResource ? app.registry.get(normalizedResource) : undefined;\n const fallback = id == null || id === '' ? '' : `#${String(id)}`;\n\n if (record == null || typeof record !== 'object') return fallback;\n\n const titleCtx: RecordTitleContext = {\n resolveEnum: (namespace, value, inlineDefault) =>\n resolveEnumLabel(caps, namespace, value, inlineDefault),\n };\n const fromHook = def?.recordTitle?.(record as never, titleCtx);\n if (typeof fromHook === 'string' && fromHook.trim() !== '') return fromHook;\n\n const field = def?.displayField;\n if (field) {\n const value = (record as Record<string, unknown>)[field];\n if (value != null && value !== '') return String(value);\n }\n return fallback;\n}\n","import { projectSource } from '@burojs/core';\nimport { useMemo } from 'react';\nimport { useFieldAccess } from './use-field-access.js';\nimport { useRecordTitle } from './use-record-title.js';\nimport { useApp } from './use-app.js';\n\n/** A record as view code may read it: the fields its user may view, or nothing yet. */\nexport interface ProjectedRecord {\n /** `pending` while a decision a read depends on is undecided, or the row is placeholder data. */\n readonly status: 'pending' | 'ready';\n /** The row without every field its user may not view (the id kept); `null` for no row. */\n readonly value: Readonly<Record<string, unknown>> | null;\n}\n\nconst PENDING: ProjectedRecord = Object.freeze({ status: 'pending', value: null });\nconst NONE: ProjectedRecord = Object.freeze({ status: 'ready', value: null });\n\n/**\n * One record of `resource`, projected by field view in record reach (P5 spec 3.6): a title, a\n * recent label, a breadcrumb or a peek reads this and never the row as read. `pending` while any\n * decision is undecided (an undecided field is never shown) and for placeholder data — rows of the\n * previous record or page never decide a title (Known finding 21). Decisions are keyed by the row\n * object they were computed for.\n */\nexport function useProjectedRecord(\n resource: string,\n row: unknown,\n opts: { readonly placeholder?: boolean } = {},\n): ProjectedRecord {\n const app = useApp();\n const record =\n row !== null && typeof row === 'object' && !Array.isArray(row)\n ? (row as Readonly<Record<string, unknown>>)\n : undefined;\n const access = useFieldAccess(resource, 'record', record);\n const placeholder = opts.placeholder === true;\n return useMemo(() => {\n if (record === undefined) return NONE;\n if (placeholder) return PENDING;\n const def = app.registry.get(resource as never) as\n | { readonly data?: { readonly idField?: string } }\n | undefined;\n const projected = projectSource(\n { status: 'ready', value: record, refreshing: false },\n access,\n 'row',\n def?.data?.idField ?? 'id',\n );\n if (projected.status !== 'ready') return PENDING;\n if (projected.withheld !== undefined) return PENDING;\n return {\n status: 'ready',\n value: projected.value as Readonly<Record<string, unknown>>,\n };\n }, [app, resource, record, access, placeholder]);\n}\n\n/**\n * A record's title as view code may show it (P5 spec 3.6, decision P5-27): `useRecordTitle` over\n * the projected row, so a display field or a `recordTitle` hook never reads a field its user may\n * not view. A hidden or undecided title falls back to the `#id` form.\n */\nexport function useProjectedTitle(\n resource: string | undefined,\n id: unknown,\n row: unknown,\n opts: { readonly placeholder?: boolean } = {},\n): string {\n const projected = useProjectedRecord(resource ?? '', row, opts);\n return useRecordTitle(resource, id, projected.value ?? undefined);\n}\n","import type { PageRequires, PermissionMap } from '@burojs/core';\nimport { usePermissions } from '../hooks/use-permissions.js';\n\n/**\n * The decision about a page's `requires` (P7 3.13): `allowed` — the user holds the pair, or the\n * page asks for none; `pending` — the permission map is absent or still loading, so nothing is\n * decided and nothing may be read; `denied` — the map is decided and the user lacks the pair\n * (a map that failed to load decides nothing in the user's favour either).\n */\nexport type PageAccess = 'allowed' | 'pending' | 'denied';\n\n/**\n * {@link usePageAccess} over a permission map. A page without `requires` is `allowed` whatever the\n * map says. Fail closed: no map, or a map still loading, is `pending`.\n */\nexport function pageAccessFor(\n page: { readonly requires?: PageRequires | undefined },\n permissions: PermissionMap | undefined,\n): PageAccess {\n const pair = page.requires?.can;\n if (pair === undefined) return 'allowed';\n if (permissions === undefined) return 'pending';\n // Only a map that finished loading decides; a failed one never decides in the user's favour.\n if (permissions.status === 'error') return 'denied';\n if (permissions.status !== 'ready') return 'pending';\n return permissions.can(pair[0], pair[1]) ? 'allowed' : 'denied';\n}\n\n/**\n * Whether the current user may open `page` (P7 3.13). Every entry to a page (the sidebar, the\n * palette, the group index), the route itself and a flow hosted on the page ask this one question,\n * so a page the user cannot open has no entry and its route is the framework not-found.\n */\nexport function usePageAccess(page: { readonly requires?: PageRequires | undefined }): PageAccess {\n return pageAccessFor(page, usePermissions());\n}\n","import {\n type AppContext,\n canonicalEntityNodeKey,\n type EntityRef,\n evaluateVisible,\n type FlowControlState,\n hrefFor,\n matchPath,\n type NavNode,\n type RegistryReader,\n} from '@burojs/core';\nimport { useMemo } from 'react';\nimport { useApp } from '../hooks/use-app.js';\nimport { type PageAccess, pageAccessFor } from '../navigation/use-page-access.js';\nimport { usePermissions, useVisibilityCtx } from '../hooks/use-permissions.js';\n\n/** The page a flow's `host: { page }` names, when it names one (P7 3.15). */\nexport function hostPageRef(host: unknown): EntityRef | undefined {\n const page = (host as { readonly page?: EntityRef } | null | undefined)?.page;\n return host !== null && typeof host === 'object' && page !== undefined ? page : undefined;\n}\n\n/** A flow's host page: where its buttons link, and whether the user may open it. */\nexport interface HostPage {\n /** The page's own path (the flow's buttons are guarded links to it). */\n readonly href: string;\n readonly access: PageAccess;\n}\n\n/**\n * The host page of a flow (P7 3.15), or `undefined` for a flow that is not hosted on one. A page\n * no layer declares is `denied` (fail closed): the flow's buttons are absent rather than links to\n * a not-found page. So is a page its own `visible`, or any group on its chain, hides: the route\n * renders not-found for it (`PageHost`), so the link would land there.\n */\nexport function hostPageFor(\n registry: RegistryReader,\n host: unknown,\n permissions: Parameters<typeof pageAccessFor>[1],\n ctx: AppContext,\n): HostPage | undefined {\n const ref = hostPageRef(host);\n if (ref === undefined) return undefined;\n const key = canonicalEntityNodeKey({ name: ref.id, ref });\n const page = registry.customPages.get(key);\n if (page === undefined) return { href: '', access: 'denied' };\n const href = hrefFor(registry, key);\n const shown = (node: unknown) =>\n evaluateVisible((node as { visible?: unknown }).visible as never, ctx);\n const chain = matchPath(registry, href)?.groupChain;\n if (chain === undefined || !shown(page) || !chain.every((group) => shown(group as NavNode)))\n return { href, access: 'denied' };\n return { href, access: pageAccessFor(page, permissions) };\n}\n\n/** {@link hostPageFor} for a component: the registry and the permission map from the context. */\nexport function useHostPage(host: unknown): HostPage | undefined {\n const app = useApp();\n const permissions = usePermissions();\n const ctx = useVisibilityCtx();\n return useMemo(\n () => hostPageFor(app.registry, host, permissions, ctx),\n [app, host, permissions, ctx],\n );\n}\n\n/**\n * A flow control's state conjoined with its host page's access (P7 3.15): a page the user cannot\n * open leaves no button (`absent`), an undecided one draws nothing yet (`undecided`).\n */\nexport function conjoinHostPage(\n state: FlowControlState,\n hostPage: HostPage | undefined,\n): FlowControlState {\n if (hostPage === undefined || state === 'absent') return state;\n if (hostPage.access === 'denied') return 'absent';\n if (hostPage.access === 'pending') return 'undecided';\n return state;\n}\n","import {\n type CompiledFlow,\n compileFlow,\n type FlowGateAnswer,\n type FlowTarget,\n resolveFlowGate,\n ruleContextFor,\n} from '@burojs/core';\nimport { useMemo } from 'react';\nimport { readPermissions, useContextSnapshot } from '../forms/controller/use-source-resolver.js';\nimport { useApp } from '../hooks/use-app.js';\n\n/**\n * A flow with no record (an app flow, or a resource-level flow) as a page asks about it (P7\n * 3.15): the flow compiled, and its gate (`resolveFlowGate`, P4 4.17) decided before anything is\n * read — `undecided` while the permission map loads, `absent` for a flow that is not offered.\n * `compiled` is `null` for a flow the application does not declare (fail closed: `absent`).\n */\nexport interface PageFlowGate {\n readonly answer: FlowGateAnswer;\n readonly compiled: CompiledFlow | null;\n}\n\nconst ABSENT: PageFlowGate = Object.freeze({\n answer: Object.freeze({ state: 'absent' as const }),\n compiled: null,\n});\n\n/**\n * The gate of a record-free flow. The same `resolveFlowGate` the app-action palette and the list\n * toolbar run, so a page offers a flow exactly where they do.\n */\nexport function usePageFlowGate(target: FlowTarget): PageFlowGate {\n const app = useApp();\n const context = useContextSnapshot();\n const permissions = readPermissions(context);\n const resource = 'resource' in target ? target.resource : null;\n const name = 'resource' in target ? target.action : target.appAction;\n return useMemo(() => {\n const def = resource === null ? app.registry.appActions.get(name) : app.registry.get(resource);\n if (def === undefined) return ABSENT;\n let compiled: CompiledFlow;\n try {\n compiled = compileFlow(def as never, name);\n } catch {\n return ABSENT;\n }\n const answer = resolveFlowGate({\n app,\n resource,\n flow: compiled,\n ctx: ruleContextFor({\n mode: 'list',\n user: context.user as never,\n scope: context.scope as never,\n ...(permissions === undefined ? {} : { permissions }),\n }),\n permissionsStatus: permissions?.status as 'loading' | 'ready' | 'error' | undefined,\n });\n return Object.freeze({ answer, compiled });\n }, [app, resource, name, context, permissions]);\n}\n","'use client';\nimport type { FlowResult } from '@burojs/core';\nimport { useCallback, useContext } from 'react';\nimport { useDispatcherEffects } from '../dispatch/dispatcher-context.js';\nimport { DismissRegistryContext, DismissScopeContext } from '../navigation/dismiss-scope.js';\nimport { useUIPresentationRuntime } from '../ui/context.js';\nimport { useOptionalPresentationMount } from '../ui/mount.js';\nimport {\n FLOW_COMPONENT,\n FlowScreenEntry,\n type FlowScreenProps,\n type FlowStart,\n} from '../ui/ui-presentations.js';\nimport { useCurrentUIActivation } from '../ui/use-ui-present.js';\n\n// Bundlers fold the development branch out of a production build.\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } };\n\n/** Missing members already reported, per provider (keyed by its outlet registry). */\nconst reportedMissing = new WeakMap<object, Set<string>>();\n\n/** @internal One development error per missing `presentationHosts` member, per provider. */\nexport function reportMissingFlowHost(provider: object, member: string): void {\n if (process.env.NODE_ENV === 'production') return;\n let seen = reportedMissing.get(provider);\n if (seen === undefined) {\n seen = new Set();\n reportedMissing.set(provider, seen);\n }\n if (seen.has(member)) return;\n seen.add(member);\n console.error(\n `[burojs] Flows with a form or a review need presentationHosts.${member}; spread shadcnPresentationHosts (or its screens) into your hosts.`,\n );\n}\n\nexport interface PresentFlowInput extends FlowStart {\n readonly host: 'dialog' | 'sheet';\n readonly label: string;\n readonly title?: string;\n}\n\n/**\n * @internal Opens a flow with a form or a review in the UI kit's host (P4 spec 4.15; P4-C review\n * I1): the host owns the run, so it outlives the control that opened it — a dirty form still\n * asks before it closes, and a pending write is never cut. The opener's dismiss scope is the\n * host's parent (closing a quick sheet asks about a dirty flow above it) and the opener's\n * dispatcher scope runs `then`. Resolves when the host closes, with the last outcome (`halted`\n * when there was none); `null` when nothing could be presented (one development error names a\n * missing host or screen).\n */\nexport function usePresentFlow(): (input: PresentFlowInput) => Promise<FlowResult> | null {\n const runtime = useUIPresentationRuntime();\n const mount = useOptionalPresentationMount();\n const registry = useContext(DismissRegistryContext);\n const enclosing = useContext(DismissScopeContext);\n const activation = useCurrentUIActivation();\n const effects = useDispatcherEffects();\n return useCallback(\n (input: PresentFlowInput): Promise<FlowResult> | null => {\n if (mount === null) return null;\n if (mount.mode === 'app' && !mount.registry.isMounted()) {\n console.error(\n '[burojs] A flow opened nothing: BuroProvider is in presentations=\"app\" mode but no <BuroPresentationOutlet/> is mounted.',\n );\n return null;\n }\n if (mount.hosts[input.host] === undefined) {\n reportMissingFlowHost(mount.registry, input.host);\n return null;\n }\n if (mount.hosts.screens?.flow === undefined) {\n reportMissingFlowHost(mount.registry, 'screens.flow');\n return null;\n }\n let last: FlowResult | undefined;\n const props: FlowScreenProps = {\n start: {\n target: input.target,\n ...(input.record === undefined ? {} : { record: input.record }),\n ...(input.args === undefined ? {} : { args: input.args }),\n ...(input.selection === undefined ? {} : { selection: input.selection }),\n },\n host: input.host,\n label: input.label,\n ...(input.title === undefined ? {} : { title: input.title }),\n ...(input.record === undefined ? {} : { record: input.record }),\n ...(input.args === undefined ? {} : { args: input.args }),\n ...(input.selection === undefined ? {} : { selection: input.selection }),\n effects,\n onSettle: (result) => {\n last = result;\n },\n };\n const presented = runtime.present({\n component: FLOW_COMPONENT,\n host: input.host,\n // By reference: the props carry functions and the run's claims (see `FlowScreenEntry`).\n props: { entry: new FlowScreenEntry(props) },\n options: { ownTitle: true, wrapper: false },\n activation,\n });\n if (!presented.ok) return null;\n const id = presented.instance.id;\n if (registry !== null && enclosing !== null) registry.recordParent(id, enclosing.id);\n // Followed on the runtime itself, not in an effect: the promise settles even when the\n // opener has gone.\n return new Promise<FlowResult>((resolve) => {\n const unsubscribe = runtime.subscribe(() => {\n if (runtime.getSnapshot().some((descriptor) => descriptor.id === id)) return;\n unsubscribe();\n resolve(last ?? Object.freeze({ outcome: 'halted', step: 'open' }));\n });\n });\n },\n [runtime, mount, registry, enclosing, activation, effects],\n );\n}\n"],"mappings":";;;;;;;;;;AAaA,SAASA,iBAAe,OAAuC,WAAsB;CACnF,OAAO;EACL,MAAM;EACN;EACA,SACE,SAAS,YACL,4BACA;CACR;AACF;AAEA,SAAS,aAAa,MAA2B,OAAqC;CACpF,OAAO,KAAK,eAAe,MAAM,cAAc,KAAK,eAAe,MAAM;AAC3E;AAEA,SAASC,oBAAkB,MAAe,OAAyB;CACjE,IAAI,OAAO,GAAG,MAAM,KAAK,GAA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