@wodecorp/openui-vue-a2ui 0.1.3 → 0.1.5

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/dist/index.mjs CHANGED
@@ -1,763 +1,4 @@
1
- import { createParser } from "@openuidev/lang-core";
2
- import { i as toJsonObject, n as dataModelToOpenUIState, r as mergeOpenUIStateIntoDataModel, t as applyDataModelUpdate } from "./json-pointer-Cdqen-LB.mjs";
3
- import { z } from "zod/v4";
4
- // src/protocol-schema.ts
5
- const jsonValueSchema = z.json();
6
- const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
7
- const versionSchema = z.literal("v1.0");
8
- const surfaceIdSchema = z.string();
9
- const extensionKeySchema = z.string().regex(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u);
10
- const extensionsSchema = z.record(extensionKeySchema, jsonValueSchema);
11
- const messageMetadataSchema = z.strictObject({ extensions: extensionsSchema.optional() });
12
- const langComponentsSchema = z.array(z.string().min(1)).min(1).describe("Complete OpenUI Lang statements or statement blocks, merged by statement ID in array order.");
13
- const a2uiFunctionCallSchema = z.strictObject({
14
- call: z.string(),
15
- catalogId: z.string().optional(),
16
- args: jsonObjectSchema.optional()
17
- });
18
- const a2uiFunctionResponseSchema = z.union([z.strictObject({
19
- functionCallId: z.string(),
20
- value: jsonValueSchema
21
- }), z.strictObject({
22
- functionCallId: z.string(),
23
- error: z.strictObject({
24
- code: z.string(),
25
- message: z.string()
26
- })
27
- })]);
28
- const createSurfaceMessageSchema = z.strictObject({
29
- version: versionSchema,
30
- createSurface: z.strictObject({
31
- surfaceId: surfaceIdSchema,
32
- catalogId: z.string().optional(),
33
- sendDataModel: z.boolean().optional().meta({ default: false }),
34
- components: langComponentsSchema.optional().describe("Optional initial OpenUI Lang statements for single-message surface creation."),
35
- dataModel: jsonObjectSchema.optional(),
36
- metadata: messageMetadataSchema.optional()
37
- })
38
- });
39
- const updateComponentsMessageSchema = z.strictObject({
40
- version: versionSchema,
41
- updateComponents: z.strictObject({
42
- surfaceId: surfaceIdSchema,
43
- components: langComponentsSchema
44
- })
45
- });
46
- const updateDataModelMessageSchema = z.strictObject({
47
- version: versionSchema,
48
- updateDataModel: z.strictObject({
49
- surfaceId: surfaceIdSchema,
50
- path: z.string().optional(),
51
- value: jsonValueSchema
52
- })
53
- });
54
- const deleteSurfaceMessageSchema = z.strictObject({
55
- version: versionSchema,
56
- deleteSurface: z.strictObject({ surfaceId: surfaceIdSchema })
57
- });
58
- const callRendererFunctionMessageSchema = z.strictObject({
59
- version: versionSchema,
60
- callRendererFunction: z.strictObject({
61
- functionCallId: z.string(),
62
- callFunction: a2uiFunctionCallSchema.extend({ catalogId: z.string() })
63
- })
64
- });
65
- const agentFunctionResponseMessageSchema = z.strictObject({
66
- version: versionSchema,
67
- agentFunctionResponse: a2uiFunctionResponseSchema
68
- });
69
- const agentToRendererMessageSchema = z.union([
70
- createSurfaceMessageSchema,
71
- updateComponentsMessageSchema,
72
- updateDataModelMessageSchema,
73
- deleteSurfaceMessageSchema,
74
- callRendererFunctionMessageSchema,
75
- agentFunctionResponseMessageSchema
76
- ]);
77
- const actionMessageSchema = z.strictObject({
78
- version: versionSchema,
79
- action: z.strictObject({
80
- name: z.string(),
81
- userMessage: z.string().optional(),
82
- surfaceId: surfaceIdSchema,
83
- sourceComponentId: z.string(),
84
- timestamp: z.iso.datetime({ offset: true }),
85
- context: jsonObjectSchema,
86
- metadata: messageMetadataSchema.optional()
87
- })
88
- });
89
- const callAgentFunctionMessageSchema = z.strictObject({
90
- version: versionSchema,
91
- callAgentFunction: z.strictObject({
92
- surfaceId: surfaceIdSchema,
93
- functionCallId: z.string(),
94
- callFunction: a2uiFunctionCallSchema
95
- })
96
- });
97
- const rendererFunctionResponseMessageSchema = z.strictObject({
98
- version: versionSchema,
99
- rendererFunctionResponse: a2uiFunctionResponseSchema
100
- });
101
- const validationErrorCodeSchema = z.enum([
102
- "VALIDATION_FAILED",
103
- "UNALLOWED_PARENT",
104
- "UNALLOWED_CHILD"
105
- ]);
106
- const validationFailedErrorMessageSchema = z.strictObject({
107
- version: versionSchema,
108
- error: z.strictObject({
109
- code: validationErrorCodeSchema,
110
- surfaceId: surfaceIdSchema,
111
- path: z.string(),
112
- message: z.string()
113
- })
114
- });
115
- const genericErrorCodeSchema = z.string().refine((code) => !validationErrorCodeSchema.options.includes(code));
116
- const genericErrorMessageSchema = z.union([z.strictObject({
117
- version: versionSchema,
118
- error: z.strictObject({
119
- code: genericErrorCodeSchema,
120
- message: z.string(),
121
- surfaceId: surfaceIdSchema
122
- })
123
- }), z.strictObject({
124
- version: versionSchema,
125
- error: z.strictObject({
126
- code: genericErrorCodeSchema,
127
- message: z.string(),
128
- functionCallId: z.string()
129
- })
130
- })]);
131
- const rendererToAgentMessageSchema = z.union([
132
- actionMessageSchema,
133
- callAgentFunctionMessageSchema,
134
- rendererFunctionResponseMessageSchema,
135
- validationFailedErrorMessageSchema,
136
- genericErrorMessageSchema
137
- ]);
138
- const rendererCapabilitiesSchema = z.strictObject({ "v1.0": z.strictObject({
139
- supportedCatalogIds: z.array(z.string()),
140
- inlineCatalogs: z.array(jsonObjectSchema).optional()
141
- }) });
142
- const agentCapabilitiesSchema = z.strictObject({ "v1.0": z.strictObject({
143
- supportedCatalogIds: z.array(z.string()).optional(),
144
- acceptsInlineCatalogs: z.boolean().optional().meta({ default: false })
145
- }) });
146
- const rendererDataModelSchema = z.strictObject({
147
- version: versionSchema,
148
- surfaces: z.record(z.string(), jsonObjectSchema)
149
- });
150
- // src/runtime-schema.ts
151
- function escapePointerToken(token) {
152
- return String(token).replace(/~/g, "~0").replace(/\//g, "~1");
153
- }
154
- function issuePath(path) {
155
- return path.length === 0 ? "/" : `/${path.map(escapePointerToken).join("/")}`;
156
- }
157
- function validateAgentToRendererMessage(input) {
158
- const object = input != null && typeof input === "object" && !Array.isArray(input) ? input : void 0;
159
- const presentKeys = object ? [
160
- "createSurface",
161
- "updateComponents",
162
- "updateDataModel",
163
- "deleteSurface",
164
- "callRendererFunction",
165
- "agentFunctionResponse"
166
- ].filter((key) => Object.prototype.hasOwnProperty.call(object, key)) : [];
167
- const result = (presentKeys.length === 1 ? {
168
- createSurface: createSurfaceMessageSchema,
169
- updateComponents: updateComponentsMessageSchema,
170
- updateDataModel: updateDataModelMessageSchema,
171
- deleteSurface: deleteSurfaceMessageSchema,
172
- callRendererFunction: callRendererFunctionMessageSchema,
173
- agentFunctionResponse: agentFunctionResponseMessageSchema
174
- }[presentKeys[0]] : agentToRendererMessageSchema).safeParse(input);
175
- if (result.success) return {
176
- success: true,
177
- message: result.data
178
- };
179
- return {
180
- success: false,
181
- issues: result.error.issues.map((issue) => ({
182
- path: issuePath(issue.path),
183
- message: issue.message
184
- }))
185
- };
186
- }
187
- // src/statement-patch.ts
188
- const STATEMENT_PATTERN = /^(\$?[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([\s\S]*)$/u;
189
- function stripFences(source) {
190
- const trimmed = source.trim();
191
- if (!trimmed.startsWith("```")) return trimmed;
192
- const firstLineEnd = trimmed.indexOf("\n");
193
- const lastFence = trimmed.lastIndexOf("```");
194
- if (firstLineEnd === -1 || lastFence <= firstLineEnd) return trimmed;
195
- return trimmed.slice(firstLineEnd + 1, lastFence).trim();
196
- }
197
- function splitStatements(source) {
198
- const statements = [];
199
- let depth = 0;
200
- let ternaryDepth = 0;
201
- let quote = false;
202
- let escaped = false;
203
- let start = 0;
204
- for (let index = 0; index < source.length; index += 1) {
205
- const character = source[index];
206
- if (escaped) {
207
- escaped = false;
208
- continue;
209
- }
210
- if (character === "\\" && quote) {
211
- escaped = true;
212
- continue;
213
- }
214
- if (quote) {
215
- if (character === quote) quote = false;
216
- continue;
217
- }
218
- if (character === "\"" || character === "'") {
219
- quote = character;
220
- continue;
221
- }
222
- if (character === "(" || character === "[" || character === "{") depth += 1;
223
- else if (character === ")" || character === "]" || character === "}") depth = Math.max(0, depth - 1);
224
- else if (character === "?" && depth === 0) ternaryDepth += 1;
225
- else if (character === ":" && depth === 0 && ternaryDepth > 0) ternaryDepth -= 1;
226
- else if (character === "\n" && depth === 0 && ternaryDepth === 0) {
227
- let next = index + 1;
228
- while (next < source.length && /\s/u.test(source[next])) next += 1;
229
- if (source[next] === "?") continue;
230
- const statement = source.slice(start, index).trim();
231
- if (statement) statements.push(statement);
232
- start = index + 1;
233
- }
234
- }
235
- const finalStatement = source.slice(start).trim();
236
- if (finalStatement) statements.push(finalStatement);
237
- return statements;
238
- }
239
- function parseStatements(source) {
240
- return splitStatements(stripFences(source)).map((raw) => {
241
- const match = STATEMENT_PATTERN.exec(raw);
242
- if (!match) throw new Error(`Invalid OpenUI Lang statement: ${raw}`);
243
- return {
244
- id: match[1],
245
- expression: match[2].trim(),
246
- raw
247
- };
248
- });
249
- }
250
- /**
251
- * Applies statement-level A2UI component patches without removing temporarily
252
- * unreachable statements. A later update may attach those statements to root.
253
- */
254
- function mergeComponentStatements(existing, components) {
255
- const statements = /* @__PURE__ */ new Map();
256
- const order = [];
257
- const upsert = (source, allowDeletion) => {
258
- for (const statement of parseStatements(source)) {
259
- if (allowDeletion && statement.expression === "null") {
260
- statements.delete(statement.id);
261
- const index = order.indexOf(statement.id);
262
- if (index !== -1) order.splice(index, 1);
263
- continue;
264
- }
265
- if (!statements.has(statement.id)) order.push(statement.id);
266
- statements.set(statement.id, statement.raw);
267
- }
268
- };
269
- if (existing.trim()) upsert(existing, false);
270
- for (const component of components) upsert(component, true);
271
- return order.map((id) => statements.get(id)).join("\n");
272
- }
273
- // src/client.ts
274
- var A2UIFunctionError = class extends Error {
275
- code;
276
- constructor(code, message) {
277
- super(message);
278
- this.name = "A2UIFunctionError";
279
- this.code = code;
280
- }
281
- };
282
- function defaultId() {
283
- return globalThis.crypto?.randomUUID?.() ?? `a2ui-${Date.now()}-${Math.random().toString(16).slice(2)}`;
284
- }
285
- function parseError(error) {
286
- return {
287
- source: "parser",
288
- code: error.code,
289
- message: error.message,
290
- statementId: error.statementId,
291
- component: error.component,
292
- path: error.path
293
- };
294
- }
295
- function isCreateSurface(message) {
296
- return "createSurface" in message;
297
- }
298
- function isUpdateComponents(message) {
299
- return "updateComponents" in message;
300
- }
301
- function isUpdateDataModel(message) {
302
- return "updateDataModel" in message;
303
- }
304
- function isDeleteSurface(message) {
305
- return "deleteSurface" in message;
306
- }
307
- function isCallRendererFunction(message) {
308
- return "callRendererFunction" in message;
309
- }
310
- function record(value) {
311
- return value != null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
312
- }
313
- function validationTarget(input) {
314
- const message = record(input);
315
- if (!message) return {};
316
- for (const key of [
317
- "createSurface",
318
- "updateComponents",
319
- "updateDataModel",
320
- "deleteSurface"
321
- ]) {
322
- const payload = record(message[key]);
323
- if (typeof payload?.surfaceId === "string") return { surfaceId: payload.surfaceId };
324
- }
325
- for (const key of ["callRendererFunction", "agentFunctionResponse"]) {
326
- const payload = record(message[key]);
327
- if (typeof payload?.functionCallId === "string") return { functionCallId: payload.functionCallId };
328
- }
329
- return {};
330
- }
331
- var A2UIClient = class {
332
- #parser;
333
- #functions;
334
- #onMessage;
335
- #rendererCapabilities;
336
- #now;
337
- #createId;
338
- #surfaces = /* @__PURE__ */ new Map();
339
- #surfaceListeners = /* @__PURE__ */ new Set();
340
- #messageListeners = /* @__PURE__ */ new Set();
341
- #pendingAgentFunctions = /* @__PURE__ */ new Map();
342
- #revision = 0;
343
- constructor(options) {
344
- this.#parser = createParser(options.schema, options.rootName);
345
- this.#functions = options.functions;
346
- this.#onMessage = options.onMessage;
347
- this.#rendererCapabilities = options.rendererCapabilities;
348
- this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
349
- this.#createId = options.createId ?? defaultId;
350
- }
351
- subscribe(listener) {
352
- this.#surfaceListeners.add(listener);
353
- return () => this.#surfaceListeners.delete(listener);
354
- }
355
- subscribeMessages(listener) {
356
- this.#messageListeners.add(listener);
357
- return () => this.#messageListeners.delete(listener);
358
- }
359
- getSurface(surfaceId) {
360
- return this.#surfaces.get(surfaceId);
361
- }
362
- getSurfaces() {
363
- return [...this.#surfaces.values()];
364
- }
365
- getRendererDataModel() {
366
- const surfaces = Object.fromEntries([...this.#surfaces].filter(([, surface]) => surface.sendDataModel).map(([surfaceId, surface]) => [surfaceId, structuredClone(surface.dataModel)]));
367
- if (Object.keys(surfaces).length === 0) return void 0;
368
- return {
369
- version: "v1.0",
370
- surfaces
371
- };
372
- }
373
- getRendererMetadata() {
374
- const dataModel = this.getRendererDataModel();
375
- return {
376
- ...this.#rendererCapabilities ? { a2uiRendererCapabilities: structuredClone(this.#rendererCapabilities) } : {},
377
- ...dataModel ? { a2uiRendererDataModel: dataModel } : {}
378
- };
379
- }
380
- async process(input) {
381
- const outbound = [];
382
- const capture = (next) => outbound.push(next);
383
- this.#messageListeners.add(capture);
384
- try {
385
- const validated = validateAgentToRendererMessage(input);
386
- if (!validated.success) return this.#invalidMessage(input, validated.issues, outbound);
387
- const message = validated.message;
388
- if (isCreateSurface(message)) return this.#createSurface(message, outbound);
389
- if (isUpdateComponents(message)) return this.#updateComponents(message, outbound);
390
- if (isUpdateDataModel(message)) return this.#updateDataModel(message, outbound);
391
- if (isDeleteSurface(message)) return this.#deleteSurface(message, outbound);
392
- if (isCallRendererFunction(message)) return await this.#callRendererFunction(message, outbound);
393
- return this.#agentFunctionResponse(message, outbound);
394
- } finally {
395
- this.#messageListeners.delete(capture);
396
- }
397
- }
398
- updateSurfaceFromOpenUIState(surfaceId, state) {
399
- const surface = this.#surfaces.get(surfaceId);
400
- if (!surface) return false;
401
- const dataModel = mergeOpenUIStateIntoDataModel(surface.dataModel, state);
402
- if (JSON.stringify(dataModel) === JSON.stringify(surface.dataModel)) return false;
403
- this.#replaceSurface({
404
- ...surface,
405
- dataModel
406
- });
407
- return true;
408
- }
409
- dispatchOpenUIAction(surfaceId, event, options = {}) {
410
- const eventSourceComponentId = event.sourceComponentId;
411
- const context = {
412
- ...toJsonObject(event.params),
413
- ...event.formState ? { formState: toJsonObject(event.formState) } : {},
414
- ...options.context
415
- };
416
- this.dispatchAction({
417
- surfaceId,
418
- sourceComponentId: options.sourceComponentId ?? (typeof eventSourceComponentId === "string" ? eventSourceComponentId : "root"),
419
- name: options.name ?? event.type,
420
- userMessage: (options.userMessage ?? event.humanFriendlyMessage) || void 0,
421
- context,
422
- metadata: options.metadata
423
- });
424
- }
425
- dispatchAction(input) {
426
- if (!this.#surfaces.has(input.surfaceId)) {
427
- this.#emitGenericError("SURFACE_NOT_FOUND", `Unknown surface: ${input.surfaceId}`, input.surfaceId);
428
- return;
429
- }
430
- const message = {
431
- version: "v1.0",
432
- action: {
433
- name: input.name,
434
- ...input.userMessage ? { userMessage: input.userMessage } : {},
435
- surfaceId: input.surfaceId,
436
- sourceComponentId: input.sourceComponentId,
437
- timestamp: this.#now().toISOString(),
438
- context: input.context ?? {},
439
- ...input.metadata ? { metadata: input.metadata } : {}
440
- }
441
- };
442
- this.#emit(message);
443
- }
444
- callAgentFunction(input) {
445
- if (!this.#surfaces.has(input.surfaceId)) {
446
- const message = `Unknown surface: ${input.surfaceId}`;
447
- this.#emitGenericError("SURFACE_NOT_FOUND", message, input.surfaceId);
448
- return Promise.reject(new A2UIFunctionError("SURFACE_NOT_FOUND", message));
449
- }
450
- const functionCallId = this.#createId();
451
- return new Promise((resolve, reject) => {
452
- this.#pendingAgentFunctions.set(functionCallId, {
453
- surfaceId: input.surfaceId,
454
- resolve,
455
- reject
456
- });
457
- this.#emit({
458
- version: "v1.0",
459
- callAgentFunction: {
460
- surfaceId: input.surfaceId,
461
- functionCallId,
462
- callFunction: {
463
- call: input.call,
464
- ...input.catalogId ? { catalogId: input.catalogId } : {},
465
- ...input.args ? { args: input.args } : {}
466
- }
467
- }
468
- });
469
- });
470
- }
471
- dispose() {
472
- for (const pending of this.#pendingAgentFunctions.values()) pending.reject(new A2UIFunctionError("CLIENT_DISPOSED", "A2UI client was disposed"));
473
- this.#pendingAgentFunctions.clear();
474
- this.#surfaces.clear();
475
- this.#surfaceListeners.clear();
476
- this.#messageListeners.clear();
477
- }
478
- #createSurface(message, outbound) {
479
- const input = message.createSurface;
480
- if (this.#surfaces.has(input.surfaceId)) {
481
- this.#emitGenericError("SURFACE_ALREADY_EXISTS", `Surface already exists: ${input.surfaceId}`, input.surfaceId);
482
- return {
483
- ok: false,
484
- outbound
485
- };
486
- }
487
- const supportedCatalogIds = this.#rendererCapabilities?.["v1.0"].supportedCatalogIds ?? [];
488
- if (input.catalogId && supportedCatalogIds.length > 0 && !supportedCatalogIds.includes(input.catalogId)) {
489
- this.#emitGenericError("UNSUPPORTED_CATALOG", `Renderer does not support catalog: ${input.catalogId}`, input.surfaceId);
490
- return {
491
- ok: false,
492
- outbound
493
- };
494
- }
495
- let source = "";
496
- let parseResult = null;
497
- let errors = [];
498
- if (input.components) try {
499
- ({source, parseResult, errors} = this.#mergeComponents("", input.components));
500
- } catch (error) {
501
- this.#emitValidationError(input.surfaceId, "/createSurface/components", error instanceof Error ? error.message : String(error));
502
- return {
503
- ok: false,
504
- outbound
505
- };
506
- }
507
- this.#replaceSurface({
508
- surfaceId: input.surfaceId,
509
- catalogId: input.catalogId,
510
- metadata: input.metadata,
511
- sendDataModel: input.sendDataModel ?? false,
512
- source,
513
- dataModel: structuredClone(input.dataModel ?? {}),
514
- parseResult,
515
- errors,
516
- revision: 0
517
- });
518
- for (const error of errors) this.#emitValidationError(input.surfaceId, "/createSurface/components", error.statementId ? `${error.statementId}: ${error.message}` : error.message);
519
- return {
520
- ok: errors.length === 0,
521
- outbound
522
- };
523
- }
524
- #updateComponents(message, outbound) {
525
- const input = message.updateComponents;
526
- const surface = this.#requireSurface(input.surfaceId);
527
- if (!surface) return {
528
- ok: false,
529
- outbound
530
- };
531
- try {
532
- const { source, parseResult, errors } = this.#mergeComponents(surface.source, input.components);
533
- this.#replaceSurface({
534
- ...surface,
535
- source,
536
- parseResult,
537
- errors
538
- });
539
- for (const error of errors) this.#emitValidationError(input.surfaceId, "/updateComponents/components", error.statementId ? `${error.statementId}: ${error.message}` : error.message);
540
- return {
541
- ok: errors.length === 0,
542
- outbound
543
- };
544
- } catch (error) {
545
- this.#emitValidationError(input.surfaceId, "/updateComponents/components", error instanceof Error ? error.message : String(error));
546
- return {
547
- ok: false,
548
- outbound
549
- };
550
- }
551
- }
552
- #updateDataModel(message, outbound) {
553
- const input = message.updateDataModel;
554
- const surface = this.#requireSurface(input.surfaceId);
555
- if (!surface) return {
556
- ok: false,
557
- outbound
558
- };
559
- try {
560
- const dataModel = applyDataModelUpdate(surface.dataModel, input.path, input.value);
561
- this.#replaceSurface({
562
- ...surface,
563
- dataModel
564
- });
565
- return {
566
- ok: true,
567
- outbound
568
- };
569
- } catch (error) {
570
- this.#emitValidationError(input.surfaceId, "/updateDataModel/path", error instanceof Error ? error.message : String(error));
571
- return {
572
- ok: false,
573
- outbound
574
- };
575
- }
576
- }
577
- #deleteSurface(message, outbound) {
578
- const surfaceId = message.deleteSurface.surfaceId;
579
- if (!this.#requireSurface(surfaceId)) return {
580
- ok: false,
581
- outbound
582
- };
583
- this.#surfaces.delete(surfaceId);
584
- for (const [functionCallId, pending] of this.#pendingAgentFunctions) if (pending.surfaceId === surfaceId) {
585
- pending.reject(new A2UIFunctionError("SURFACE_DELETED", `Surface was deleted: ${surfaceId}`));
586
- this.#pendingAgentFunctions.delete(functionCallId);
587
- }
588
- this.#notify();
589
- return {
590
- ok: true,
591
- outbound
592
- };
593
- }
594
- async #callRendererFunction(message, outbound) {
595
- const { functionCallId, callFunction } = message.callRendererFunction;
596
- const { call, catalogId, args = {} } = callFunction;
597
- const registration = this.#functions?.[call];
598
- if (!registration) {
599
- this.#emitGenericError("INVALID_FUNCTION_CALL", `Renderer function is not registered: ${call}`, void 0, functionCallId);
600
- return {
601
- ok: false,
602
- outbound
603
- };
604
- }
605
- const fn = typeof registration === "function" ? registration : registration.handler;
606
- if (typeof registration === "function" || (registration.allowedCallers ?? "rendererOnly") === "rendererOnly" || registration.catalogId !== catalogId) {
607
- this.#emitGenericError("INVALID_FUNCTION_CALL", `Renderer function is not callable from catalog ${catalogId}: ${call}`, void 0, functionCallId);
608
- return {
609
- ok: false,
610
- outbound
611
- };
612
- }
613
- try {
614
- const value = await fn(args);
615
- this.#emit({
616
- version: "v1.0",
617
- rendererFunctionResponse: {
618
- functionCallId,
619
- value
620
- }
621
- });
622
- return {
623
- ok: true,
624
- outbound
625
- };
626
- } catch (error) {
627
- this.#emit({
628
- version: "v1.0",
629
- rendererFunctionResponse: {
630
- functionCallId,
631
- error: {
632
- code: "EXECUTION_FAILED",
633
- message: error instanceof Error ? error.message : String(error)
634
- }
635
- }
636
- });
637
- return {
638
- ok: false,
639
- outbound
640
- };
641
- }
642
- }
643
- #agentFunctionResponse(message, outbound) {
644
- const response = message.agentFunctionResponse;
645
- const pending = this.#pendingAgentFunctions.get(response.functionCallId);
646
- if (!pending) return {
647
- ok: false,
648
- outbound,
649
- issues: [{
650
- path: "/agentFunctionResponse/functionCallId",
651
- message: `Unknown functionCallId: ${response.functionCallId}`
652
- }]
653
- };
654
- this.#pendingAgentFunctions.delete(response.functionCallId);
655
- if ("error" in response) {
656
- pending.reject(new A2UIFunctionError(response.error.code, response.error.message));
657
- return {
658
- ok: true,
659
- outbound
660
- };
661
- }
662
- pending.resolve(response.value);
663
- return {
664
- ok: true,
665
- outbound
666
- };
667
- }
668
- #replaceSurface(surface) {
669
- this.#revision += 1;
670
- this.#surfaces.set(surface.surfaceId, {
671
- ...surface,
672
- revision: this.#revision
673
- });
674
- this.#notify();
675
- }
676
- #mergeComponents(existing, components) {
677
- const source = mergeComponentStatements(existing, components);
678
- const parseResult = this.#parser.parse(source);
679
- return {
680
- source,
681
- parseResult,
682
- errors: parseResult.meta.errors.map(parseError)
683
- };
684
- }
685
- #invalidMessage(input, issues, outbound) {
686
- const target = validationTarget(input);
687
- const issue = issues[0] ?? {
688
- path: "/",
689
- message: "Invalid A2UI message"
690
- };
691
- if (target.surfaceId !== void 0) {
692
- this.#emitValidationError(target.surfaceId, issue.path, issue.message);
693
- return {
694
- ok: false,
695
- outbound,
696
- issues
697
- };
698
- }
699
- if (target.functionCallId !== void 0) {
700
- this.#emitGenericError("INVALID_MESSAGE", `${issue.path}: ${issue.message}`, void 0, target.functionCallId);
701
- return {
702
- ok: false,
703
- outbound,
704
- issues
705
- };
706
- }
707
- return {
708
- ok: false,
709
- outbound,
710
- issues
711
- };
712
- }
713
- #requireSurface(surfaceId) {
714
- const surface = this.#surfaces.get(surfaceId);
715
- if (!surface) this.#emitGenericError("SURFACE_NOT_FOUND", `Unknown surface: ${surfaceId}`, surfaceId);
716
- return surface;
717
- }
718
- #emitValidationError(surfaceId, path, message) {
719
- const error = {
720
- version: "v1.0",
721
- error: {
722
- code: "VALIDATION_FAILED",
723
- surfaceId,
724
- path,
725
- message
726
- }
727
- };
728
- this.#emit(error);
729
- }
730
- #emitGenericError(code, message, surfaceId, functionCallId) {
731
- if (surfaceId === void 0 && functionCallId === void 0) return;
732
- const error = surfaceId !== void 0 ? {
733
- version: "v1.0",
734
- error: {
735
- code,
736
- message,
737
- surfaceId
738
- }
739
- } : {
740
- version: "v1.0",
741
- error: {
742
- code,
743
- message,
744
- functionCallId
745
- }
746
- };
747
- this.#emit(error);
748
- }
749
- #emit(message) {
750
- const metadata = this.getRendererMetadata();
751
- this.#onMessage?.(message, metadata);
752
- for (const listener of this.#messageListeners) listener(message, metadata);
753
- }
754
- #notify() {
755
- for (const listener of this.#surfaceListeners) listener();
756
- }
757
- };
758
- function createA2UIClient(options) {
759
- return new A2UIClient(options);
760
- }
761
- export { A2UIClient, A2UIFunctionError, a2uiFunctionCallSchema, a2uiFunctionResponseSchema, actionMessageSchema, agentCapabilitiesSchema, agentFunctionResponseMessageSchema, agentToRendererMessageSchema, applyDataModelUpdate, callAgentFunctionMessageSchema, callRendererFunctionMessageSchema, createA2UIClient, createSurfaceMessageSchema, dataModelToOpenUIState, deleteSurfaceMessageSchema, genericErrorMessageSchema, jsonObjectSchema, jsonValueSchema, mergeOpenUIStateIntoDataModel, messageMetadataSchema, rendererCapabilitiesSchema, rendererDataModelSchema, rendererFunctionResponseMessageSchema, rendererToAgentMessageSchema, updateComponentsMessageSchema, updateDataModelMessageSchema, validateAgentToRendererMessage, validationFailedErrorMessageSchema };
762
-
763
- //# sourceMappingURL=index.mjs.map
1
+ import{createParser as e}from"@openuidev/lang-core";import{i as t,n,r,t as i}from"./json-pointer-D7Ll5GM3.mjs";import{z as a}from"zod/v4";const o=a.json(),s=a.record(a.string(),o),c=a.literal(`v1.0`),l=a.string(),u=a.string().regex(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u),d=a.record(u,o),f=a.strictObject({extensions:d.optional()}),p=a.array(a.string().min(1)).min(1).describe(`Complete OpenUI Lang statements or statement blocks, merged by statement ID in array order.`),m=a.strictObject({call:a.string(),catalogId:a.string().optional(),args:s.optional()}),h=a.union([a.strictObject({functionCallId:a.string(),value:o}),a.strictObject({functionCallId:a.string(),error:a.strictObject({code:a.string(),message:a.string()})})]),g=a.strictObject({version:c,createSurface:a.strictObject({surfaceId:l,catalogId:a.string().optional(),sendDataModel:a.boolean().optional().meta({default:!1}),components:p.optional().describe(`Optional initial OpenUI Lang statements for single-message surface creation.`),dataModel:s.optional(),metadata:f.optional()})}),_=a.strictObject({version:c,updateComponents:a.strictObject({surfaceId:l,components:p})}),v=a.strictObject({version:c,updateDataModel:a.strictObject({surfaceId:l,path:a.string().optional(),value:o})}),y=a.strictObject({version:c,deleteSurface:a.strictObject({surfaceId:l})}),b=a.strictObject({version:c,callRendererFunction:a.strictObject({functionCallId:a.string(),callFunction:m.extend({catalogId:a.string()})})}),x=a.strictObject({version:c,agentFunctionResponse:h}),S=a.union([g,_,v,y,b,x]),C=a.strictObject({version:c,action:a.strictObject({name:a.string(),userMessage:a.string().optional(),surfaceId:l,sourceComponentId:a.string(),timestamp:a.iso.datetime({offset:!0}),context:s,metadata:f.optional()})}),w=a.strictObject({version:c,callAgentFunction:a.strictObject({surfaceId:l,functionCallId:a.string(),callFunction:m})}),T=a.strictObject({version:c,rendererFunctionResponse:h}),E=a.enum([`VALIDATION_FAILED`,`UNALLOWED_PARENT`,`UNALLOWED_CHILD`]),D=a.strictObject({version:c,error:a.strictObject({code:E,surfaceId:l,path:a.string(),message:a.string()})}),O=a.string().refine(e=>!E.options.includes(e)),k=a.union([a.strictObject({version:c,error:a.strictObject({code:O,message:a.string(),surfaceId:l})}),a.strictObject({version:c,error:a.strictObject({code:O,message:a.string(),functionCallId:a.string()})})]),A=a.union([C,w,T,D,k]),j=a.strictObject({"v1.0":a.strictObject({supportedCatalogIds:a.array(a.string()),inlineCatalogs:a.array(s).optional()})}),M=a.strictObject({"v1.0":a.strictObject({supportedCatalogIds:a.array(a.string()).optional(),acceptsInlineCatalogs:a.boolean().optional().meta({default:!1})})}),N=a.strictObject({version:c,surfaces:a.record(a.string(),s)});function P(e){return String(e).replace(/~/g,`~0`).replace(/\//g,`~1`)}function F(e){return e.length===0?`/`:`/${e.map(P).join(`/`)}`}function I(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e:void 0,n=t?[`createSurface`,`updateComponents`,`updateDataModel`,`deleteSurface`,`callRendererFunction`,`agentFunctionResponse`].filter(e=>Object.prototype.hasOwnProperty.call(t,e)):[],r=(n.length===1?{createSurface:g,updateComponents:_,updateDataModel:v,deleteSurface:y,callRendererFunction:b,agentFunctionResponse:x}[n[0]]:S).safeParse(e);return r.success?{success:!0,message:r.data}:{success:!1,issues:r.error.issues.map(e=>({path:F(e.path),message:e.message}))}}const L=/^(\$?[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([\s\S]*)$/u;function R(e){let t=e.trim();if(!t.startsWith("```"))return t;let n=t.indexOf(`
2
+ `),r=t.lastIndexOf("```");return n===-1||r<=n?t:t.slice(n+1,r).trim()}function z(e){let t=[],n=0,r=0,i=!1,a=!1,o=0;for(let s=0;s<e.length;s+=1){let c=e[s];if(a)a=!1;else if(c===`\\`&&i)a=!0;else if(i)c===i&&(i=!1);else if(c===`"`||c===`'`)i=c;else if(c===`(`||c===`[`||c===`{`)n+=1;else if(c===`)`||c===`]`||c===`}`)n=Math.max(0,n-1);else if(c===`?`&&n===0)r+=1;else if(c===`:`&&n===0&&r>0)--r;else if(c===`
3
+ `&&n===0&&r===0){let n=s+1;for(;n<e.length&&/\s/u.test(e[n]);)n+=1;if(e[n]===`?`)continue;let r=e.slice(o,s).trim();r&&t.push(r),o=s+1}}let s=e.slice(o).trim();return s&&t.push(s),t}function B(e){return z(R(e)).map(e=>{let t=L.exec(e);if(!t)throw Error(`Invalid OpenUI Lang statement: ${e}`);return{id:t[1],expression:t[2].trim(),raw:e}})}function V(e,t){let n=/* @__PURE__ */ new Map,r=[],i=(e,t)=>{for(let i of B(e))if(t&&i.expression===`null`){n.delete(i.id);let e=r.indexOf(i.id);e!==-1&&r.splice(e,1)}else n.has(i.id)||r.push(i.id),n.set(i.id,i.raw)};e.trim()&&i(e,!1);for(let e of t)i(e,!0);return r.map(e=>n.get(e)).join(`
4
+ `)}var H=class extends Error{code;constructor(e,t){super(t),this.name=`A2UIFunctionError`,this.code=e}};function U(){return globalThis.crypto?.randomUUID?.()??`a2ui-${Date.now()}-${Math.random().toString(16).slice(2)}`}function W(e){return{source:`parser`,code:e.code,message:e.message,statementId:e.statementId,component:e.component,path:e.path}}function G(e){return`createSurface`in e}function K(e){return`updateComponents`in e}function q(e){return`updateDataModel`in e}function J(e){return`deleteSurface`in e}function Y(e){return`callRendererFunction`in e}function X(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Z(e){let t=X(e);if(!t)return{};for(let e of[`createSurface`,`updateComponents`,`updateDataModel`,`deleteSurface`]){let n=X(t[e]);if(typeof n?.surfaceId==`string`)return{surfaceId:n.surfaceId}}for(let e of[`callRendererFunction`,`agentFunctionResponse`]){let n=X(t[e]);if(typeof n?.functionCallId==`string`)return{functionCallId:n.functionCallId}}return{}}var Q=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Map;#s=/* @__PURE__ */ new Set;#c=/* @__PURE__ */ new Set;#l=/* @__PURE__ */ new Map;#u=0;constructor(t){this.#e=e(t.schema,t.rootName),this.#t=t.functions,this.#n=t.onMessage,this.#r=t.rendererCapabilities,this.#i=t.now??(()=>/* @__PURE__ */ new Date),this.#a=t.createId??U}subscribe(e){return this.#s.add(e),()=>this.#s.delete(e)}subscribeMessages(e){return this.#c.add(e),()=>this.#c.delete(e)}getSurface(e){return this.#o.get(e)}getSurfaces(){return[...this.#o.values()]}getRendererDataModel(){let e=Object.fromEntries([...this.#o].filter(([,e])=>e.sendDataModel).map(([e,t])=>[e,structuredClone(t.dataModel)]));if(Object.keys(e).length!==0)return{version:`v1.0`,surfaces:e}}getRendererMetadata(){let e=this.getRendererDataModel();return{...this.#r?{a2uiRendererCapabilities:structuredClone(this.#r)}:{},...e?{a2uiRendererDataModel:e}:{}}}async process(e){let t=[],n=e=>t.push(e);this.#c.add(n);try{let n=I(e);if(!n.success)return this.#y(e,n.issues,t);let r=n.message;return G(r)?this.#d(r,t):K(r)?this.#f(r,t):q(r)?this.#p(r,t):J(r)?this.#m(r,t):Y(r)?await this.#h(r,t):this.#g(r,t)}finally{this.#c.delete(n)}}updateSurfaceFromOpenUIState(e,t){let n=this.#o.get(e);if(!n)return!1;let i=r(n.dataModel,t);return JSON.stringify(i)!==JSON.stringify(n.dataModel)&&(this.#_({...n,dataModel:i}),!0)}dispatchOpenUIAction(e,n,r={}){let i=n.sourceComponentId,a={...t(n.params),...n.formState?{formState:t(n.formState)}:{},...r.context};this.dispatchAction({surfaceId:e,sourceComponentId:r.sourceComponentId??(typeof i==`string`?i:`root`),name:r.name??n.type,userMessage:(r.userMessage??n.humanFriendlyMessage)||void 0,context:a,metadata:r.metadata})}dispatchAction(e){if(!this.#o.has(e.surfaceId)){this.#S(`SURFACE_NOT_FOUND`,`Unknown surface: ${e.surfaceId}`,e.surfaceId);return}let t={version:`v1.0`,action:{name:e.name,...e.userMessage?{userMessage:e.userMessage}:{},surfaceId:e.surfaceId,sourceComponentId:e.sourceComponentId,timestamp:this.#i().toISOString(),context:e.context??{},...e.metadata?{metadata:e.metadata}:{}}};this.#C(t)}callAgentFunction(e){if(!this.#o.has(e.surfaceId)){let t=`Unknown surface: ${e.surfaceId}`;return this.#S(`SURFACE_NOT_FOUND`,t,e.surfaceId),Promise.reject(new H(`SURFACE_NOT_FOUND`,t))}let t=this.#a();return new Promise((n,r)=>{this.#l.set(t,{surfaceId:e.surfaceId,resolve:n,reject:r}),this.#C({version:`v1.0`,callAgentFunction:{surfaceId:e.surfaceId,functionCallId:t,callFunction:{call:e.call,...e.catalogId?{catalogId:e.catalogId}:{},...e.args?{args:e.args}:{}}}})})}dispose(){for(let e of this.#l.values())e.reject(new H(`CLIENT_DISPOSED`,`A2UI client was disposed`));this.#l.clear(),this.#o.clear(),this.#s.clear(),this.#c.clear()}#d(e,t){let n=e.createSurface;if(this.#o.has(n.surfaceId))return this.#S(`SURFACE_ALREADY_EXISTS`,`Surface already exists: ${n.surfaceId}`,n.surfaceId),{ok:!1,outbound:t};let r=this.#r?.[`v1.0`].supportedCatalogIds??[];if(n.catalogId&&r.length>0&&!r.includes(n.catalogId))return this.#S(`UNSUPPORTED_CATALOG`,`Renderer does not support catalog: ${n.catalogId}`,n.surfaceId),{ok:!1,outbound:t};let i=``,a=null,o=[];if(n.components)try{({source:i,parseResult:a,errors:o}=this.#v(``,n.components))}catch(e){return this.#x(n.surfaceId,`/createSurface/components`,e instanceof Error?e.message:String(e)),{ok:!1,outbound:t}}this.#_({surfaceId:n.surfaceId,catalogId:n.catalogId,metadata:n.metadata,sendDataModel:n.sendDataModel??!1,source:i,dataModel:structuredClone(n.dataModel??{}),parseResult:a,errors:o,revision:0});for(let e of o)this.#x(n.surfaceId,`/createSurface/components`,e.statementId?`${e.statementId}: ${e.message}`:e.message);return{ok:o.length===0,outbound:t}}#f(e,t){let n=e.updateComponents,r=this.#b(n.surfaceId);if(!r)return{ok:!1,outbound:t};try{let{source:e,parseResult:i,errors:a}=this.#v(r.source,n.components);this.#_({...r,source:e,parseResult:i,errors:a});for(let e of a)this.#x(n.surfaceId,`/updateComponents/components`,e.statementId?`${e.statementId}: ${e.message}`:e.message);return{ok:a.length===0,outbound:t}}catch(e){return this.#x(n.surfaceId,`/updateComponents/components`,e instanceof Error?e.message:String(e)),{ok:!1,outbound:t}}}#p(e,t){let n=e.updateDataModel,r=this.#b(n.surfaceId);if(!r)return{ok:!1,outbound:t};try{let e=i(r.dataModel,n.path,n.value);return this.#_({...r,dataModel:e}),{ok:!0,outbound:t}}catch(e){return this.#x(n.surfaceId,`/updateDataModel/path`,e instanceof Error?e.message:String(e)),{ok:!1,outbound:t}}}#m(e,t){let n=e.deleteSurface.surfaceId;if(!this.#b(n))return{ok:!1,outbound:t};this.#o.delete(n);for(let[e,t]of this.#l)t.surfaceId===n&&(t.reject(new H(`SURFACE_DELETED`,`Surface was deleted: ${n}`)),this.#l.delete(e));return this.#w(),{ok:!0,outbound:t}}async#h(e,t){let{functionCallId:n,callFunction:r}=e.callRendererFunction,{call:i,catalogId:a,args:o={}}=r,s=this.#t?.[i];if(!s)return this.#S(`INVALID_FUNCTION_CALL`,`Renderer function is not registered: ${i}`,void 0,n),{ok:!1,outbound:t};let c=typeof s==`function`?s:s.handler;if(typeof s==`function`||(s.allowedCallers??`rendererOnly`)===`rendererOnly`||s.catalogId!==a)return this.#S(`INVALID_FUNCTION_CALL`,`Renderer function is not callable from catalog ${a}: ${i}`,void 0,n),{ok:!1,outbound:t};try{let e=await c(o);return this.#C({version:`v1.0`,rendererFunctionResponse:{functionCallId:n,value:e}}),{ok:!0,outbound:t}}catch(e){return this.#C({version:`v1.0`,rendererFunctionResponse:{functionCallId:n,error:{code:`EXECUTION_FAILED`,message:e instanceof Error?e.message:String(e)}}}),{ok:!1,outbound:t}}}#g(e,t){let n=e.agentFunctionResponse,r=this.#l.get(n.functionCallId);return r?(this.#l.delete(n.functionCallId),`error`in n?(r.reject(new H(n.error.code,n.error.message)),{ok:!0,outbound:t}):(r.resolve(n.value),{ok:!0,outbound:t})):{ok:!1,outbound:t,issues:[{path:`/agentFunctionResponse/functionCallId`,message:`Unknown functionCallId: ${n.functionCallId}`}]}}#_(e){this.#u+=1,this.#o.set(e.surfaceId,{...e,revision:this.#u}),this.#w()}#v(e,t){let n=V(e,t),r=this.#e.parse(n);return{source:n,parseResult:r,errors:r.meta.errors.map(W)}}#y(e,t,n){let r=Z(e),i=t[0]??{path:`/`,message:`Invalid A2UI message`};return r.surfaceId===void 0?(r.functionCallId===void 0||this.#S(`INVALID_MESSAGE`,`${i.path}: ${i.message}`,void 0,r.functionCallId),{ok:!1,outbound:n,issues:t}):(this.#x(r.surfaceId,i.path,i.message),{ok:!1,outbound:n,issues:t})}#b(e){let t=this.#o.get(e);return t||this.#S(`SURFACE_NOT_FOUND`,`Unknown surface: ${e}`,e),t}#x(e,t,n){let r={version:`v1.0`,error:{code:`VALIDATION_FAILED`,surfaceId:e,path:t,message:n}};this.#C(r)}#S(e,t,n,r){if(n===void 0&&r===void 0)return;let i=n===void 0?{version:`v1.0`,error:{code:e,message:t,functionCallId:r}}:{version:`v1.0`,error:{code:e,message:t,surfaceId:n}};this.#C(i)}#C(e){let t=this.getRendererMetadata();this.#n?.(e,t);for(let n of this.#c)n(e,t)}#w(){for(let e of this.#s)e()}};function $(e){return new Q(e)}export{Q as A2UIClient,H as A2UIFunctionError,m as a2uiFunctionCallSchema,h as a2uiFunctionResponseSchema,C as actionMessageSchema,M as agentCapabilitiesSchema,x as agentFunctionResponseMessageSchema,S as agentToRendererMessageSchema,i as applyDataModelUpdate,w as callAgentFunctionMessageSchema,b as callRendererFunctionMessageSchema,$ as createA2UIClient,g as createSurfaceMessageSchema,n as dataModelToOpenUIState,y as deleteSurfaceMessageSchema,k as genericErrorMessageSchema,s as jsonObjectSchema,o as jsonValueSchema,r as mergeOpenUIStateIntoDataModel,f as messageMetadataSchema,j as rendererCapabilitiesSchema,N as rendererDataModelSchema,T as rendererFunctionResponseMessageSchema,A as rendererToAgentMessageSchema,_ as updateComponentsMessageSchema,v as updateDataModelMessageSchema,I as validateAgentToRendererMessage,D as validationFailedErrorMessageSchema};