@kittl/sdk 0.0.9 → 1.0.0-alpha.2

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.
@@ -0,0 +1,1184 @@
1
+ // @ts-self-types="./sdk.d.ts"
2
+ /*! Kittl SDK - https://kittl.com - see license for terms */
3
+
4
+ "use strict";
5
+ (() => {
6
+
7
+ var FROM_EXTENSION_COMMANDS = {
8
+ /** Capability-owned AI callback registration. */
9
+ AI_GENERATOR_SUBSCRIBE: "ai-generator-subscribe",
10
+ /** Capability-owned AI callback teardown. */
11
+ AI_GENERATOR_UNSUBSCRIBE: "ai-generator-unsubscribe",
12
+ /** SDK API call */
13
+ SDK_CALL: "sdk-call",
14
+ /** AI handler registration */
15
+ AI_REGISTER_HANDLER: "ai-register-handler",
16
+ /** AI handler unregistration */
17
+ AI_UNREGISTER_HANDLER: "ai-unregister-handler",
18
+ /** File browser tab registration */
19
+ FILE_BROWSER_REGISTER: "file-browser-register",
20
+ /** File browser fetch content response */
21
+ FILE_BROWSER_FETCH_CONTENT_RESPONSE: "file-browser-fetch-content-response",
22
+ /** Stateless message send */
23
+ STATELESS_SEND: "stateless-send",
24
+ /** Stateless subscription */
25
+ STATELESS_SUBSCRIBE: "stateless-subscribe",
26
+ /** Stateless unsubscription */
27
+ STATELESS_UNSUBSCRIBE: "stateless-unsubscribe",
28
+ /** App state subscription */
29
+ APP_STATE_SUBSCRIBE: "app-state-subscribe",
30
+ /** App state unsubscription */
31
+ APP_STATE_UNSUBSCRIBE: "app-state-unsubscribe",
32
+ /** Batch creation */
33
+ BATCH_CREATE: "batch-create",
34
+ /** Batch commit */
35
+ BATCH_COMMIT: "batch-commit",
36
+ /** OAuth flow start */
37
+ AUTH_START: "auth-start",
38
+ /** OAuth token exchange */
39
+ AUTH_EXCHANGE: "auth-exchange",
40
+ /** Get OAuth token */
41
+ AUTH_GET_TOKEN: "auth-get-token",
42
+ /** Refresh OAuth token */
43
+ AUTH_REFRESH: "auth-refresh",
44
+ /** OAuth logout */
45
+ AUTH_LOGOUT: "auth-logout",
46
+ /** Get user token for authentication */
47
+ AUTH_GET_USER_TOKEN: "auth-get-user-token",
48
+ /** Context subscription */
49
+ CONTEXT_SUBSCRIBE: "context-subscribe",
50
+ /** Context unsubscription */
51
+ CONTEXT_UNSUBSCRIBE: "context-unsubscribe",
52
+ /** Design state subscription */
53
+ DESIGN_STATE_SUBSCRIBE: "design-state-subscribe",
54
+ /** Design state unsubscription */
55
+ DESIGN_STATE_UNSUBSCRIBE: "design-state-unsubscribe",
56
+ /** Extension loaded notification */
57
+ LOADED: "loaded"
58
+ };
59
+ var TO_EXTENSION_COMMANDS = {
60
+ /** Callback payload for generator or pending-set subscriptions. */
61
+ AI_GENERATOR_UPDATE: "ai-generator-update",
62
+ /** SDK API response */
63
+ SDK_RESPONSE: "sdk-response",
64
+ /** File browser fetch content request */
65
+ FILE_BROWSER_FETCH_CONTENT_REQUEST: "file-browser-fetch-content-request",
66
+ /** Stateless message push */
67
+ STATELESS_MESSAGE: "stateless-message",
68
+ /** Context update push */
69
+ CONTEXT_UPDATE: "context-update",
70
+ /** AI generation update push */
71
+ AI_GENERATION_UPDATE: "ai-generation-update",
72
+ /** Design state update push */
73
+ DESIGN_STATE_UPDATE: "design-state-update",
74
+ /** App state update push */
75
+ APP_STATE_UPDATE: "app-state-update"
76
+ };
77
+
78
+ function isAIGeneratorUpdateMessage(data) {
79
+ return !!data && typeof data === "object" && "command" in data && data.command === "ai-generator-update" && "subscriptionId" in data && typeof data.subscriptionId === "string";
80
+ }
81
+
82
+ var isSDKResponseMessage = (data) => {
83
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.SDK_RESPONSE && "messageId" in data && typeof data.messageId === "string";
84
+ };
85
+ var isStatelessPushMessage = (data) => {
86
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.STATELESS_MESSAGE && "type" in data && typeof data.type === "string" && "payload" in data && typeof data.payload === "object" && data.payload !== null;
87
+ };
88
+ var isAIGenerationUpdatePushMessage = (data) => {
89
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.AI_GENERATION_UPDATE && "subscriptionId" in data && typeof data.subscriptionId === "string" && "update" in data && typeof data.update === "object" && data.update !== null;
90
+ };
91
+ var isDesignStateUpdatePushMessage = (data) => {
92
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.DESIGN_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
93
+ };
94
+ var isAppStateUpdatePushMessage = (data) => {
95
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.APP_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
96
+ };
97
+ var isContextUpdatePushMessage = (data) => {
98
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.CONTEXT_UPDATE && "subscriptionId" in data && typeof data.subscriptionId === "string" && "context" in data && typeof data.context === "object" && data.context !== null;
99
+ };
100
+ var isFileBrowserFetchContentRequestMessage = (data) => {
101
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_REQUEST && "requestId" in data && typeof data.requestId === "string" && "subscriptionId" in data && typeof data.subscriptionId === "string";
102
+ };
103
+
104
+ var generateMessageId = () => {
105
+ if (crypto?.randomUUID && typeof crypto.randomUUID === "function") {
106
+ return crypto.randomUUID();
107
+ }
108
+ return Math.random().toString(36).substring(7);
109
+ };
110
+
111
+ var buildMethodPath = (rootPrefix, pathSegments) => {
112
+ if (!rootPrefix) {
113
+ return pathSegments.join(".");
114
+ }
115
+ if (pathSegments.length === 0) {
116
+ return rootPrefix;
117
+ }
118
+ return `${rootPrefix}.${pathSegments.join(".")}`;
119
+ };
120
+ var createCallablePathProxy = (options) => {
121
+ const createNode = (pathSegments) => {
122
+ const target = () => {
123
+ };
124
+ const handler = {
125
+ get: (_target, prop) => {
126
+ if (typeof prop === "symbol") {
127
+ return Reflect.get(target, prop);
128
+ }
129
+ return createNode([...pathSegments, String(prop)]);
130
+ },
131
+ apply: (_target, _thisArg, args) => {
132
+ const context = {
133
+ pathSegments,
134
+ methodPath: buildMethodPath(options.rootPrefix ?? "", pathSegments),
135
+ args
136
+ };
137
+ options.beforeInvoke?.(context);
138
+ return options.onInvoke(context);
139
+ }
140
+ };
141
+ return new Proxy(target, handler);
142
+ };
143
+ return createNode([]);
144
+ };
145
+
146
+ var parentDomain;
147
+ var APPROVED_EXTENSION_COMMUNICATION_DOMAINS = [
148
+ "https://app.stagingdesigner.com",
149
+ "https://*.stagingdesigner.com",
150
+ "http://localhost:3000",
151
+ "https://app.kittl.com",
152
+ // website, for sandboxed standalone dashboard pages
153
+ "http://localhost:3003",
154
+ "https://www.kittl.com"
155
+ ];
156
+ var toOrigin = (value) => {
157
+ if (!value) {
158
+ return null;
159
+ }
160
+ try {
161
+ return new URL(value).origin;
162
+ } catch (_error) {
163
+ return null;
164
+ }
165
+ };
166
+ var escapeRegex = (value) => {
167
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
168
+ };
169
+ var matchesApprovedDomain = (origin, approvedDomain) => {
170
+ const normalized = approvedDomain.trim();
171
+ if (!normalized) {
172
+ return false;
173
+ }
174
+ if (normalized.includes("*")) {
175
+ const wildcardRegex = new RegExp(
176
+ // because we use wildcards only in the middle of the string
177
+ // we know that our list must start with the regex and end with the regex
178
+ // so we add the ^ and $ to the regex too
179
+ `^${escapeRegex(normalized).replace(/\\\*/g, ".*")}$`
180
+ );
181
+ return wildcardRegex.test(origin);
182
+ }
183
+ return origin === normalized;
184
+ };
185
+ var getParentDomain = () => {
186
+ if (parentDomain) {
187
+ return parentDomain;
188
+ }
189
+ const referrer = window.document.referrer;
190
+ const ancestorOrigins = window.location.ancestorOrigins;
191
+ const ancestorOrigin = ancestorOrigins && ancestorOrigins.length > 0 ? ancestorOrigins[ancestorOrigins.length - 1] : void 0;
192
+ const currentDomainOrigin = toOrigin(referrer) ?? toOrigin(ancestorOrigin);
193
+ if (!currentDomainOrigin) {
194
+ throw new Error("No current domain origin found");
195
+ }
196
+ const approvedParentDomain = APPROVED_EXTENSION_COMMUNICATION_DOMAINS.find(
197
+ (domain) => {
198
+ return matchesApprovedDomain(currentDomainOrigin, domain);
199
+ }
200
+ );
201
+ if (!approvedParentDomain) {
202
+ throw new Error("No approved parent domain found");
203
+ }
204
+ parentDomain = currentDomainOrigin;
205
+ return parentDomain;
206
+ };
207
+
208
+ var pendingRequests = /* @__PURE__ */ new Map();
209
+ var sdkVersion;
210
+ function setSDKVersion(version2) {
211
+ sdkVersion = version2;
212
+ }
213
+ var postMessageToParent = (message) => {
214
+ window.parent.postMessage(
215
+ sdkVersion === void 0 ? message : { ...message, sdkVersion },
216
+ getParentDomain()
217
+ );
218
+ };
219
+ var sendMessage = (message) => {
220
+ postMessageToParent(message);
221
+ return new Promise((resolve, reject) => {
222
+ pendingRequests.set(message.messageId, {
223
+ resolve: (value) => {
224
+ resolve(value);
225
+ },
226
+ reject
227
+ });
228
+ });
229
+ };
230
+ var sendLoaded = () => {
231
+ const parent = window.parent;
232
+ if (!parent || parent === window) {
233
+ return;
234
+ }
235
+ const message = { command: FROM_EXTENSION_COMMANDS.LOADED };
236
+ postMessageToParent(message);
237
+ };
238
+
239
+ var createSDKCallMessage = {
240
+ aiGenerator: (dots, args, messageId) => ({
241
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
242
+ dots,
243
+ args,
244
+ messageId,
245
+ apiType: "aiGenerator"
246
+ }),
247
+ mockup: (dots, args, messageId) => ({
248
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
249
+ dots,
250
+ args,
251
+ messageId,
252
+ apiType: "mockup"
253
+ }),
254
+ fileBrowser: (dots, args, messageId) => ({
255
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
256
+ dots,
257
+ args,
258
+ messageId,
259
+ apiType: "fileBrowser"
260
+ }),
261
+ ai: (dots, args, messageId) => ({
262
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
263
+ dots,
264
+ args,
265
+ messageId,
266
+ apiType: "ai"
267
+ }),
268
+ context: (dots, args, messageId) => ({
269
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
270
+ dots,
271
+ args,
272
+ messageId,
273
+ apiType: "context"
274
+ }),
275
+ design: (dots, args, messageId) => ({
276
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
277
+ dots,
278
+ args,
279
+ messageId,
280
+ apiType: "design"
281
+ }),
282
+ export: (dots, args, messageId) => ({
283
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
284
+ dots,
285
+ args,
286
+ messageId,
287
+ apiType: "export"
288
+ }),
289
+ font: (dots, args, messageId) => ({
290
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
291
+ dots,
292
+ args,
293
+ messageId,
294
+ apiType: "font"
295
+ }),
296
+ project: (dots, args, messageId) => ({
297
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
298
+ dots,
299
+ args,
300
+ messageId,
301
+ apiType: "project"
302
+ }),
303
+ state: (dots, args, messageId) => ({
304
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
305
+ dots,
306
+ args,
307
+ messageId,
308
+ apiType: "state"
309
+ }),
310
+ upload: (dots, args, messageId) => ({
311
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
312
+ dots,
313
+ args,
314
+ messageId,
315
+ apiType: "upload"
316
+ }),
317
+ data: (dots, args, messageId) => ({
318
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
319
+ dots,
320
+ args,
321
+ messageId,
322
+ apiType: "data"
323
+ }),
324
+ brandKit: (dots, args, messageId) => ({
325
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
326
+ dots,
327
+ args,
328
+ messageId,
329
+ apiType: "brandKit"
330
+ }),
331
+ openMicroEditor: (dots, args, messageId) => ({
332
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
333
+ dots,
334
+ args,
335
+ messageId,
336
+ apiType: "openMicroEditor"
337
+ }),
338
+ openMainEditor: (dots, args, messageId) => ({
339
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
340
+ dots,
341
+ args,
342
+ messageId,
343
+ apiType: "openMainEditor"
344
+ }),
345
+ agent: (dots, args, messageId) => ({
346
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
347
+ dots,
348
+ args,
349
+ messageId,
350
+ apiType: "agent"
351
+ })
352
+ };
353
+ function createApiProxy(apiType) {
354
+ return createCallablePathProxy({
355
+ onInvoke: ({ pathSegments, args }) => {
356
+ return sendMessage(
357
+ createSDKCallMessage[apiType](
358
+ [...pathSegments],
359
+ [...args],
360
+ generateMessageId()
361
+ )
362
+ );
363
+ }
364
+ });
365
+ }
366
+
367
+ function createAIGeneratorBridgeApi() {
368
+ const callbacks = /* @__PURE__ */ new Map();
369
+ const proxy = createApiProxy("aiGenerator");
370
+ async function subscribe(request, callback) {
371
+ const subscriptionId = generateMessageId();
372
+ callbacks.set(subscriptionId, callback);
373
+ let response;
374
+ try {
375
+ response = await sendMessage({
376
+ command: "ai-generator-subscribe",
377
+ ...request,
378
+ subscriptionId,
379
+ messageId: generateMessageId()
380
+ });
381
+ } catch (error) {
382
+ callbacks.delete(subscriptionId);
383
+ throw error;
384
+ }
385
+ if (!response.isOk) {
386
+ callbacks.delete(subscriptionId);
387
+ throw new Error(response.error.message);
388
+ }
389
+ return () => {
390
+ callbacks.delete(subscriptionId);
391
+ postMessageToParent({
392
+ command: "ai-generator-unsubscribe",
393
+ subscriptionId
394
+ });
395
+ };
396
+ }
397
+ const methods = {
398
+ registerGenerator: (id, callback) => subscribe({ method: "registerGenerator", args: [id] }, (update) => {
399
+ if (update) callback(update);
400
+ }),
401
+ subscribeToGenerationUpdates: (ids, callback) => subscribe(
402
+ { method: "subscribeToGenerationUpdates", args: [ids] },
403
+ (update) => {
404
+ if (update) callback(update);
405
+ }
406
+ ),
407
+ subscribeToPendingGenerations: (callback) => subscribe(
408
+ { method: "subscribeToPendingGenerations", args: [] },
409
+ () => callback()
410
+ ),
411
+ /** Callers may reuse richer internal submission objects; never send their local abort callbacks. */
412
+ cancelGenerations: (submission) => proxy.cancelGenerations({
413
+ generationIds: submission.generationIds,
414
+ until: submission.until
415
+ })
416
+ };
417
+ return {
418
+ api: new Proxy(proxy, {
419
+ get: (target, property, receiver) => property in methods ? methods[property] : Reflect.get(target, property, receiver)
420
+ }),
421
+ dispatch: (message) => callbacks.get(message.subscriptionId)?.(message.update)
422
+ };
423
+ }
424
+
425
+ var generationHandlers = /* @__PURE__ */ new Map();
426
+ var generationSubscriptions = /* @__PURE__ */ new Map();
427
+ var dispatchAIGenerationUpdate = (subscriptionId, update) => {
428
+ const handler = generationHandlers.get(subscriptionId);
429
+ if (!handler) {
430
+ return;
431
+ }
432
+ void handler(update);
433
+ };
434
+ function createAIApiProxy() {
435
+ const unregisterGenerationHandler = (generatorId) => {
436
+ const subscriptionId = generationSubscriptions.get(generatorId);
437
+ if (!subscriptionId) {
438
+ return;
439
+ }
440
+ generationHandlers.delete(subscriptionId);
441
+ generationSubscriptions.delete(generatorId);
442
+ const unregisterMessage = {
443
+ command: FROM_EXTENSION_COMMANDS.AI_UNREGISTER_HANDLER,
444
+ generatorId,
445
+ subscriptionId
446
+ };
447
+ postMessageToParent(unregisterMessage);
448
+ };
449
+ return {
450
+ spendCredits: async (options) => {
451
+ const { onAccept, onDecline, ...serializable } = options;
452
+ const message = {
453
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
454
+ dots: ["spendCredits"],
455
+ args: [serializable],
456
+ messageId: generateMessageId(),
457
+ apiType: "ai"
458
+ };
459
+ const response = await sendMessage(message);
460
+ if (response.isOk && response.result.success) {
461
+ onAccept?.();
462
+ } else {
463
+ onDecline?.();
464
+ }
465
+ return response;
466
+ },
467
+ startGeneration: (generatorId, inputSettings, output) => {
468
+ const message = {
469
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
470
+ dots: ["startGeneration"],
471
+ args: [generatorId, inputSettings, output],
472
+ messageId: generateMessageId(),
473
+ apiType: "ai"
474
+ };
475
+ return sendMessage(message);
476
+ },
477
+ registerHandler: async (generatorId, onStatusUpdate) => {
478
+ if (generationSubscriptions.has(generatorId)) {
479
+ return {
480
+ isOk: false,
481
+ error: {
482
+ message: `AI handler for generator "${generatorId}" is already registered`,
483
+ name: "SdkInternalError"
484
+ }
485
+ };
486
+ }
487
+ const subscriptionId = generateMessageId();
488
+ generationHandlers.set(subscriptionId, onStatusUpdate);
489
+ generationSubscriptions.set(generatorId, subscriptionId);
490
+ const registerMessage = {
491
+ command: FROM_EXTENSION_COMMANDS.AI_REGISTER_HANDLER,
492
+ messageId: generateMessageId(),
493
+ generatorId,
494
+ subscriptionId
495
+ };
496
+ try {
497
+ const response = await sendMessage(registerMessage);
498
+ if (!response.isOk) {
499
+ generationHandlers.delete(subscriptionId);
500
+ generationSubscriptions.delete(generatorId);
501
+ return response;
502
+ }
503
+ return {
504
+ isOk: true,
505
+ result: () => unregisterGenerationHandler(generatorId)
506
+ };
507
+ } catch {
508
+ generationHandlers.delete(subscriptionId);
509
+ generationSubscriptions.delete(generatorId);
510
+ return {
511
+ isOk: false,
512
+ error: {
513
+ message: "Failed to register AI handler",
514
+ name: "SdkInternalError"
515
+ }
516
+ };
517
+ }
518
+ },
519
+ unregisterHandler: async (generatorId) => {
520
+ unregisterGenerationHandler(generatorId);
521
+ return { isOk: true, result: void 0 };
522
+ }
523
+ };
524
+ }
525
+
526
+ var fetchContentHandlers = /* @__PURE__ */ new Map();
527
+ var tabIdToSubscriptionId = /* @__PURE__ */ new Map();
528
+ var removeSubscriptionHandlers = (subscriptionId) => {
529
+ fetchContentHandlers.delete(subscriptionId);
530
+ };
531
+ var dispatchFileBrowserFetchContentRequest = (requestId, subscriptionId, params) => {
532
+ const handler = fetchContentHandlers.get(subscriptionId);
533
+ if (!handler) {
534
+ const responseMessage = {
535
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
536
+ requestId,
537
+ content: []
538
+ };
539
+ postMessageToParent(responseMessage);
540
+ return;
541
+ }
542
+ void handler(params).then((result) => {
543
+ const responseMessage = {
544
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
545
+ requestId,
546
+ content: result.content,
547
+ next: result.next
548
+ };
549
+ postMessageToParent(responseMessage);
550
+ }).catch((error) => {
551
+ const responseMessage = {
552
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
553
+ requestId,
554
+ content: [],
555
+ error: error instanceof Error ? error.message : "Unknown error"
556
+ };
557
+ postMessageToParent(responseMessage);
558
+ });
559
+ };
560
+ function createFileBrowserApiProxy() {
561
+ return {
562
+ registerUploadBrowser: async (tab) => {
563
+ const subscriptionId = generateMessageId();
564
+ const existingSubscriptionId = tabIdToSubscriptionId.get(tab.id);
565
+ if (existingSubscriptionId) {
566
+ removeSubscriptionHandlers(existingSubscriptionId);
567
+ }
568
+ fetchContentHandlers.set(subscriptionId, tab.fetchContent);
569
+ tabIdToSubscriptionId.set(tab.id, subscriptionId);
570
+ const registerMessage = {
571
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_REGISTER,
572
+ messageId: generateMessageId(),
573
+ tabId: tab.id,
574
+ label: tab.label,
575
+ order: tab.order,
576
+ emptyState: tab.emptyState,
577
+ subscriptionId
578
+ };
579
+ try {
580
+ const response = await sendMessage(registerMessage);
581
+ if (!response.isOk) {
582
+ removeSubscriptionHandlers(subscriptionId);
583
+ tabIdToSubscriptionId.delete(tab.id);
584
+ return {
585
+ isOk: false,
586
+ error: response.error
587
+ };
588
+ }
589
+ return {
590
+ isOk: true,
591
+ result: void 0
592
+ };
593
+ } catch {
594
+ removeSubscriptionHandlers(subscriptionId);
595
+ tabIdToSubscriptionId.delete(tab.id);
596
+ return {
597
+ isOk: false,
598
+ error: {
599
+ message: "Failed to register upload browser",
600
+ name: "SdkInternalError"
601
+ }
602
+ };
603
+ }
604
+ }
605
+ };
606
+ }
607
+
608
+ var sendUnsubscribe = (selectorIds) => {
609
+ const message = {
610
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_UNSUBSCRIBE,
611
+ selectorIds
612
+ };
613
+ postMessageToParent(message);
614
+ };
615
+ var createAppStateBridgeApi = () => {
616
+ const localSubscriptions = /* @__PURE__ */ new Map();
617
+ async function subscribe(paths, callback) {
618
+ if (paths.length === 0) {
619
+ return () => {
620
+ };
621
+ }
622
+ const values = new Array(paths.length).fill(void 0);
623
+ const selectorIds = [];
624
+ const pathArrays = [];
625
+ for (const dotPath of paths) {
626
+ const segments = dotPath.split(".");
627
+ if (segments.some((s) => s === "")) {
628
+ throw new Error(
629
+ `Invalid app state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
630
+ );
631
+ }
632
+ selectorIds.push(generateMessageId());
633
+ pathArrays.push(segments);
634
+ }
635
+ const messageId = generateMessageId();
636
+ const subscribeMessage = {
637
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_SUBSCRIBE,
638
+ messageId,
639
+ selectorIds,
640
+ paths: pathArrays
641
+ };
642
+ const response = await sendMessage(subscribeMessage);
643
+ if (!response.isOk) {
644
+ throw new Error(`app-state-subscribe failed: ${response.error.message}`);
645
+ }
646
+ for (let i = 0; i < selectorIds.length; i++) {
647
+ localSubscriptions.set(selectorIds[i], {
648
+ callback: (value) => {
649
+ values[i] = value;
650
+ callback(...values);
651
+ }
652
+ });
653
+ }
654
+ return () => {
655
+ for (const selectorId of selectorIds) {
656
+ localSubscriptions.delete(selectorId);
657
+ }
658
+ sendUnsubscribe(selectorIds);
659
+ };
660
+ }
661
+ const dispatch = (updates) => {
662
+ for (const { selectorId, value } of updates) {
663
+ const entry = localSubscriptions.get(selectorId);
664
+ if (entry) {
665
+ entry.callback(value);
666
+ }
667
+ }
668
+ };
669
+ return { subscribe, dispatch };
670
+ };
671
+
672
+ var SandboxedAuthClient = class {
673
+ /**
674
+ * Binds the public start method because the exported SDK API may pass it
675
+ * around without its client object as the receiver.
676
+ */
677
+ constructor() {
678
+ this.startAuth = this.startAuth.bind(this);
679
+ }
680
+ /**
681
+ * Starts provider authentication and optionally adds an RFC 7636 PKCE
682
+ * challenge to the request. Successful responses include the verifier that
683
+ * the caller must pass to {@link exchangeCode}.
684
+ */
685
+ async startAuth(request) {
686
+ const state = generateMessageId();
687
+ let pkceCode = "";
688
+ let code_verifier = "";
689
+ if (request.generatePKCE) {
690
+ code_verifier = this.generatePKCECode();
691
+ pkceCode = await this.hashPKCECode(code_verifier);
692
+ }
693
+ const message = {
694
+ command: FROM_EXTENSION_COMMANDS.AUTH_START,
695
+ messageId: generateMessageId(),
696
+ state,
697
+ provider: request.provider,
698
+ params: {
699
+ ...request.params,
700
+ ...pkceCode ? {
701
+ code_challenge: pkceCode,
702
+ code_challenge_method: "S256"
703
+ } : {}
704
+ }
705
+ };
706
+ const response = await sendMessage(message);
707
+ if (!response.isOk) {
708
+ return response;
709
+ }
710
+ return {
711
+ ...response,
712
+ result: {
713
+ ...response.result,
714
+ code_verifier
715
+ }
716
+ };
717
+ }
718
+ /** Exchanges the provider authorization code for an auth token. */
719
+ exchangeCode(request) {
720
+ const message = {
721
+ command: FROM_EXTENSION_COMMANDS.AUTH_EXCHANGE,
722
+ messageId: generateMessageId(),
723
+ code: request.code,
724
+ code_verifier: request.code_verifier,
725
+ provider: request.provider,
726
+ params: request.params,
727
+ headers: request.headers
728
+ };
729
+ return sendMessage(message);
730
+ }
731
+ /** Requests the current auth token for a provider. */
732
+ getAuthToken(request) {
733
+ const message = {
734
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_TOKEN,
735
+ messageId: generateMessageId(),
736
+ provider: request.provider
737
+ };
738
+ return sendMessage(message);
739
+ }
740
+ /** Refreshes the auth token for a provider. */
741
+ refreshToken(request) {
742
+ const message = {
743
+ command: FROM_EXTENSION_COMMANDS.AUTH_REFRESH,
744
+ messageId: generateMessageId(),
745
+ provider: request.provider
746
+ };
747
+ return sendMessage(message);
748
+ }
749
+ /** Logs the current user out of a provider. */
750
+ logout(request) {
751
+ const message = {
752
+ command: FROM_EXTENSION_COMMANDS.AUTH_LOGOUT,
753
+ messageId: generateMessageId(),
754
+ provider: request.provider
755
+ };
756
+ return sendMessage(message);
757
+ }
758
+ /** Requests the authenticated user's user token from the parent window. */
759
+ getUserToken() {
760
+ const message = {
761
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_USER_TOKEN,
762
+ messageId: generateMessageId()
763
+ };
764
+ return sendMessage(message);
765
+ }
766
+ /** Hashes a PKCE verifier and encodes the SHA-256 digest as Base64URL. */
767
+ async hashPKCECode(input) {
768
+ const subtle = window.crypto?.subtle;
769
+ if (!subtle) {
770
+ throw new Error("Web Crypto SubtleCrypto API not available");
771
+ }
772
+ const textAsBuffer = new TextEncoder().encode(input);
773
+ const hashBuffer = await subtle.digest("SHA-256", textAsBuffer);
774
+ const hashArray = new Uint8Array(hashBuffer);
775
+ const binaryString = String.fromCharCode(...hashArray);
776
+ const base64 = btoa(binaryString);
777
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
778
+ }
779
+ /** Generates a high-entropy RFC 7636-compatible PKCE verifier. */
780
+ generatePKCECode() {
781
+ if (!window.crypto) {
782
+ throw new Error("Crypto API not available");
783
+ }
784
+ const array = new Uint32Array(56);
785
+ window.crypto.getRandomValues(array);
786
+ return Array.from(array, (dec) => `0${dec.toString(16)}`.slice(-2)).join(
787
+ ""
788
+ );
789
+ }
790
+ };
791
+
792
+ var createBatchFor = async (apiType) => {
793
+ const response = await sendMessage({
794
+ command: FROM_EXTENSION_COMMANDS.BATCH_CREATE,
795
+ messageId: generateMessageId()
796
+ });
797
+ if (!response.isOk) {
798
+ throw response.error;
799
+ }
800
+ const { batchKey } = response.result;
801
+ const sendDesignCall = (dots, args) => {
802
+ const message = {
803
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
804
+ dots: apiType === "project" ? ["design", "api", ...dots] : dots,
805
+ args,
806
+ messageId: generateMessageId(),
807
+ apiType,
808
+ batchKey
809
+ };
810
+ return sendMessage(message);
811
+ };
812
+ const commit = async () => {
813
+ const res = await sendMessage({
814
+ command: FROM_EXTENSION_COMMANDS.BATCH_COMMIT,
815
+ messageId: generateMessageId(),
816
+ batchKey
817
+ });
818
+ if (!res.isOk) {
819
+ throw res.error;
820
+ }
821
+ };
822
+ const buildNode = (pathSegments) => {
823
+ const target = () => {
824
+ };
825
+ return new Proxy(target, {
826
+ get: (_t, prop) => {
827
+ if (typeof prop === "symbol" || prop === "then") return void 0;
828
+ if (prop === "commit") return commit;
829
+ return buildNode([...pathSegments, prop]);
830
+ },
831
+ apply: (_t, _this, args) => {
832
+ return sendDesignCall(pathSegments, args);
833
+ }
834
+ });
835
+ };
836
+ return buildNode([]);
837
+ };
838
+ var createBatch = () => createBatchFor("design");
839
+ var createProjectBatch = () => createBatchFor("project");
840
+
841
+ var createContextBridgeApi = () => {
842
+ const contextProxy = createApiProxy("context");
843
+ const subscriptionCallbacks = /* @__PURE__ */ new Map();
844
+ const dispatch = (message) => {
845
+ const cb = subscriptionCallbacks.get(message.subscriptionId);
846
+ cb?.(message.context);
847
+ };
848
+ const subscribeImpl = async (callback) => {
849
+ const subscriptionId = generateMessageId();
850
+ const messageId = generateMessageId();
851
+ subscriptionCallbacks.set(subscriptionId, callback);
852
+ let response;
853
+ try {
854
+ response = await sendMessage({
855
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_SUBSCRIBE,
856
+ messageId,
857
+ subscriptionId
858
+ });
859
+ } catch (error) {
860
+ subscriptionCallbacks.delete(subscriptionId);
861
+ throw error;
862
+ }
863
+ if (!response.isOk) {
864
+ subscriptionCallbacks.delete(subscriptionId);
865
+ throw new Error(`context-subscribe failed: ${response.error.message}`);
866
+ }
867
+ return () => {
868
+ subscriptionCallbacks.delete(subscriptionId);
869
+ const message = {
870
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_UNSUBSCRIBE,
871
+ subscriptionId
872
+ };
873
+ postMessageToParent(message);
874
+ };
875
+ };
876
+ const api = new Proxy(contextProxy, {
877
+ get(target, prop, receiver) {
878
+ if (prop === "subscribe") {
879
+ return subscribeImpl;
880
+ }
881
+ return Reflect.get(target, prop, receiver);
882
+ }
883
+ });
884
+ return { api, dispatch };
885
+ };
886
+
887
+ var sendUnsubscribe2 = (selectorIds) => {
888
+ const message = {
889
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_UNSUBSCRIBE,
890
+ selectorIds
891
+ };
892
+ postMessageToParent(message);
893
+ };
894
+ var createDesignStateBridgeApi = () => {
895
+ const localSubscriptions = /* @__PURE__ */ new Map();
896
+ async function subscribe(paths, callback) {
897
+ if (paths.length === 0) {
898
+ return () => {
899
+ };
900
+ }
901
+ const values = new Array(paths.length).fill(void 0);
902
+ const selectorIds = [];
903
+ const pathArrays = [];
904
+ for (const dotPath of paths) {
905
+ const segments = dotPath.split(".");
906
+ if (segments.some((s) => s === "")) {
907
+ throw new Error(
908
+ `Invalid design state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
909
+ );
910
+ }
911
+ selectorIds.push(generateMessageId());
912
+ pathArrays.push(segments);
913
+ }
914
+ const messageId = generateMessageId();
915
+ const subscribeMessage = {
916
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_SUBSCRIBE,
917
+ messageId,
918
+ selectorIds,
919
+ paths: pathArrays
920
+ };
921
+ const response = await sendMessage(subscribeMessage);
922
+ if (!response.isOk) {
923
+ throw new Error(
924
+ `design-state-subscribe failed: ${response.error.message}`
925
+ );
926
+ }
927
+ for (let i = 0; i < selectorIds.length; i++) {
928
+ localSubscriptions.set(selectorIds[i], {
929
+ callback: (value) => {
930
+ values[i] = value;
931
+ callback(...values);
932
+ }
933
+ });
934
+ }
935
+ return () => {
936
+ for (const selectorId of selectorIds) {
937
+ localSubscriptions.delete(selectorId);
938
+ }
939
+ sendUnsubscribe2(selectorIds);
940
+ };
941
+ }
942
+ const dispatch = (updates) => {
943
+ for (const { selectorId, value } of updates) {
944
+ const entry = localSubscriptions.get(selectorId);
945
+ if (entry) {
946
+ entry.callback(value);
947
+ }
948
+ }
949
+ };
950
+ return { subscribe, dispatch };
951
+ };
952
+
953
+ var createStatelessBridgeApi = () => {
954
+ const subscribers = /* @__PURE__ */ new Map();
955
+ return {
956
+ send: (message) => {
957
+ const messageId = generateMessageId();
958
+ const bridgeMessage = {
959
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SEND,
960
+ messageId,
961
+ type: message.type,
962
+ payload: message.payload
963
+ };
964
+ return sendMessage(bridgeMessage);
965
+ },
966
+ subscribe: async (key, handler) => {
967
+ let handlers = subscribers.get(key);
968
+ if (!handlers) {
969
+ handlers = /* @__PURE__ */ new Set();
970
+ subscribers.set(key, handlers);
971
+ }
972
+ handlers.add(handler);
973
+ const messageId = generateMessageId();
974
+ const subscribeMessage = {
975
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SUBSCRIBE,
976
+ messageId,
977
+ key
978
+ };
979
+ return sendMessage(subscribeMessage);
980
+ },
981
+ unsubscribe: async (key) => {
982
+ subscribers.delete(key);
983
+ const messageId = generateMessageId();
984
+ const unsubscribeMessage = {
985
+ command: FROM_EXTENSION_COMMANDS.STATELESS_UNSUBSCRIBE,
986
+ messageId,
987
+ key
988
+ };
989
+ return sendMessage(unsubscribeMessage);
990
+ },
991
+ dispatch: (type, payload) => {
992
+ const handlers = subscribers.get(type);
993
+ if (handlers) {
994
+ for (const handler of handlers) {
995
+ handler(payload);
996
+ }
997
+ }
998
+ }
999
+ };
1000
+ };
1001
+
1002
+ var statelessApi = createStatelessBridgeApi();
1003
+ var designStateApi = createDesignStateBridgeApi();
1004
+ var appStateApi = createAppStateBridgeApi();
1005
+ var { api: contextApi, dispatch: dispatchContextUpdate } = createContextBridgeApi();
1006
+ var authClient = new SandboxedAuthClient();
1007
+ var aiGeneratorBridge = createAIGeneratorBridgeApi();
1008
+ var handleIncomingMessage = (event) => {
1009
+ const parent = window.parent;
1010
+ if (!parent || parent === window) {
1011
+ return;
1012
+ }
1013
+ if (event.source !== parent) {
1014
+ return;
1015
+ }
1016
+ const { data } = event;
1017
+ if (isSDKResponseMessage(data)) {
1018
+ const resolver = pendingRequests.get(data.messageId);
1019
+ if (resolver) {
1020
+ pendingRequests.delete(data.messageId);
1021
+ const response = data.response;
1022
+ resolver.resolve(response);
1023
+ }
1024
+ return;
1025
+ }
1026
+ if (isStatelessPushMessage(data)) {
1027
+ statelessApi.dispatch(data.type, data.payload);
1028
+ return;
1029
+ }
1030
+ if (isAIGeneratorUpdateMessage(data)) {
1031
+ aiGeneratorBridge.dispatch(data);
1032
+ return;
1033
+ }
1034
+ if (isAIGenerationUpdatePushMessage(data)) {
1035
+ dispatchAIGenerationUpdate(data.subscriptionId, data.update);
1036
+ return;
1037
+ }
1038
+ if (isDesignStateUpdatePushMessage(data)) {
1039
+ designStateApi.dispatch(data.updates);
1040
+ return;
1041
+ }
1042
+ if (isAppStateUpdatePushMessage(data)) {
1043
+ appStateApi.dispatch(data.updates);
1044
+ return;
1045
+ }
1046
+ if (isContextUpdatePushMessage(data)) {
1047
+ dispatchContextUpdate(data);
1048
+ return;
1049
+ }
1050
+ if (isFileBrowserFetchContentRequestMessage(data)) {
1051
+ dispatchFileBrowserFetchContentRequest(
1052
+ data.requestId,
1053
+ data.subscriptionId,
1054
+ data.params
1055
+ );
1056
+ }
1057
+ };
1058
+ var projectProxy = createApiProxy("project");
1059
+ var projectApi = {
1060
+ design: {
1061
+ state: {
1062
+ getState: projectProxy.design.state.getState,
1063
+ subscribe: designStateApi.subscribe
1064
+ },
1065
+ api: projectProxy.design.api,
1066
+ createBatch: createProjectBatch
1067
+ },
1068
+ app: {
1069
+ state: {
1070
+ getState: projectProxy.app.state.getState,
1071
+ subscribe: appStateApi.subscribe
1072
+ },
1073
+ api: projectProxy.app.api
1074
+ }
1075
+ };
1076
+ var bridgeHandlers = {
1077
+ agent: createApiProxy("agent"),
1078
+ aiGenerator: aiGeneratorBridge.api,
1079
+ brandKit: createApiProxy("brandKit"),
1080
+ mockup: createApiProxy("mockup"),
1081
+ ai: createAIApiProxy(),
1082
+ context: contextApi,
1083
+ data: createApiProxy("data"),
1084
+ design: createApiProxy("design"),
1085
+ designStore: designStateApi,
1086
+ appStore: appStateApi,
1087
+ export: createApiProxy("export"),
1088
+ font: createApiProxy("font"),
1089
+ project: projectApi,
1090
+ state: createApiProxy("state"),
1091
+ upload: createApiProxy("upload"),
1092
+ fileBrowser: { getFiles: createApiProxy("fileBrowser").getFiles },
1093
+ fileBrowserRegistration: createFileBrowserApiProxy(),
1094
+ openMicroEditor: createApiProxy("openMicroEditor"),
1095
+ openMainEditor: createApiProxy("openMainEditor"),
1096
+ auth: authClient,
1097
+ stateless: statelessApi,
1098
+ createBatch,
1099
+ createProjectBatch
1100
+ };
1101
+
1102
+ // src/api/utils.ts
1103
+ function unwrapResult(result) {
1104
+ if (result.isOk) {
1105
+ return result.result;
1106
+ }
1107
+ throw result.error;
1108
+ }
1109
+
1110
+ // package.json
1111
+ var version = "1.0.0";
1112
+
1113
+ // src/utils/syncHtmlDataThemeFromHostContext.ts
1114
+ async function syncHtmlDataThemeFromHostContext(kittl2) {
1115
+ if (typeof document === "undefined") {
1116
+ return;
1117
+ }
1118
+ const parent = window.parent;
1119
+ if (!parent || parent === window) {
1120
+ return;
1121
+ }
1122
+ const contextResponse = await kittl2.context.get();
1123
+ if (contextResponse.isOk) {
1124
+ document.documentElement.dataset.theme = contextResponse.result.colorScheme;
1125
+ }
1126
+ await kittl2.context.subscribe((ctx) => {
1127
+ document.documentElement.dataset.theme = ctx.colorScheme;
1128
+ });
1129
+ }
1130
+
1131
+ // src/createKittlSDK.ts
1132
+ function createKittlSDK(apis) {
1133
+ const kittl2 = {
1134
+ onLoadedCallback: null,
1135
+ loaded: false,
1136
+ onReady: (callback) => {
1137
+ if (kittl2.loaded) {
1138
+ callback();
1139
+ return;
1140
+ }
1141
+ kittl2.onLoadedCallback = callback;
1142
+ },
1143
+ ...apis
1144
+ };
1145
+ const initSdk = () => {
1146
+ kittl2.loaded = true;
1147
+ window.addEventListener(
1148
+ "message",
1149
+ (event) => {
1150
+ handleIncomingMessage(event);
1151
+ }
1152
+ );
1153
+ const { context } = apis;
1154
+ const themeSynced = context?.get && context.subscribe ? syncHtmlDataThemeFromHostContext({
1155
+ context
1156
+ }) : Promise.resolve();
1157
+ void themeSynced.catch(() => void 0).then(() => {
1158
+ kittl2.onLoadedCallback?.();
1159
+ sendLoaded();
1160
+ });
1161
+ };
1162
+ if (typeof document !== "undefined" && typeof window !== "undefined") {
1163
+ setSDKVersion(version);
1164
+ window.kittl = kittl2;
1165
+ if (document.readyState === "loading") {
1166
+ document.addEventListener("DOMContentLoaded", initSdk);
1167
+ } else {
1168
+ initSdk();
1169
+ }
1170
+ }
1171
+ return kittl2;
1172
+ }
1173
+
1174
+ // src/dashboardStandalonePage.ts
1175
+ var kittl = createKittlSDK({
1176
+ auth: bridgeHandlers.auth,
1177
+ context: bridgeHandlers.context,
1178
+ upload: bridgeHandlers.upload,
1179
+ brandKit: bridgeHandlers.brandKit,
1180
+ openMicroEditor: bridgeHandlers.openMicroEditor,
1181
+ openMainEditor: bridgeHandlers.openMainEditor,
1182
+ fileBrowser: bridgeHandlers.fileBrowser
1183
+ });
1184
+ })();