@superblocksteam/library 2.0.54 → 2.0.56-next.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 (37) hide show
  1. package/dist/{devtools-consolidated-BJ2tPWBk.js → devtools-consolidated-Dm9AFGZs.js} +2 -2
  2. package/dist/{devtools-consolidated-BJ2tPWBk.js.map → devtools-consolidated-Dm9AFGZs.js.map} +1 -1
  3. package/dist/{early-console-buffer-Bd5jqqBJ.js → early-console-buffer-SSPd-jq2.js} +1 -1
  4. package/dist/{early-console-buffer-Bd5jqqBJ.js.map → early-console-buffer-SSPd-jq2.js.map} +1 -1
  5. package/dist/jsx-dev-runtime/index.d.ts +14 -0
  6. package/dist/jsx-dev-runtime/index.d.ts.map +1 -0
  7. package/dist/jsx-dev-runtime/index.js +329 -0
  8. package/dist/jsx-dev-runtime/index.js.map +1 -0
  9. package/dist/jsx-runtime/index.d.ts +7 -0
  10. package/dist/jsx-runtime/index.d.ts.map +1 -0
  11. package/dist/jsx-runtime/index.js +10 -0
  12. package/dist/jsx-runtime/index.js.map +1 -0
  13. package/dist/{index.css → lib/index.css} +17 -11
  14. package/dist/lib/index.css.map +1 -0
  15. package/dist/lib/index.d.ts +786 -0
  16. package/dist/lib/index.d.ts.map +1 -0
  17. package/dist/lib/index.js +4991 -0
  18. package/dist/lib/index.js.map +1 -0
  19. package/dist/{logs-BA3qqo2m.js → logs-CgCPS9qr.js} +2 -2
  20. package/dist/{logs-BA3qqo2m.js.map → logs-CgCPS9qr.js.map} +1 -1
  21. package/dist/{utils-xmrGF_mk.js → utils-AzBGeVXo.js} +1 -1
  22. package/dist/{utils-xmrGF_mk.js.map → utils-AzBGeVXo.js.map} +1 -1
  23. package/dist/utils-DR35eYvX.js +3 -0
  24. package/dist/widget-wrapper-naming-ChBggw6W.js +3049 -0
  25. package/dist/widget-wrapper-naming-ChBggw6W.js.map +1 -0
  26. package/package.json +27 -14
  27. package/dist/build-manifest-BNJahcH4.js +0 -6
  28. package/dist/build-manifest-BNJahcH4.js.map +0 -1
  29. package/dist/index.css.map +0 -1
  30. package/dist/index.d.ts +0 -1339
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/index.js +0 -11471
  33. package/dist/index.js.map +0 -1
  34. package/dist/root-store-Cc3dO2jP.js +0 -4721
  35. package/dist/root-store-Cc3dO2jP.js.map +0 -1
  36. package/dist/root-store-xviorlO5.js +0 -4
  37. package/dist/utils-BVE4VhSk.js +0 -3
@@ -0,0 +1,3049 @@
1
+ import { t as getTracer } from "./utils-AzBGeVXo.js";
2
+ import { getQueryParams, pathStringToArray, toMobXPatch } from "@superblocksteam/library-shared";
3
+ import * as React$1 from "react";
4
+ import React, { createContext, isValidElement, useCallback, useContext, useSyncExternalStore } from "react";
5
+ import { action, entries, isComputedProp, isObservableArray, isObservableMap, isObservableObject, makeAutoObservable, makeObservable, observable, observe, reaction, toJS, values } from "mobx";
6
+ import { matchRoutes } from "react-router";
7
+ import { pick, throttle } from "lodash";
8
+ import { ApiResponseType, OrchestratorViewMode, SUPERBLOCKS_AUTHORIZATION_HEADER, SUPERBLOCKS_REQUEST_ID_HEADER, ViewMode, decodeBytestrings } from "@superblocksteam/shared";
9
+ import { NotificationPosition } from "@superblocksteam/library-shared/types";
10
+ import isString from "lodash/isString";
11
+ import { toast } from "sonner";
12
+ import styled from "styled-components";
13
+ import { jsx, jsxs } from "react/jsx-runtime";
14
+ import { ROOT_CONTEXT, context, propagation, trace } from "@opentelemetry/api";
15
+ import diff from "microdiff";
16
+ import { InputType, PropsCategory } from "@superblocksteam/library-shared/props";
17
+
18
+ //#region src/lib/internal-details/is-edit-mode.ts
19
+ const getIsEditMode = () => {
20
+ return window._SB_VIEW_MODE === "dev";
21
+ };
22
+ let editMode;
23
+ const isEditMode = () => {
24
+ if (editMode === void 0) editMode = getIsEditMode();
25
+ return editMode;
26
+ };
27
+
28
+ //#endregion
29
+ //#region src/lib/utils/clean-object.ts
30
+ const isReactElement = (obj) => {
31
+ return obj && (obj.$$typeof === Symbol.for("react.element") || isValidElement(obj) || typeof Node !== "undefined" && obj instanceof Node);
32
+ };
33
+ /**
34
+ * Cleans an object by removing proxy wrappers and filtering out functions.
35
+ * This is useful for preparing objects for JSON serialization.
36
+ */
37
+ function cleanObject(obj) {
38
+ obj = toJS(obj);
39
+ if (!obj || typeof obj !== "object") return typeof obj === "function" ? void 0 : obj;
40
+ if (Array.isArray(obj)) return obj.map(cleanObject).filter((item) => item !== void 0);
41
+ if (isReactElement(obj)) return;
42
+ return Object.entries(obj).reduce((acc, [key, value]) => {
43
+ if (obj === value || key === "bind") return acc;
44
+ const cleaned = cleanObject(value);
45
+ if (cleaned !== void 0) acc[key] = cleaned;
46
+ return acc;
47
+ }, {});
48
+ }
49
+
50
+ //#endregion
51
+ //#region src/lib/internal-details/lib/iframe.ts
52
+ function isEmbeddedBySuperblocksFirstParty() {
53
+ return typeof window !== "undefined" && window !== window.parent;
54
+ }
55
+ const PARENT_REF = typeof window !== "undefined" && window !== window.parent ? window.parent : null;
56
+ const SELF_REF = typeof window !== "undefined" ? window : null;
57
+ function parentMessageHandler(e) {
58
+ if (e.source !== PARENT_REF && e.source !== SELF_REF) return;
59
+ const event = new SbIframeEventInternal(e.data.type, e.data);
60
+ iframeMessageHandler.dispatchEvent(event);
61
+ }
62
+ if (isEmbeddedBySuperblocksFirstParty() && PARENT_REF) typeof window !== "undefined" && window.addEventListener("message", parentMessageHandler);
63
+ /** @deprecated Use editorBridge instead */
64
+ function sendMessageImmediately(message, options) {
65
+ if (!PARENT_REF) {
66
+ console.warn("PARENT_REF is not set, message not delivered. Message: ", message);
67
+ return;
68
+ }
69
+ message = cleanObject(message);
70
+ if (isEmbeddedBySuperblocksFirstParty()) {
71
+ if (!PARENT_REF) throw new Error("Parent is not set");
72
+ try {
73
+ PARENT_REF.postMessage({
74
+ ...message,
75
+ startTime: options?.overrideStartTime ?? +/* @__PURE__ */ new Date()
76
+ }, "*");
77
+ } catch (e) {
78
+ console.error("Error sending message to parent", message, e);
79
+ }
80
+ }
81
+ }
82
+ var SbIframeEventInternal = class extends Event {
83
+ data;
84
+ constructor(type, data) {
85
+ super(type);
86
+ this.data = data;
87
+ }
88
+ };
89
+ var SbMessageHandler = class extends EventTarget {};
90
+ const iframeMessageHandler = new SbMessageHandler();
91
+
92
+ //#endregion
93
+ //#region src/edit-mode/base-editor-bridge.ts
94
+ var DeployedParentBridge = class {
95
+ navigateTo(url, newWindow) {
96
+ sendMessageImmediately({
97
+ type: "navigate-to",
98
+ payload: {
99
+ url,
100
+ newWindow
101
+ }
102
+ });
103
+ }
104
+ connected() {}
105
+ sendReady() {}
106
+ sendLoadError(_error) {}
107
+ sendNotification(_type, _message, _description) {}
108
+ selectWidgets(_sourceIds) {}
109
+ editOpRequest(_type, _payload) {}
110
+ undo() {}
111
+ redo() {}
112
+ sendStreamedApiEvent(_event, _apiName) {}
113
+ sendStreamedApiMessage(_message, _apiName) {}
114
+ setApiStarted(_apiName) {}
115
+ setApiResponse(_apiName, _response) {}
116
+ updatePropertiesPanels(_updates) {}
117
+ addPropertiesPanel(_id, _definition) {}
118
+ addApiRunRecord(_apiId, _run) {}
119
+ updateApiRunRecord(_apiId, _callId, _updates) {}
120
+ initializeEditorSyncedStore(_payload) {}
121
+ updateEditorSyncedStore(_payload) {}
122
+ resolvePromise(_callbackId, _payload) {}
123
+ rejectPromise(_callbackId, _payload) {}
124
+ canvasClicked() {}
125
+ registerContextMenuClick(_sourceId, _clientX, _clientY) {}
126
+ updateRoute(routeInfo) {
127
+ sendMessageImmediately({
128
+ type: "route-change",
129
+ payload: routeInfo
130
+ });
131
+ }
132
+ socketError(_message) {}
133
+ aiGenerate(_prompt) {}
134
+ addComponentToAiContext(_sourceId, _selectorId) {}
135
+ toggleComponentInAiContext(_sourceId, _selectorId, _label) {}
136
+ setAiContextMode(_mode) {}
137
+ sendAiLoaderState(_shouldShowLoader) {}
138
+ sendRuntimeError(_data) {}
139
+ sendClearRuntimeError(_id) {}
140
+ setInteractionMode(_mode) {}
141
+ };
142
+
143
+ //#endregion
144
+ //#region src/edit-mode/get-edit-store.ts
145
+ /**
146
+ * Get the global EditStore instance
147
+ * @returns The EditStore instance
148
+ */
149
+ function getEditStore() {
150
+ if (!window.__SUPERBLOCKS_EDITOR_HOOK__ || !window.__SUPERBLOCKS_EDITOR_HOOK__.isInitialized) throw new Error("EditStore not initialized");
151
+ return window.__SUPERBLOCKS_EDITOR_HOOK__;
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/edit-mode/message-queue.ts
156
+ const MESSAGE_BATCH_TIME = 50;
157
+ const DEFAULT_KEY = "default";
158
+ var MessageQueue = class {
159
+ keyedActionQueue = {};
160
+ constructor() {}
161
+ flattenKeyedQueue() {
162
+ return Object.values(this.keyedActionQueue).flat();
163
+ }
164
+ triggerSendFromQueue = throttle(() => {
165
+ sendMessageImmediately({
166
+ type: "iframe-action-batch",
167
+ payload: this.flattenKeyedQueue()
168
+ }, { overrideStartTime: Date.now() - MESSAGE_BATCH_TIME });
169
+ this.keyedActionQueue = {};
170
+ }, MESSAGE_BATCH_TIME);
171
+ queueMessage(message, mergeOptions) {
172
+ if (mergeOptions) {
173
+ const { key, mergeFn } = mergeOptions;
174
+ this.keyedActionQueue[key] ??= [];
175
+ this.keyedActionQueue[key] = mergeFn(this.keyedActionQueue[key], message);
176
+ } else {
177
+ this.keyedActionQueue[DEFAULT_KEY] ??= [];
178
+ this.keyedActionQueue[DEFAULT_KEY].push(message);
179
+ }
180
+ this.triggerSendFromQueue();
181
+ }
182
+ };
183
+ var message_queue_default = new MessageQueue();
184
+
185
+ //#endregion
186
+ //#region src/edit-mode/superblocks-editor-bridge.ts
187
+ var SuperblocksEditorBridge = class SuperblocksEditorBridge {
188
+ static instance;
189
+ messagesToSend = [];
190
+ connectedToParent = false;
191
+ static getInstance() {
192
+ const editMode$1 = isEditMode();
193
+ if (!SuperblocksEditorBridge.instance) SuperblocksEditorBridge.instance = editMode$1 ? new SuperblocksEditorBridge() : new DeployedParentBridge();
194
+ return SuperblocksEditorBridge.instance;
195
+ }
196
+ connected() {
197
+ this.connectedToParent = true;
198
+ this.messagesToSend.forEach((message) => this.queueMessage(message.payload, message.mergeOptions));
199
+ this.messagesToSend = [];
200
+ }
201
+ sendReady() {
202
+ this.sendImmediate({
203
+ type: "sb-ready",
204
+ payload: void 0
205
+ }, true);
206
+ }
207
+ sendLoadError(error) {
208
+ this.sendImmediate({
209
+ type: "sb-load-error",
210
+ payload: { error }
211
+ }, true);
212
+ }
213
+ sendNotification(type, message, description) {
214
+ this.queueMessage({
215
+ type: "codeMode/sendNotification",
216
+ payload: {
217
+ type,
218
+ message,
219
+ description
220
+ }
221
+ });
222
+ }
223
+ selectWidgets(sourceIds) {
224
+ this.queueMessage({
225
+ type: "client:selectWidgets",
226
+ payload: { sourceIds }
227
+ });
228
+ }
229
+ editOpRequest(type, payload) {
230
+ this.sendImmediate({
231
+ type: "sb-edit-operation-request",
232
+ payload: {
233
+ type,
234
+ payload
235
+ }
236
+ });
237
+ }
238
+ undo() {
239
+ this.sendImmediate({
240
+ type: "undo",
241
+ payload: void 0
242
+ });
243
+ }
244
+ redo() {
245
+ this.sendImmediate({
246
+ type: "redo",
247
+ payload: void 0
248
+ });
249
+ }
250
+ sendStreamedApiEvent(event, apiName) {
251
+ this.sendImmediate({
252
+ type: "api/stream-event",
253
+ payload: {
254
+ event,
255
+ apiName
256
+ }
257
+ });
258
+ }
259
+ sendStreamedApiMessage(message, apiName) {
260
+ this.sendImmediate({
261
+ type: "api/stream-message",
262
+ payload: {
263
+ message,
264
+ apiName
265
+ }
266
+ });
267
+ }
268
+ setApiStarted(apiName) {
269
+ this.sendImmediate({
270
+ type: "api/started-execution",
271
+ payload: { apiName }
272
+ });
273
+ }
274
+ setApiResponse(apiName, response) {
275
+ this.sendImmediate({
276
+ type: "api/set-api-response",
277
+ payload: {
278
+ apiName,
279
+ response
280
+ }
281
+ });
282
+ }
283
+ navigateTo(path, newWindow) {
284
+ this.sendImmediate({
285
+ type: "navigate-to",
286
+ payload: {
287
+ url: path,
288
+ newWindow
289
+ }
290
+ });
291
+ }
292
+ updatePropertiesPanels(updates) {
293
+ this.queueMessage({
294
+ type: "codeMode/updatePropertiesPanels",
295
+ payload: updates
296
+ });
297
+ }
298
+ addPropertiesPanel(id, definition) {
299
+ this.queueMessage({
300
+ type: "codeMode/addPropertiesPanel",
301
+ payload: {
302
+ id,
303
+ definition
304
+ }
305
+ });
306
+ }
307
+ addApiRunRecord(apiId, run) {
308
+ this.queueMessage({
309
+ type: "codeMode/addApiRunRecord",
310
+ payload: {
311
+ apiId,
312
+ run
313
+ }
314
+ });
315
+ }
316
+ updateApiRunRecord(apiId, callId, updates) {
317
+ this.queueMessage({
318
+ type: "codeMode/updateApiRunRecord",
319
+ payload: {
320
+ apiId,
321
+ callId,
322
+ updates
323
+ }
324
+ });
325
+ }
326
+ initializeEditorSyncedStore(payload) {
327
+ this.queueMessage({
328
+ type: "codeMode/editor-synced-store/init",
329
+ payload
330
+ });
331
+ }
332
+ mergeSyncedStoreUpdate(existingActions, newAction) {
333
+ if (!existingActions || existingActions.length === 0) return [newAction];
334
+ const firstAction = existingActions[0];
335
+ const newActionPatches = newAction.payload.patch;
336
+ firstAction.payload.patch = Array.isArray(firstAction.payload.patch) ? firstAction.payload.patch : [firstAction.payload.patch];
337
+ firstAction.payload.patch.push(...Array.isArray(newActionPatches) ? newActionPatches : [newActionPatches]);
338
+ return existingActions;
339
+ }
340
+ updateEditorSyncedStore(payload) {
341
+ this.queueMessage({
342
+ type: "codeMode/editor-synced-store/update",
343
+ payload
344
+ }, {
345
+ key: `synced-store-update-${payload.storeId}`,
346
+ mergeFn: this.mergeSyncedStoreUpdate
347
+ });
348
+ }
349
+ resolvePromise(callbackId, payload) {
350
+ this.sendImmediate({
351
+ type: "resolve-promise",
352
+ callbackId,
353
+ payload
354
+ });
355
+ }
356
+ rejectPromise(callbackId, payload) {
357
+ this.sendImmediate({
358
+ type: "reject-promise",
359
+ callbackId,
360
+ payload
361
+ });
362
+ }
363
+ canvasClicked() {
364
+ this.sendImmediate({
365
+ type: "register-click",
366
+ payload: {
367
+ type: "INSIDE_IFRAME_CLICKED",
368
+ context: {
369
+ sourceId: "",
370
+ clientX: 0,
371
+ clientY: 0
372
+ }
373
+ }
374
+ });
375
+ }
376
+ registerContextMenuClick(sourceId, clientX, clientY) {
377
+ this.sendImmediate({
378
+ type: "register-click",
379
+ payload: {
380
+ type: "OPEN_CONTEXT_MENU",
381
+ context: {
382
+ sourceId,
383
+ clientX,
384
+ clientY
385
+ }
386
+ }
387
+ });
388
+ }
389
+ updateRoute(routeInfo) {
390
+ this.sendImmediate({
391
+ type: "route-change",
392
+ payload: routeInfo
393
+ }, true);
394
+ }
395
+ addComponentToAiContext(sourceId, selectorId) {
396
+ const editStore = getEditStore();
397
+ if (editStore?.ai.isAlternateSourceIdTarget(sourceId, selectorId)) {
398
+ editStore.ai.addTargetedSelector(selectorId);
399
+ return;
400
+ }
401
+ this.sendImmediate({
402
+ type: "ai-updates",
403
+ payload: {
404
+ type: "add-component-to-context",
405
+ component: sourceId
406
+ }
407
+ });
408
+ }
409
+ toggleComponentInAiContext(sourceId, selectorId, label) {
410
+ const editStore = getEditStore();
411
+ if (editStore?.ai.isAlternateSourceIdTarget(sourceId, selectorId)) {
412
+ editStore.ai.toggleTargetedSelector(selectorId);
413
+ return;
414
+ }
415
+ this.sendImmediate({
416
+ type: "ai-updates",
417
+ payload: {
418
+ type: "toggle-component-in-context",
419
+ component: sourceId,
420
+ label
421
+ }
422
+ });
423
+ }
424
+ setAiContextMode(mode) {
425
+ this.sendImmediate({
426
+ type: "ai-updates",
427
+ payload: {
428
+ type: "set-ai-context-mode",
429
+ mode
430
+ }
431
+ });
432
+ }
433
+ aiGenerate(prompt, forceSend = false) {
434
+ const sanitizedPrompt = clampPromptLength(prompt);
435
+ this.sendImmediate({
436
+ type: "ai-updates",
437
+ payload: {
438
+ type: "ai-generate",
439
+ prompt: sanitizedPrompt
440
+ }
441
+ }, forceSend);
442
+ }
443
+ sendAiLoaderState(shouldShowLoader) {
444
+ this.sendImmediate({
445
+ type: "ai-updates",
446
+ payload: {
447
+ type: "loader-state",
448
+ shouldShowLoader
449
+ }
450
+ });
451
+ }
452
+ socketError(message) {
453
+ this.sendImmediate({
454
+ type: "socket/error",
455
+ payload: { message }
456
+ });
457
+ }
458
+ sendRuntimeError(data) {
459
+ this.sendImmediate({
460
+ type: "runtime-error",
461
+ payload: data
462
+ });
463
+ }
464
+ sendClearRuntimeError(id) {
465
+ this.sendImmediate({
466
+ type: "clear-runtime-error",
467
+ payload: { id }
468
+ });
469
+ }
470
+ setInteractionMode(mode) {
471
+ this.sendImmediate({
472
+ type: "set-interaction-mode",
473
+ payload: { interactionMode: mode }
474
+ });
475
+ }
476
+ queueMessage(message, mergeOptions) {
477
+ if (!this.connectedToParent) this.messagesToSend.push({
478
+ payload: message,
479
+ mergeOptions
480
+ });
481
+ else message_queue_default.queueMessage(message, mergeOptions);
482
+ }
483
+ sendImmediate(message, forceSend = false) {
484
+ if (!this.connectedToParent && !forceSend) this.messagesToSend.push({ payload: message });
485
+ else sendMessageImmediately(message);
486
+ }
487
+ };
488
+ const MAX_AI_PROMPT_LENGTH = 16e3;
489
+ const TRUNCATION_SUFFIX = "... (truncated)";
490
+ function clampPromptLength(prompt) {
491
+ if (prompt.length <= MAX_AI_PROMPT_LENGTH) return prompt;
492
+ const available = Math.max(MAX_AI_PROMPT_LENGTH - 15, 0);
493
+ return `${prompt.slice(0, available)}${TRUNCATION_SUFFIX}`;
494
+ }
495
+ const editorBridge = SuperblocksEditorBridge.getInstance();
496
+
497
+ //#endregion
498
+ //#region src/lib/internal-details/location-store.ts
499
+ var LocationStore = class {
500
+ route;
501
+ rootStore;
502
+ constructor(rootStore) {
503
+ this.rootStore = rootStore;
504
+ }
505
+ @action updateLocation(location, routes, params) {
506
+ this.route = this.locationToRouteInfo(location, routes, params);
507
+ this.sendLocationToEditor();
508
+ }
509
+ sendLocationToEditor() {
510
+ if (!this.route) return;
511
+ editorBridge.updateRoute(this.route);
512
+ }
513
+ /**
514
+ * Recursively searches through route tree (including nested children) to find a matching route
515
+ */
516
+ findMatchingRoute(routes, pathname) {
517
+ return matchRoutes(routes, pathname)?.at(-1);
518
+ }
519
+ locationToRouteInfo(location, routes, params) {
520
+ const match = this.findMatchingRoute(routes, location.pathname);
521
+ if (!match?.pathname) return;
522
+ return {
523
+ hash: location.hash,
524
+ pathname: location.pathname,
525
+ queryParams: getQueryParams(location.search),
526
+ route: match.pathname,
527
+ routeParams: params
528
+ };
529
+ }
530
+ };
531
+
532
+ //#endregion
533
+ //#region src/lib/user-facing/assets/icons/system-danger.svg
534
+ var _path$5;
535
+ function _extends$5() {
536
+ return _extends$5 = Object.assign ? Object.assign.bind() : function(n) {
537
+ for (var e = 1; e < arguments.length; e++) {
538
+ var t = arguments[e];
539
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
540
+ }
541
+ return n;
542
+ }, _extends$5.apply(null, arguments);
543
+ }
544
+ var SvgSystemDanger = function SvgSystemDanger$1(props) {
545
+ return /* @__PURE__ */ React$1.createElement("svg", _extends$5({
546
+ xmlns: "http://www.w3.org/2000/svg",
547
+ width: 16,
548
+ height: 16,
549
+ fill: "none"
550
+ }, props), _path$5 || (_path$5 = /* @__PURE__ */ React$1.createElement("path", {
551
+ fill: "currentColor",
552
+ fillRule: "evenodd",
553
+ d: "M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m.75-10a.75.75 0 0 0-1.5 0v3a.75.75 0 1 0 1.5 0zM8 9.75a1 1 0 1 0 0 2 1 1 0 0 0 0-2",
554
+ clipRule: "evenodd"
555
+ })));
556
+ };
557
+ var system_danger_default = SvgSystemDanger;
558
+
559
+ //#endregion
560
+ //#region src/lib/user-facing/assets/icons/system-error.svg
561
+ var _path$4;
562
+ function _extends$4() {
563
+ return _extends$4 = Object.assign ? Object.assign.bind() : function(n) {
564
+ for (var e = 1; e < arguments.length; e++) {
565
+ var t = arguments[e];
566
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
567
+ }
568
+ return n;
569
+ }, _extends$4.apply(null, arguments);
570
+ }
571
+ var SvgSystemError = function SvgSystemError$1(props) {
572
+ return /* @__PURE__ */ React$1.createElement("svg", _extends$4({
573
+ xmlns: "http://www.w3.org/2000/svg",
574
+ width: 16,
575
+ height: 16,
576
+ fill: "none"
577
+ }, props), _path$4 || (_path$4 = /* @__PURE__ */ React$1.createElement("path", {
578
+ fill: "currentColor",
579
+ fillRule: "evenodd",
580
+ d: "M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0M5.942 5.058a.625.625 0 1 0-.884.884L7.116 8l-2.058 2.058a.625.625 0 1 0 .884.884L8 8.884l2.058 2.058a.625.625 0 1 0 .884-.884L8.884 8l2.058-2.058a.625.625 0 1 0-.884-.884L8 7.116z",
581
+ clipRule: "evenodd"
582
+ })));
583
+ };
584
+ var system_error_default = SvgSystemError;
585
+
586
+ //#endregion
587
+ //#region src/lib/user-facing/assets/icons/system-info.svg
588
+ var _path$3;
589
+ function _extends$3() {
590
+ return _extends$3 = Object.assign ? Object.assign.bind() : function(n) {
591
+ for (var e = 1; e < arguments.length; e++) {
592
+ var t = arguments[e];
593
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
594
+ }
595
+ return n;
596
+ }, _extends$3.apply(null, arguments);
597
+ }
598
+ var SvgSystemInfo = function SvgSystemInfo$1(props) {
599
+ return /* @__PURE__ */ React$1.createElement("svg", _extends$3({
600
+ xmlns: "http://www.w3.org/2000/svg",
601
+ width: 16,
602
+ height: 16,
603
+ fill: "none"
604
+ }, props), _path$3 || (_path$3 = /* @__PURE__ */ React$1.createElement("path", {
605
+ fill: "currentColor",
606
+ d: "M8 1a7 7 0 1 0 7 7 7.014 7.014 0 0 0-7-7m-.135 3.23a.808.808 0 1 1 0 1.616.808.808 0 0 1 0-1.615m.673 7.54H8a.54.54 0 0 1-.538-.54V8a.538.538 0 1 1 0-1.077H8a.54.54 0 0 1 .538.539v3.23a.538.538 0 1 1 0 1.077"
607
+ })));
608
+ };
609
+ var system_info_default = SvgSystemInfo;
610
+
611
+ //#endregion
612
+ //#region src/lib/user-facing/assets/icons/system-success.svg
613
+ var _path$2;
614
+ function _extends$2() {
615
+ return _extends$2 = Object.assign ? Object.assign.bind() : function(n) {
616
+ for (var e = 1; e < arguments.length; e++) {
617
+ var t = arguments[e];
618
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
619
+ }
620
+ return n;
621
+ }, _extends$2.apply(null, arguments);
622
+ }
623
+ var SvgSystemSuccess = function SvgSystemSuccess$1(props) {
624
+ return /* @__PURE__ */ React$1.createElement("svg", _extends$2({
625
+ xmlns: "http://www.w3.org/2000/svg",
626
+ width: 16,
627
+ height: 16,
628
+ fill: "none"
629
+ }, props), _path$2 || (_path$2 = /* @__PURE__ */ React$1.createElement("path", {
630
+ fill: "currentColor",
631
+ fillRule: "evenodd",
632
+ d: "M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.442-8.058a.625.625 0 1 0-.884-.884L7.5 9.116 5.942 7.558a.625.625 0 1 0-.884.884l2 2c.244.244.64.244.884 0z",
633
+ clipRule: "evenodd"
634
+ })));
635
+ };
636
+ var system_success_default = SvgSystemSuccess;
637
+
638
+ //#endregion
639
+ //#region src/lib/user-facing/styling/colors.ts
640
+ const colors = {
641
+ WHITE: "#FFFFFF",
642
+ BLACK: "#000000",
643
+ PLATFORM_BLACK: "#0E141B",
644
+ OFF_WHITE: "#F2F2F2",
645
+ DISABLED: "rgba(0, 0, 0, 0.25)",
646
+ GREY_25: "#F9FAFB",
647
+ GREY_50: "#F3F4F6",
648
+ GREY_100: "#E8EAED",
649
+ GREY_200: "#C6CAD2",
650
+ GREY_300: "#A4AAB7",
651
+ GREY_400: "#818A9C",
652
+ GREY_500: "#6C7689",
653
+ GREY_600: "#5A6272",
654
+ GREY_700: "#454D5F",
655
+ GREY_800: "#2F3437",
656
+ GREY_900: "#121517",
657
+ GRAY_GRID: "#CCD3DB",
658
+ RED_500_8: "rgba(255, 72, 72, 0.08)",
659
+ RED_25: "#FF48481F",
660
+ RED_500: "#FF4848",
661
+ RED_600: "#DB4949",
662
+ RED_700: "#C54141",
663
+ ORANGE_25: "#FFEEC5",
664
+ ORANGE_600: "#FA8A0F",
665
+ SUBTLE_BLUE: "#29bbff14",
666
+ SUBTLE_BLUE_SOLID: "#eefaff",
667
+ ACCENT_BLUE_NEW_DARKER: "#0087E0",
668
+ BLUE_MINMAX_LABELS: "#0062A3",
669
+ DRAG_PREVIEW_BLUE: "rgba(0, 135, 224, 0.16)",
670
+ ACCENT_BLUE_500: "#27BBFF",
671
+ ACCENT_BLUE_500_04: "#27BBFF0A",
672
+ ACCENT_BLUE_500_25: "#27BBFF14",
673
+ ACCENT_BLUE_500_50: "#27BBFF1F",
674
+ ACCENT_BLUE_500_18: "#27BBFF2E",
675
+ ACCENT_BLUE_500_24: "#27BBFF3D",
676
+ ACCENT_BLUE_500_48: "#27BBFF7A",
677
+ ACCENT_BLUE_600: "#00A8F5",
678
+ ACCENT_BLUE_700: "#009AE0",
679
+ ACCENT_ORANGE: "#FF9F35",
680
+ ACCENT_ORANGE_04: "#FF9F350A",
681
+ ACCENT_ORANGE_24: "#FF9F353D",
682
+ LIGHT_ORANGE: "#FF9F351E",
683
+ ACCENT_ORANGE_600: "#FA8A0F",
684
+ SUBTLE_PURPLE: "#643ADF14",
685
+ ACCENT_PURPLE: "#643ADF",
686
+ LIGHT_PURPLE: "#643ADF1E",
687
+ ACCENT_PURPLE_500: "#7C4FF8",
688
+ ACCENT_PURPLE_600: "#5227CE",
689
+ SUBTLE_GREEN: "#14CDB714",
690
+ LIGHT_GREEN: "#9BDCAD",
691
+ ACCENT_GREEN: "#14CDB7",
692
+ ACCENT_GREEN_600: "#08BAA5",
693
+ LIGHT_PINK: `rgba(255, 98, 164, 0.12)`,
694
+ ACCENT_PINK: "#FF62A4",
695
+ HOVER_BLUE: "#E3F8FF",
696
+ HOVER_GREEN: "#14CDB724",
697
+ CLICK_GREEN: "#14CDB734",
698
+ INFO: "#27BBFF",
699
+ WARNING: "#FF9F35",
700
+ DANGER: "#F45252",
701
+ DANGER_BRIGHT: "rgba(255, 72, 72, 1.0)",
702
+ DANGER_SUBTLE: "#F452521F",
703
+ SUCCESS: "#0CC26D",
704
+ NONE: "transparent"
705
+ };
706
+
707
+ //#endregion
708
+ //#region src/lib/user-facing/themes/classnames.ts
709
+ const MODIFIER_CLASSNAMES = {
710
+ DISABLED_MODIFIER: "sb-disabled",
711
+ ERROR_MODIFIER: "sb-error",
712
+ ACTIVE_MODIFIER: "sb-active"
713
+ };
714
+ const CLASS_NAMES = {
715
+ ...MODIFIER_CLASSNAMES,
716
+ HEADING1: "sb-heading-1",
717
+ HEADING2: "sb-heading-2",
718
+ HEADING3: "sb-heading-3",
719
+ HEADING4: "sb-heading-4",
720
+ HEADING5: "sb-heading-5",
721
+ HEADING6: "sb-heading-6",
722
+ BODY1: "sb-body-1",
723
+ BODY2: "sb-body-2",
724
+ BODY3: "sb-body-3",
725
+ LINK: "sb-link",
726
+ INPUT_LABEL: "sb-input-label",
727
+ LABEL: "sb-label",
728
+ CODE_TEXT: "sb-code",
729
+ INPUT_TEXT: "sb-input-text",
730
+ INPUT_PLACEHOLDER: "sb-input-placeholder",
731
+ BUTTON_LABEL: "sb-button-label",
732
+ SYSTEM_TEXT: "sb-system-text",
733
+ BUILTIN_BODY: "sb-builtin-body",
734
+ ELLIPSIS_TEXT: "sb-ellipsis-text",
735
+ BUTTON: "sb-button",
736
+ PRIMARY_BUTTON: "sb-button-primary",
737
+ SECONDARY_BUTTON: "sb-button-secondary",
738
+ SECONDARY_NEUTRAL_BUTTON: "sb-button-secondary-neutral",
739
+ TERTIARY_BUTTON: "sb-button-tertiary",
740
+ SYSTEM_BUTTON: "sb-button-system",
741
+ INPUT: "sb-input",
742
+ SWITCH: "sb-switch",
743
+ CHECKBOX: "sb-checkbox",
744
+ RADIO: "sb-radio",
745
+ SECTION: "sb-section",
746
+ ROUNDED_CONTAINER: "sb-rounded-container",
747
+ CANVAS: "sb-canvas",
748
+ DEFAULT_CONTAINER: "sb-default-container",
749
+ DEFAULT_CONTAINER_STYLE_CARD: "sb-default-container-style-card",
750
+ DEFAULT_CONTAINER_STYLE_NONE: "sb-default-container-style-none",
751
+ DEFAULT_CONTAINER_BORDER: "sb-default-container-border",
752
+ CONTAINER_BORDER_OUTLINE: "sb-container-border-overlay",
753
+ POPOVER_WRAPPER: "sb-popover-wrapper",
754
+ TAB: "sb-tab",
755
+ MODAL: "sb-modal",
756
+ SLIDEOUT: "sb-slideout",
757
+ BORDER_BOTTOM: "sb-util-border-bottom",
758
+ BORDER_TOP: "sb-util-border-top",
759
+ NOTIFICATION: "sb-notification",
760
+ STYLED_SCROLLBAR: "sb-scrollable",
761
+ TOOLTIP: "sb-tooltip",
762
+ DROPDOWN: "sb-dropdown",
763
+ DROPDOWN_MENU: "sb-dropdown-menu",
764
+ MENU_ITEM: "sb-menu-item",
765
+ TAG_INPUT: "sb-tag-input",
766
+ DATEPICKER: "sb-datepicker",
767
+ DROPDOWN_CLEAR_ICON: "sb-dropdown-clear-icon",
768
+ CARET_ICON: "sb-caret-icon",
769
+ PRIMARY_COLOR_ICON: "sb-primary-color-icon",
770
+ CLOSE_ICON: "sb-close-icon",
771
+ ICON: "sb-icon",
772
+ PAGINATOR: "sb-rc-paginator",
773
+ CODE_EDITOR: "sb-code-editor",
774
+ ERROR_INLINE_MESSAGE: "sb-error-inline-message"
775
+ };
776
+
777
+ //#endregion
778
+ //#region src/lib/user-facing/utils/notification.tsx
779
+ const activeNotifications = /* @__PURE__ */ new Map();
780
+ const StatusIconWrapper = styled.div`
781
+ color: ${(props) => props.color};
782
+ font-size: 16px;
783
+ margin-top: -2px;
784
+ margin-left: -10px;
785
+ svg {
786
+ width: 18px;
787
+ height: 18px;
788
+ }
789
+ `;
790
+ const MessageWrapper = styled.div`
791
+ font-size: 12px;
792
+ font-weight: 500;
793
+ line-height: 1.3;
794
+ margin-left: -26px;
795
+ margin-right: 0;
796
+ white-space: pre-wrap;
797
+ `;
798
+ const DescriptionWrapper = styled.div`
799
+ font-size: 12px;
800
+ margin-left: -26px;
801
+ margin-right: -10px;
802
+ `;
803
+ const styleMessage = (message, dataTest) => {
804
+ return /* @__PURE__ */ jsx(MessageWrapper, {
805
+ "data-test": dataTest ? dataTest : "notification",
806
+ children: message
807
+ });
808
+ };
809
+ const styleDescription = (description) => {
810
+ if (!description) return;
811
+ return /* @__PURE__ */ jsx(DescriptionWrapper, { children: description });
812
+ };
813
+ const messageWithCount = (key, message, dataTest) => {
814
+ let updatedMessage = message;
815
+ if (key) {
816
+ const count = (activeNotifications.get(key)?.count ?? 0) + 1;
817
+ activeNotifications.set(key, {
818
+ count,
819
+ message
820
+ });
821
+ if (count > 1 && isString(message)) updatedMessage = `${message} (${count} times)`;
822
+ }
823
+ return styleMessage(updatedMessage, dataTest);
824
+ };
825
+ /**
826
+ * When a Key is used,
827
+ * duplicate notifications are not shown but the timeout is added to the first notification.
828
+ * @returns A string key based on inputs
829
+ */
830
+ const getKey = (type, message, description, duration) => {
831
+ return isString(message) ? `${type}--${String(message)}--${description}--${duration}` : void 0;
832
+ };
833
+ const removeNotificationsWithKey = (key) => {
834
+ document.querySelectorAll(`[data-testid="notification_${key}"]`).forEach((el) => {
835
+ el.remove();
836
+ });
837
+ };
838
+ const attrSafeKey = (str) => {
839
+ return str.replace(/\W+/g, "_");
840
+ };
841
+ const getIcon = (type) => {
842
+ let icon;
843
+ let color;
844
+ switch (type) {
845
+ case "success":
846
+ icon = /* @__PURE__ */ jsx(system_success_default, {});
847
+ color = colors.SUCCESS;
848
+ break;
849
+ case "error":
850
+ icon = /* @__PURE__ */ jsx(system_error_default, {});
851
+ color = colors.DANGER;
852
+ break;
853
+ case "info":
854
+ icon = /* @__PURE__ */ jsx(system_info_default, {});
855
+ color = colors.INFO;
856
+ break;
857
+ case "warning":
858
+ icon = /* @__PURE__ */ jsx(system_danger_default, {});
859
+ color = colors.WARNING;
860
+ break;
861
+ }
862
+ return /* @__PURE__ */ jsx(StatusIconWrapper, {
863
+ color,
864
+ children: icon
865
+ });
866
+ };
867
+ function onAlertClose(key) {
868
+ if (key) activeNotifications.delete(key);
869
+ }
870
+ const positionToPlacement = {
871
+ [NotificationPosition.bottom]: "bottom-center",
872
+ [NotificationPosition.top]: "top-center",
873
+ [NotificationPosition.topLeft]: "top-left",
874
+ [NotificationPosition.topRight]: "top-right",
875
+ [NotificationPosition.bottomLeft]: "bottom-left",
876
+ [NotificationPosition.bottomRight]: "bottom-right"
877
+ };
878
+ function sendNotification({ message, description, duration, key = getKey("success", message, description, duration), placement = NotificationPosition.bottomRight, style, dataTest, type }) {
879
+ const icon = getIcon(type);
880
+ const handleClose = () => {
881
+ onAlertClose(key);
882
+ if (key) removeNotificationsWithKey(attrSafeKey(`notification-${key}`));
883
+ };
884
+ if (key) {
885
+ toast.dismiss(key);
886
+ removeNotificationsWithKey(attrSafeKey(`notification-${key}`));
887
+ }
888
+ const position = positionToPlacement[placement];
889
+ toast.success(messageWithCount(key, message, dataTest), {
890
+ id: key,
891
+ description: styleDescription(description),
892
+ icon,
893
+ duration: duration ? duration * 1e3 : void 0,
894
+ position,
895
+ className: CLASS_NAMES.NOTIFICATION,
896
+ style,
897
+ onDismiss: handleClose,
898
+ onAutoClose: handleClose
899
+ });
900
+ }
901
+
902
+ //#endregion
903
+ //#region src/lib/internal-details/superblocks-context.tsx
904
+ var SuperblocksAppContext = class {
905
+ context;
906
+ constructor() {
907
+ makeAutoObservable(this);
908
+ }
909
+ get user() {
910
+ return this.context?.user;
911
+ }
912
+ get groups() {
913
+ return this.context?.groups;
914
+ }
915
+ get selectedProfile() {
916
+ return this.context?.profiles?.selected;
917
+ }
918
+ get profiles() {
919
+ return this.context?.profiles;
920
+ }
921
+ setProfile(profileName) {
922
+ const profile = this.context?.profiles?.available.find((profile$1) => profile$1.displayName === profileName);
923
+ if (profile && this.context?.profiles) this.context.profiles.selected = profile;
924
+ else if (!profile || !this.context?.profiles) throw new Error(`Profile ${profileName} not found`);
925
+ }
926
+ updateContext(context$2) {
927
+ this.context = {
928
+ ...this.context,
929
+ ...context$2
930
+ };
931
+ }
932
+ };
933
+ const context$1 = new SuperblocksAppContext();
934
+ const SuperblocksContext = createContext(context$1);
935
+ function SuperblocksContextProvider({ children, value: contextOverride }) {
936
+ if (contextOverride) return /* @__PURE__ */ jsx(SuperblocksContext.Provider, {
937
+ value: contextOverride,
938
+ children
939
+ });
940
+ return /* @__PURE__ */ jsx(SuperblocksContext.Provider, {
941
+ value: context$1,
942
+ children
943
+ });
944
+ }
945
+ function useSuperblocksContext() {
946
+ return useContext(SuperblocksContext);
947
+ }
948
+ function useSuperblocksUser() {
949
+ const context$2 = useSuperblocksContext();
950
+ return useSyncExternalStore((onStoreChange) => {
951
+ return reaction(() => context$2.user, onStoreChange);
952
+ }, () => {
953
+ return context$2.user;
954
+ }, () => {
955
+ return context$2.user;
956
+ });
957
+ }
958
+ function useSuperblocksGroups() {
959
+ const context$2 = useSuperblocksContext();
960
+ return useSyncExternalStore((onStoreChange) => {
961
+ return reaction(() => context$2.groups, onStoreChange);
962
+ }, () => {
963
+ return context$2.groups;
964
+ }, () => {
965
+ return context$2.groups;
966
+ });
967
+ }
968
+ function useSuperblocksProfiles() {
969
+ const context$2 = useSuperblocksContext();
970
+ return {
971
+ profiles: useSyncExternalStore((onStoreChange) => {
972
+ return reaction(() => context$2.profiles, onStoreChange);
973
+ }, () => {
974
+ return context$2.profiles;
975
+ }, () => {
976
+ return context$2.profiles;
977
+ }),
978
+ setProfile: useCallback((profileName) => {
979
+ context$2.setProfile(profileName);
980
+ }, [context$2])
981
+ };
982
+ }
983
+
984
+ //#endregion
985
+ //#region src/lib/internal-details/lib/resolve-id-singleton.ts
986
+ const EMBED_STRING = `embedded-`;
987
+ let promiseCount = 0;
988
+ const resolverMap = /* @__PURE__ */ new Map();
989
+ const rejectorMap = /* @__PURE__ */ new Map();
990
+ const multiUseCallbacks = /* @__PURE__ */ new Map();
991
+ function addNewPromise(resolver, isMultiUse = false, rejecter) {
992
+ const promiseId = `${isEmbeddedBySuperblocksFirstParty() ? EMBED_STRING : ""}p${++promiseCount}`;
993
+ resolverMap.set(promiseId, resolver);
994
+ if (isMultiUse) multiUseCallbacks.set(promiseId, resolver);
995
+ if (rejecter) rejectorMap.set(promiseId, rejecter);
996
+ return promiseId;
997
+ }
998
+ function resolveById(id, payload) {
999
+ const isEmbedId = id.startsWith(EMBED_STRING);
1000
+ if (isEmbeddedBySuperblocksFirstParty() && !isEmbedId || !isEmbeddedBySuperblocksFirstParty() && isEmbedId) editorBridge.resolvePromise(id, payload);
1001
+ else try {
1002
+ const resolver = resolverMap.get(id);
1003
+ if (!resolver) throw new Error(`Promise not found for id ${id}`);
1004
+ resolver(payload);
1005
+ if (!multiUseCallbacks.has(id)) {
1006
+ resolverMap.delete(id);
1007
+ rejectorMap.delete(id);
1008
+ }
1009
+ } catch (e) {
1010
+ console.log("Error resolving promise", e);
1011
+ }
1012
+ }
1013
+ function rejectById(id, payload) {
1014
+ const isEmbedId = id.startsWith(EMBED_STRING);
1015
+ if (isEmbeddedBySuperblocksFirstParty() && !isEmbedId || !isEmbeddedBySuperblocksFirstParty() && isEmbedId) editorBridge.rejectPromise(id, payload);
1016
+ else try {
1017
+ const rejecter = rejectorMap.get(id);
1018
+ if (!rejecter) throw new Error(`Promise not found for id ${id}`);
1019
+ rejecter(payload);
1020
+ if (!multiUseCallbacks.has(id)) {
1021
+ resolverMap.delete(id);
1022
+ rejectorMap.delete(id);
1023
+ }
1024
+ } catch (e) {
1025
+ console.log("Error rejecting promise", e);
1026
+ }
1027
+ }
1028
+
1029
+ //#endregion
1030
+ //#region src/lib/tracing/context-utils.ts
1031
+ function getContextFromTraceHeaders(traceHeaders) {
1032
+ let parentContext = context.active();
1033
+ try {
1034
+ parentContext = propagation.extract(context.active(), traceHeaders);
1035
+ } catch (error) {
1036
+ console.warn("Failed to extract parent context from headers", traceHeaders, error);
1037
+ }
1038
+ return parentContext;
1039
+ }
1040
+ function createIframeSpan(name, attributes, parentContext) {
1041
+ return getTracer("superblocks-iframe").startSpan(name, { attributes }, parentContext);
1042
+ }
1043
+ function getTraceContextHeadersFromSpan(span) {
1044
+ const traceContextHeaders = {};
1045
+ const contextWithSpan = trace.setSpan(ROOT_CONTEXT, span);
1046
+ propagation.inject(contextWithSpan, traceContextHeaders);
1047
+ return traceContextHeaders;
1048
+ }
1049
+
1050
+ //#endregion
1051
+ //#region src/lib/utils/generate-id.ts
1052
+ const generateId = () => {
1053
+ return Math.random().toString(36).substring(2, 15);
1054
+ };
1055
+
1056
+ //#endregion
1057
+ //#region src/lib/internal-details/lib/features/api-utils.ts
1058
+ async function executeV2Api(params) {
1059
+ const { body, apiName, controlFlowOnlyFiles, notifyOnSystemError, eventType, onMessage, processStreamEvents, responseType, abortController, baseUrl, viewMode, accessToken, token, traceHeaders } = params;
1060
+ let parentContext = context.active();
1061
+ if (traceHeaders) parentContext = getContextFromTraceHeaders(traceHeaders);
1062
+ let applicationId = "unknown";
1063
+ if ("fetchByPath" in body) applicationId = body.fetchByPath.applicationId;
1064
+ const span = createIframeSpan("iframe_execute_v2_api", {
1065
+ "api-name": apiName || "unknown",
1066
+ "application-id": applicationId,
1067
+ event_type: eventType,
1068
+ response_type: responseType,
1069
+ view_mode: viewMode
1070
+ }, parentContext);
1071
+ try {
1072
+ let cleanedBody;
1073
+ try {
1074
+ cleanedBody = cleanObject(body);
1075
+ } catch {
1076
+ cleanedBody = structuredClone(body);
1077
+ }
1078
+ if (controlFlowOnlyFiles && controlFlowOnlyFiles.length > 0) cleanedBody = {
1079
+ ...cleanedBody,
1080
+ files: controlFlowOnlyFiles
1081
+ };
1082
+ const traceContextHeaders = getTraceContextHeadersFromSpan(span);
1083
+ const init = {
1084
+ method: HttpMethod.Post,
1085
+ body: JSON.stringify(cleanedBody),
1086
+ signal: abortController?.signal,
1087
+ headers: {
1088
+ [SUPERBLOCKS_AUTHORIZATION_HEADER]: `Bearer ${accessToken}`,
1089
+ Authorization: `Bearer ${token}`,
1090
+ [SUPERBLOCKS_REQUEST_ID_HEADER]: generateId(),
1091
+ ...traceContextHeaders
1092
+ },
1093
+ credentials: "include"
1094
+ };
1095
+ return responseType === ApiResponseType.STREAM ? await fetchServerStream({
1096
+ augmentedInit: init,
1097
+ fullUrl: baseUrl,
1098
+ timeoutId: setTimeout(() => {}, 1e3),
1099
+ onMessage,
1100
+ processStreamEvents
1101
+ }) : await fetchServer({
1102
+ augmentedInit: init,
1103
+ fullUrl: baseUrl,
1104
+ timeoutId: setTimeout(() => {}, 1e3)
1105
+ });
1106
+ } catch (err) {
1107
+ const message = `Failed to execute ${apiName || "API"}. ${err}`;
1108
+ const suppressError = viewMode !== ViewMode.EDITOR && err?.code === 20;
1109
+ if (notifyOnSystemError && !suppressError) console.log(message);
1110
+ return { systemError: message };
1111
+ } finally {
1112
+ span.end();
1113
+ }
1114
+ }
1115
+ const HttpMethod = {
1116
+ Get: "GET",
1117
+ Post: "POST",
1118
+ Put: "PUT",
1119
+ Patch: "PATCH",
1120
+ Delete: "DELETE"
1121
+ };
1122
+ const stream = async ({ url, headers, body, onMessage, onComplete, onError, defaultError, method, baseUrl = "/api/", signal, init: overrideInit }) => {
1123
+ const init = overrideInit ?? {
1124
+ body: JSON.stringify(body),
1125
+ headers,
1126
+ method
1127
+ };
1128
+ try {
1129
+ const response = await fetch(`${baseUrl}${url}`, init);
1130
+ if (!response.ok) try {
1131
+ const parsed = await response.json();
1132
+ throw new HttpError(response.status, !response.status || response.status >= 500, parsed?.error?.message ?? parsed?.responseMeta?.error?.message ?? defaultError);
1133
+ } catch (e) {
1134
+ if (e instanceof HttpError) throw e;
1135
+ throw new HttpError(response.status, !response.status || response.status >= 500, response.statusText);
1136
+ }
1137
+ if (!response.body) return;
1138
+ const reader = response.body.getReader();
1139
+ const decoder = new TextDecoder();
1140
+ let done = false;
1141
+ let lastChunk = "";
1142
+ while (!done) {
1143
+ if (signal && signal.aborted) return;
1144
+ const { value, done: readerDone } = await reader.read();
1145
+ const chunk = lastChunk + decoder.decode(value);
1146
+ const messages = chunk.split("\n");
1147
+ let jsonValues = [];
1148
+ try {
1149
+ jsonValues = messages.filter(Boolean).map((message) => JSON.parse(message.trim()));
1150
+ lastChunk = "";
1151
+ } catch (e) {
1152
+ lastChunk = chunk;
1153
+ if (readerDone) throw e;
1154
+ }
1155
+ for (const jsonValue of jsonValues.filter(Boolean)) {
1156
+ if (jsonValue?.error) {
1157
+ onError(jsonValue.error.message ?? defaultError);
1158
+ return;
1159
+ }
1160
+ onMessage(jsonValue);
1161
+ }
1162
+ done = readerDone && lastChunk === "";
1163
+ }
1164
+ } catch (e) {
1165
+ if (e.name === "AbortError") console.log("Fetch was cancelled");
1166
+ else onError(e.message ?? defaultError, e.code);
1167
+ } finally {
1168
+ onComplete();
1169
+ }
1170
+ };
1171
+ const handleError = (rawError, { fullUrl, augmentedInit }) => {
1172
+ const error = rawError instanceof TypeError ? new HttpError(0, true, rawError.message) : rawError;
1173
+ console.error(`Request to '${fullUrl} has failed
1174
+ Response Status: ${error.code}
1175
+ Response Status Text: ${error.message}`);
1176
+ let critical = error.critical;
1177
+ if (fullUrl.match(/apis\/.*/) && (critical || error.code === 0)) critical = false;
1178
+ if (fullUrl.match(/\/(commits|deployment).*/) && error.code === 500) critical = false;
1179
+ if (augmentedInit.method === HttpMethod.Get && fullUrl.match(/apis\/.*/)) critical = true;
1180
+ else if (fullUrl.match(/apis\/.*/)) {}
1181
+ if (error.code && error.code < 500 && error.code >= 400) {
1182
+ if (error.code === 404) critical = true;
1183
+ }
1184
+ if (error.code >= 500) critical = false;
1185
+ };
1186
+ const fetchServerStream = async ({ augmentedInit, fullUrl, timeoutId, onMessage, processStreamEvents }) => {
1187
+ const handleMessage = (message) => {
1188
+ if (message?.result?.event?.data) onMessage && onMessage(message.result.event.data);
1189
+ else if (message?.result?.event?.start || message?.result?.event?.end) processStreamEvents && processStreamEvents(message);
1190
+ };
1191
+ const onComplete = () => {
1192
+ clearTimeout(timeoutId);
1193
+ };
1194
+ const onError = (error, statusCode) => {
1195
+ if (statusCode != null) handleError(new HttpError(statusCode, !statusCode || statusCode >= 500, error), {
1196
+ fullUrl,
1197
+ augmentedInit,
1198
+ timeoutId
1199
+ });
1200
+ else handleError(new TypeError(error), {
1201
+ fullUrl,
1202
+ augmentedInit,
1203
+ timeoutId
1204
+ });
1205
+ };
1206
+ return stream({
1207
+ url: fullUrl,
1208
+ init: augmentedInit,
1209
+ onMessage: handleMessage,
1210
+ onComplete,
1211
+ onError,
1212
+ baseUrl: "",
1213
+ signal: augmentedInit?.signal ?? void 0
1214
+ });
1215
+ };
1216
+ const getErrorMessageFromObject = (message) => {
1217
+ const messageJSONString = JSON.stringify(message);
1218
+ const match = /"message"\s*:\s*"([^"]*)"/.exec(messageJSONString);
1219
+ return match ? match[1] : messageJSONString;
1220
+ };
1221
+ const fetchServer = ({ augmentedInit, fullUrl, timeoutId }) => {
1222
+ return fetch(fullUrl, augmentedInit).then(async (response) => {
1223
+ try {
1224
+ if (response.status === 204) return null;
1225
+ const json = await response.json();
1226
+ if (response.ok && json) {
1227
+ if (json.data == null) return json;
1228
+ return json.data;
1229
+ } else {
1230
+ let message = json.responseMeta?.error?.message ?? json?.message;
1231
+ if (typeof message === "object") message = getErrorMessageFromObject(message);
1232
+ throw new HttpError(response.status, !response.status || response.status >= 500, message);
1233
+ }
1234
+ } catch (e) {
1235
+ if (e instanceof HttpError) throw e;
1236
+ throw new HttpError(response.status, !response.status || response.status >= 500, response.statusText);
1237
+ }
1238
+ }).catch((rawError) => {
1239
+ handleError(rawError, {
1240
+ fullUrl,
1241
+ augmentedInit,
1242
+ timeoutId
1243
+ });
1244
+ }).finally(() => clearTimeout(timeoutId));
1245
+ };
1246
+ var HttpError = class extends Error {
1247
+ code;
1248
+ critical;
1249
+ constructor(code, critical = false, m) {
1250
+ super(m);
1251
+ this.code = code;
1252
+ this.critical = critical;
1253
+ }
1254
+ };
1255
+ const parseStreamResult = (streamResult, options) => {
1256
+ if (!streamResult || !Array.isArray(streamResult) || !streamResult.length) return;
1257
+ const execution = streamResult[0].result.execution;
1258
+ const [errors, events] = streamResult.reduce((accum, event) => {
1259
+ if (event.result.event.end && event.result.event.end.error) accum[0].push(event.result.event.end.error);
1260
+ accum[1].push(event.result.event);
1261
+ return accum;
1262
+ }, [[], []]);
1263
+ const result = {
1264
+ execution,
1265
+ events,
1266
+ errors,
1267
+ status: "STATUS_COMPLETED"
1268
+ };
1269
+ if (options?.includeFinalOutput) {
1270
+ let returnBlockOutput;
1271
+ for (let i = 0; i < streamResult.length; i++) {
1272
+ const streamEvent = streamResult[i];
1273
+ if (streamEvent.result.event.type === "BLOCK_TYPE_RETURN" && streamEvent.result.event.end) {
1274
+ returnBlockOutput = streamEvent.result.event.end?.output;
1275
+ break;
1276
+ }
1277
+ }
1278
+ if (returnBlockOutput) result.output = returnBlockOutput;
1279
+ else result.output = streamResult[streamResult.length - 1].result.event.end?.output;
1280
+ }
1281
+ return result;
1282
+ };
1283
+ const isApiV2ExecutionResponse = (response) => {
1284
+ return !!response && "output" in response && response?.output?.result != null;
1285
+ };
1286
+ const decodeBytestringsInV2ExecutionResponse = (response) => {
1287
+ if (!isApiV2ExecutionResponse(response)) return;
1288
+ if (response.output) response.output.result = decodeBytestrings(response.output.result, false);
1289
+ if (Array.isArray(response.events)) response.events.forEach((event) => {
1290
+ const typedEvent = event;
1291
+ if (typedEvent?.end?.output?.result != null) typedEvent.end.output.result = decodeBytestrings(typedEvent.end.output.result, false);
1292
+ });
1293
+ };
1294
+
1295
+ //#endregion
1296
+ //#region src/lib/internal-details/lib/features/file-utils.ts
1297
+ function getFileUploadId(file) {
1298
+ return `${file.name.replace(/[^a-zA-Z0-9.-]/g, "_")}-${file.size}-${file.lastModified}`;
1299
+ }
1300
+ function getFileInputData(f) {
1301
+ const superblocksId = getFileUploadId(f);
1302
+ const nameParts = f.name.split(".");
1303
+ const extension = nameParts.length > 1 ? nameParts.pop() || "" : "";
1304
+ return {
1305
+ $superblocksId: superblocksId,
1306
+ name: f.name,
1307
+ extension,
1308
+ type: f.type,
1309
+ size: f.size,
1310
+ encoding: "text"
1311
+ };
1312
+ }
1313
+ async function formatFileForRequest(file, fileId) {
1314
+ return {
1315
+ originalName: fileId,
1316
+ buffer: await new Promise((resolve, reject) => {
1317
+ const reader = new FileReader();
1318
+ reader.onload = () => resolve(reader.result.split(",")[1]);
1319
+ reader.onerror = () => reject(new Error(reader.error?.message || "Unknown error reading file"));
1320
+ reader.readAsDataURL(file);
1321
+ }),
1322
+ encoding: "base64",
1323
+ mimetype: "text/plain"
1324
+ };
1325
+ }
1326
+ async function getInputsWithFileMetadata(inputs) {
1327
+ const filesForRequest = {};
1328
+ const processValue = async (value) => {
1329
+ if (value === void 0) return null;
1330
+ if (value instanceof File) {
1331
+ const inputData = getFileInputData(value);
1332
+ if (!filesForRequest[inputData.$superblocksId]) filesForRequest[inputData.$superblocksId] = await formatFileForRequest(value, inputData.$superblocksId);
1333
+ return inputData;
1334
+ } else if (Array.isArray(value)) return await Promise.all(value.map((item) => processValue(item)));
1335
+ else if (typeof value === "object" && value != null && value.constructor === Object) return await processObject(value);
1336
+ return value;
1337
+ };
1338
+ const processObject = async (obj) => {
1339
+ const result = {};
1340
+ for (const [key, value] of Object.entries(obj)) result[key] = await processValue(value);
1341
+ return result;
1342
+ };
1343
+ return {
1344
+ inputs: await processObject(inputs),
1345
+ files: Object.values(filesForRequest)
1346
+ };
1347
+ }
1348
+
1349
+ //#endregion
1350
+ //#region src/lib/internal-details/lib/features/api-store.ts
1351
+ var ApiManager = class {
1352
+ agentUrls = [];
1353
+ token;
1354
+ accessToken;
1355
+ runningApiControllers = {};
1356
+ waitForInitApiPromise = void 0;
1357
+ callContexts = {};
1358
+ constructor(rootStore) {
1359
+ this.rootStore = rootStore;
1360
+ }
1361
+ setTokens(token, accessToken) {
1362
+ this.token = token;
1363
+ this.accessToken = accessToken;
1364
+ }
1365
+ isInitialized() {
1366
+ return !!this.token && !!this.accessToken;
1367
+ }
1368
+ async awaitInitApiIfNeeded() {
1369
+ if (this.waitForInitApiPromise) await this.waitForInitApiPromise;
1370
+ }
1371
+ @action async rerunApiByCallId(callId) {
1372
+ const context$2 = this.callContexts[callId];
1373
+ if (!context$2) {
1374
+ console.error(`No call context found for callId: ${callId}`);
1375
+ throw new Error(`No call context found for callId: ${callId}`);
1376
+ }
1377
+ if (context$2.callback) {
1378
+ await context$2.callback();
1379
+ return {
1380
+ data: void 0,
1381
+ error: void 0
1382
+ };
1383
+ }
1384
+ const result = await this.executeApiInternal({
1385
+ apiId: context$2.apiId,
1386
+ apiName: context$2.apiName,
1387
+ path: context$2.path,
1388
+ inputs: context$2.inputs,
1389
+ options: context$2.options,
1390
+ callId,
1391
+ callback: void 0
1392
+ });
1393
+ return {
1394
+ data: result.data,
1395
+ error: result.error
1396
+ };
1397
+ }
1398
+ @action async runApiByPath({ path, inputs, callId, callback, isTestRun }) {
1399
+ await this.awaitInitApiIfNeeded();
1400
+ const apiName = path.match(/^\/apis\/([^/]+)\/api\.yaml$/)?.[1];
1401
+ if (!apiName) throw new Error(`Invalid path: ${path}`);
1402
+ editorBridge.setApiStarted(apiName);
1403
+ const result = await this.executeApiInternal({
1404
+ apiId: apiName,
1405
+ apiName,
1406
+ path,
1407
+ inputs,
1408
+ options: inputs ?? {},
1409
+ callId,
1410
+ isTestRun,
1411
+ callback
1412
+ });
1413
+ editorBridge.setApiResponse(apiName, result.parsedResult);
1414
+ return {
1415
+ data: result.data,
1416
+ error: result.error
1417
+ };
1418
+ }
1419
+ async executeApiInternal({ apiId, apiName, path, inputs, options, callId: providedCallId, callback, isTestRun }) {
1420
+ const executionStartTime = Date.now();
1421
+ const callId = providedCallId ?? `${apiId}-${executionStartTime}-${Math.random().toString(36).substr(2, 9)}`;
1422
+ const isRerun = !!this.callContexts[callId];
1423
+ if (isRerun) editorBridge.updateApiRunRecord(apiId, callId, { loading: true });
1424
+ if (!this.rootStore.applicationId) {
1425
+ sendNotification({
1426
+ message: "No application ID was found, ensure the app was bootstrap correctly.",
1427
+ type: "error"
1428
+ });
1429
+ return {
1430
+ parsedResult: {
1431
+ status: "STATUS_COMPLETED",
1432
+ execution: "",
1433
+ errors: [{ message: "No application ID was found, ensure the app was bootstrap correctly." }]
1434
+ },
1435
+ data: null,
1436
+ error: "No application ID was found"
1437
+ };
1438
+ }
1439
+ if (!this.agentUrls.length) {
1440
+ sendNotification({
1441
+ message: "No active agent found",
1442
+ type: "error"
1443
+ });
1444
+ return {
1445
+ parsedResult: {
1446
+ status: "STATUS_COMPLETED",
1447
+ execution: "",
1448
+ errors: [{ message: "No active agent found" }]
1449
+ },
1450
+ data: null,
1451
+ error: "No active agent found"
1452
+ };
1453
+ }
1454
+ const agentBaseUrl = this.agentUrls[Math.floor(Math.random() * this.agentUrls.length)];
1455
+ const orchestratorUrl = new URL("v2/execute", agentBaseUrl).href;
1456
+ const profileKey = context$1.profiles?.selected?.key ?? "staging";
1457
+ const profileId = context$1.profiles?.selected?.id ?? "";
1458
+ const events = [];
1459
+ await this.rootStore.editStore?.operationManager.ensureFilesSynced();
1460
+ const abortController = new AbortController();
1461
+ this.runningApiControllers[apiName] = abortController;
1462
+ const editMode$1 = isEditMode();
1463
+ const isStream = editMode$1 ? true : false;
1464
+ const authResult = await new Promise((resolve) => {
1465
+ const callbackId = addNewPromise(resolve);
1466
+ window.parent.postMessage({
1467
+ type: "authenticate-api-request",
1468
+ payload: {
1469
+ apiId,
1470
+ callbackId
1471
+ }
1472
+ }, "*");
1473
+ });
1474
+ if (authResult?.errors && authResult.errors.length > 0) console.error("API Authentication returned with errors", authResult.errors);
1475
+ const { traceHeaders,...restArgs } = options;
1476
+ const { inputs: finalInputs, files } = await getInputsWithFileMetadata({
1477
+ ...restArgs,
1478
+ ...inputs
1479
+ });
1480
+ const syncResponse = await executeV2Api({
1481
+ body: {
1482
+ inputs: finalInputs,
1483
+ fetchByPath: {
1484
+ path,
1485
+ applicationId: this.rootStore.applicationId ?? "",
1486
+ branchName: "main",
1487
+ profile: {
1488
+ name: profileKey,
1489
+ id: profileId
1490
+ },
1491
+ viewMode: OrchestratorViewMode.UNSPECIFIED
1492
+ },
1493
+ options: {
1494
+ includeEventOutputs: editMode$1,
1495
+ includeEvents: isStream || editMode$1,
1496
+ includeResolved: editMode$1
1497
+ }
1498
+ },
1499
+ apiName,
1500
+ controlFlowOnlyFiles: files,
1501
+ environment: profileKey,
1502
+ eventType: "api",
1503
+ notifyOnSystemError: true,
1504
+ responseType: isStream ? ApiResponseType.STREAM : ApiResponseType.SYNC,
1505
+ baseUrl: isStream ? orchestratorUrl + "/stream" : orchestratorUrl,
1506
+ agents: [],
1507
+ viewMode: editMode$1 ? ViewMode.EDITOR : ViewMode.DEPLOYED,
1508
+ accessToken: this.accessToken ?? "",
1509
+ token: this.token ?? "",
1510
+ traceHeaders,
1511
+ abortController,
1512
+ onMessage: (message) => {
1513
+ editorBridge.sendStreamedApiMessage(message, apiName);
1514
+ },
1515
+ processStreamEvents: (event) => {
1516
+ events.push(event);
1517
+ editorBridge.sendStreamedApiEvent(event, apiName);
1518
+ }
1519
+ });
1520
+ const parsedResult = (isStream ? parseStreamResult(events, { includeFinalOutput: true }) : syncResponse) ?? void 0;
1521
+ if (parsedResult) decodeBytestringsInV2ExecutionResponse(parsedResult);
1522
+ delete this.runningApiControllers[apiName];
1523
+ const error = this.findError(parsedResult ?? void 0);
1524
+ const data = isApiV2ExecutionResponse(parsedResult) ? parsedResult?.output?.result : null;
1525
+ const timeTaken = Date.now() - executionStartTime;
1526
+ this.callContexts[callId] = {
1527
+ apiId,
1528
+ apiName,
1529
+ path,
1530
+ inputs,
1531
+ options,
1532
+ callback
1533
+ };
1534
+ if (isRerun) editorBridge.updateApiRunRecord(apiId, callId, {
1535
+ timestamp: executionStartTime,
1536
+ statusCode: this.extractStatusCode(parsedResult),
1537
+ timeTaken,
1538
+ inputs,
1539
+ response: data,
1540
+ error,
1541
+ loading: false,
1542
+ isTestRun
1543
+ });
1544
+ else editorBridge.addApiRunRecord(apiId, {
1545
+ id: `${apiId}-${executionStartTime}`,
1546
+ callId,
1547
+ timestamp: executionStartTime,
1548
+ statusCode: this.extractStatusCode(parsedResult),
1549
+ timeTaken,
1550
+ inputs,
1551
+ response: data,
1552
+ error,
1553
+ loading: false,
1554
+ isTestRun
1555
+ });
1556
+ return {
1557
+ parsedResult,
1558
+ data,
1559
+ error
1560
+ };
1561
+ }
1562
+ findError(apiResponse) {
1563
+ if (apiResponse && "systemError" in apiResponse) return;
1564
+ const firstUnhandledError = apiResponse?.errors?.find((error) => !error?.handled);
1565
+ if (!firstUnhandledError) return;
1566
+ return `Error in API: ${firstUnhandledError?.message}`;
1567
+ }
1568
+ extractStatusCode(response) {
1569
+ if (!response) return 500;
1570
+ if ("systemError" in response) return 500;
1571
+ if ("errors" in response && response.errors && response.errors.length > 0) return 500;
1572
+ if ("status" in response && response.status === "STATUS_COMPLETED") return 200;
1573
+ return 500;
1574
+ }
1575
+ @action async cancelApi(apiName, _scopeId) {
1576
+ const abortController = this.runningApiControllers[apiName];
1577
+ if (!abortController) {
1578
+ console.warn(`No running API execution found for ${apiName}`);
1579
+ return;
1580
+ }
1581
+ abortController.abort();
1582
+ delete this.runningApiControllers[apiName];
1583
+ editorBridge.setApiResponse(apiName, {
1584
+ status: "STATUS_CANCELLED",
1585
+ execution: null,
1586
+ events: [],
1587
+ errors: [{ message: "API execution was cancelled" }],
1588
+ output: null
1589
+ });
1590
+ }
1591
+ };
1592
+ var api_store_default = ApiManager;
1593
+
1594
+ //#endregion
1595
+ //#region src/lib/internal-details/lib/evaluator/sanitize-object.ts
1596
+ const objectFallbackCache = /* @__PURE__ */ new WeakMap();
1597
+ function sanitizeObject(obj) {
1598
+ if (!objectFallbackCache.has(obj)) objectFallbackCache.set(obj, {});
1599
+ const fallbackCache = objectFallbackCache.get(obj);
1600
+ return new Proxy(obj, { get(target, prop) {
1601
+ try {
1602
+ const value = target[prop];
1603
+ if (typeof prop === "string") fallbackCache[prop] = value;
1604
+ return value;
1605
+ } catch (error) {
1606
+ if (error instanceof Promise) return typeof prop === "string" ? fallbackCache[prop] : void 0;
1607
+ throw error;
1608
+ }
1609
+ } });
1610
+ }
1611
+ function sanitizedToJS(value) {
1612
+ if (value === null || value === void 0 || typeof value !== "object") return toJS(value);
1613
+ return toJS(sanitizeObject(value));
1614
+ }
1615
+
1616
+ //#endregion
1617
+ //#region src/edit-mode/mobx-sync/create-patch.ts
1618
+ const microPatches = (oldValue, newValue, baseStr) => {
1619
+ const cleanedOldValue = removeBindAndReactElements(oldValue);
1620
+ const cleanedNewValue = removeBindAndReactElements(newValue);
1621
+ if (cleanedOldValue === void 0) return [{
1622
+ op: "add",
1623
+ path: pathStringToArray(baseStr),
1624
+ value: cleanedNewValue
1625
+ }];
1626
+ if (isPrimitive(cleanedOldValue) || isPrimitive(cleanedNewValue)) {
1627
+ if (cleanedOldValue !== cleanedNewValue) return [{
1628
+ op: "update",
1629
+ path: pathStringToArray(baseStr),
1630
+ value: cleanedNewValue
1631
+ }];
1632
+ return [];
1633
+ }
1634
+ const diffs = diff(cleanedOldValue, cleanedNewValue);
1635
+ const basePath = pathStringToArray(baseStr);
1636
+ return diffs.map((diff$1) => toMobXPatchFromMicroDiff(diff$1, basePath));
1637
+ };
1638
+ function isPrimitive(value) {
1639
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined";
1640
+ }
1641
+ function toMobXPatchFromMicroDiff(diff$1, basePath) {
1642
+ const type = diff$1.type;
1643
+ const fullPath = [...basePath, ...diff$1.path];
1644
+ switch (type) {
1645
+ case "CREATE": return {
1646
+ op: "add",
1647
+ path: fullPath,
1648
+ value: diff$1.value
1649
+ };
1650
+ case "CHANGE": return {
1651
+ op: "update",
1652
+ path: fullPath,
1653
+ value: diff$1.value
1654
+ };
1655
+ case "REMOVE": return {
1656
+ op: "remove",
1657
+ path: fullPath
1658
+ };
1659
+ default: throw new Error(`Unhandled diff type: ${type}`);
1660
+ }
1661
+ }
1662
+ const removeBindAndReactElements = (value) => {
1663
+ if (!value || typeof value !== "object") return value;
1664
+ if (isReactElement(value)) return;
1665
+ if (Array.isArray(value)) return value.map(removeBindAndReactElements);
1666
+ return Object.fromEntries(Object.entries(value).map(([key, value$1]) => {
1667
+ if (key === "bind") return [key, void 0];
1668
+ return [key, removeBindAndReactElements(value$1)];
1669
+ }));
1670
+ };
1671
+
1672
+ //#endregion
1673
+ //#region src/edit-mode/mobx-sync/deep-observe.ts
1674
+ function buildPath(entry) {
1675
+ if (!entry) return "ROOT";
1676
+ const res = [];
1677
+ while (entry.parent) {
1678
+ res.push(entry.path);
1679
+ entry = entry.parent;
1680
+ }
1681
+ return res.reverse().join("/");
1682
+ }
1683
+ function isRecursivelyObservable(thing) {
1684
+ return isObservableObject(thing) || isObservableArray(thing) || isObservableMap(thing);
1685
+ }
1686
+ /**
1687
+ * Given an object, deeply observes the given object.
1688
+ * It is like `observe` from mobx, but applied recursively, including all future children.
1689
+ *
1690
+ * Note that the given object cannot ever contain cycles and should be a tree.
1691
+ *
1692
+ * As benefit: path and root will be provided in the callback, so the signature of the listener is
1693
+ * (change, path, root) => void
1694
+ *
1695
+ * The returned disposer can be invoked to clean up the listener
1696
+ *
1697
+ * deepObserve cannot be used on computed values.
1698
+ *
1699
+ * @example
1700
+ * const disposer = deepObserve(target, (change, path) => {
1701
+ * console.dir(change)
1702
+ * })
1703
+ */
1704
+ function deepObserve(target, listener) {
1705
+ const entrySet = /* @__PURE__ */ new WeakMap();
1706
+ function genericListener(change) {
1707
+ const entry = entrySet.get(change.object);
1708
+ processChange(change, entry);
1709
+ listener(change, buildPath(entry), target);
1710
+ }
1711
+ function processChange(change, parent) {
1712
+ switch (change.type) {
1713
+ case "add":
1714
+ observeRecursively(change.newValue, parent, change.name);
1715
+ break;
1716
+ case "update":
1717
+ unobserveRecursively(change.oldValue);
1718
+ observeRecursively(change.newValue, parent, change.name || "" + change.index);
1719
+ break;
1720
+ case "remove":
1721
+ case "delete":
1722
+ unobserveRecursively(change.oldValue);
1723
+ break;
1724
+ case "splice":
1725
+ change.removed.map(unobserveRecursively);
1726
+ change.added.forEach((value, idx) => observeRecursively(value, parent, "" + (change.index + idx)));
1727
+ for (let i = change.index + change.addedCount; i < change.object.length; i++) if (isRecursivelyObservable(change.object[i])) {
1728
+ const entry = entrySet.get(change.object[i]);
1729
+ if (entry) entry.path = "" + i;
1730
+ }
1731
+ break;
1732
+ }
1733
+ }
1734
+ function observeRecursively(thing, parent, path) {
1735
+ if (isRecursivelyObservable(thing)) {
1736
+ const entry = entrySet.get(thing);
1737
+ if (entry) {
1738
+ if (entry.parent !== parent || entry.path !== path) throw new Error(`The same observable object cannot appear twice in the same tree, trying to assign it to '${buildPath(parent)}/${path}', but it already exists at '${buildPath(entry.parent)}/${entry.path}'`);
1739
+ } else {
1740
+ const entry$1 = {
1741
+ parent,
1742
+ path,
1743
+ dispose: observe(thing, genericListener)
1744
+ };
1745
+ entrySet.set(thing, entry$1);
1746
+ entries(thing).forEach(([key, value]) => observeRecursively(value, entry$1, "" + key));
1747
+ }
1748
+ }
1749
+ }
1750
+ function unobserveRecursively(thing) {
1751
+ if (isRecursivelyObservable(thing)) {
1752
+ const entry = entrySet.get(thing);
1753
+ if (!entry) return;
1754
+ entrySet.delete(thing);
1755
+ entry.dispose();
1756
+ values(thing).forEach(unobserveRecursively);
1757
+ }
1758
+ }
1759
+ observeRecursively(target, void 0, "");
1760
+ return () => {
1761
+ unobserveRecursively(target);
1762
+ };
1763
+ }
1764
+
1765
+ //#endregion
1766
+ //#region src/edit-mode/mobx-sync/mobx-editor-sync.ts
1767
+ /**
1768
+ * Syncs a mobx store to the editor automatically through postmessage
1769
+ */
1770
+ function startEditorSync(options) {
1771
+ if (!isEditMode()) return () => {};
1772
+ const { store, storeId, keys, projection, debounce } = options;
1773
+ const reactionOptions = {
1774
+ delay: debounce,
1775
+ name: `editor-sync(${storeId})`
1776
+ };
1777
+ let initialState;
1778
+ if (keys) initialState = sanitizedToJS(pick(store, Object.keys(keys)));
1779
+ else if (projection) initialState = sanitizedToJS(projection(store));
1780
+ else initialState = sanitizedToJS(store);
1781
+ editorBridge.initializeEditorSyncedStore({
1782
+ storeId,
1783
+ initialState
1784
+ });
1785
+ if (projection) {
1786
+ const initialProjection = projection(store);
1787
+ const projectionKeys = Object.keys(initialProjection);
1788
+ const createDisposer = (key) => {
1789
+ let lastValue;
1790
+ return reaction(() => {
1791
+ return sanitizedToJS(projection(store)[key]);
1792
+ }, (value) => {
1793
+ const diffs = microPatches(lastValue, value, key);
1794
+ lastValue = value;
1795
+ if (!(diffs.length === 0)) editorBridge.updateEditorSyncedStore({
1796
+ storeId,
1797
+ patch: diffs
1798
+ });
1799
+ }, reactionOptions);
1800
+ };
1801
+ const projectionDisposers = projectionKeys.reduce((acc, key) => {
1802
+ acc[key] = createDisposer(key);
1803
+ return acc;
1804
+ }, {});
1805
+ const projectionKeysDisposer = reaction(() => Object.keys(projection(store)), (newKeys) => {
1806
+ const lastKeys = Object.keys(projectionDisposers);
1807
+ const deletedKeys = lastKeys.filter((key) => !newKeys.includes(key));
1808
+ newKeys.filter((key) => !lastKeys.includes(key)).forEach((key) => {
1809
+ projectionDisposers[key] = createDisposer(key);
1810
+ editorBridge.updateEditorSyncedStore({
1811
+ storeId,
1812
+ patch: {
1813
+ op: "update",
1814
+ path: [key],
1815
+ value: sanitizedToJS(projection(store)[key])
1816
+ }
1817
+ });
1818
+ });
1819
+ deletedKeys.forEach((key) => {
1820
+ projectionDisposers[key]();
1821
+ delete projectionDisposers[key];
1822
+ editorBridge.updateEditorSyncedStore({
1823
+ storeId,
1824
+ patch: {
1825
+ op: "remove",
1826
+ path: [key]
1827
+ }
1828
+ });
1829
+ });
1830
+ }, reactionOptions);
1831
+ return () => {
1832
+ projectionKeysDisposer();
1833
+ Object.values(projectionDisposers).forEach((disposer) => disposer());
1834
+ };
1835
+ }
1836
+ const keyArr = Object.keys(keys ?? store);
1837
+ const computedKeys = keyArr.filter((key) => isComputedProp(store, key));
1838
+ const observableKeys = keyArr.filter((key) => !computedKeys.includes(key));
1839
+ const disposers = [];
1840
+ const computedDisposers = computedKeys.map((key) => reaction(() => store[key], (value) => {
1841
+ editorBridge.updateEditorSyncedStore({
1842
+ storeId,
1843
+ patch: {
1844
+ op: "update",
1845
+ path: [key],
1846
+ value
1847
+ }
1848
+ });
1849
+ }, reactionOptions));
1850
+ disposers.push(...computedDisposers);
1851
+ if (observableKeys.length > 0 || !(keys !== void 0)) {
1852
+ const deepDisposer = deepObserve(store, (change, pathStr) => {
1853
+ const patch = toMobXPatch(change, pathStr);
1854
+ if (keys && !keys[patch.path[0]]) return;
1855
+ try {
1856
+ editorBridge.updateEditorSyncedStore({
1857
+ storeId,
1858
+ patch
1859
+ });
1860
+ } catch (error) {
1861
+ console.error(`[startEditorSync][${storeId}] Failed to send patch:`, error);
1862
+ }
1863
+ });
1864
+ disposers.push(deepDisposer);
1865
+ }
1866
+ return () => {
1867
+ disposers.forEach((disposer) => disposer());
1868
+ };
1869
+ }
1870
+
1871
+ //#endregion
1872
+ //#region src/lib/user-facing/properties-panel/properties-panel-definition.ts
1873
+ function createPropertiesPanelDefinition(sections, componentProps) {
1874
+ const sectionDefs = [];
1875
+ const getSectionChildren = (propDefinitions, parentPath) => {
1876
+ const properties = [];
1877
+ /**
1878
+ * There are three ways we can display a Composite prop:
1879
+ * 1. Prop control + popover panel (e.g: TextStyle)
1880
+ * 2. Prop control (e.g: Border)
1881
+ * 3. Inline, without a prop control (e.g: Search prop on Table, which contains backgroundColor, borderRadius, etc.)
1882
+ *
1883
+ * isCompositeWithInlineNestedProps is used to determine if a prop is of type (3).
1884
+ */
1885
+ const isCompositeWithInlineNestedProps = (prop, fullPath) => {
1886
+ if (!(prop instanceof CompositeProp) || !prop.hasPropertiesPanelDisplay()) return false;
1887
+ const displayMode = prop.propertiesPanelChildrenDisplayMode();
1888
+ if (!displayMode) return false;
1889
+ return (typeof displayMode === "function" ? displayMode(componentProps, fullPath) : displayMode)?.type === "inline";
1890
+ };
1891
+ for (const [name, prop] of Object.entries(propDefinitions)) {
1892
+ if (!prop) continue;
1893
+ const fullPath = parentPath ? `${parentPath}.${name}` : name;
1894
+ if (isCompositeWithInlineNestedProps(prop, fullPath)) {
1895
+ const inlinePropertiesDefs = getSectionChildren(prop.nestedProps, fullPath);
1896
+ properties.push(...inlinePropertiesDefs);
1897
+ } else if (prop.hasPropertiesPanelDisplay()) {
1898
+ const def = prop.setName(fullPath).toDefinition(componentProps);
1899
+ if (def) properties.push(def);
1900
+ }
1901
+ }
1902
+ return properties;
1903
+ };
1904
+ for (const section of Object.values(sections)) {
1905
+ const children = getSectionChildren(section.props, "");
1906
+ if (children.length === 0) continue;
1907
+ sectionDefs.push({
1908
+ name: section.name,
1909
+ category: section.category,
1910
+ children,
1911
+ showHeader: section.propertiesPanelConfig.showHeader,
1912
+ isDefaultOpen: section.propertiesPanelConfig.isDefaultOpen,
1913
+ headerType: section.propertiesPanelConfig.headerType,
1914
+ subHeader: section.propertiesPanelConfig.subHeader
1915
+ });
1916
+ }
1917
+ return { sections: sectionDefs };
1918
+ }
1919
+
1920
+ //#endregion
1921
+ //#region src/lib/user-facing/properties-panel/props-builder.ts
1922
+ function mergeRelations(existingRelations, relations) {
1923
+ if (!existingRelations || existingRelations.length === 0) return relations;
1924
+ if (!relations || relations.length === 0) return existingRelations;
1925
+ return existingRelations && existingRelations.length > 0 ? existingRelations.flatMap((existing) => relations.map((relation) => [...existing, ...relation])) : relations;
1926
+ }
1927
+ function getChildren(input, path, props) {
1928
+ function getChildrenFromSection(section) {
1929
+ return Object.keys(section.props).reduce((acc, key) => {
1930
+ const prop = section.props[key];
1931
+ if (!prop) return acc;
1932
+ const definition = prop.setName(path + "." + key).toDefinition(props);
1933
+ if (definition) acc[key] = definition;
1934
+ return acc;
1935
+ }, {});
1936
+ }
1937
+ let children;
1938
+ if (input instanceof Section) children = getChildrenFromSection(input);
1939
+ else if (Object.values(input).every((c) => c instanceof Section)) children = Object.values(input).reduce((acc, section) => {
1940
+ return {
1941
+ ...acc,
1942
+ ...getChildrenFromSection(section)
1943
+ };
1944
+ }, {});
1945
+ else children = Object.fromEntries(Object.entries(input).map(([key, prop]) => {
1946
+ return [key, prop.setName(path + "." + key).toDefinition(props)];
1947
+ }));
1948
+ return children;
1949
+ }
1950
+ var Section = class Section {
1951
+ props = {};
1952
+ propertiesPanelConfig = {
1953
+ showHeader: true,
1954
+ isDefaultOpen: true
1955
+ };
1956
+ constructor(category) {
1957
+ this.category = category;
1958
+ }
1959
+ static category(category) {
1960
+ return new Section(category);
1961
+ }
1962
+ children(props) {
1963
+ if (props instanceof CompositeProp || props instanceof RecordProp) this.props = {
1964
+ ...this.props,
1965
+ ...props.getProps()
1966
+ };
1967
+ else if (props instanceof UnionProp) this.props = {
1968
+ ...this.props,
1969
+ ...props.getProps()
1970
+ };
1971
+ else this.props = {
1972
+ ...this.props,
1973
+ ...props
1974
+ };
1975
+ return this;
1976
+ }
1977
+ add = this.children;
1978
+ propertiesPanel(config) {
1979
+ this.propertiesPanelConfig = {
1980
+ ...this.propertiesPanelConfig,
1981
+ ...config
1982
+ };
1983
+ return this;
1984
+ }
1985
+ get name() {
1986
+ switch (this.category) {
1987
+ case PropsCategory.Content: return "Content";
1988
+ case PropsCategory.Routing: return "Routing";
1989
+ case PropsCategory.Interaction: return "Interaction";
1990
+ case PropsCategory.Layout: return "Layout";
1991
+ case PropsCategory.Appearance: return "Appearance";
1992
+ case PropsCategory.Permissions: return "Permissions";
1993
+ case PropsCategory.EventHandlers: return "Actions";
1994
+ case PropsCategory.Styles: return "Styles";
1995
+ case PropsCategory.Uncategorized: return "Uncategorized";
1996
+ default: return "Uncategorized";
1997
+ }
1998
+ }
1999
+ };
2000
+ var Prop = class Prop {
2001
+ prop;
2002
+ /**
2003
+ * Relations are an array of arrays
2004
+ * each sub-array is AND requirements, and each element is an OR requirement
2005
+ */
2006
+ relations = [];
2007
+ constructor(typeString) {
2008
+ this.prop = {
2009
+ path: "",
2010
+ dataType: typeString
2011
+ };
2012
+ }
2013
+ static unset() {
2014
+ return new Prop("any");
2015
+ }
2016
+ static string() {
2017
+ return new Prop("string");
2018
+ }
2019
+ static number() {
2020
+ return new Prop("number");
2021
+ }
2022
+ static boolean() {
2023
+ return new Prop("boolean");
2024
+ }
2025
+ static array() {
2026
+ return new Prop("array");
2027
+ }
2028
+ static any() {
2029
+ return new Prop("any");
2030
+ }
2031
+ static jsx() {
2032
+ return new Prop("jsx");
2033
+ }
2034
+ static literal(value) {
2035
+ switch (typeof value) {
2036
+ case "string": return Prop.string().default(value);
2037
+ case "number": return Prop.number().default(value);
2038
+ case "boolean": return Prop.boolean().default(value);
2039
+ default: {
2040
+ const exhaustiveCheck = value;
2041
+ throw new Error(`Invalid literal value: ${exhaustiveCheck}`);
2042
+ }
2043
+ }
2044
+ }
2045
+ static eventHandler() {
2046
+ return new Prop("eventHandler");
2047
+ }
2048
+ static function(implementation) {
2049
+ return new FunctionProp(implementation);
2050
+ }
2051
+ /**
2052
+ * Creates a composite property, which is a property that contains nested properties. For example,
2053
+ * the following composite property:
2054
+ *
2055
+ * ```ts
2056
+ * const prop = Prop.composite({
2057
+ * name: Prop.string(),
2058
+ * age: Prop.number(),
2059
+ * });
2060
+ * ```
2061
+ *
2062
+ * is equivalent to the following type:
2063
+ *
2064
+ * ```ts
2065
+ * type Prop = {
2066
+ * name: string;
2067
+ * age: number;
2068
+ * };
2069
+ * ```
2070
+ */
2071
+ static composite(props) {
2072
+ return new CompositeProp(props);
2073
+ }
2074
+ /**
2075
+ * Creates a record property, which is a record that maps string keys to the nestedproperties. For example,
2076
+ * the following record property:
2077
+ *
2078
+ * ```ts
2079
+ * const prop = Prop.record({
2080
+ * name: Prop.string(),
2081
+ * age: Prop.number(),
2082
+ * });
2083
+ * ```
2084
+ *
2085
+ * is equivalent to the following type:
2086
+ *
2087
+ * ```ts
2088
+ * type Prop = Record<string, {
2089
+ * name: string;
2090
+ * age: number;
2091
+ * }>;
2092
+ * ```
2093
+ */
2094
+ static record(props) {
2095
+ return new RecordProp(props);
2096
+ }
2097
+ static union(props) {
2098
+ return new UnionProp(props.shared, props.variants);
2099
+ }
2100
+ default(de) {
2101
+ this.prop.default = de;
2102
+ if (this.prop.propertiesPanelDisplay && this.prop.propertiesPanelDisplay.defaultValue === void 0) this.prop.propertiesPanelDisplay.defaultValue = de;
2103
+ return this;
2104
+ }
2105
+ contextual(computedArgs) {
2106
+ this.prop.contextual = true;
2107
+ this.prop.computedArgs = computedArgs;
2108
+ return this;
2109
+ }
2110
+ setName(name) {
2111
+ this.prop.path = name;
2112
+ return this;
2113
+ }
2114
+ propertiesPanel(schema) {
2115
+ let baseControlType;
2116
+ let isJSConvertible = true;
2117
+ let isTriggerProperty = false;
2118
+ let inputType;
2119
+ switch (this.prop.dataType) {
2120
+ case "string":
2121
+ baseControlType = "INPUT_TEXT";
2122
+ break;
2123
+ case "number":
2124
+ baseControlType = "INPUT_TEXT";
2125
+ inputType = InputType.NUMBER;
2126
+ break;
2127
+ case "array":
2128
+ baseControlType = "INPUT_TEXT";
2129
+ break;
2130
+ case "boolean":
2131
+ baseControlType = "SWITCH";
2132
+ break;
2133
+ case "eventHandler":
2134
+ baseControlType = "EVENT_HANDLER";
2135
+ isJSConvertible = false;
2136
+ isTriggerProperty = true;
2137
+ break;
2138
+ case "jsx":
2139
+ baseControlType = "JSX";
2140
+ break;
2141
+ case "any":
2142
+ default:
2143
+ baseControlType = "INPUT_JS_EXPR";
2144
+ break;
2145
+ }
2146
+ const propertiesPanelDisplay = {
2147
+ controlType: baseControlType,
2148
+ isJSConvertible,
2149
+ isTriggerProperty,
2150
+ defaultValue: schema.defaultValue ?? this.prop.default,
2151
+ defaultOnAdd: this.prop.propertiesPanelDisplay?.defaultOnAdd,
2152
+ inputType,
2153
+ ...schema
2154
+ };
2155
+ this.prop.propertiesPanelDisplay = propertiesPanelDisplay;
2156
+ return this;
2157
+ }
2158
+ setDisplayProperty(property, value) {
2159
+ if (!this.prop.propertiesPanelDisplay) return this;
2160
+ this.prop.propertiesPanelDisplay[property] = value;
2161
+ return this;
2162
+ }
2163
+ docs(docs) {
2164
+ this.prop.docs = docs;
2165
+ return this;
2166
+ }
2167
+ build() {
2168
+ return this.prop;
2169
+ }
2170
+ toDefinition(props) {
2171
+ const evaluatedProperties = Object.entries(this.prop.propertiesPanelDisplay ?? {}).reduce((acc, [key, value]) => {
2172
+ if (typeof value === "function") try {
2173
+ acc[key] = value.bind(props)(this.prop.path);
2174
+ } catch (e) {
2175
+ console.error(`Error evaluating property ${key}:`, e);
2176
+ }
2177
+ return acc;
2178
+ }, {});
2179
+ if (evaluatedProperties.isVisible === false) return;
2180
+ const propertiesPanelDisplay = {
2181
+ ...this.prop.propertiesPanelDisplay,
2182
+ ...evaluatedProperties
2183
+ };
2184
+ if ("treatDefaultAsNull" in propertiesPanelDisplay) {
2185
+ if (propertiesPanelDisplay.treatDefaultAsNull) {
2186
+ if (propertiesPanelDisplay.defaultOnAdd === void 0) propertiesPanelDisplay.defaultOnAdd = propertiesPanelDisplay.defaultValue;
2187
+ propertiesPanelDisplay.defaultValue = void 0;
2188
+ }
2189
+ }
2190
+ let panelConfig;
2191
+ const childrenDisplay = propertiesPanelDisplay?.childrenDisplayMode;
2192
+ if (childrenDisplay?.type === "popover") {
2193
+ if (!(this instanceof CompositeProp || this instanceof RecordProp)) {
2194
+ console.error(this);
2195
+ throw new Error("Only composite properties can be used in popover properties at the moment");
2196
+ }
2197
+ const content = this.getProps();
2198
+ const { type,...rest } = childrenDisplay;
2199
+ let contentDef;
2200
+ if (content instanceof Section) contentDef = { content };
2201
+ else if (Object.values(content).every((c) => c instanceof Section)) contentDef = content;
2202
+ else contentDef = { content: Section.category(PropsCategory.Content).propertiesPanel({ showHeader: false }).children(content) };
2203
+ panelConfig = {
2204
+ ...createPropertiesPanelDefinition(contentDef, props),
2205
+ ...rest
2206
+ };
2207
+ }
2208
+ if (this.prop.computedArgs) propertiesPanelDisplay.computedArgs = typeof this.prop.computedArgs === "function" ? this.prop.computedArgs(props) : this.prop.computedArgs;
2209
+ const propertiesPanelDisplayWithPanelConfig = {
2210
+ ...propertiesPanelDisplay,
2211
+ ...panelConfig && { panelConfig }
2212
+ };
2213
+ return {
2214
+ path: this.prop.path,
2215
+ dataType: this.prop.dataType,
2216
+ relations: this.relations,
2217
+ propertiesPanelDisplay: propertiesPanelDisplayWithPanelConfig
2218
+ };
2219
+ }
2220
+ getRelations() {
2221
+ return this.relations;
2222
+ }
2223
+ dependsOn(relations) {
2224
+ this.relations = relations;
2225
+ return this;
2226
+ }
2227
+ hasPropertiesPanelDisplay() {
2228
+ return this.prop.propertiesPanelDisplay !== void 0;
2229
+ }
2230
+ get type() {
2231
+ return this.prop.dataType;
2232
+ }
2233
+ get path() {
2234
+ return this.prop.path;
2235
+ }
2236
+ };
2237
+ /**
2238
+ * See {@link Prop.composite}
2239
+ */
2240
+ var CompositeProp = class extends Prop {
2241
+ typeString = "composite";
2242
+ nestedProps;
2243
+ constructor(props) {
2244
+ super("composite");
2245
+ this.nestedProps = props;
2246
+ }
2247
+ getProps() {
2248
+ return this.nestedProps;
2249
+ }
2250
+ toDefinition(props) {
2251
+ const definition = super.toDefinition(props);
2252
+ if (!definition) return;
2253
+ return {
2254
+ ...definition,
2255
+ children: getChildren(this.nestedProps, this.prop.path, props)
2256
+ };
2257
+ }
2258
+ propertiesPanelChildrenDisplayMode() {
2259
+ return this.prop.propertiesPanelDisplay?.childrenDisplayMode;
2260
+ }
2261
+ };
2262
+ /**
2263
+ * See {@link Prop.record}
2264
+ */
2265
+ var RecordProp = class extends Prop {
2266
+ typeString = "recordOf";
2267
+ nestedProps;
2268
+ constructor(props) {
2269
+ super("recordOf");
2270
+ this.nestedProps = props;
2271
+ }
2272
+ getProps() {
2273
+ return this.nestedProps;
2274
+ }
2275
+ toDefinition(props) {
2276
+ const definition = super.toDefinition(props);
2277
+ if (!definition) return;
2278
+ return {
2279
+ ...definition,
2280
+ children: getChildren(this.nestedProps, this.prop.path, props)
2281
+ };
2282
+ }
2283
+ };
2284
+ var FunctionProp = class extends Prop {
2285
+ typeString = "function";
2286
+ _actionPanel;
2287
+ constructor(implementation) {
2288
+ super("function");
2289
+ this.default(implementation);
2290
+ }
2291
+ actionPanel(panel) {
2292
+ this._actionPanel = panel || {};
2293
+ return this;
2294
+ }
2295
+ getActionPanel() {
2296
+ return this._actionPanel;
2297
+ }
2298
+ };
2299
+ var UnionProp = class extends Prop {
2300
+ typeString = "union";
2301
+ shared;
2302
+ variants;
2303
+ constructor(shared, variants) {
2304
+ super("any");
2305
+ this.shared = shared;
2306
+ this.variants = variants;
2307
+ }
2308
+ getProps() {
2309
+ const sharedKeys = Object.keys(this.shared);
2310
+ const variants = this.variants;
2311
+ const preMergeRelationsMap = variants.reduce((acc, v) => {
2312
+ Object.entries(v).forEach(([key, prop]) => {
2313
+ const existingRelations = acc[key] ?? [];
2314
+ const newRelations = prop.getRelations() ?? [];
2315
+ acc[key] = [...existingRelations, ...newRelations];
2316
+ });
2317
+ return acc;
2318
+ }, {});
2319
+ const mergedVariants = variants.reduce((acc, v) => {
2320
+ const relations = Object.entries(v).filter(([key]) => sharedKeys.includes(key)).map(([key, prop]) => {
2321
+ return {
2322
+ key,
2323
+ value: prop.build().default
2324
+ };
2325
+ });
2326
+ const filteredVariant = Object.fromEntries(Object.entries(v).filter(([key]) => !sharedKeys.includes(key)).map(([key, prop]) => {
2327
+ const existingRelations = prop?.getRelations() ?? [];
2328
+ const preMergeRelations = preMergeRelationsMap[key];
2329
+ const existingNonPreMergeRelations = existingRelations.filter((r) => !preMergeRelations.some((p) => p === r));
2330
+ const newProp = prop.dependsOn([...existingNonPreMergeRelations, ...mergeRelations(preMergeRelations, [relations])]);
2331
+ if (acc[key]) {
2332
+ const existingPropRelations = acc[key].getRelations() ?? [];
2333
+ const newPropRelations = newProp.getRelations() ?? [];
2334
+ const seenHashes = /* @__PURE__ */ new Set();
2335
+ const uniqueRelations = [...existingPropRelations, ...newPropRelations].filter((relationGroup) => {
2336
+ const hash = relationGroup.map((r) => `${r.key}:${String(r.value)}`).sort().join("|");
2337
+ if (seenHashes.has(hash)) return false;
2338
+ seenHashes.add(hash);
2339
+ return true;
2340
+ });
2341
+ return [key, acc[key].dependsOn(uniqueRelations)];
2342
+ }
2343
+ return [key, newProp];
2344
+ }));
2345
+ return {
2346
+ ...acc,
2347
+ ...filteredVariant
2348
+ };
2349
+ }, {});
2350
+ return {
2351
+ ...this.shared,
2352
+ ...mergedVariants
2353
+ };
2354
+ }
2355
+ };
2356
+
2357
+ //#endregion
2358
+ //#region src/lib/user-facing/properties-panel/create-managed-props-list.ts
2359
+ const RECORD_PATH_IDENTIFIER = "*";
2360
+ function buildCompositeDefault(prop, name, parentDefault) {
2361
+ const defaultThroughParent = parentDefault?.[name];
2362
+ const selfDefault = prop.build().default;
2363
+ let propDefault = defaultThroughParent ?? selfDefault;
2364
+ if (!propDefault && typeof parentDefault === "function") propDefault = function getNestedDefault(s) {
2365
+ return parentDefault.call(this, s)?.[name];
2366
+ };
2367
+ return propDefault;
2368
+ }
2369
+ function buildPropLeafDefault(prop, name, parentDefault) {
2370
+ const defaultThroughParent = parentDefault?.[name];
2371
+ let propDefault = prop.build().default ?? defaultThroughParent;
2372
+ if (!propDefault && typeof parentDefault === "function") propDefault = function getNestedDefault(s) {
2373
+ return parentDefault.call(this, s)?.[name];
2374
+ };
2375
+ return propDefault;
2376
+ }
2377
+ /**
2378
+ * Core traversal function that walks through all properties in sections
2379
+ * and calls the provided callback for each leaf property.
2380
+ */
2381
+ function traverseProps(sections, onProp, parentPath = "") {
2382
+ const processProps = ({ props, parentPath: parentPath$1, parentDefault }) => {
2383
+ for (const [name, prop] of Object.entries(props)) {
2384
+ if (!prop) continue;
2385
+ const fullPath = parentPath$1 ? `${parentPath$1}.${name}` : name;
2386
+ if (prop instanceof CompositeProp) {
2387
+ const compositeDefault = buildCompositeDefault(prop, name, parentDefault);
2388
+ processProps({
2389
+ props: prop.nestedProps,
2390
+ parentPath: fullPath,
2391
+ parentDefault: compositeDefault
2392
+ });
2393
+ } else if (prop instanceof RecordProp) {
2394
+ const recordPath = `${fullPath}.${RECORD_PATH_IDENTIFIER}`;
2395
+ processProps({
2396
+ props: prop.nestedProps,
2397
+ parentPath: recordPath,
2398
+ parentDefault: prop.build().default
2399
+ });
2400
+ } else if (prop instanceof Section) processProps({
2401
+ props: prop.props,
2402
+ parentPath: parentPath$1
2403
+ });
2404
+ else if (prop instanceof UnionProp) {
2405
+ const sharedKeys = Object.keys(prop.shared);
2406
+ processProps({
2407
+ props: prop.shared,
2408
+ parentPath: fullPath
2409
+ });
2410
+ for (const variant of prop.variants) processProps({
2411
+ props: Object.fromEntries(Object.entries(variant).filter(([key]) => !sharedKeys.includes(key))),
2412
+ parentPath: fullPath
2413
+ });
2414
+ } else if (prop instanceof Prop) onProp(prop, fullPath, name, parentDefault);
2415
+ else console.warn("Invalid prop type", {
2416
+ name,
2417
+ prop
2418
+ });
2419
+ }
2420
+ };
2421
+ for (const section of Object.values(sections)) processProps({
2422
+ props: section.props,
2423
+ parentPath,
2424
+ parentDefault: void 0
2425
+ });
2426
+ }
2427
+ function createManagedPropsList(sections, parentPath = "") {
2428
+ const managedPropsList = [];
2429
+ traverseProps(sections, (prop, fullPath, name, parentDefault) => {
2430
+ let configuredProp = prop.setName(fullPath);
2431
+ const propDefault = buildPropLeafDefault(prop, name, parentDefault);
2432
+ if (propDefault !== void 0) configuredProp = configuredProp.default(propDefault);
2433
+ const builtProp = configuredProp.build();
2434
+ if (builtProp.dataType === "internal") return;
2435
+ managedPropsList.push({ ...builtProp });
2436
+ }, parentPath);
2437
+ return managedPropsList;
2438
+ }
2439
+
2440
+ //#endregion
2441
+ //#region src/lib/internal-details/lib/features/type-defs-utils.ts
2442
+ const analyzePropertyType = (propData, prop) => {
2443
+ let dataType;
2444
+ if (propData.dataType === "composite" && prop && typeof prop.getProps === "function") {
2445
+ const nestedProps = prop.getProps();
2446
+ const objectFields = {};
2447
+ for (const [key, nestedProp] of Object.entries(nestedProps)) if (nestedProp && typeof nestedProp.build === "function") {
2448
+ const nestedPropData = nestedProp.build();
2449
+ if (nestedPropData && nestedPropData.isExternallyReadable) objectFields[key] = analyzePropertyType(nestedPropData, nestedProp);
2450
+ }
2451
+ if (Object.keys(objectFields).length > 0) dataType = objectFields;
2452
+ } else if (propData.dataType === "dimension") dataType = {
2453
+ mode: "string",
2454
+ value: "number"
2455
+ };
2456
+ else if (propData.dataType === "string" || propData.dataType === "number" || propData.dataType === "boolean" || propData.dataType === "array" || propData.dataType === "function") dataType = propData.dataType;
2457
+ else dataType = "unknown";
2458
+ return dataType;
2459
+ };
2460
+
2461
+ //#endregion
2462
+ //#region src/lib/internal-details/lib/features/component-registry.ts
2463
+ /**
2464
+ * TODO: The component registry could be split into two a thin layer always on, and move some stuff to the EditStore.
2465
+ * Some of the actions (rename, delete) and some of the data (isDroppable) are editor-only.
2466
+ */
2467
+ var ComponentRegistry = class {
2468
+ _componentRegistry = /* @__PURE__ */ new Map();
2469
+ _componentToType = /* @__PURE__ */ new WeakMap();
2470
+ _defaultContainerType;
2471
+ _defaultButtonType;
2472
+ _defaultTextType;
2473
+ constructor(rootStore) {
2474
+ this.rootStore = rootStore;
2475
+ makeAutoObservable(this);
2476
+ startEditorSync({
2477
+ store: this,
2478
+ storeId: "component-registry",
2479
+ keys: {
2480
+ customComponentList: true,
2481
+ libraryComponentCatalogs: true,
2482
+ libraryComponentEditorConfigs: true,
2483
+ entityDefinitions: true
2484
+ }
2485
+ });
2486
+ }
2487
+ getOrCreateMetadata(type) {
2488
+ let metadata = this._componentRegistry.get(type);
2489
+ if (!metadata) {
2490
+ metadata = {
2491
+ type,
2492
+ propertiesDefinition: {},
2493
+ managedProps: [],
2494
+ internalProps: [],
2495
+ editorTemplates: [],
2496
+ editorConfig: void 0
2497
+ };
2498
+ this._componentRegistry.set(type, metadata);
2499
+ }
2500
+ return metadata;
2501
+ }
2502
+ addComponent(type, rawComponent, propertiesDefinition) {
2503
+ const metadata = this.getOrCreateMetadata(type);
2504
+ metadata.propertiesDefinition = propertiesDefinition;
2505
+ if (typeof rawComponent !== "string") this._componentToType.set(rawComponent, type);
2506
+ }
2507
+ deleteComponent(type) {
2508
+ this._componentRegistry.delete(type);
2509
+ }
2510
+ renameComponent(oldName, newName) {
2511
+ const metadata = this._componentRegistry.get(oldName);
2512
+ if (metadata) {
2513
+ metadata.type = newName;
2514
+ this._componentRegistry.set(newName, metadata);
2515
+ this._componentRegistry.delete(oldName);
2516
+ }
2517
+ }
2518
+ addManagedProps(type, props) {
2519
+ const metadata = this.getOrCreateMetadata(type);
2520
+ metadata.managedProps = props;
2521
+ }
2522
+ deleteManagedProps(type) {
2523
+ const metadata = this.getOrCreateMetadata(type);
2524
+ metadata.managedProps = [];
2525
+ }
2526
+ addEditorTemplate(type, template) {
2527
+ const metadata = this.getOrCreateMetadata(type);
2528
+ const existingTemplates = metadata.editorTemplates;
2529
+ if (existingTemplates.some((t) => t.catalog?.displayName === template.catalog?.displayName && t.catalog?.category === template.catalog?.category)) return;
2530
+ metadata.editorTemplates = [...existingTemplates, template];
2531
+ }
2532
+ getEditorTemplates(type) {
2533
+ return this._componentRegistry.get(type)?.editorTemplates;
2534
+ }
2535
+ getEditorConfigFromComponentType(type) {
2536
+ const componentStrType = this.getTypeForComponent(type);
2537
+ return componentStrType ? this.getEditorConfig(componentStrType) : void 0;
2538
+ }
2539
+ addEditorConfig(type, config) {
2540
+ if (config.useAs) {
2541
+ if (config.useAs.defaultContainer) this._defaultContainerType = type;
2542
+ if (config.useAs.defaultButton) this._defaultButtonType = type;
2543
+ if (config.useAs.defaultText) this._defaultTextType = type;
2544
+ }
2545
+ const metadata = this.getOrCreateMetadata(type);
2546
+ metadata.editorConfig = config;
2547
+ }
2548
+ addInternalProps(type, props) {
2549
+ const metadata = this.getOrCreateMetadata(type);
2550
+ metadata.internalProps = props;
2551
+ }
2552
+ getInternalProps(type) {
2553
+ return this._componentRegistry.get(type)?.internalProps ?? [];
2554
+ }
2555
+ getEditorConfig(type) {
2556
+ return this._componentRegistry.get(type)?.editorConfig;
2557
+ }
2558
+ get entityDefinitions() {
2559
+ const entityDefinitions = {};
2560
+ for (const [componentType, metadata] of this._componentRegistry.entries()) {
2561
+ const propertiesDefinition = metadata.propertiesDefinition;
2562
+ if (!propertiesDefinition) continue;
2563
+ const entityDefinition = {
2564
+ description: metadata.editorConfig?.description,
2565
+ props: {}
2566
+ };
2567
+ for (const section of Object.values(propertiesDefinition)) for (const [propKey, propValue] of Object.entries(section.props)) {
2568
+ if (!propValue) continue;
2569
+ const prop = propValue;
2570
+ const propData = prop.build();
2571
+ if (propData && propData.isExternallyReadable) {
2572
+ const dataType = analyzePropertyType(propData, prop);
2573
+ const entityDefEntry = {
2574
+ label: propData.docs?.label,
2575
+ description: propData.docs?.description,
2576
+ isSettable: propData.isExternallySettable,
2577
+ dataType
2578
+ };
2579
+ entityDefinition.props[propKey] = entityDefEntry;
2580
+ }
2581
+ }
2582
+ entityDefinitions[componentType] = entityDefinition;
2583
+ }
2584
+ return entityDefinitions;
2585
+ }
2586
+ get libraryComponentCatalogs() {
2587
+ const catalogs = [];
2588
+ for (const [componentType, metadata] of this._componentRegistry.entries()) for (const template of metadata.editorTemplates) {
2589
+ const catalog = template.catalog;
2590
+ if (catalog) catalogs.push({
2591
+ ...catalog,
2592
+ componentType
2593
+ });
2594
+ }
2595
+ return catalogs;
2596
+ }
2597
+ get libraryComponentEditorConfigs() {
2598
+ const configs = {};
2599
+ for (const [componentType, metadata] of this._componentRegistry.entries()) if (metadata.editorConfig) configs[componentType] = metadata.editorConfig;
2600
+ return configs;
2601
+ }
2602
+ get customComponentList() {
2603
+ return Array.from(this._componentRegistry.keys());
2604
+ }
2605
+ get containerTypes() {
2606
+ return new Set([this.defaultTagNames.container]);
2607
+ }
2608
+ get defaultTagNames() {
2609
+ if (!this._defaultContainerType) console.warn("No default container registered - defaulting to 'Container'.");
2610
+ if (!this._defaultButtonType) console.warn("No default button registered - defaulting to 'Button'.");
2611
+ if (!this._defaultTextType) console.warn("No default text registered - defaulting to 'Text'.");
2612
+ return {
2613
+ container: this._defaultContainerType ?? "Container",
2614
+ button: this._defaultButtonType ?? "Button",
2615
+ text: this._defaultTextType ?? "Text"
2616
+ };
2617
+ }
2618
+ get managedPropsRegistry() {
2619
+ const registry = /* @__PURE__ */ new Map();
2620
+ for (const [type, metadata] of this._componentRegistry.entries()) registry.set(type, metadata.managedProps);
2621
+ return registry;
2622
+ }
2623
+ getManagedProps(type) {
2624
+ return this._componentRegistry.get(type)?.managedProps ?? [];
2625
+ }
2626
+ /**
2627
+ * Get the component type string for a raw component reference.
2628
+ * Used for registry-based component identity checking.
2629
+ */
2630
+ getTypeForComponent(component) {
2631
+ return this._componentToType.get(component);
2632
+ }
2633
+ /**
2634
+ * Check if a component or element type is registered in the component registry.
2635
+ * Accepts both component references and string element names (e.g., "div").
2636
+ * Used for component identity checking instead of symbol-based approach.
2637
+ */
2638
+ hasComponent(component) {
2639
+ if (typeof component === "string") return this._componentRegistry.has(component);
2640
+ return this._componentToType.has(component);
2641
+ }
2642
+ /**
2643
+ * Get the property path with the record identifier if it exists. For example,
2644
+ * `columns.columnName.label` becomes `columns.*.label`, for record properties.
2645
+ */
2646
+ getPropertyWithRecordIdentifier(type, path) {
2647
+ const managedProps = this.getManagedProps(type);
2648
+ const splitPath = path.split(".");
2649
+ if (splitPath.length === 1) return path;
2650
+ const [parentKey, _maybeTheRecordKey, ...rest] = splitPath;
2651
+ for (const prop of managedProps) if (prop.path.startsWith(parentKey) && prop.path.includes(RECORD_PATH_IDENTIFIER) && rest.length > 0 && prop.path.endsWith(rest.join("."))) return [
2652
+ parentKey,
2653
+ RECORD_PATH_IDENTIFIER,
2654
+ rest.join(".")
2655
+ ].join(".");
2656
+ return path;
2657
+ }
2658
+ };
2659
+
2660
+ //#endregion
2661
+ //#region src/lib/internal-details/lib/root-store.ts
2662
+ var RootStore = class {
2663
+ apis;
2664
+ componentRegistry;
2665
+ editStore;
2666
+ locationStore;
2667
+ currentPageScopeId;
2668
+ applicationId;
2669
+ userId;
2670
+ windowOriginUrl;
2671
+ editorRegisteredCallbacks = [];
2672
+ constructor() {
2673
+ this.apis = new api_store_default(this);
2674
+ this.componentRegistry = new ComponentRegistry(this);
2675
+ this.locationStore = new LocationStore(this);
2676
+ makeObservable(this, {
2677
+ editStore: observable.shallow,
2678
+ setEditStore: action,
2679
+ applicationId: observable,
2680
+ userId: observable
2681
+ });
2682
+ }
2683
+ setEditStore(editStore) {
2684
+ if (this.editStore) return;
2685
+ this.editStore = editStore;
2686
+ this.editorRegisteredCallbacks.forEach((fn) => fn());
2687
+ this.editorRegisteredCallbacks = [];
2688
+ }
2689
+ onEditorRegistered(fn) {
2690
+ this.editorRegisteredCallbacks.push(fn);
2691
+ }
2692
+ };
2693
+ var root_store_default = new RootStore();
2694
+
2695
+ //#endregion
2696
+ //#region src/lib/user-facing/assets/images/clark.svg
2697
+ var _path$1, _path2, _path3, _path4, _path5, _path6, _path7, _defs;
2698
+ function _extends$1() {
2699
+ return _extends$1 = Object.assign ? Object.assign.bind() : function(n) {
2700
+ for (var e = 1; e < arguments.length; e++) {
2701
+ var t = arguments[e];
2702
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
2703
+ }
2704
+ return n;
2705
+ }, _extends$1.apply(null, arguments);
2706
+ }
2707
+ var SvgClark = function SvgClark$1(props) {
2708
+ return /* @__PURE__ */ React$1.createElement("svg", _extends$1({
2709
+ xmlns: "http://www.w3.org/2000/svg",
2710
+ width: 28,
2711
+ height: 20,
2712
+ fill: "none"
2713
+ }, props), _path$1 || (_path$1 = /* @__PURE__ */ React$1.createElement("path", {
2714
+ fill: "url(#clark_svg__a)",
2715
+ d: "M20.41 1.239a5.16 5.16 0 0 0-4.703 5.413l2.648-.232a2.227 2.227 0 1 1 2.886 2.49l.18 2.062.035.02c.575-.05 1.213-.454 1.57-.748 1.617-1.337 1.71-3.2 1.705-3.672 0-.063.047-.117.11-.123l.27-.024a.18.18 0 0 0 .167-.206c-.068-.444-.304-1.577-1.018-2.419-.064-.074-.019-.194.079-.203l.402-.035c.142-.012.218-.166.13-.28-.492-.64-1.994-2.26-4.46-2.043"
2716
+ })), _path2 || (_path2 = /* @__PURE__ */ React$1.createElement("path", {
2717
+ fill: "#2A333D",
2718
+ d: "M18.333 6.987a2.226 2.226 0 0 0 2.411 2.024l.555-.048c-.612-2.74-1.987-3.551-1.987-3.551.153-.386 1.044-.836 1.044-.836a2.226 2.226 0 0 0-2.023 2.411",
2719
+ opacity: .12
2720
+ })), _path3 || (_path3 = /* @__PURE__ */ React$1.createElement("path", {
2721
+ fill: "url(#clark_svg__b)",
2722
+ d: "m6.65 12.564.045.492-.228-2.607A2.338 2.338 0 1 1 8.58 6.587l2.588-.226a5.16 5.16 0 0 0-5.371-3.584c-2.467.216-3.665 2.072-4.039 2.787-.066.127.035.266.177.253l.403-.035c.097-.008.162.102.113.186-.558.953-.593 2.11-.583 2.56a.18.18 0 0 0 .2.173l.27-.023a.12.12 0 0 1 .13.101c.078.467.492 2.285 2.317 3.32.402.228 1.291.515 1.866.465"
2723
+ })), _path4 || (_path4 = /* @__PURE__ */ React$1.createElement("path", {
2724
+ fill: "#2A333D",
2725
+ d: "M9.161 7.938a2.337 2.337 0 0 1-2.124 2.53l-.582.052c.133-2.944 1.406-4.032 1.406-4.032-.227-.371-1.231-.675-1.231-.675A2.337 2.337 0 0 1 9.16 7.938",
2726
+ opacity: .12
2727
+ })), _path5 || (_path5 = /* @__PURE__ */ React$1.createElement("path", {
2728
+ fill: "currentColor",
2729
+ fillRule: "evenodd",
2730
+ d: "M21.72 10.543c-.461-3.366-2.697-6.01-6.685-6.252-.109-.006-.163-.01-.202-.031a.2.2 0 0 1-.078-.084c-.02-.04-.02-.092-.02-.197v-.572a.192.192 0 0 0-.308-.153l-.938.708a.192.192 0 0 1-.309-.154v-.361a.192.192 0 0 0-.318-.145l-.807.717a9 9 0 0 1-.5.431 2 2 0 0 1-.305.2c-.119.069-.414.205-1.004.477-2.794 1.29-4.104 3.885-3.852 6.757.43 4.911 3.404 6.652 8.266 6.226 4.215-.368 7.758-2.469 7.06-7.567M11.64 10.2c.142.62-.16 1.221-.678 1.34-.518.12-1.053-.286-1.197-.907a1.3 1.3 0 0 1-.018-.521.384.384 0 1 0 .376-.667.8.8 0 0 1 .32-.153c.517-.12 1.053.287 1.196.908m7.042-.148c.51-.146.782-.761.606-1.374-.176-.612-.732-.99-1.242-.844a.83.83 0 0 0-.375.23.384.384 0 1 1-.284.713q-.01.211.052.431c.176.613.732.99 1.243.844m-5.448 3.596-.253-2.896a2.08 2.08 0 0 1 4.092-.685l.704 2.82a2.31 2.31 0 1 1-4.543.761",
2731
+ clipRule: "evenodd"
2732
+ })), _path6 || (_path6 = /* @__PURE__ */ React$1.createElement("path", {
2733
+ fill: "url(#clark_svg__c)",
2734
+ d: "M13.88 14.096a2.3 2.3 0 0 0 1.847.492 2.3 2.3 0 0 0 1.585-1.066 1.79 1.79 0 0 1-3.431.574",
2735
+ opacity: .5
2736
+ })), _path7 || (_path7 = /* @__PURE__ */ React$1.createElement("path", {
2737
+ fill: "url(#clark_svg__d)",
2738
+ d: "M13.191 13.144a2.312 2.312 0 0 0 4.465-.748l.123.491a2.31 2.31 0 1 1-4.544.761z",
2739
+ opacity: .5
2740
+ })), _defs || (_defs = /* @__PURE__ */ React$1.createElement("defs", null, /* @__PURE__ */ React$1.createElement("linearGradient", {
2741
+ id: "clark_svg__a",
2742
+ x1: 21.636,
2743
+ x2: 17.027,
2744
+ y1: 4.149,
2745
+ y2: 8.785,
2746
+ gradientUnits: "userSpaceOnUse"
2747
+ }, /* @__PURE__ */ React$1.createElement("stop", { stopColor: "currentColor" }), /* @__PURE__ */ React$1.createElement("stop", {
2748
+ offset: 1,
2749
+ stopColor: "currentColor",
2750
+ stopOpacity: .84
2751
+ })), /* @__PURE__ */ React$1.createElement("linearGradient", {
2752
+ id: "clark_svg__b",
2753
+ x1: 4.534,
2754
+ x2: 10.643,
2755
+ y1: 6.603,
2756
+ y2: 9.712,
2757
+ gradientUnits: "userSpaceOnUse"
2758
+ }, /* @__PURE__ */ React$1.createElement("stop", { stopColor: "currentColor" }), /* @__PURE__ */ React$1.createElement("stop", {
2759
+ offset: 1,
2760
+ stopColor: "currentColor",
2761
+ stopOpacity: .84
2762
+ })), /* @__PURE__ */ React$1.createElement("linearGradient", {
2763
+ id: "clark_svg__c",
2764
+ x1: 15.788,
2765
+ x2: 16.004,
2766
+ y1: 13.866,
2767
+ y2: 15.093,
2768
+ gradientUnits: "userSpaceOnUse"
2769
+ }, /* @__PURE__ */ React$1.createElement("stop", {
2770
+ stopColor: "currentColor",
2771
+ stopOpacity: .6
2772
+ }), /* @__PURE__ */ React$1.createElement("stop", {
2773
+ offset: 1,
2774
+ stopColor: "currentColor"
2775
+ })), /* @__PURE__ */ React$1.createElement("linearGradient", {
2776
+ id: "clark_svg__d",
2777
+ x1: 15.704,
2778
+ x2: 16.07,
2779
+ y1: 13.597,
2780
+ y2: 15.67,
2781
+ gradientUnits: "userSpaceOnUse"
2782
+ }, /* @__PURE__ */ React$1.createElement("stop", {
2783
+ stopColor: "currentColor",
2784
+ stopOpacity: .6
2785
+ }), /* @__PURE__ */ React$1.createElement("stop", {
2786
+ offset: 1,
2787
+ stopColor: "currentColor"
2788
+ })))));
2789
+ };
2790
+ var clark_default = SvgClark;
2791
+
2792
+ //#endregion
2793
+ //#region src/lib/internal-details/internal-components/common.ts
2794
+ const ErrorIconContainer = styled.div`
2795
+ width: 60px;
2796
+ height: 60px;
2797
+ min-width: 60px;
2798
+ min-height: 60px;
2799
+ background: linear-gradient(135deg, #aab 0%, #000033 50%, #000066 100%);
2800
+ border-radius: 16px;
2801
+ display: flex;
2802
+ align-items: center;
2803
+ justify-content: center;
2804
+ margin: 0 auto 16px;
2805
+ flex-shrink: 0;
2806
+ animation: scaleIn 0.3s ease-out forwards;
2807
+ opacity: 0;
2808
+ box-shadow:
2809
+ 0 0 1px black,
2810
+ 0 4px 12px rgba(0, 85, 187, 0.15),
2811
+ 0 2px 4px rgba(0, 85, 187, 0.05);
2812
+
2813
+ @keyframes scaleIn {
2814
+ from {
2815
+ transform: scale(0.8);
2816
+ opacity: 0;
2817
+ }
2818
+ to {
2819
+ transform: scale(1);
2820
+ opacity: 1;
2821
+ }
2822
+ }
2823
+ `;
2824
+ const StyledClarkIcon = styled(clark_default)`
2825
+ width: 54px;
2826
+ height: 54px;
2827
+ color: white;
2828
+ margin-top: 3px;
2829
+ margin-left: 1px;
2830
+ animation: scaleIn 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
2831
+ opacity: 0;
2832
+
2833
+ @keyframes scaleIn {
2834
+ 0% {
2835
+ transform: scale(0.6);
2836
+ opacity: 0;
2837
+ }
2838
+ 50% {
2839
+ transform: scale(1.1);
2840
+ }
2841
+ 100% {
2842
+ transform: scale(1);
2843
+ opacity: 1;
2844
+ }
2845
+ }
2846
+ `;
2847
+ const ErrorTitle = styled.h2`
2848
+ font-family: Inter;
2849
+ color: rgba(0, 0, 0, 0.85);
2850
+ font-weight: 600;
2851
+ font-size: 24px;
2852
+ line-height: 1.35;
2853
+ text-align: center;
2854
+ margin-bottom: 6px;
2855
+ flex-shrink: 0;
2856
+ `;
2857
+ const ErrorMessage = styled.p`
2858
+ font-family: Inter;
2859
+ font-size: 14px;
2860
+ color: #6c7689;
2861
+ line-height: 1.5715;
2862
+ text-align: center;
2863
+ flex-shrink: 0;
2864
+ margin-top: 0;
2865
+ margin-bottom: 16px;
2866
+ `;
2867
+ const ErrorDetails = styled.details`
2868
+ margin-top: 24px;
2869
+ text-align: left;
2870
+ background-color: #f9fafb;
2871
+ border-radius: 6px;
2872
+ padding: 16px;
2873
+ box-shadow:
2874
+ 0px 0px 1px 0px #22272f52,
2875
+ 0px 1px 3px 0px #22272f1f;
2876
+ flex-shrink: 0;
2877
+ font-family: Inter;
2878
+
2879
+ &[open] summary {
2880
+ margin-bottom: 12px;
2881
+ }
2882
+ `;
2883
+ const ErrorSummary = styled.summary`
2884
+ cursor: pointer;
2885
+ font-weight: 500;
2886
+ color: #374151;
2887
+ font-size: 14px;
2888
+ user-select: none;
2889
+ `;
2890
+ const ErrorStack = styled.pre`
2891
+ font-size: 12px;
2892
+ color: #dc2626;
2893
+ overflow: auto;
2894
+ white-space: pre-wrap;
2895
+ margin: 16px;
2896
+ font-family: monospace;
2897
+ `;
2898
+ const ErrorContainer = styled.div`
2899
+ position: absolute;
2900
+ inset: 0;
2901
+ display: flex;
2902
+ align-items: center;
2903
+ justify-content: center;
2904
+ z-index: 10;
2905
+ background: rgba(255, 255, 255, 0.5);
2906
+ pointer-events: auto;
2907
+ `;
2908
+ const ErrorContent = styled.div`
2909
+ max-width: 700px;
2910
+ padding: 40px;
2911
+ overflow-y: auto;
2912
+ flex: 1;
2913
+ display: flex;
2914
+ flex-direction: column;
2915
+ gap: 20px;
2916
+
2917
+ opacity: 0;
2918
+ animation: fadeIn 0.3s ease-out forwards;
2919
+
2920
+ @keyframes fadeIn {
2921
+ from {
2922
+ opacity: 0;
2923
+ }
2924
+ to {
2925
+ opacity: 1;
2926
+ }
2927
+ }
2928
+ `;
2929
+ const SecondaryButton = styled.button`
2930
+ color: ${colors.GREY_700};
2931
+ border: 1px solid ${colors.GREY_100};
2932
+ width: fit-content;
2933
+ border-radius: 4px;
2934
+ padding: 6px 12px;
2935
+ cursor: pointer;
2936
+ height: fit-content;
2937
+ font-size: 12px;
2938
+
2939
+ &:hover {
2940
+ opacity: 0.8;
2941
+ }
2942
+
2943
+ &:active {
2944
+ opacity: 0.6;
2945
+ }
2946
+ `;
2947
+ const ActionsContainer = styled.div`
2948
+ display: flex;
2949
+ gap: 12px;
2950
+ align-items: center;
2951
+ justify-content: center;
2952
+ `;
2953
+
2954
+ //#endregion
2955
+ //#region src/edit-mode/assets/ai-stars.svg
2956
+ var _path;
2957
+ function _extends() {
2958
+ return _extends = Object.assign ? Object.assign.bind() : function(n) {
2959
+ for (var e = 1; e < arguments.length; e++) {
2960
+ var t = arguments[e];
2961
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
2962
+ }
2963
+ return n;
2964
+ }, _extends.apply(null, arguments);
2965
+ }
2966
+ var SvgAiStars = function SvgAiStars$1(props) {
2967
+ return /* @__PURE__ */ React$1.createElement("svg", _extends({
2968
+ xmlns: "http://www.w3.org/2000/svg",
2969
+ width: 13,
2970
+ height: 14,
2971
+ fill: "none"
2972
+ }, props), _path || (_path = /* @__PURE__ */ React$1.createElement("path", {
2973
+ fill: "currentColor",
2974
+ fillRule: "evenodd",
2975
+ d: "M10.5.9a.6.6 0 0 1 .586.472l.133.605a.4.4 0 0 0 .305.305l.605.132a.6.6 0 0 1 0 1.172l-.605.133a.4.4 0 0 0-.305.305l-.133.605a.6.6 0 0 1-1.172 0l-.132-.605a.4.4 0 0 0-.305-.305l-.605-.133a.6.6 0 0 1 0-1.172l.605-.132a.4.4 0 0 0 .305-.305l.132-.605A.6.6 0 0 1 10.5.9M5.077 3.833a.6.6 0 0 0-1.153 0l-.215.74A2.4 2.4 0 0 1 2.074 6.21l-.741.215a.6.6 0 0 0 0 1.153l.74.215A2.4 2.4 0 0 1 3.71 9.427l.215.74a.6.6 0 0 0 1.153 0l.215-.74a2.4 2.4 0 0 1 1.635-1.635l.74-.215a.6.6 0 0 0 0-1.153l-.74-.215a2.4 2.4 0 0 1-1.635-1.635zm6.01 5.539a.6.6 0 0 0-1.173 0l-.132.605a.4.4 0 0 1-.305.305l-.605.133a.6.6 0 0 0 0 1.172l.605.132a.4.4 0 0 1 .305.305l.132.605a.6.6 0 0 0 1.172 0l.133-.605a.4.4 0 0 1 .305-.305l.605-.132a.6.6 0 0 0 0-1.172l-.605-.133a.4.4 0 0 1-.305-.305z",
2976
+ clipRule: "evenodd"
2977
+ })));
2978
+ };
2979
+ var ai_stars_default = SvgAiStars;
2980
+
2981
+ //#endregion
2982
+ //#region src/lib/internal-details/internal-components/fix-with-clark-button.tsx
2983
+ const MAX_STACK_FRAMES = 10;
2984
+ const MAX_PROMPT_LENGTH = 8e3;
2985
+ function buildRuntimeErrorPrompt(error) {
2986
+ const defaultPrompt = "Fix this error: Unknown error";
2987
+ if (!error) return defaultPrompt;
2988
+ const [messageLine, ...rawFrames] = error.stack?.split("\n") ?? [];
2989
+ const message = (messageLine || error.message || error.toString()).trim();
2990
+ const filteredFrames = rawFrames.filter((line) => line && !line.includes("node_modules"));
2991
+ const selectedFrames = filteredFrames.slice(0, MAX_STACK_FRAMES);
2992
+ const omittedCount = filteredFrames.length - selectedFrames.length;
2993
+ const frameSection = [...selectedFrames, ...omittedCount > 0 ? [`... (${omittedCount} additional frame${omittedCount > 1 ? "s" : ""} omitted)`] : []].map((line) => line.trimEnd()).join("\n");
2994
+ const prompt = `Fix this error: ${frameSection ? `${message}\n${frameSection}` : message}`;
2995
+ if (prompt.length <= MAX_PROMPT_LENGTH) return prompt;
2996
+ const suffix = "... (truncated)";
2997
+ const availableChars = Math.max(MAX_PROMPT_LENGTH - 15, 0);
2998
+ return `${prompt.slice(0, availableChars)}${suffix}`;
2999
+ }
3000
+ const FixWithClarkButtonContainer = styled.button`
3001
+ padding: 6px 12px;
3002
+ background-color: ${colors.ACCENT_BLUE_500};
3003
+ border-radius: 4px;
3004
+ border: none;
3005
+ color: white;
3006
+ height: fit-content;
3007
+ display: flex;
3008
+ gap: 4px;
3009
+ cursor: pointer;
3010
+ transition: opacity 0.2s;
3011
+ font-size: 12px;
3012
+ align-items: center;
3013
+
3014
+ &:hover:not(:disabled) {
3015
+ opacity: 0.8;
3016
+ }
3017
+
3018
+ &:disabled {
3019
+ opacity: 0.5;
3020
+ cursor: not-allowed;
3021
+ }
3022
+ `;
3023
+ function FixWithClarkButton({ identifier, error, onClick }) {
3024
+ const isAiEditing = root_store_default.editStore?.ai.getIsEditing() ?? false;
3025
+ const handleFixWithAi = () => {
3026
+ onClick?.();
3027
+ if (identifier) editorBridge.addComponentToAiContext(identifier.sourceId, identifier.selectorId);
3028
+ const prompt = buildRuntimeErrorPrompt(error);
3029
+ editorBridge.aiGenerate(prompt, true);
3030
+ };
3031
+ return /* @__PURE__ */ jsxs(FixWithClarkButtonContainer, {
3032
+ onClick: handleFixWithAi,
3033
+ disabled: isAiEditing,
3034
+ children: [/* @__PURE__ */ jsx(ai_stars_default, {}), " Fix with Clark"]
3035
+ });
3036
+ }
3037
+
3038
+ //#endregion
3039
+ //#region src/lib/utils/widget-wrapper-naming.ts
3040
+ const getWidgetAnchorName = (selectorId) => {
3041
+ return `--widget-${selectorId}`;
3042
+ };
3043
+ const getWidgetRectAnchorName = (selectorId) => {
3044
+ return `--widget-rect-${selectorId}`;
3045
+ };
3046
+
3047
+ //#endregion
3048
+ export { useSuperblocksUser as A, generateId as C, useSuperblocksContext as D, SuperblocksContextProvider as E, iframeMessageHandler as F, isEmbeddedBySuperblocksFirstParty as I, isEditMode as L, colors as M, editorBridge as N, useSuperblocksGroups as O, getEditStore as P, startEditorSync as S, resolveById as T, createManagedPropsList as _, ActionsContainer as a, Section as b, ErrorDetails as c, ErrorStack as d, ErrorSummary as f, root_store_default as g, StyledClarkIcon as h, ai_stars_default as i, sendNotification as j, useSuperblocksProfiles as k, ErrorIconContainer as l, SecondaryButton as m, getWidgetRectAnchorName as n, ErrorContainer as o, ErrorTitle as p, FixWithClarkButton as r, ErrorContent as s, getWidgetAnchorName as t, ErrorMessage as u, Prop as v, rejectById as w, createPropertiesPanelDefinition as x, PropsCategory as y };
3049
+ //# sourceMappingURL=widget-wrapper-naming-ChBggw6W.js.map