@tangle-network/agent-app 0.45.21 → 0.45.22

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 (110) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +21 -4
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/chunk-CCVG2TL6.js +327 -0
  16. package/dist/chunk-CCVG2TL6.js.map +1 -0
  17. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  18. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  19. package/dist/chunk-F7VH4G5C.js +283 -0
  20. package/dist/chunk-F7VH4G5C.js.map +1 -0
  21. package/dist/chunk-I24YIKHO.js +183 -0
  22. package/dist/chunk-I24YIKHO.js.map +1 -0
  23. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  24. package/dist/chunk-NZVBJM73.js.map +1 -0
  25. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  26. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  27. package/dist/chunk-PC2WYTK7.js +405 -0
  28. package/dist/chunk-PC2WYTK7.js.map +1 -0
  29. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  30. package/dist/chunk-TX6S7XXU.js.map +1 -0
  31. package/dist/chunk-UGWQLQDS.js +35 -0
  32. package/dist/chunk-UGWQLQDS.js.map +1 -0
  33. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  34. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  35. package/dist/design-canvas/index.d.ts +3 -3
  36. package/dist/design-canvas/index.js +2 -2
  37. package/dist/design-canvas-react/engine.js +4 -4
  38. package/dist/design-canvas-react/index.js +7 -7
  39. package/dist/design-canvas-react/lazy.js +1 -1
  40. package/dist/documents/index.d.ts +233 -0
  41. package/dist/documents/index.js +495 -0
  42. package/dist/documents/index.js.map +1 -0
  43. package/dist/documents/pdf-inspector.d.ts +60 -0
  44. package/dist/documents/pdf-inspector.js +100 -0
  45. package/dist/documents/pdf-inspector.js.map +1 -0
  46. package/dist/eval/index.d.ts +1 -1
  47. package/dist/fold-DACU7gtf.d.ts +320 -0
  48. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  49. package/dist/openui/index.d.ts +208 -0
  50. package/dist/openui/index.js +350 -0
  51. package/dist/openui/index.js.map +1 -0
  52. package/dist/openui-react/index.d.ts +119 -0
  53. package/dist/openui-react/index.js +149 -0
  54. package/dist/openui-react/index.js.map +1 -0
  55. package/dist/platform/index.js +2 -2
  56. package/dist/preset-cloudflare/index.d.ts +2 -2
  57. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  58. package/dist/record/drizzle.d.ts +682 -0
  59. package/dist/record/drizzle.js +579 -0
  60. package/dist/record/drizzle.js.map +1 -0
  61. package/dist/record/index.d.ts +16 -0
  62. package/dist/record/index.js +35 -0
  63. package/dist/record/index.js.map +1 -0
  64. package/dist/runtime/index.d.ts +3 -3
  65. package/dist/sandbox/index.d.ts +2 -2
  66. package/dist/sandbox/index.js +3 -2
  67. package/dist/sequences/index.d.ts +3 -3
  68. package/dist/sequences/index.js +1 -1
  69. package/dist/session-shell/index.d.ts +173 -1
  70. package/dist/session-shell/index.js +13 -1
  71. package/dist/teams/index.js +9 -9
  72. package/dist/teams/invitations-api.js +3 -3
  73. package/dist/tools/index.d.ts +5 -5
  74. package/dist/tools/index.js +3 -2
  75. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  76. package/dist/types-DrBidf3O.d.ts +123 -0
  77. package/dist/values-C7RidJuI.d.ts +156 -0
  78. package/dist/web/index.d.ts +197 -31
  79. package/dist/web/index.js +15 -3
  80. package/dist/web-react/async/index.d.ts +309 -0
  81. package/dist/web-react/async/index.js +327 -0
  82. package/dist/web-react/async/index.js.map +1 -0
  83. package/dist/web-react/index.d.ts +338 -2
  84. package/dist/web-react/index.js +52 -6
  85. package/dist/work-product/index.d.ts +1 -1
  86. package/dist/work-product/index.js +2 -1
  87. package/dist/work-product/index.js.map +1 -1
  88. package/dist/workspace-react/index.js +1 -1
  89. package/package.json +43 -3
  90. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  91. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  92. package/dist/chunk-AH3IOSWF.js.map +0 -1
  93. package/dist/chunk-GINKOZFD.js +0 -214
  94. package/dist/chunk-GINKOZFD.js.map +0 -1
  95. package/dist/chunk-J25RST7G.js +0 -126
  96. package/dist/chunk-J25RST7G.js.map +0 -1
  97. package/dist/chunk-WBHPN5DY.js +0 -158
  98. package/dist/chunk-WBHPN5DY.js.map +0 -1
  99. package/dist/chunk-YEFFHORB.js.map +0 -1
  100. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  101. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  102. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  103. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  104. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  105. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  106. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  107. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  108. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  109. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  110. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,309 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+
3
+ /**
4
+ * The fetch-state contract: a failed load cannot render as empty data.
5
+ *
6
+ * Three shapes produce that defect, and two audited verticals shipped dozens of
7
+ * each: a `catch` handler that only clears a loading flag, an early return on a
8
+ * non-ok response, and a bare `null` returned while loading. All three end with
9
+ * the same pixels a successful-but-empty load produces — "No templates
10
+ * available", an empty member list, a blank conversation — so the reader cannot
11
+ * tell "we asked and there is nothing" from "we could not ask", and the retry
12
+ * that would fix it is never offered.
13
+ *
14
+ * `AsyncResourceState` makes the two outcomes separate variants: `error` is the
15
+ * only one carrying a message and it is never reachable with a value, `empty` is
16
+ * the only one carrying a resolved-but-empty value and it never carries a
17
+ * message. A component rendering one is structurally not rendering the other.
18
+ *
19
+ * This file is React-free so the state model, the emptiness rule and the
20
+ * Response readers can be unit-tested and reused outside a component.
21
+ */
22
+ /**
23
+ * - `idle` — no load has been attempted (the hook is disabled, or its inputs
24
+ * are not resolved yet). Distinct from `loading`: nothing is in flight.
25
+ * - `loading` — a load is in flight and no value is held.
26
+ * - `error` — the load failed. Carries the message and never a value.
27
+ * - `empty` — the load succeeded and the value is empty. Never carries a message.
28
+ * - `ready` — the load succeeded and the value is non-empty.
29
+ */
30
+ type AsyncResourceStatus = 'idle' | 'loading' | 'error' | 'empty' | 'ready';
31
+ /** Re-runs the load. Present on every variant so the error branch can never be
32
+ * rendered without the action that recovers from it. */
33
+ interface AsyncRetryable {
34
+ readonly retry: () => void;
35
+ }
36
+ type AsyncResourceState<T> = ({
37
+ readonly status: 'idle';
38
+ } & AsyncRetryable) | ({
39
+ readonly status: 'loading';
40
+ } & AsyncRetryable) | ({
41
+ readonly status: 'error';
42
+ readonly message: string;
43
+ readonly error: unknown;
44
+ } & AsyncRetryable) | ({
45
+ readonly status: 'empty';
46
+ readonly value: T;
47
+ } & AsyncRetryable) | ({
48
+ readonly status: 'ready';
49
+ readonly value: T;
50
+ } & AsyncRetryable);
51
+ /** The state model without the retry action — what a reducer produces. */
52
+ type AsyncResolution<T> = {
53
+ readonly status: 'idle';
54
+ } | {
55
+ readonly status: 'loading';
56
+ } | {
57
+ readonly status: 'error';
58
+ readonly message: string;
59
+ readonly error: unknown;
60
+ } | {
61
+ readonly status: 'empty';
62
+ readonly value: T;
63
+ } | {
64
+ readonly status: 'ready';
65
+ readonly value: T;
66
+ };
67
+ declare const DEFAULT_ASYNC_ERROR_MESSAGE = "Something went wrong. Please try again.";
68
+ /**
69
+ * Default emptiness rule: `null`/`undefined`, an empty array, an empty `Map` or
70
+ * `Set`. A string, a number and a plain object are `ready` — `''` and `{}` are
71
+ * legitimate values for the resources that produce them, and guessing otherwise
72
+ * would route a real answer into the empty branch. Pass `isEmpty` for a shape
73
+ * this cannot see into (`{ items: [] }`, a paged envelope, a count).
74
+ */
75
+ declare function defaultIsEmpty(value: unknown): boolean;
76
+ /** Best available human-readable message for a thrown value. Never returns an
77
+ * empty string — a blank error block reads as a rendering bug. */
78
+ declare function asyncErrorMessage(error: unknown, fallback?: string): string;
79
+ /** Classifies a successfully loaded value into `ready` or `empty`. */
80
+ declare function resolveAsyncValue<T>(value: T, isEmpty?: (value: T) => boolean): AsyncResolution<T>;
81
+ /**
82
+ * A non-ok HTTP response, as a throwable. `requireOk`/`readOkJson` raise this so
83
+ * a non-ok response reaches the `error` branch instead of an early `return` that
84
+ * leaves the caller rendering the empty branch.
85
+ */
86
+ declare class AsyncRequestError extends Error {
87
+ readonly status: number;
88
+ readonly statusText: string;
89
+ readonly url: string;
90
+ /** First 200 characters of the response body when it could be read, else `''`.
91
+ * Kept off `message` so a server's HTML error page never becomes UI copy. */
92
+ readonly body: string;
93
+ constructor(response: {
94
+ status: number;
95
+ statusText?: string;
96
+ url?: string;
97
+ }, body?: string);
98
+ }
99
+ /** Returns the response when ok; throws `AsyncRequestError` otherwise. Reads the
100
+ * body only on the failure path, so the caller keeps an unconsumed stream. */
101
+ declare function requireOk(response: Response): Promise<Response>;
102
+ /**
103
+ * `requireOk` + `response.json()`. Without `parse` the result is `unknown`, so a
104
+ * caller narrows at the JSON boundary rather than inheriting an unchecked shape;
105
+ * with `parse` the validator runs inside the load and a rejection lands in the
106
+ * `error` branch.
107
+ */
108
+ declare function readOkJson(response: Response): Promise<unknown>;
109
+ declare function readOkJson<T>(response: Response, parse: (data: unknown) => T): Promise<T>;
110
+
111
+ interface AsyncLoadContext {
112
+ /** Aborted when the inputs change, a retry supersedes this load, or the
113
+ * component unmounts. Forward it to `fetch` so a superseded request stops. */
114
+ readonly signal: AbortSignal;
115
+ }
116
+ interface UseAsyncResourceOptions<T> {
117
+ /**
118
+ * The one load. Reject (or throw) to reach the `error` branch — a non-ok
119
+ * response must reject too, which is what `requireOk`/`readOkJson` are for.
120
+ * Read from a ref internally, so an inline arrow does not re-trigger; `deps`
121
+ * is what declares when the load must run again.
122
+ */
123
+ load: (context: AsyncLoadContext) => Promise<T>;
124
+ /** Re-runs the load when any entry changes by `Object.is`, like `useEffect`. */
125
+ deps?: readonly unknown[];
126
+ /** `false` holds the resource at `idle` and runs nothing — for inputs that are
127
+ * not resolved yet. Flipping it to `true` starts the load. */
128
+ enabled?: boolean;
129
+ /** First-render seed (an SSR/loader page). The hook starts resolved and skips
130
+ * the first load. Read once — later identity changes are ignored, so a
131
+ * revalidating loader belongs in `deps`, not here. */
132
+ initialValue?: T;
133
+ /** Splits a successful load into `empty` vs `ready`. Default: `defaultIsEmpty`. */
134
+ isEmpty?: (value: T) => boolean;
135
+ /** Maps a thrown value to the message the `error` branch renders. */
136
+ errorMessage?: (error: unknown) => string;
137
+ }
138
+ /**
139
+ * The five-state fetch machine: `idle | loading | error | empty | ready`.
140
+ *
141
+ * What it guarantees, and what the hand-rolled versions it replaces did not:
142
+ *
143
+ * - a rejected load lands on `error` with a message and a `retry`, never on an
144
+ * empty list;
145
+ * - `empty` is only reachable from a load that actually succeeded;
146
+ * - a superseded load (inputs changed, retry pressed, component unmounted) is
147
+ * aborted and its late result is dropped by a monotonic sequence guard, so it
148
+ * cannot repaint a newer view.
149
+ */
150
+ declare function useAsyncResource<T>({ load, deps, enabled, initialValue, isEmpty, errorMessage, }: UseAsyncResourceOptions<T>): AsyncResourceState<T>;
151
+
152
+ /**
153
+ * The brand that makes "Saved" unreachable without a confirmed write.
154
+ *
155
+ * A resolved promise is not a success: `fetch` resolves on a 404, and the
156
+ * shipped defect this closes is a save button that rendered "Saved" because the
157
+ * only thing awaited was that the request came back at all. The success variant
158
+ * therefore carries a symbol no object literal can spell, so the only way into
159
+ * `succeeded` is `confirmWrite` / `confirmResponse` / `confirmJson` — each of
160
+ * which has already checked that the write landed.
161
+ */
162
+ declare const CONFIRMED_WRITE: unique symbol;
163
+ interface MutationConfirmed<T> {
164
+ readonly succeeded: true;
165
+ readonly value: T;
166
+ readonly [CONFIRMED_WRITE]: true;
167
+ }
168
+ interface MutationRejected {
169
+ readonly succeeded: false;
170
+ /** Safe to render: what the user is told the write did not do. */
171
+ readonly message: string;
172
+ readonly error?: unknown;
173
+ }
174
+ type MutationOutcome<T> = MutationConfirmed<T> | MutationRejected;
175
+ /** Confirms a write whose success is already established (an SDK call that
176
+ * throws on failure, a store returning its own typed outcome). The deliberate
177
+ * act is the point — this call is what an audit greps for. */
178
+ declare function confirmWrite<T>(value: T): MutationConfirmed<T>;
179
+ /** A write that did not land. Constructible by hand: failing loud is never the
180
+ * direction that needs guarding. */
181
+ declare function rejectWrite(message: string, error?: unknown): MutationRejected;
182
+ /** Confirms only a 2xx response. A 404/500 becomes a rejection carrying the
183
+ * status — never a success, whatever the promise did. */
184
+ declare function confirmResponse(response: Response): Promise<MutationOutcome<Response>>;
185
+ /** `confirmResponse` + a JSON body. A non-ok status, an unreadable body and a
186
+ * throwing `parse` are all rejections. */
187
+ declare function confirmJson<T>(response: Response, parse: (data: unknown) => T): Promise<MutationOutcome<T>>;
188
+ /** True only for a value built by one of the confirm helpers. Takes `unknown`
189
+ * because an untyped consumer can return anything from `mutate`. */
190
+ declare function isConfirmedWrite<T>(outcome: unknown): outcome is MutationConfirmed<T>;
191
+ type MutationState<T> = {
192
+ readonly status: 'idle';
193
+ } | {
194
+ readonly status: 'pending';
195
+ } | {
196
+ readonly status: 'succeeded';
197
+ readonly value: T;
198
+ } | {
199
+ readonly status: 'failed';
200
+ readonly message: string;
201
+ readonly error: unknown;
202
+ };
203
+ interface UseConfirmedMutationOptions<TInput, TValue> {
204
+ /**
205
+ * Performs the write and returns a confirmation. Anything else — including a
206
+ * hand-written `{ succeeded: true }` — is treated as a failed write, because
207
+ * an unbranded object is exactly the shape produced by code that never
208
+ * checked the response.
209
+ *
210
+ * The context signal aborts only when a later `run` supersedes this one. It is
211
+ * NOT aborted on unmount: a write the user asked for must not be cancelled by
212
+ * navigating away.
213
+ */
214
+ mutate: (input: TInput, context: AsyncLoadContext) => Promise<MutationOutcome<TValue>>;
215
+ /** Fires after the state reaches `succeeded` (latest run only). */
216
+ onSucceeded?: (value: TValue) => void;
217
+ /** Fires after the state reaches `failed` (latest run only). */
218
+ onFailed?: (message: string, error: unknown) => void;
219
+ /** Maps a thrown value to the message the `failed` state renders. */
220
+ errorMessage?: (error: unknown) => string;
221
+ }
222
+ interface ConfirmedMutation<TInput, TValue> {
223
+ readonly state: MutationState<TValue>;
224
+ /** Runs the write. Never rejects — the outcome is returned and mirrored into
225
+ * `state`. Concurrent runs are last-write-wins; disable the control while
226
+ * `state.status === 'pending'`. */
227
+ readonly run: (input: TInput) => Promise<MutationOutcome<TValue>>;
228
+ /** Back to `idle` (dismisses a "Saved" or error affordance). */
229
+ readonly reset: () => void;
230
+ }
231
+ /**
232
+ * `idle | pending | succeeded | failed` over a write that must confirm itself.
233
+ *
234
+ * `succeeded` is reachable only through a branded confirmation, so the audited
235
+ * "Saved on a 404" bug cannot be written with this hook: the 404 path produces
236
+ * `failed` carrying the status, and a `mutate` that forgot to check produces
237
+ * `failed` carrying the contract violation rather than a success it never
238
+ * earned.
239
+ */
240
+ declare function useConfirmedMutation<TInput, TValue>({ mutate, onSucceeded, onFailed, errorMessage, }: UseConfirmedMutationOptions<TInput, TValue>): ConfirmedMutation<TInput, TValue>;
241
+
242
+ interface AsyncEmptyAction {
243
+ label: string;
244
+ onClick: () => void;
245
+ }
246
+ interface AsyncEmptySpec {
247
+ /** What is not there, in the reader's words ("No templates yet"). Required:
248
+ * an empty state with nothing to say is the state this module exists to
249
+ * stop being mistaken for a failure. */
250
+ title: string;
251
+ description?: string;
252
+ /** The next action. An element is rendered as supplied (a link, a dialog
253
+ * trigger); the object form renders the standard button. */
254
+ action?: AsyncEmptyAction | ReactElement;
255
+ }
256
+ interface AsyncErrorRenderProps {
257
+ message: string;
258
+ retry: () => void;
259
+ }
260
+ interface AsyncViewProps<T> {
261
+ state: AsyncResourceState<T>;
262
+ /** Rendered only for `ready`, with the loaded value — the branch cannot be
263
+ * entered without one. */
264
+ children: (value: T) => ReactNode;
265
+ /** Required: `empty` must name what is missing and what to do about it. */
266
+ empty: AsyncEmptySpec | ReactElement;
267
+ /** Must return an element. Returning nothing is what produced the blank
268
+ * screens this component replaces, so a nullish return falls back to the
269
+ * built-in block rather than rendering nothing. */
270
+ renderLoading?: () => ReactElement;
271
+ renderError?: (props: AsyncErrorRenderProps) => ReactElement;
272
+ /** `idle` renders the loading block by default — from the reader's side,
273
+ * "not started" and "in flight" are the same wait. */
274
+ renderIdle?: () => ReactElement;
275
+ loadingLabel?: string;
276
+ retryLabel?: string;
277
+ /** Applied to the wrapper around the non-`ready` branches. `ready` renders the
278
+ * children with no wrapper element, so grids and lists keep their layout. */
279
+ className?: string;
280
+ }
281
+ /**
282
+ * Renders the branch the state is actually in.
283
+ *
284
+ * The three anti-patterns this replaces (`catch` that only clears a loading
285
+ * flag, early return on a non-ok response, bare `null` while loading) all end at
286
+ * the same rendered output as a successful-but-empty load. Here every branch is
287
+ * reached from a different variant and each renders visibly: `loading` and
288
+ * `idle` render a labelled busy block, `error` renders the message plus the
289
+ * retry, `empty` renders the caller's copy and next action, and `ready` is the
290
+ * only branch with a value to hand to `children`.
291
+ */
292
+ declare function AsyncView<T>({ state, children, empty, renderLoading, renderError, renderIdle, loadingLabel, retryLabel, className, }: AsyncViewProps<T>): ReactElement;
293
+ interface MutationStatusLabels {
294
+ pending?: string;
295
+ succeeded?: string;
296
+ }
297
+ interface MutationStatusProps<T> {
298
+ state: MutationState<T>;
299
+ labels?: MutationStatusLabels;
300
+ className?: string;
301
+ }
302
+ /**
303
+ * The write's own status line. "Saved" renders only from `succeeded`, which
304
+ * `useConfirmedMutation` can only reach through a confirmed write, so the label
305
+ * cannot appear over a failed request.
306
+ */
307
+ declare function MutationStatus<T>({ state, labels, className }: MutationStatusProps<T>): ReactElement | null;
308
+
309
+ export { type AsyncEmptyAction, type AsyncEmptySpec, type AsyncErrorRenderProps, type AsyncLoadContext, AsyncRequestError, type AsyncResolution, type AsyncResourceState, type AsyncResourceStatus, type AsyncRetryable, AsyncView, type AsyncViewProps, CONFIRMED_WRITE, type ConfirmedMutation, DEFAULT_ASYNC_ERROR_MESSAGE, type MutationConfirmed, type MutationOutcome, type MutationRejected, type MutationState, MutationStatus, type MutationStatusLabels, type MutationStatusProps, type UseAsyncResourceOptions, type UseConfirmedMutationOptions, asyncErrorMessage, confirmJson, confirmResponse, confirmWrite, defaultIsEmpty, isConfirmedWrite, readOkJson, rejectWrite, requireOk, resolveAsyncValue, useAsyncResource, useConfirmedMutation };
@@ -0,0 +1,327 @@
1
+ // src/web-react/async/state.ts
2
+ var DEFAULT_ASYNC_ERROR_MESSAGE = "Something went wrong. Please try again.";
3
+ function defaultIsEmpty(value) {
4
+ if (value === null || value === void 0) return true;
5
+ if (Array.isArray(value)) return value.length === 0;
6
+ if (value instanceof Map || value instanceof Set) return value.size === 0;
7
+ return false;
8
+ }
9
+ function hasMessage(value) {
10
+ return "message" in value;
11
+ }
12
+ function asyncErrorMessage(error, fallback = DEFAULT_ASYNC_ERROR_MESSAGE) {
13
+ if (typeof error === "string" && error.trim() !== "") return error;
14
+ if (typeof error === "object" && error !== null && hasMessage(error)) {
15
+ const message = error.message;
16
+ if (typeof message === "string" && message.trim() !== "") return message;
17
+ }
18
+ return fallback;
19
+ }
20
+ function resolveAsyncValue(value, isEmpty = defaultIsEmpty) {
21
+ return isEmpty(value) ? { status: "empty", value } : { status: "ready", value };
22
+ }
23
+ var AsyncRequestError = class extends Error {
24
+ status;
25
+ statusText;
26
+ url;
27
+ /** First 200 characters of the response body when it could be read, else `''`.
28
+ * Kept off `message` so a server's HTML error page never becomes UI copy. */
29
+ body;
30
+ constructor(response, body = "") {
31
+ const statusText = response.statusText ?? "";
32
+ super(`Request failed (${response.status}${statusText ? ` ${statusText}` : ""})`);
33
+ this.name = "AsyncRequestError";
34
+ this.status = response.status;
35
+ this.statusText = statusText;
36
+ this.url = response.url ?? "";
37
+ this.body = body;
38
+ }
39
+ };
40
+ async function readBodySnippet(response) {
41
+ try {
42
+ return (await response.text()).slice(0, 200);
43
+ } catch {
44
+ return "";
45
+ }
46
+ }
47
+ async function requireOk(response) {
48
+ if (response.ok) return response;
49
+ throw new AsyncRequestError(response, await readBodySnippet(response));
50
+ }
51
+ async function readOkJson(response, parse) {
52
+ await requireOk(response);
53
+ let data;
54
+ try {
55
+ data = await response.json();
56
+ } catch (error) {
57
+ throw new Error("The response was not valid JSON.", { cause: error });
58
+ }
59
+ return parse ? parse(data) : data;
60
+ }
61
+
62
+ // src/web-react/async/use-async-resource.ts
63
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
64
+ function useChangeToken(deps) {
65
+ const ref = useRef({ deps, token: 0 });
66
+ const changed = ref.current.deps.length !== deps.length || deps.some((dep, index) => !Object.is(dep, ref.current.deps[index]));
67
+ if (changed) ref.current = { deps, token: ref.current.token + 1 };
68
+ return ref.current.token;
69
+ }
70
+ var NO_DEPS = [];
71
+ function useAsyncResource({
72
+ load,
73
+ deps = NO_DEPS,
74
+ enabled = true,
75
+ initialValue,
76
+ isEmpty,
77
+ errorMessage
78
+ }) {
79
+ const loadRef = useRef(load);
80
+ loadRef.current = load;
81
+ const isEmptyRef = useRef(isEmpty ?? defaultIsEmpty);
82
+ isEmptyRef.current = isEmpty ?? defaultIsEmpty;
83
+ const errorMessageRef = useRef(errorMessage);
84
+ errorMessageRef.current = errorMessage;
85
+ const [resolution, setResolution] = useState(() => {
86
+ if (initialValue !== void 0) return resolveAsyncValue(initialValue, isEmpty ?? defaultIsEmpty);
87
+ return enabled ? { status: "loading" } : { status: "idle" };
88
+ });
89
+ const [reloadKey, setReloadKey] = useState(0);
90
+ const seqRef = useRef(0);
91
+ const seededRef = useRef(initialValue !== void 0);
92
+ const token = useChangeToken(deps);
93
+ useEffect(() => {
94
+ if (!enabled) return;
95
+ if (seededRef.current) {
96
+ seededRef.current = false;
97
+ return;
98
+ }
99
+ const seq = ++seqRef.current;
100
+ const controller = new AbortController();
101
+ setResolution({ status: "loading" });
102
+ void (async () => {
103
+ try {
104
+ const value = await loadRef.current({ signal: controller.signal });
105
+ if (seq !== seqRef.current || controller.signal.aborted) return;
106
+ setResolution(resolveAsyncValue(value, isEmptyRef.current));
107
+ } catch (error) {
108
+ if (seq !== seqRef.current || controller.signal.aborted) return;
109
+ setResolution({
110
+ status: "error",
111
+ message: errorMessageRef.current ? errorMessageRef.current(error) : asyncErrorMessage(error),
112
+ error
113
+ });
114
+ }
115
+ })();
116
+ return () => controller.abort();
117
+ }, [token, enabled, reloadKey]);
118
+ const retry = useCallback(() => {
119
+ setReloadKey((key) => key + 1);
120
+ }, []);
121
+ return useMemo(() => {
122
+ switch (resolution.status) {
123
+ case "ready":
124
+ return { status: "ready", value: resolution.value, retry };
125
+ case "empty":
126
+ return { status: "empty", value: resolution.value, retry };
127
+ case "error":
128
+ return { status: "error", message: resolution.message, error: resolution.error, retry };
129
+ case "loading":
130
+ return { status: "loading", retry };
131
+ case "idle":
132
+ return { status: "idle", retry };
133
+ }
134
+ }, [resolution, retry]);
135
+ }
136
+
137
+ // src/web-react/async/use-confirmed-mutation.ts
138
+ import { useCallback as useCallback2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
139
+ var CONFIRMED_WRITE = /* @__PURE__ */ Symbol("agent-app.confirmed-write");
140
+ function confirmWrite(value) {
141
+ return { succeeded: true, value, [CONFIRMED_WRITE]: true };
142
+ }
143
+ function rejectWrite(message, error) {
144
+ return error === void 0 ? { succeeded: false, message } : { succeeded: false, message, error };
145
+ }
146
+ async function confirmResponse(response) {
147
+ try {
148
+ return confirmWrite(await requireOk(response));
149
+ } catch (error) {
150
+ return rejectWrite(asyncErrorMessage(error), error);
151
+ }
152
+ }
153
+ async function confirmJson(response, parse) {
154
+ try {
155
+ return confirmWrite(await readOkJson(response, parse));
156
+ } catch (error) {
157
+ return rejectWrite(asyncErrorMessage(error), error);
158
+ }
159
+ }
160
+ function isConfirmedWrite(outcome) {
161
+ if (typeof outcome !== "object" || outcome === null) return false;
162
+ return outcome[CONFIRMED_WRITE] === true;
163
+ }
164
+ function asRejection(outcome) {
165
+ if (typeof outcome !== "object" || outcome === null) return null;
166
+ const candidate = outcome;
167
+ if (candidate.succeeded !== false) return null;
168
+ const message = typeof candidate.message === "string" && candidate.message.trim() !== "" ? candidate.message : UNCONFIRMED_MESSAGE;
169
+ return rejectWrite(message, candidate.error);
170
+ }
171
+ var UNCONFIRMED_MESSAGE = "The write could not be confirmed.";
172
+ var UNCONFIRMED_CONTRACT = "mutate() resolved without a confirmation. Return confirmWrite(value), confirmResponse(response) or confirmJson(response, parse) so the success state proves the write landed.";
173
+ function useConfirmedMutation({
174
+ mutate,
175
+ onSucceeded,
176
+ onFailed,
177
+ errorMessage
178
+ }) {
179
+ const mutateRef = useRef2(mutate);
180
+ mutateRef.current = mutate;
181
+ const onSucceededRef = useRef2(onSucceeded);
182
+ onSucceededRef.current = onSucceeded;
183
+ const onFailedRef = useRef2(onFailed);
184
+ onFailedRef.current = onFailed;
185
+ const errorMessageRef = useRef2(errorMessage);
186
+ errorMessageRef.current = errorMessage;
187
+ const [state, setState] = useState2({ status: "idle" });
188
+ const seqRef = useRef2(0);
189
+ const inFlightRef = useRef2(null);
190
+ const run = useCallback2(async (input) => {
191
+ inFlightRef.current?.abort();
192
+ const controller = new AbortController();
193
+ inFlightRef.current = controller;
194
+ const seq = ++seqRef.current;
195
+ setState({ status: "pending" });
196
+ let outcome;
197
+ try {
198
+ const returned = await mutateRef.current(input, { signal: controller.signal });
199
+ outcome = isConfirmedWrite(returned) ? returned : asRejection(returned) ?? rejectWrite(UNCONFIRMED_MESSAGE, new Error(UNCONFIRMED_CONTRACT));
200
+ } catch (error) {
201
+ outcome = rejectWrite(errorMessageRef.current ? errorMessageRef.current(error) : asyncErrorMessage(error), error);
202
+ }
203
+ if (seq !== seqRef.current) return outcome;
204
+ if (outcome.succeeded) {
205
+ setState({ status: "succeeded", value: outcome.value });
206
+ onSucceededRef.current?.(outcome.value);
207
+ } else {
208
+ setState({ status: "failed", message: outcome.message, error: outcome.error });
209
+ onFailedRef.current?.(outcome.message, outcome.error);
210
+ }
211
+ return outcome;
212
+ }, []);
213
+ const reset = useCallback2(() => {
214
+ seqRef.current += 1;
215
+ inFlightRef.current?.abort();
216
+ inFlightRef.current = null;
217
+ setState({ status: "idle" });
218
+ }, []);
219
+ return useMemo2(() => ({ state, run, reset }), [state, run, reset]);
220
+ }
221
+
222
+ // src/web-react/async/async-view.tsx
223
+ import { isValidElement } from "react";
224
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
225
+ var BLOCK_CLASS = "flex flex-col items-center justify-center gap-2 px-4 py-10 text-center";
226
+ function AsyncView({
227
+ state,
228
+ children,
229
+ empty,
230
+ renderLoading,
231
+ renderError,
232
+ renderIdle,
233
+ loadingLabel = "Loading\u2026",
234
+ retryLabel = "Retry",
235
+ className
236
+ }) {
237
+ if (state.status === "ready") return /* @__PURE__ */ jsx(Fragment, { children: children(state.value) });
238
+ const branch = () => {
239
+ switch (state.status) {
240
+ case "idle":
241
+ return renderIdle?.() ?? /* @__PURE__ */ jsx(LoadingBlock, { label: loadingLabel });
242
+ case "loading":
243
+ return renderLoading?.() ?? /* @__PURE__ */ jsx(LoadingBlock, { label: loadingLabel });
244
+ case "error":
245
+ return renderError?.({ message: state.message, retry: state.retry }) ?? /* @__PURE__ */ jsx(ErrorBlock, { message: state.message, retry: state.retry, retryLabel });
246
+ case "empty":
247
+ if (isValidElement(empty)) return empty;
248
+ return typeof empty === "object" && empty !== null && typeof empty.title === "string" ? /* @__PURE__ */ jsx(EmptyBlock, { spec: empty }) : /* @__PURE__ */ jsx(EmptyBlock, { spec: { title: "Nothing here yet." } });
249
+ }
250
+ };
251
+ return /* @__PURE__ */ jsx("div", { "data-async-state": state.status, className, children: branch() });
252
+ }
253
+ function LoadingBlock({ label }) {
254
+ return /* @__PURE__ */ jsxs("div", { role: "status", "aria-live": "polite", "aria-busy": "true", className: BLOCK_CLASS, children: [
255
+ /* @__PURE__ */ jsx(
256
+ "span",
257
+ {
258
+ className: "h-4 w-4 animate-spin rounded-full border-2 border-border border-t-transparent",
259
+ "aria-hidden": "true"
260
+ }
261
+ ),
262
+ /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: label })
263
+ ] });
264
+ }
265
+ function ErrorBlock({
266
+ message,
267
+ retry,
268
+ retryLabel
269
+ }) {
270
+ return /* @__PURE__ */ jsxs("div", { role: "alert", className: BLOCK_CLASS, children: [
271
+ /* @__PURE__ */ jsx("p", { className: "max-w-md text-sm text-muted-foreground", children: message }),
272
+ /* @__PURE__ */ jsx(
273
+ "button",
274
+ {
275
+ type: "button",
276
+ onClick: retry,
277
+ className: "h-8 rounded-md border border-border px-3 text-xs font-medium text-foreground transition hover:bg-accent/30",
278
+ children: retryLabel
279
+ }
280
+ )
281
+ ] });
282
+ }
283
+ function EmptyBlock({ spec }) {
284
+ return /* @__PURE__ */ jsxs("div", { className: BLOCK_CLASS, children: [
285
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-foreground", children: spec.title }),
286
+ spec.description ? /* @__PURE__ */ jsx("p", { className: "max-w-md text-sm text-muted-foreground", children: spec.description }) : null,
287
+ spec.action ? isValidElement(spec.action) ? spec.action : /* @__PURE__ */ jsx(
288
+ "button",
289
+ {
290
+ type: "button",
291
+ onClick: spec.action.onClick,
292
+ className: "h-8 rounded-md border border-border px-3 text-xs font-medium text-foreground transition hover:bg-accent/30",
293
+ children: spec.action.label
294
+ }
295
+ ) : null
296
+ ] });
297
+ }
298
+ function MutationStatus({ state, labels, className }) {
299
+ if (state.status === "idle") return null;
300
+ if (state.status === "pending") {
301
+ return /* @__PURE__ */ jsx("span", { role: "status", "aria-live": "polite", className: className ?? "text-xs text-muted-foreground", children: labels?.pending ?? "Saving\u2026" });
302
+ }
303
+ if (state.status === "succeeded") {
304
+ return /* @__PURE__ */ jsx("span", { role: "status", "aria-live": "polite", className: className ?? "text-xs text-muted-foreground", children: labels?.succeeded ?? "Saved" });
305
+ }
306
+ return /* @__PURE__ */ jsx("span", { role: "alert", className: className ?? "text-xs text-destructive", children: state.message });
307
+ }
308
+ export {
309
+ AsyncRequestError,
310
+ AsyncView,
311
+ CONFIRMED_WRITE,
312
+ DEFAULT_ASYNC_ERROR_MESSAGE,
313
+ MutationStatus,
314
+ asyncErrorMessage,
315
+ confirmJson,
316
+ confirmResponse,
317
+ confirmWrite,
318
+ defaultIsEmpty,
319
+ isConfirmedWrite,
320
+ readOkJson,
321
+ rejectWrite,
322
+ requireOk,
323
+ resolveAsyncValue,
324
+ useAsyncResource,
325
+ useConfirmedMutation
326
+ };
327
+ //# sourceMappingURL=index.js.map