@cloudlet/toast 1.0.0-rc.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +84 -16
  2. package/README.md +7 -5
  3. package/dist/contracts/controller.d.ts +7 -2
  4. package/dist/contracts/controller.d.ts.map +1 -1
  5. package/dist/contracts/events.d.ts +1 -1
  6. package/dist/contracts/events.d.ts.map +1 -1
  7. package/dist/contracts/internal.d.ts +23 -0
  8. package/dist/contracts/internal.d.ts.map +1 -1
  9. package/dist/contracts/notifications.d.ts +38 -6
  10. package/dist/contracts/notifications.d.ts.map +1 -1
  11. package/dist/contracts/snapshots.d.ts +3 -1
  12. package/dist/contracts/snapshots.d.ts.map +1 -1
  13. package/dist/core/bridge.d.ts +5 -0
  14. package/dist/core/bridge.d.ts.map +1 -0
  15. package/dist/core/bridge.js +345 -0
  16. package/dist/core/bridge.js.map +1 -0
  17. package/dist/core/controller.d.ts +122 -3
  18. package/dist/core/controller.d.ts.map +1 -1
  19. package/dist/core/controller.js +400 -541
  20. package/dist/core/controller.js.map +1 -1
  21. package/dist/core/validation.d.ts.map +1 -1
  22. package/dist/core/validation.js +181 -89
  23. package/dist/core/validation.js.map +1 -1
  24. package/dist/react/announcer.d.ts.map +1 -1
  25. package/dist/react/announcer.js +29 -23
  26. package/dist/react/announcer.js.map +1 -1
  27. package/dist/react/bindings.d.ts +9 -0
  28. package/dist/react/bindings.d.ts.map +1 -1
  29. package/dist/react/bindings.js +32 -69
  30. package/dist/react/bindings.js.map +1 -1
  31. package/dist/react/card.d.ts +5 -3
  32. package/dist/react/card.d.ts.map +1 -1
  33. package/dist/react/card.js +146 -34
  34. package/dist/react/card.js.map +1 -1
  35. package/dist/react/generators.d.ts +2 -2
  36. package/dist/react/generators.js.map +1 -1
  37. package/dist/react/gestures.js.map +1 -1
  38. package/dist/react/host.d.ts.map +1 -1
  39. package/dist/react/host.js +9 -5
  40. package/dist/react/host.js.map +1 -1
  41. package/dist/react/motion.d.ts +3 -3
  42. package/dist/react/motion.js.map +1 -1
  43. package/dist/react/plan.d.ts +1 -1
  44. package/dist/react/plan.d.ts.map +1 -1
  45. package/dist/react/plan.js +1 -0
  46. package/dist/react/plan.js.map +1 -1
  47. package/dist/react/renderer.d.ts +7 -0
  48. package/dist/react/renderer.d.ts.map +1 -0
  49. package/dist/react/renderer.js +62 -0
  50. package/dist/react/renderer.js.map +1 -0
  51. package/dist/react.d.ts +7 -5
  52. package/dist/react.d.ts.map +1 -1
  53. package/dist/styles.css +1 -1
  54. package/package.json +4 -2
  55. package/src/contracts/controller.ts +7 -2
  56. package/src/contracts/events.ts +2 -1
  57. package/src/contracts/internal.ts +20 -0
  58. package/src/contracts/notifications.ts +45 -6
  59. package/src/contracts/snapshots.ts +3 -0
  60. package/src/core/bridge.ts +336 -0
  61. package/src/core/controller.ts +118 -271
  62. package/src/core/validation.ts +49 -4
  63. package/src/react/announcer.ts +9 -0
  64. package/src/react/bindings.tsx +28 -72
  65. package/src/react/card.tsx +92 -9
  66. package/src/react/generators.ts +2 -2
  67. package/src/react/gestures.ts +1 -1
  68. package/src/react/host.tsx +22 -7
  69. package/src/react/motion.ts +4 -4
  70. package/src/react/plan.ts +4 -3
  71. package/src/react/renderer.tsx +77 -0
  72. package/src/react.ts +7 -5
@@ -80,10 +80,25 @@ export type AnnouncementAcknowledgement =
80
80
  | { readonly kind: 'operation'; readonly handle: NotificationHandle; readonly token: OperationAttemptToken; readonly phase: OperationAnnouncementPhase }
81
81
  | { readonly kind: 'overflow'; readonly count: number };
82
82
 
83
+ /** Messages from the last submit: `form` under the form, `fields` under each field. */
84
+ export interface FormErrors {
85
+ readonly form: string | null;
86
+ readonly fields: Readonly<Record<string, string>>;
87
+ }
88
+
89
+ /** The values a form action holds for one record; only the renderer sees them. */
90
+ export interface FormDraft {
91
+ readonly handle: NotificationHandle;
92
+ readonly values: Readonly<Record<string, string>>;
93
+ readonly errors: FormErrors;
94
+ }
95
+
83
96
  export interface RendererSnapshot<Slot = never> extends ControllerSnapshot<Slot> {
84
97
  readonly presentation: RendererPresentation | null;
85
98
  readonly focusRequest: FocusRequest | null;
86
99
  readonly announcements: AnnouncementLedgerSnapshot;
100
+ /** One entry per record with a form action, in notification order. */
101
+ readonly forms: readonly FormDraft[];
87
102
  }
88
103
 
89
104
  export type AttachResult =
@@ -105,6 +120,8 @@ export type RendererCloseReason = Extract<CloseReason, 'close-button' | 'swipe'
105
120
 
106
121
  export type ActionResult =
107
122
  | { readonly status: 'started' }
123
+ /** A form failed `required`, `maxLength` or `validate`; the messages are in the record's draft. */
124
+ | { readonly status: 'invalid'; readonly errors: FormErrors }
108
125
  | { readonly status: 'rejected'; readonly reason: BridgeRejection | 'no-command' | 'already-pending' };
109
126
 
110
127
  export type RetryOperationResult =
@@ -143,7 +160,10 @@ export interface RendererBridge<Slot = never> {
143
160
  readonly acknowledgeOverflow: (lease: HostLease) => BridgeResult;
144
161
  readonly acknowledgeAnnouncements: (lease: HostLease, acknowledgements: readonly AnnouncementAcknowledgement[]) => BridgeResult;
145
162
  readonly dismiss: (lease: HostLease, handle: NotificationHandle, reason: RendererCloseReason) => MutationResult | { readonly status: 'rejected'; readonly reason: 'stale-lease' };
163
+ /** Runs a command, or validates and submits a form. */
146
164
  readonly invokeAction: (lease: HostLease, handle: NotificationHandle) => ActionResult;
165
+ readonly setFormValue: (lease: HostLease, handle: NotificationHandle, name: string, value: string) =>
166
+ BridgeResult | { readonly status: 'rejected'; readonly reason: 'no-form' | 'already-pending' };
147
167
  readonly retryOperation: (lease: HostLease, handle: NotificationHandle, expected: OperationAttemptToken) => RetryOperationResult;
148
168
  readonly cancelOperation: (lease: HostLease, handle: NotificationHandle, expected: OperationAttemptToken, reason?: unknown) => CancelOperationResult;
149
169
  readonly reportDiagnostic: (lease: HostLease, diagnostic: Diagnostic) => BridgeResult;
@@ -36,14 +36,53 @@ export interface NavigationAction {
36
36
  readonly rel?: string;
37
37
  }
38
38
 
39
- export type PrimaryAction = CommandAction | NavigationAction;
39
+ export type FormFieldKind = 'text' | 'textarea';
40
+ export type FormInputMode = 'text' | 'email' | 'numeric' | 'decimal' | 'tel' | 'url' | 'search';
40
41
 
41
- export interface NotificationContent<Slot = never> {
42
+ /** One field of a form action. `label` is read by screen readers; the placeholder falls back to it. */
43
+ export interface FormField<Name extends string = string> {
44
+ readonly name: Name;
45
+ readonly kind: FormFieldKind;
46
+ readonly label: string;
47
+ readonly placeholder?: string;
48
+ readonly defaultValue?: string;
49
+ readonly required?: boolean;
50
+ readonly maxLength?: number;
51
+ readonly autoComplete?: string;
52
+ readonly inputMode?: FormInputMode;
53
+ }
54
+
55
+ /** Field values as typed, without trimming. */
56
+ export type FormValues<Name extends string = string> = Readonly<Record<Name, string>>;
57
+
58
+ export interface FormContext<Name extends string = string> extends ActionContext {
59
+ readonly values: FormValues<Name>;
60
+ }
61
+
62
+ /** `true` accepts; a string is a message under the form; an object holds messages under fields. */
63
+ export type FormValidation<Name extends string = string> = true | string | Readonly<Partial<Record<Name, string>>>;
64
+
65
+ /** A form in the Island: one to three fields and a submit button with command semantics. */
66
+ export interface FormAction<Name extends string = string> {
67
+ readonly kind: 'form';
68
+ readonly fields: readonly FormField<Name>[];
69
+ /** The submit button's accessible name, like the label of a command. */
70
+ readonly label: string;
71
+ // Methods, not function properties: a form typed with its field names stays assignable to `FormAction`.
72
+ run(context: FormContext<Name>): unknown;
73
+ errorMessage?(error: unknown): string;
74
+ /** Runs on submit after `required` and `maxLength`. */
75
+ validate?(values: FormValues<Name>): FormValidation<Name>;
76
+ }
77
+
78
+ export type PrimaryAction<Name extends string = string> = CommandAction | NavigationAction | FormAction<Name>;
79
+
80
+ export interface NotificationContent<Slot = never, Name extends string = string> {
42
81
  readonly title: string;
43
82
  readonly description?: Description<Slot>;
44
83
  readonly icon?: Slot;
45
84
  readonly progress?: Progress;
46
- readonly action?: PrimaryAction;
85
+ readonly action?: PrimaryAction<Name>;
47
86
  readonly announcementPriority?: AnnouncementPriority;
48
87
  /** Omitted = policy default; null = persistent; number = readable milliseconds. */
49
88
  readonly duration?: Duration;
@@ -66,7 +105,7 @@ export interface CloseNotice {
66
105
  readonly reason: CloseReason;
67
106
  }
68
107
 
69
- export interface NotificationSpec<Slot = never> extends NotificationContent<Slot> {
108
+ export interface NotificationSpec<Slot = never, Name extends string = string> extends NotificationContent<Slot, Name> {
70
109
  readonly id?: string;
71
110
  readonly kind?: NotificationKind;
72
111
  readonly priority?: Priority;
@@ -75,13 +114,13 @@ export interface NotificationSpec<Slot = never> extends NotificationContent<Slot
75
114
  }
76
115
 
77
116
  /** Omitted preserves; null removes optional content. IDs/dedupe keys are immutable. */
78
- export interface NotificationPatch<Slot = never> {
117
+ export interface NotificationPatch<Slot = never, Name extends string = string> {
79
118
  readonly title?: string;
80
119
  readonly kind?: NotificationKind;
81
120
  readonly description?: Description<Slot> | null;
82
121
  readonly icon?: Slot | null;
83
122
  readonly progress?: Progress | null;
84
- readonly action?: PrimaryAction | null;
123
+ readonly action?: PrimaryAction<Name> | null;
85
124
  readonly priority?: Priority;
86
125
  readonly announcementPriority?: AnnouncementPriority;
87
126
  readonly duration?: Duration;
@@ -12,6 +12,7 @@ export type PauseReason =
12
12
  | 'action-pending'
13
13
  | 'content-transition'
14
14
  | 'island'
15
+ | 'draft'
15
16
  | 'document-hidden'
16
17
  | 'window-blur';
17
18
 
@@ -34,6 +35,8 @@ export interface NotificationSnapshot<Slot = never> {
34
35
  readonly pauseReasons: readonly PauseReason[];
35
36
  readonly operation: OperationSnapshot | null;
36
37
  readonly action: ActionSnapshot;
38
+ /** A form action whose values differ from their defaults. The values stay inside Cloudlet. */
39
+ readonly draft: boolean;
37
40
  }
38
41
 
39
42
  export type IslandReason = 'user' | 'attention';
@@ -0,0 +1,336 @@
1
+ import type { Diagnostic } from '../contracts/events.js';
2
+ import type { ActionAttemptToken, NotificationHandle, OperationAttemptToken } from '../contracts/identity.js';
3
+ import type {
4
+ AnnouncementAcknowledgement, BridgeRejection, BridgeResult, FocusRequestToken, FormErrors, HostLease, HostOptions, PauseChange,
5
+ PresentationToken, RendererBridge,
6
+ } from '../contracts/internal.js';
7
+ import type { CancellationSignal } from '../contracts/operations.js';
8
+ import type { CloudletController } from '../contracts/controller.js';
9
+ import type { IslandReason, PauseReason } from '../contracts/snapshots.js';
10
+ import {
11
+ APPLIED, ATTENTION_DELAY, NO_FORM_ERRORS, RENDERER_SERVER, UNCHANGED, getControllerKernel, reject,
12
+ type ControllerKernel, type FormState, type OperationBinding, type RecordState,
13
+ } from './controller.js';
14
+ import { validDelay } from './validation.js';
15
+
16
+ // The renderer's side of a controller. It is imported only by react/renderer.tsx, so it travels
17
+ // in the lazily loaded renderer chunk; the controller keeps a kernel of the state it touches.
18
+ const freeze = Object.freeze;
19
+ const bridges = new WeakMap<object, RendererBridge<unknown>>();
20
+
21
+ export function getRendererBridge<Slot, Signal extends CancellationSignal>(controller: CloudletController<Slot, Signal>): RendererBridge<Slot> {
22
+ let bridge = bridges.get(controller);
23
+ if (!bridge) {
24
+ bridge = createRendererBridge(getControllerKernel<Slot>(controller)) as RendererBridge<unknown>;
25
+ bridges.set(controller, bridge);
26
+ }
27
+ return bridge as RendererBridge<Slot>;
28
+ }
29
+
30
+ function createRendererBridge<Slot>(k: ControllerKernel<Slot>): RendererBridge<Slot> {
31
+ const leaseError = (value: HostLease): 'disposed' | 'stale-lease' | undefined =>
32
+ k.disposed ? 'disposed' : k.lease === null || value !== k.lease ? 'stale-lease' : undefined;
33
+ const currentError = (handle: NotificationHandle): BridgeRejection | undefined =>
34
+ k.handleError(handle) ?? (k.records.get(handle.id) !== k.presented ? 'not-current' : undefined);
35
+ function withCurrent<Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result) {
36
+ return k.withRecord((record, ...args: Args) => record !== k.presented ? reject('not-current') : action(record, ...args));
37
+ }
38
+ function withOperation<Args extends unknown[], Result>(action: (operation: OperationBinding, ...args: Args) => Result) {
39
+ return k.withRecord((record, expected: OperationAttemptToken, ...args: Args) => {
40
+ const operation = record.operation;
41
+ return !operation ? reject('no-operation') : operation.getSnapshot().token !== expected
42
+ ? reject('stale-operation-token') : action(operation, ...args);
43
+ });
44
+ }
45
+ function validHostOptions(value: HostOptions | undefined): boolean {
46
+ if (value === undefined) return true;
47
+ return value !== null && typeof value === 'object' && Object.keys(value).every((key) => key === 'attentionDelay')
48
+ && (value.attentionDelay === undefined || validDelay(value.attentionDelay));
49
+ }
50
+ // Preserve the bridge's lease-first validation order in one entry guard.
51
+ function withLease<Args extends unknown[], Result>(action: (...args: Args) => Result) {
52
+ return (value: HostLease, ...args: Args) => {
53
+ const error = leaseError(value);
54
+ return error ? reject(error) : action(...args);
55
+ };
56
+ }
57
+ /** `required` and `maxLength` first, then the form's own `validate`; null lets the submit run. */
58
+ function checkForm(form: FormState, handle: NotificationHandle): FormErrors | null {
59
+ const messages = k.options.messages;
60
+ const fields: Record<string, string> = {};
61
+ for (const field of form.action.fields) {
62
+ const value = form.values[field.name] ?? '';
63
+ if (field.required && !value.trim()) fields[field.name] = messages?.fieldRequired ?? 'This field is required';
64
+ else if (field.maxLength !== undefined && value.length > field.maxLength) fields[field.name] = messages?.fieldTooLong ?? 'This text is too long';
65
+ }
66
+ if (Object.keys(fields).length) return freeze({ form: null, fields: freeze(fields) });
67
+ if (!form.action.validate) return null;
68
+ let result: unknown;
69
+ try {
70
+ result = form.action.validate(form.values);
71
+ } catch (error) {
72
+ k.failure('callback-error', 'action.validate', error, handle);
73
+ return freeze({ form: messages?.actionError ?? 'Action failed', fields: freeze({}) });
74
+ }
75
+ if (result === true) return null;
76
+ if (typeof result === 'string' && result.trim()) return freeze({ form: result, fields: freeze({}) });
77
+ const names = form.action.fields.map((field) => field.name);
78
+ if (result !== null && typeof result === 'object' && Object.getPrototypeOf(result) === Object.prototype &&
79
+ Object.entries(result).every(([name, message]) => names.includes(name) && typeof message === 'string' && message.trim())) {
80
+ return Object.keys(result).length ? freeze({ form: null, fields: freeze({ ...result as Record<string, string> }) }) : null;
81
+ }
82
+ k.diagnostic({ code: 'callback-error', source: 'action.validate', handle,
83
+ message: 'validate must return true, a message, or messages keyed by field name' });
84
+ return freeze({ form: messages?.actionError ?? 'Action failed', fields: freeze({}) });
85
+ }
86
+ const bridge = freeze<RendererBridge<Slot>>({
87
+ renderError: k.options.messages?.renderError ?? 'Content unavailable',
88
+ reportInvalidContainer(message, error) {
89
+ if (!k.disposed) k.diagnostic({ code: 'invalid-container', source: 'Toaster.container', message, ...(error === undefined ? {} : { error }) });
90
+ },
91
+ attach(hostOptions) {
92
+ if (k.disposed) return reject('disposed');
93
+ if (k.lease !== null) {
94
+ k.diagnostic({ code: 'second-host', source: 'attach', message: 'A renderer is already attached' });
95
+ return reject('host-exists');
96
+ }
97
+ if (!validHostOptions(hostOptions)) return reject('invalid-input');
98
+ const nextLease = k.token() as HostLease;
99
+ k.mutate(() => {
100
+ k.lease = k.lastLease = nextLease;
101
+ k.hostDelay = hostOptions?.attentionDelay;
102
+ if (k.presented) k.assign(k.presented);
103
+ });
104
+ return { status: 'attached', lease: nextLease };
105
+ },
106
+ detach(value) {
107
+ if (k.disposed) return reject('disposed');
108
+ if (k.lease === null && k.lastLease !== null && value === k.lastLease) return UNCHANGED;
109
+ const error = leaseError(value);
110
+ if (error) return reject(error);
111
+ return k.mutate(() => {
112
+ k.lease = null;
113
+ k.hostDelay = undefined;
114
+ k.setHostAutoDismiss(undefined);
115
+ k.focusRequest = null;
116
+ k.focused = null;
117
+ k.globalPauses.clear();
118
+ for (const record of k.records.values()) { record.pauses.clear(); record.readable = false; record.presentation = null; }
119
+ });
120
+ },
121
+ getSnapshot: () => k.rendererSnapshot,
122
+ getServerSnapshot: () => RENDERER_SERVER,
123
+ subscribe: k.subscribe,
124
+ onEvent: k.onEvent,
125
+ openIsland: withLease((reason: IslandReason, handle?: NotificationHandle) => {
126
+ if (reason !== 'user' && reason !== 'attention') return reject('invalid-input');
127
+ let record: RecordState<Slot> | null;
128
+ if (handle === undefined) record = k.newest();
129
+ else {
130
+ const error = k.handleError(handle);
131
+ if (error) return reject(error);
132
+ record = k.records.get(handle.id)!;
133
+ }
134
+ if (!record) return reject('empty');
135
+ const target = record;
136
+ if (k.island?.current === target) return UNCHANGED;
137
+ // An open Island only moves its slider; the opening reason is kept.
138
+ return k.mutate(() => {
139
+ if (k.island) k.island.current = target;
140
+ else k.island = { reason, current: target };
141
+ });
142
+ }),
143
+ collapseIsland: withLease(() => k.island ? k.mutate(() => { k.island = null; }) : UNCHANGED),
144
+ setAutoDismiss: withLease((value?: boolean) => {
145
+ if (value !== undefined && typeof value !== 'boolean') return reject('invalid-input');
146
+ if (k.autoDismissing(value) === k.autoDismissing(k.hostAutoDismiss)) { k.hostAutoDismiss = value; return UNCHANGED; }
147
+ return k.mutate(() => k.setHostAutoDismiss(value));
148
+ }),
149
+ navigate: withLease(k.withRecord((record) => {
150
+ if (!k.island) return reject('island-closed');
151
+ if (k.island.current === record) return UNCHANGED;
152
+ return k.mutate(() => {
153
+ k.island!.current = record;
154
+ // Navigation is interaction: a pending auto-open restarts its delay,
155
+ // and reaching the initiator by hand fulfils it.
156
+ if (k.attention?.record === record) k.attention = null;
157
+ else if (k.attention) { k.attention.waiting = false; k.attention.due = k.clock.now() + (k.hostDelay ?? k.options.attentionDelay ?? ATTENTION_DELAY); }
158
+ });
159
+ })),
160
+ setPause: withLease((change: PauseChange) => {
161
+ if (!change || typeof change.active !== 'boolean') return reject('invalid-input');
162
+ let set: Set<PauseReason>;
163
+ if (change.scope === 'host') {
164
+ if (!['hover', 'focus', 'document-hidden', 'window-blur'].includes(change.reason)) return reject('invalid-input');
165
+ set = k.globalPauses;
166
+ } else if (change.scope === 'notification') {
167
+ const error = currentError(change.handle);
168
+ if (error) return reject(error);
169
+ if (!['gesture', 'content-transition'].includes(change.reason)) return reject('invalid-input');
170
+ set = k.records.get(change.handle.id)!.pauses;
171
+ } else return reject('invalid-input');
172
+ if (set.has(change.reason) === change.active) return UNCHANGED;
173
+ return k.mutate(() => {
174
+ if (change.active) set.add(change.reason); else set.delete(change.reason);
175
+ });
176
+ }),
177
+ // Informational since the stack has no slots to protect; it has no observable effect.
178
+ setFocused: withLease((handle: NotificationHandle | null) => {
179
+ const error = (handle === null ? undefined : currentError(handle));
180
+ if (error) return reject(error);
181
+ if (k.focused === handle) return UNCHANGED;
182
+ k.focused = handle;
183
+ return APPLIED;
184
+ }),
185
+ beginPresentation: withLease(withCurrent((record, previous: PresentationToken) => {
186
+ if (record.presentation !== previous) return reject('stale-presentation');
187
+ const presentation = k.token() as PresentationToken;
188
+ k.mutate(() => { record.presentation = presentation; record.readable = false; });
189
+ return { status: 'started' as const, token: presentation };
190
+ })),
191
+ acknowledgePresentation: withLease(withCurrent((record, presentation: PresentationToken) => {
192
+ if (record.presentation !== presentation) return reject('stale-presentation');
193
+ if (record.readable) return UNCHANGED;
194
+ return k.mutate((deliveries) => {
195
+ deliveries.push({ type: 'presented', handle: record.handle, firstPresentation: !record.everPresented });
196
+ record.readable = record.everPresented = true;
197
+ });
198
+ })),
199
+ acknowledgeFocus: withLease((focusToken: FocusRequestToken, outcome: 'focused' | 'unavailable') => {
200
+ if (k.focusRequest?.token !== focusToken) return reject('stale-focus-request');
201
+ if (outcome !== 'focused' && outcome !== 'unavailable') return reject('invalid-input');
202
+ return k.mutate(() => { k.focusRequest = null; });
203
+ }),
204
+ acknowledgeOverflow: withLease(() => {
205
+ return k.acknowledgeOverflow();
206
+ }),
207
+ acknowledgeAnnouncements: withLease((acknowledgements: readonly AnnouncementAcknowledgement[]) => {
208
+ return acknowledgeAnnouncements(acknowledgements);
209
+ }),
210
+ dismiss: withLease((handle: NotificationHandle, reason: 'close-button' | 'swipe' | 'navigation') => {
211
+ const error = k.handleError(handle);
212
+ if (error) return reject(error);
213
+ // Renderer close reasons are a closed protocol, never an exit callback.
214
+ if (!['close-button', 'swipe', 'navigation'].includes(reason)) return reject('invalid-input');
215
+ return k.dismiss(handle, reason);
216
+ }),
217
+ invokeAction: withLease(k.withRecord((record) => {
218
+ const handle = record.handle;
219
+ const action = record.content.action;
220
+ if (!action || action.kind === 'link') return reject('no-command');
221
+ if (record.action.status === 'pending') return reject('already-pending');
222
+ const form = k.formOf(record);
223
+ if (form) {
224
+ const errors = checkForm(form, handle);
225
+ if (errors) {
226
+ k.mutate(() => { form.errors = errors; });
227
+ return { status: 'invalid' as const, errors };
228
+ }
229
+ }
230
+ const actionToken = k.token() as ActionAttemptToken;
231
+ const live = () => !k.disposed && k.records.get(handle.id) === record &&
232
+ record.action.status === 'pending' && record.action.token === actionToken;
233
+ const now = k.settle();
234
+ record.action = freeze({ status: 'pending', token: actionToken });
235
+ if (form) form.errors = NO_FORM_ERRORS;
236
+ k.commit([{ type: 'action-started', handle, token: actionToken }], now);
237
+ function failed(reason: unknown): void {
238
+ if (!live()) return;
239
+ let message = k.options.messages?.actionError ?? 'Action failed';
240
+ if (action && action.kind !== 'link' && action.errorMessage) {
241
+ try {
242
+ const mapped = action.errorMessage(reason);
243
+ if (typeof mapped !== 'string' || !mapped.trim()) throw new TypeError('Invalid action error message');
244
+ message = mapped;
245
+ } catch (error) {
246
+ if (!k.disposed) k.failure('mapper-error', 'action.errorMessage', error, handle);
247
+ }
248
+ }
249
+ if (!live()) return;
250
+ const now = k.settle();
251
+ record.action = freeze({ status: 'failed', token: actionToken, message });
252
+ k.commit([{ type: 'action-failed', handle, token: actionToken, message }], now);
253
+ }
254
+ let result: Promise<unknown>;
255
+ try {
256
+ result = Promise.resolve(form ? form.action.run(freeze({ handle, token: actionToken, values: form.values }))
257
+ : action.kind === 'command' ? action.run(freeze({ handle, token: actionToken })) : undefined);
258
+ }
259
+ catch (error) { result = Promise.reject(error); }
260
+ void result.then(() => {
261
+ if (live()) k.dismiss(handle, 'action-success');
262
+ }, failed).catch((error: unknown) => {
263
+ if (!k.disposed) k.failure('callback-error', 'action-settlement', error, handle);
264
+ });
265
+ return { status: 'started' as const };
266
+ })),
267
+ setFormValue: withLease(k.withRecord((record, name: string, value: string) => {
268
+ const form = k.formOf(record);
269
+ if (!form) return reject('no-form');
270
+ if (typeof value !== 'string' || !form.action.fields.some((field) => field.name === name)) return reject('invalid-input');
271
+ if (record.action.status === 'pending') return reject('already-pending');
272
+ if (form.values[name] === value) return UNCHANGED;
273
+ return k.mutate(() => {
274
+ form.values = freeze({ ...form.values, [name]: value });
275
+ // Editing a field clears its own message; the rest wait for the next submit.
276
+ if (form.errors.fields[name] !== undefined) {
277
+ const { [name]: _, ...fields } = form.errors.fields;
278
+ form.errors = freeze({ form: form.errors.form, fields: freeze(fields) });
279
+ }
280
+ });
281
+ })),
282
+ retryOperation: withLease(withOperation((operation) => {
283
+ const result = operation.retry();
284
+ return result.status === 'started' ? { status: 'started' as const, token: result.attempt.token } : result;
285
+ })),
286
+ cancelOperation: withLease(withOperation((operation, reason?: unknown) => operation.cancel(reason))),
287
+ reportDiagnostic: withLease((report: Diagnostic) => {
288
+ if (!report || typeof report.source !== 'string' || typeof report.message !== 'string'
289
+ || !['invalid-input', 'second-host', 'stale-host', 'mapper-error', 'callback-error', 'listener-error', 'cancellation-error', 'slot-error', 'formatter-error', 'invalid-container'].includes(report.code)) return reject('invalid-input');
290
+ k.diagnostic(report);
291
+ return APPLIED;
292
+ }),
293
+ });
294
+
295
+ function acknowledgeAnnouncements(acks: readonly AnnouncementAcknowledgement[]): BridgeResult {
296
+ if (!Array.isArray(acks)) return reject('invalid-input');
297
+ // Stage only effective changes; no ledger mutation occurs until every
298
+ // acknowledgement has passed validation. Repeated counts remain monotonic.
299
+ const changes: (() => void)[] = [];
300
+ const validCount = (count: number, maximum: number) => Number.isSafeInteger(count) && count >= 0 && count <= maximum;
301
+ for (const ack of acks) {
302
+ if (!ack || typeof ack !== 'object') return reject('invalid-input');
303
+ if (ack.kind === 'overflow') {
304
+ if (!validCount(ack.count, k.overflow)) return reject('invalid-input');
305
+ if (ack.count > k.overflowAnnounced) changes.push(() => { k.overflowAnnounced = Math.max(k.overflowAnnounced, ack.count); });
306
+ continue;
307
+ }
308
+ const error = k.handleError(ack.handle);
309
+ if (error) return reject(error);
310
+ const record = k.records.get(ack.handle.id)!;
311
+ if (ack.kind === 'operation') {
312
+ const operation = record.operation?.getSnapshot();
313
+ if (!operation || operation.token !== ack.token) return reject('stale-operation-token');
314
+ if (!['started', 'fulfilled', 'rejected', 'cancelled', 'cancel-requested'].includes(ack.phase)) return reject('invalid-input');
315
+ if (ack.phase === 'cancel-requested' ? !operation.cancelRequested
316
+ : ack.phase !== 'started' && ack.phase !== operation.status) return reject('invalid-input');
317
+ if (!record.operationAnnounced.has(ack.phase)) changes.push(() => { record.operationAnnounced.add(ack.phase); });
318
+ } else if (ack.kind === 'action') {
319
+ if (record.action.status === 'idle' || record.action.token !== ack.token || record.action.status !== ack.status) return reject('invalid-input');
320
+ if (record.actionAnnounced?.token !== ack.token || record.actionAnnounced?.status !== ack.status) {
321
+ changes.push(() => { record.actionAnnounced = freeze({ token: ack.token, status: ack.status }); });
322
+ }
323
+ } else if (ack.kind === 'occurrences') {
324
+ if (!validCount(ack.count, record.occurrences)) return reject('invalid-input');
325
+ if (ack.count > record.occurrencesAnnounced) changes.push(() => { record.occurrencesAnnounced = Math.max(record.occurrencesAnnounced, ack.count); });
326
+ } else if (ack.kind === 'queued' || ack.kind === 'first-presentation') {
327
+ const key = ack.kind === 'queued' ? 'queuedAnnounced' : 'firstAnnounced';
328
+ if (!record[key]) changes.push(() => { record[key] = true; });
329
+ } else return reject('invalid-input');
330
+ }
331
+ if (!changes.length) return UNCHANGED;
332
+ return k.mutate(() => { for (const apply of changes) apply(); });
333
+ }
334
+
335
+ return bridge;
336
+ }