@kittl/sdk 0.0.8 → 1.0.0-alpha.1

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,1462 @@
1
+ // @ts-self-types="./sdk.d.ts"
2
+ /*! Kittl SDK - https://kittl.com - see license for terms */
3
+
4
+ var FROM_EXTENSION_COMMANDS = {
5
+ /** Capability-owned AI callback registration. */
6
+ AI_GENERATOR_SUBSCRIBE: "ai-generator-subscribe",
7
+ /** Capability-owned AI callback teardown. */
8
+ AI_GENERATOR_UNSUBSCRIBE: "ai-generator-unsubscribe",
9
+ /** SDK API call */
10
+ SDK_CALL: "sdk-call",
11
+ /** AI handler registration */
12
+ AI_REGISTER_HANDLER: "ai-register-handler",
13
+ /** AI handler unregistration */
14
+ AI_UNREGISTER_HANDLER: "ai-unregister-handler",
15
+ /** File browser tab registration */
16
+ FILE_BROWSER_REGISTER: "file-browser-register",
17
+ /** File browser fetch content response */
18
+ FILE_BROWSER_FETCH_CONTENT_RESPONSE: "file-browser-fetch-content-response",
19
+ /** Stateless message send */
20
+ STATELESS_SEND: "stateless-send",
21
+ /** Stateless subscription */
22
+ STATELESS_SUBSCRIBE: "stateless-subscribe",
23
+ /** Stateless unsubscription */
24
+ STATELESS_UNSUBSCRIBE: "stateless-unsubscribe",
25
+ /** App state subscription */
26
+ APP_STATE_SUBSCRIBE: "app-state-subscribe",
27
+ /** App state unsubscription */
28
+ APP_STATE_UNSUBSCRIBE: "app-state-unsubscribe",
29
+ /** Batch creation */
30
+ BATCH_CREATE: "batch-create",
31
+ /** Batch commit */
32
+ BATCH_COMMIT: "batch-commit",
33
+ /** OAuth flow start */
34
+ AUTH_START: "auth-start",
35
+ /** OAuth token exchange */
36
+ AUTH_EXCHANGE: "auth-exchange",
37
+ /** Get OAuth token */
38
+ AUTH_GET_TOKEN: "auth-get-token",
39
+ /** Refresh OAuth token */
40
+ AUTH_REFRESH: "auth-refresh",
41
+ /** OAuth logout */
42
+ AUTH_LOGOUT: "auth-logout",
43
+ /** Get user token for authentication */
44
+ AUTH_GET_USER_TOKEN: "auth-get-user-token",
45
+ /** Context subscription */
46
+ CONTEXT_SUBSCRIBE: "context-subscribe",
47
+ /** Context unsubscription */
48
+ CONTEXT_UNSUBSCRIBE: "context-unsubscribe",
49
+ /** Design state subscription */
50
+ DESIGN_STATE_SUBSCRIBE: "design-state-subscribe",
51
+ /** Design state unsubscription */
52
+ DESIGN_STATE_UNSUBSCRIBE: "design-state-unsubscribe",
53
+ /** Extension loaded notification */
54
+ LOADED: "loaded"
55
+ };
56
+ var TO_EXTENSION_COMMANDS = {
57
+ /** Callback payload for generator or pending-set subscriptions. */
58
+ AI_GENERATOR_UPDATE: "ai-generator-update",
59
+ /** SDK API response */
60
+ SDK_RESPONSE: "sdk-response",
61
+ /** File browser fetch content request */
62
+ FILE_BROWSER_FETCH_CONTENT_REQUEST: "file-browser-fetch-content-request",
63
+ /** Stateless message push */
64
+ STATELESS_MESSAGE: "stateless-message",
65
+ /** Context update push */
66
+ CONTEXT_UPDATE: "context-update",
67
+ /** AI generation update push */
68
+ AI_GENERATION_UPDATE: "ai-generation-update",
69
+ /** Design state update push */
70
+ DESIGN_STATE_UPDATE: "design-state-update",
71
+ /** App state update push */
72
+ APP_STATE_UPDATE: "app-state-update"
73
+ };
74
+
75
+ function isAIGeneratorUpdateMessage(data) {
76
+ return !!data && typeof data === "object" && "command" in data && data.command === "ai-generator-update" && "subscriptionId" in data && typeof data.subscriptionId === "string";
77
+ }
78
+
79
+ var isSDKResponseMessage = (data) => {
80
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.SDK_RESPONSE && "messageId" in data && typeof data.messageId === "string";
81
+ };
82
+ var isStatelessPushMessage = (data) => {
83
+ 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;
84
+ };
85
+ var isAIGenerationUpdatePushMessage = (data) => {
86
+ 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;
87
+ };
88
+ var isDesignStateUpdatePushMessage = (data) => {
89
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.DESIGN_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
90
+ };
91
+ var isAppStateUpdatePushMessage = (data) => {
92
+ return typeof data === "object" && data !== null && "command" in data && data.command === TO_EXTENSION_COMMANDS.APP_STATE_UPDATE && "updates" in data && Array.isArray(data.updates);
93
+ };
94
+ var isContextUpdatePushMessage = (data) => {
95
+ 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;
96
+ };
97
+ var isFileBrowserFetchContentRequestMessage = (data) => {
98
+ 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";
99
+ };
100
+
101
+ var generateMessageId = () => {
102
+ if (crypto?.randomUUID && typeof crypto.randomUUID === "function") {
103
+ return crypto.randomUUID();
104
+ }
105
+ return Math.random().toString(36).substring(7);
106
+ };
107
+
108
+ var buildMethodPath = (rootPrefix, pathSegments) => {
109
+ if (!rootPrefix) {
110
+ return pathSegments.join(".");
111
+ }
112
+ if (pathSegments.length === 0) {
113
+ return rootPrefix;
114
+ }
115
+ return `${rootPrefix}.${pathSegments.join(".")}`;
116
+ };
117
+ var createCallablePathProxy = (options) => {
118
+ const createNode = (pathSegments) => {
119
+ const target = () => {
120
+ };
121
+ const handler = {
122
+ get: (_target, prop) => {
123
+ if (typeof prop === "symbol") {
124
+ return Reflect.get(target, prop);
125
+ }
126
+ return createNode([...pathSegments, String(prop)]);
127
+ },
128
+ apply: (_target, _thisArg, args) => {
129
+ const context = {
130
+ pathSegments,
131
+ methodPath: buildMethodPath(options.rootPrefix ?? "", pathSegments),
132
+ args
133
+ };
134
+ options.beforeInvoke?.(context);
135
+ return options.onInvoke(context);
136
+ }
137
+ };
138
+ return new Proxy(target, handler);
139
+ };
140
+ return createNode([]);
141
+ };
142
+
143
+ var parentDomain;
144
+ var APPROVED_EXTENSION_COMMUNICATION_DOMAINS = [
145
+ "https://app.stagingdesigner.com",
146
+ "https://*.stagingdesigner.com",
147
+ "http://localhost:3000",
148
+ "https://app.kittl.com",
149
+ // website, for sandboxed standalone dashboard pages
150
+ "http://localhost:3003",
151
+ "https://www.kittl.com"
152
+ ];
153
+ var toOrigin = (value) => {
154
+ if (!value) {
155
+ return null;
156
+ }
157
+ try {
158
+ return new URL(value).origin;
159
+ } catch (_error) {
160
+ return null;
161
+ }
162
+ };
163
+ var escapeRegex = (value) => {
164
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165
+ };
166
+ var matchesApprovedDomain = (origin, approvedDomain) => {
167
+ const normalized = approvedDomain.trim();
168
+ if (!normalized) {
169
+ return false;
170
+ }
171
+ if (normalized.includes("*")) {
172
+ const wildcardRegex = new RegExp(
173
+ // because we use wildcards only in the middle of the string
174
+ // we know that our list must start with the regex and end with the regex
175
+ // so we add the ^ and $ to the regex too
176
+ `^${escapeRegex(normalized).replace(/\\\*/g, ".*")}$`
177
+ );
178
+ return wildcardRegex.test(origin);
179
+ }
180
+ return origin === normalized;
181
+ };
182
+ var getParentDomain = () => {
183
+ if (parentDomain) {
184
+ return parentDomain;
185
+ }
186
+ const referrer = window.document.referrer;
187
+ const ancestorOrigins = window.location.ancestorOrigins;
188
+ const ancestorOrigin = ancestorOrigins && ancestorOrigins.length > 0 ? ancestorOrigins[ancestorOrigins.length - 1] : void 0;
189
+ const currentDomainOrigin = toOrigin(referrer) ?? toOrigin(ancestorOrigin);
190
+ if (!currentDomainOrigin) {
191
+ throw new Error("No current domain origin found");
192
+ }
193
+ const approvedParentDomain = APPROVED_EXTENSION_COMMUNICATION_DOMAINS.find(
194
+ (domain) => {
195
+ return matchesApprovedDomain(currentDomainOrigin, domain);
196
+ }
197
+ );
198
+ if (!approvedParentDomain) {
199
+ throw new Error("No approved parent domain found");
200
+ }
201
+ parentDomain = currentDomainOrigin;
202
+ return parentDomain;
203
+ };
204
+
205
+ var pendingRequests = /* @__PURE__ */ new Map();
206
+ var sdkVersion;
207
+ function setSDKVersion(version2) {
208
+ sdkVersion = version2;
209
+ }
210
+ var postMessageToParent = (message) => {
211
+ window.parent.postMessage(
212
+ sdkVersion === void 0 ? message : { ...message, sdkVersion },
213
+ getParentDomain()
214
+ );
215
+ };
216
+ var sendMessage = (message) => {
217
+ postMessageToParent(message);
218
+ return new Promise((resolve, reject) => {
219
+ pendingRequests.set(message.messageId, {
220
+ resolve: (value) => {
221
+ resolve(value);
222
+ },
223
+ reject
224
+ });
225
+ });
226
+ };
227
+ var sendLoaded = () => {
228
+ const parent = window.parent;
229
+ if (!parent || parent === window) {
230
+ return;
231
+ }
232
+ const message = { command: FROM_EXTENSION_COMMANDS.LOADED };
233
+ postMessageToParent(message);
234
+ };
235
+
236
+ var createSDKCallMessage = {
237
+ aiGenerator: (dots, args, messageId) => ({
238
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
239
+ dots,
240
+ args,
241
+ messageId,
242
+ apiType: "aiGenerator"
243
+ }),
244
+ mockup: (dots, args, messageId) => ({
245
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
246
+ dots,
247
+ args,
248
+ messageId,
249
+ apiType: "mockup"
250
+ }),
251
+ fileBrowser: (dots, args, messageId) => ({
252
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
253
+ dots,
254
+ args,
255
+ messageId,
256
+ apiType: "fileBrowser"
257
+ }),
258
+ ai: (dots, args, messageId) => ({
259
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
260
+ dots,
261
+ args,
262
+ messageId,
263
+ apiType: "ai"
264
+ }),
265
+ context: (dots, args, messageId) => ({
266
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
267
+ dots,
268
+ args,
269
+ messageId,
270
+ apiType: "context"
271
+ }),
272
+ design: (dots, args, messageId) => ({
273
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
274
+ dots,
275
+ args,
276
+ messageId,
277
+ apiType: "design"
278
+ }),
279
+ export: (dots, args, messageId) => ({
280
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
281
+ dots,
282
+ args,
283
+ messageId,
284
+ apiType: "export"
285
+ }),
286
+ font: (dots, args, messageId) => ({
287
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
288
+ dots,
289
+ args,
290
+ messageId,
291
+ apiType: "font"
292
+ }),
293
+ project: (dots, args, messageId) => ({
294
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
295
+ dots,
296
+ args,
297
+ messageId,
298
+ apiType: "project"
299
+ }),
300
+ state: (dots, args, messageId) => ({
301
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
302
+ dots,
303
+ args,
304
+ messageId,
305
+ apiType: "state"
306
+ }),
307
+ upload: (dots, args, messageId) => ({
308
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
309
+ dots,
310
+ args,
311
+ messageId,
312
+ apiType: "upload"
313
+ }),
314
+ data: (dots, args, messageId) => ({
315
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
316
+ dots,
317
+ args,
318
+ messageId,
319
+ apiType: "data"
320
+ }),
321
+ brandKit: (dots, args, messageId) => ({
322
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
323
+ dots,
324
+ args,
325
+ messageId,
326
+ apiType: "brandKit"
327
+ }),
328
+ openMicroEditor: (dots, args, messageId) => ({
329
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
330
+ dots,
331
+ args,
332
+ messageId,
333
+ apiType: "openMicroEditor"
334
+ }),
335
+ openMainEditor: (dots, args, messageId) => ({
336
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
337
+ dots,
338
+ args,
339
+ messageId,
340
+ apiType: "openMainEditor"
341
+ })
342
+ };
343
+ function createApiProxy(apiType) {
344
+ return createCallablePathProxy({
345
+ onInvoke: ({ pathSegments, args }) => {
346
+ return sendMessage(
347
+ createSDKCallMessage[apiType](
348
+ [...pathSegments],
349
+ [...args],
350
+ generateMessageId()
351
+ )
352
+ );
353
+ }
354
+ });
355
+ }
356
+
357
+ function createAIGeneratorBridgeApi() {
358
+ const callbacks = /* @__PURE__ */ new Map();
359
+ const proxy = createApiProxy("aiGenerator");
360
+ async function subscribe(request, callback) {
361
+ const subscriptionId = generateMessageId();
362
+ callbacks.set(subscriptionId, callback);
363
+ let response;
364
+ try {
365
+ response = await sendMessage({
366
+ command: "ai-generator-subscribe",
367
+ ...request,
368
+ subscriptionId,
369
+ messageId: generateMessageId()
370
+ });
371
+ } catch (error) {
372
+ callbacks.delete(subscriptionId);
373
+ throw error;
374
+ }
375
+ if (!response.isOk) {
376
+ callbacks.delete(subscriptionId);
377
+ throw new Error(response.error.message);
378
+ }
379
+ return () => {
380
+ callbacks.delete(subscriptionId);
381
+ postMessageToParent({
382
+ command: "ai-generator-unsubscribe",
383
+ subscriptionId
384
+ });
385
+ };
386
+ }
387
+ const methods = {
388
+ registerGenerator: (id, callback) => subscribe({ method: "registerGenerator", args: [id] }, (update) => {
389
+ if (update) callback(update);
390
+ }),
391
+ subscribeToGenerationUpdates: (ids, callback) => subscribe(
392
+ { method: "subscribeToGenerationUpdates", args: [ids] },
393
+ (update) => {
394
+ if (update) callback(update);
395
+ }
396
+ ),
397
+ subscribeToPendingGenerations: (callback) => subscribe(
398
+ { method: "subscribeToPendingGenerations", args: [] },
399
+ () => callback()
400
+ ),
401
+ /** Callers may reuse richer internal submission objects; never send their local abort callbacks. */
402
+ cancelGenerations: (submission) => proxy.cancelGenerations({
403
+ generationIds: submission.generationIds,
404
+ until: submission.until
405
+ })
406
+ };
407
+ return {
408
+ api: new Proxy(proxy, {
409
+ get: (target, property, receiver) => property in methods ? methods[property] : Reflect.get(target, property, receiver)
410
+ }),
411
+ dispatch: (message) => callbacks.get(message.subscriptionId)?.(message.update)
412
+ };
413
+ }
414
+
415
+ var generationHandlers = /* @__PURE__ */ new Map();
416
+ var generationSubscriptions = /* @__PURE__ */ new Map();
417
+ var dispatchAIGenerationUpdate = (subscriptionId, update) => {
418
+ const handler = generationHandlers.get(subscriptionId);
419
+ if (!handler) {
420
+ return;
421
+ }
422
+ void handler(update);
423
+ };
424
+ function createAIApiProxy() {
425
+ const unregisterGenerationHandler = (generatorId) => {
426
+ const subscriptionId = generationSubscriptions.get(generatorId);
427
+ if (!subscriptionId) {
428
+ return;
429
+ }
430
+ generationHandlers.delete(subscriptionId);
431
+ generationSubscriptions.delete(generatorId);
432
+ const unregisterMessage = {
433
+ command: FROM_EXTENSION_COMMANDS.AI_UNREGISTER_HANDLER,
434
+ generatorId,
435
+ subscriptionId
436
+ };
437
+ postMessageToParent(unregisterMessage);
438
+ };
439
+ return {
440
+ spendCredits: async (options) => {
441
+ const { onAccept, onDecline, ...serializable } = options;
442
+ const message = {
443
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
444
+ dots: ["spendCredits"],
445
+ args: [serializable],
446
+ messageId: generateMessageId(),
447
+ apiType: "ai"
448
+ };
449
+ const response = await sendMessage(message);
450
+ if (response.isOk && response.result.success) {
451
+ onAccept?.();
452
+ } else {
453
+ onDecline?.();
454
+ }
455
+ return response;
456
+ },
457
+ startGeneration: (generatorId, inputSettings, output) => {
458
+ const message = {
459
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
460
+ dots: ["startGeneration"],
461
+ args: [generatorId, inputSettings, output],
462
+ messageId: generateMessageId(),
463
+ apiType: "ai"
464
+ };
465
+ return sendMessage(message);
466
+ },
467
+ registerHandler: async (generatorId, onStatusUpdate) => {
468
+ if (generationSubscriptions.has(generatorId)) {
469
+ return {
470
+ isOk: false,
471
+ error: {
472
+ message: `AI handler for generator "${generatorId}" is already registered`,
473
+ name: "SdkInternalError"
474
+ }
475
+ };
476
+ }
477
+ const subscriptionId = generateMessageId();
478
+ generationHandlers.set(subscriptionId, onStatusUpdate);
479
+ generationSubscriptions.set(generatorId, subscriptionId);
480
+ const registerMessage = {
481
+ command: FROM_EXTENSION_COMMANDS.AI_REGISTER_HANDLER,
482
+ messageId: generateMessageId(),
483
+ generatorId,
484
+ subscriptionId
485
+ };
486
+ try {
487
+ const response = await sendMessage(registerMessage);
488
+ if (!response.isOk) {
489
+ generationHandlers.delete(subscriptionId);
490
+ generationSubscriptions.delete(generatorId);
491
+ return response;
492
+ }
493
+ return {
494
+ isOk: true,
495
+ result: () => unregisterGenerationHandler(generatorId)
496
+ };
497
+ } catch {
498
+ generationHandlers.delete(subscriptionId);
499
+ generationSubscriptions.delete(generatorId);
500
+ return {
501
+ isOk: false,
502
+ error: {
503
+ message: "Failed to register AI handler",
504
+ name: "SdkInternalError"
505
+ }
506
+ };
507
+ }
508
+ },
509
+ unregisterHandler: async (generatorId) => {
510
+ unregisterGenerationHandler(generatorId);
511
+ return { isOk: true, result: void 0 };
512
+ }
513
+ };
514
+ }
515
+
516
+ var fetchContentHandlers = /* @__PURE__ */ new Map();
517
+ var tabIdToSubscriptionId = /* @__PURE__ */ new Map();
518
+ var removeSubscriptionHandlers = (subscriptionId) => {
519
+ fetchContentHandlers.delete(subscriptionId);
520
+ };
521
+ var dispatchFileBrowserFetchContentRequest = (requestId, subscriptionId, params) => {
522
+ const handler = fetchContentHandlers.get(subscriptionId);
523
+ if (!handler) {
524
+ const responseMessage = {
525
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
526
+ requestId,
527
+ content: []
528
+ };
529
+ postMessageToParent(responseMessage);
530
+ return;
531
+ }
532
+ void handler(params).then((result) => {
533
+ const responseMessage = {
534
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
535
+ requestId,
536
+ content: result.content,
537
+ next: result.next
538
+ };
539
+ postMessageToParent(responseMessage);
540
+ }).catch((error) => {
541
+ const responseMessage = {
542
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_FETCH_CONTENT_RESPONSE,
543
+ requestId,
544
+ content: [],
545
+ error: error instanceof Error ? error.message : "Unknown error"
546
+ };
547
+ postMessageToParent(responseMessage);
548
+ });
549
+ };
550
+ function createFileBrowserApiProxy() {
551
+ return {
552
+ registerUploadBrowser: async (tab) => {
553
+ const subscriptionId = generateMessageId();
554
+ const existingSubscriptionId = tabIdToSubscriptionId.get(tab.id);
555
+ if (existingSubscriptionId) {
556
+ removeSubscriptionHandlers(existingSubscriptionId);
557
+ }
558
+ fetchContentHandlers.set(subscriptionId, tab.fetchContent);
559
+ tabIdToSubscriptionId.set(tab.id, subscriptionId);
560
+ const registerMessage = {
561
+ command: FROM_EXTENSION_COMMANDS.FILE_BROWSER_REGISTER,
562
+ messageId: generateMessageId(),
563
+ tabId: tab.id,
564
+ label: tab.label,
565
+ order: tab.order,
566
+ emptyState: tab.emptyState,
567
+ subscriptionId
568
+ };
569
+ try {
570
+ const response = await sendMessage(registerMessage);
571
+ if (!response.isOk) {
572
+ removeSubscriptionHandlers(subscriptionId);
573
+ tabIdToSubscriptionId.delete(tab.id);
574
+ return {
575
+ isOk: false,
576
+ error: response.error
577
+ };
578
+ }
579
+ return {
580
+ isOk: true,
581
+ result: void 0
582
+ };
583
+ } catch {
584
+ removeSubscriptionHandlers(subscriptionId);
585
+ tabIdToSubscriptionId.delete(tab.id);
586
+ return {
587
+ isOk: false,
588
+ error: {
589
+ message: "Failed to register upload browser",
590
+ name: "SdkInternalError"
591
+ }
592
+ };
593
+ }
594
+ }
595
+ };
596
+ }
597
+
598
+ var sendUnsubscribe = (selectorIds) => {
599
+ const message = {
600
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_UNSUBSCRIBE,
601
+ selectorIds
602
+ };
603
+ postMessageToParent(message);
604
+ };
605
+ var createAppStateBridgeApi = () => {
606
+ const localSubscriptions = /* @__PURE__ */ new Map();
607
+ async function subscribe(paths, callback) {
608
+ if (paths.length === 0) {
609
+ return () => {
610
+ };
611
+ }
612
+ const values = new Array(paths.length).fill(void 0);
613
+ const selectorIds = [];
614
+ const pathArrays = [];
615
+ for (const dotPath of paths) {
616
+ const segments = dotPath.split(".");
617
+ if (segments.some((s) => s === "")) {
618
+ throw new Error(
619
+ `Invalid app state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
620
+ );
621
+ }
622
+ selectorIds.push(generateMessageId());
623
+ pathArrays.push(segments);
624
+ }
625
+ const messageId = generateMessageId();
626
+ const subscribeMessage = {
627
+ command: FROM_EXTENSION_COMMANDS.APP_STATE_SUBSCRIBE,
628
+ messageId,
629
+ selectorIds,
630
+ paths: pathArrays
631
+ };
632
+ const response = await sendMessage(subscribeMessage);
633
+ if (!response.isOk) {
634
+ throw new Error(`app-state-subscribe failed: ${response.error.message}`);
635
+ }
636
+ for (let i = 0; i < selectorIds.length; i++) {
637
+ localSubscriptions.set(selectorIds[i], {
638
+ callback: (value) => {
639
+ values[i] = value;
640
+ callback(...values);
641
+ }
642
+ });
643
+ }
644
+ return () => {
645
+ for (const selectorId of selectorIds) {
646
+ localSubscriptions.delete(selectorId);
647
+ }
648
+ sendUnsubscribe(selectorIds);
649
+ };
650
+ }
651
+ const dispatch = (updates) => {
652
+ for (const { selectorId, value } of updates) {
653
+ const entry = localSubscriptions.get(selectorId);
654
+ if (entry) {
655
+ entry.callback(value);
656
+ }
657
+ }
658
+ };
659
+ return { subscribe, dispatch };
660
+ };
661
+
662
+ var SandboxedAuthClient = class {
663
+ /**
664
+ * Binds the public start method because the exported SDK API may pass it
665
+ * around without its client object as the receiver.
666
+ */
667
+ constructor() {
668
+ this.startAuth = this.startAuth.bind(this);
669
+ }
670
+ /**
671
+ * Starts provider authentication and optionally adds an RFC 7636 PKCE
672
+ * challenge to the request. Successful responses include the verifier that
673
+ * the caller must pass to {@link exchangeCode}.
674
+ */
675
+ async startAuth(request) {
676
+ const state = generateMessageId();
677
+ let pkceCode = "";
678
+ let code_verifier = "";
679
+ if (request.generatePKCE) {
680
+ code_verifier = this.generatePKCECode();
681
+ pkceCode = await this.hashPKCECode(code_verifier);
682
+ }
683
+ const message = {
684
+ command: FROM_EXTENSION_COMMANDS.AUTH_START,
685
+ messageId: generateMessageId(),
686
+ state,
687
+ provider: request.provider,
688
+ params: {
689
+ ...request.params,
690
+ ...pkceCode ? {
691
+ code_challenge: pkceCode,
692
+ code_challenge_method: "S256"
693
+ } : {}
694
+ }
695
+ };
696
+ const response = await sendMessage(message);
697
+ if (!response.isOk) {
698
+ return response;
699
+ }
700
+ return {
701
+ ...response,
702
+ result: {
703
+ ...response.result,
704
+ code_verifier
705
+ }
706
+ };
707
+ }
708
+ /** Exchanges the provider authorization code for an auth token. */
709
+ exchangeCode(request) {
710
+ const message = {
711
+ command: FROM_EXTENSION_COMMANDS.AUTH_EXCHANGE,
712
+ messageId: generateMessageId(),
713
+ code: request.code,
714
+ code_verifier: request.code_verifier,
715
+ provider: request.provider,
716
+ params: request.params,
717
+ headers: request.headers
718
+ };
719
+ return sendMessage(message);
720
+ }
721
+ /** Requests the current auth token for a provider. */
722
+ getAuthToken(request) {
723
+ const message = {
724
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_TOKEN,
725
+ messageId: generateMessageId(),
726
+ provider: request.provider
727
+ };
728
+ return sendMessage(message);
729
+ }
730
+ /** Refreshes the auth token for a provider. */
731
+ refreshToken(request) {
732
+ const message = {
733
+ command: FROM_EXTENSION_COMMANDS.AUTH_REFRESH,
734
+ messageId: generateMessageId(),
735
+ provider: request.provider
736
+ };
737
+ return sendMessage(message);
738
+ }
739
+ /** Logs the current user out of a provider. */
740
+ logout(request) {
741
+ const message = {
742
+ command: FROM_EXTENSION_COMMANDS.AUTH_LOGOUT,
743
+ messageId: generateMessageId(),
744
+ provider: request.provider
745
+ };
746
+ return sendMessage(message);
747
+ }
748
+ /** Requests the authenticated user's user token from the parent window. */
749
+ getUserToken() {
750
+ const message = {
751
+ command: FROM_EXTENSION_COMMANDS.AUTH_GET_USER_TOKEN,
752
+ messageId: generateMessageId()
753
+ };
754
+ return sendMessage(message);
755
+ }
756
+ /** Hashes a PKCE verifier and encodes the SHA-256 digest as Base64URL. */
757
+ async hashPKCECode(input) {
758
+ const subtle = window.crypto?.subtle;
759
+ if (!subtle) {
760
+ throw new Error("Web Crypto SubtleCrypto API not available");
761
+ }
762
+ const textAsBuffer = new TextEncoder().encode(input);
763
+ const hashBuffer = await subtle.digest("SHA-256", textAsBuffer);
764
+ const hashArray = new Uint8Array(hashBuffer);
765
+ const binaryString = String.fromCharCode(...hashArray);
766
+ const base64 = btoa(binaryString);
767
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
768
+ }
769
+ /** Generates a high-entropy RFC 7636-compatible PKCE verifier. */
770
+ generatePKCECode() {
771
+ if (!window.crypto) {
772
+ throw new Error("Crypto API not available");
773
+ }
774
+ const array = new Uint32Array(56);
775
+ window.crypto.getRandomValues(array);
776
+ return Array.from(array, (dec) => `0${dec.toString(16)}`.slice(-2)).join(
777
+ ""
778
+ );
779
+ }
780
+ };
781
+
782
+ var createBatchFor = async (apiType) => {
783
+ const response = await sendMessage({
784
+ command: FROM_EXTENSION_COMMANDS.BATCH_CREATE,
785
+ messageId: generateMessageId()
786
+ });
787
+ if (!response.isOk) {
788
+ throw response.error;
789
+ }
790
+ const { batchKey } = response.result;
791
+ const sendDesignCall = (dots, args) => {
792
+ const message = {
793
+ command: FROM_EXTENSION_COMMANDS.SDK_CALL,
794
+ dots: apiType === "project" ? ["design", "api", ...dots] : dots,
795
+ args,
796
+ messageId: generateMessageId(),
797
+ apiType,
798
+ batchKey
799
+ };
800
+ return sendMessage(message);
801
+ };
802
+ const commit = async () => {
803
+ const res = await sendMessage({
804
+ command: FROM_EXTENSION_COMMANDS.BATCH_COMMIT,
805
+ messageId: generateMessageId(),
806
+ batchKey
807
+ });
808
+ if (!res.isOk) {
809
+ throw res.error;
810
+ }
811
+ };
812
+ const buildNode = (pathSegments) => {
813
+ const target = () => {
814
+ };
815
+ return new Proxy(target, {
816
+ get: (_t, prop) => {
817
+ if (typeof prop === "symbol" || prop === "then") return void 0;
818
+ if (prop === "commit") return commit;
819
+ return buildNode([...pathSegments, prop]);
820
+ },
821
+ apply: (_t, _this, args) => {
822
+ return sendDesignCall(pathSegments, args);
823
+ }
824
+ });
825
+ };
826
+ return buildNode([]);
827
+ };
828
+ var createBatch = () => createBatchFor("design");
829
+ var createProjectBatch = () => createBatchFor("project");
830
+
831
+ var createContextBridgeApi = () => {
832
+ const contextProxy = createApiProxy("context");
833
+ const subscriptionCallbacks = /* @__PURE__ */ new Map();
834
+ const dispatch = (message) => {
835
+ const cb = subscriptionCallbacks.get(message.subscriptionId);
836
+ cb?.(message.context);
837
+ };
838
+ const subscribeImpl = async (callback) => {
839
+ const subscriptionId = generateMessageId();
840
+ const messageId = generateMessageId();
841
+ subscriptionCallbacks.set(subscriptionId, callback);
842
+ let response;
843
+ try {
844
+ response = await sendMessage({
845
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_SUBSCRIBE,
846
+ messageId,
847
+ subscriptionId
848
+ });
849
+ } catch (error) {
850
+ subscriptionCallbacks.delete(subscriptionId);
851
+ throw error;
852
+ }
853
+ if (!response.isOk) {
854
+ subscriptionCallbacks.delete(subscriptionId);
855
+ throw new Error(`context-subscribe failed: ${response.error.message}`);
856
+ }
857
+ return () => {
858
+ subscriptionCallbacks.delete(subscriptionId);
859
+ const message = {
860
+ command: FROM_EXTENSION_COMMANDS.CONTEXT_UNSUBSCRIBE,
861
+ subscriptionId
862
+ };
863
+ postMessageToParent(message);
864
+ };
865
+ };
866
+ const api = new Proxy(contextProxy, {
867
+ get(target, prop, receiver) {
868
+ if (prop === "subscribe") {
869
+ return subscribeImpl;
870
+ }
871
+ return Reflect.get(target, prop, receiver);
872
+ }
873
+ });
874
+ return { api, dispatch };
875
+ };
876
+
877
+ var sendUnsubscribe2 = (selectorIds) => {
878
+ const message = {
879
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_UNSUBSCRIBE,
880
+ selectorIds
881
+ };
882
+ postMessageToParent(message);
883
+ };
884
+ var createDesignStateBridgeApi = () => {
885
+ const localSubscriptions = /* @__PURE__ */ new Map();
886
+ async function subscribe(paths, callback) {
887
+ if (paths.length === 0) {
888
+ return () => {
889
+ };
890
+ }
891
+ const values = new Array(paths.length).fill(void 0);
892
+ const selectorIds = [];
893
+ const pathArrays = [];
894
+ for (const dotPath of paths) {
895
+ const segments = dotPath.split(".");
896
+ if (segments.some((s) => s === "")) {
897
+ throw new Error(
898
+ `Invalid design state path: '${dotPath}'. Path must be a non-empty dot-separated string.`
899
+ );
900
+ }
901
+ selectorIds.push(generateMessageId());
902
+ pathArrays.push(segments);
903
+ }
904
+ const messageId = generateMessageId();
905
+ const subscribeMessage = {
906
+ command: FROM_EXTENSION_COMMANDS.DESIGN_STATE_SUBSCRIBE,
907
+ messageId,
908
+ selectorIds,
909
+ paths: pathArrays
910
+ };
911
+ const response = await sendMessage(subscribeMessage);
912
+ if (!response.isOk) {
913
+ throw new Error(
914
+ `design-state-subscribe failed: ${response.error.message}`
915
+ );
916
+ }
917
+ for (let i = 0; i < selectorIds.length; i++) {
918
+ localSubscriptions.set(selectorIds[i], {
919
+ callback: (value) => {
920
+ values[i] = value;
921
+ callback(...values);
922
+ }
923
+ });
924
+ }
925
+ return () => {
926
+ for (const selectorId of selectorIds) {
927
+ localSubscriptions.delete(selectorId);
928
+ }
929
+ sendUnsubscribe2(selectorIds);
930
+ };
931
+ }
932
+ const dispatch = (updates) => {
933
+ for (const { selectorId, value } of updates) {
934
+ const entry = localSubscriptions.get(selectorId);
935
+ if (entry) {
936
+ entry.callback(value);
937
+ }
938
+ }
939
+ };
940
+ return { subscribe, dispatch };
941
+ };
942
+
943
+ var createStatelessBridgeApi = () => {
944
+ const subscribers = /* @__PURE__ */ new Map();
945
+ return {
946
+ send: (message) => {
947
+ const messageId = generateMessageId();
948
+ const bridgeMessage = {
949
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SEND,
950
+ messageId,
951
+ type: message.type,
952
+ payload: message.payload
953
+ };
954
+ return sendMessage(bridgeMessage);
955
+ },
956
+ subscribe: async (key, handler) => {
957
+ let handlers = subscribers.get(key);
958
+ if (!handlers) {
959
+ handlers = /* @__PURE__ */ new Set();
960
+ subscribers.set(key, handlers);
961
+ }
962
+ handlers.add(handler);
963
+ const messageId = generateMessageId();
964
+ const subscribeMessage = {
965
+ command: FROM_EXTENSION_COMMANDS.STATELESS_SUBSCRIBE,
966
+ messageId,
967
+ key
968
+ };
969
+ return sendMessage(subscribeMessage);
970
+ },
971
+ unsubscribe: async (key) => {
972
+ subscribers.delete(key);
973
+ const messageId = generateMessageId();
974
+ const unsubscribeMessage = {
975
+ command: FROM_EXTENSION_COMMANDS.STATELESS_UNSUBSCRIBE,
976
+ messageId,
977
+ key
978
+ };
979
+ return sendMessage(unsubscribeMessage);
980
+ },
981
+ dispatch: (type, payload) => {
982
+ const handlers = subscribers.get(type);
983
+ if (handlers) {
984
+ for (const handler of handlers) {
985
+ handler(payload);
986
+ }
987
+ }
988
+ }
989
+ };
990
+ };
991
+
992
+ var statelessApi = createStatelessBridgeApi();
993
+ var designStateApi = createDesignStateBridgeApi();
994
+ var appStateApi = createAppStateBridgeApi();
995
+ var { api: contextApi, dispatch: dispatchContextUpdate } = createContextBridgeApi();
996
+ var authClient = new SandboxedAuthClient();
997
+ var aiGeneratorBridge = createAIGeneratorBridgeApi();
998
+ var handleIncomingMessage = (event) => {
999
+ const parent = window.parent;
1000
+ if (!parent || parent === window) {
1001
+ return;
1002
+ }
1003
+ if (event.source !== parent) {
1004
+ return;
1005
+ }
1006
+ const { data } = event;
1007
+ if (isSDKResponseMessage(data)) {
1008
+ const resolver = pendingRequests.get(data.messageId);
1009
+ if (resolver) {
1010
+ pendingRequests.delete(data.messageId);
1011
+ const response = data.response;
1012
+ resolver.resolve(response);
1013
+ }
1014
+ return;
1015
+ }
1016
+ if (isStatelessPushMessage(data)) {
1017
+ statelessApi.dispatch(data.type, data.payload);
1018
+ return;
1019
+ }
1020
+ if (isAIGeneratorUpdateMessage(data)) {
1021
+ aiGeneratorBridge.dispatch(data);
1022
+ return;
1023
+ }
1024
+ if (isAIGenerationUpdatePushMessage(data)) {
1025
+ dispatchAIGenerationUpdate(data.subscriptionId, data.update);
1026
+ return;
1027
+ }
1028
+ if (isDesignStateUpdatePushMessage(data)) {
1029
+ designStateApi.dispatch(data.updates);
1030
+ return;
1031
+ }
1032
+ if (isAppStateUpdatePushMessage(data)) {
1033
+ appStateApi.dispatch(data.updates);
1034
+ return;
1035
+ }
1036
+ if (isContextUpdatePushMessage(data)) {
1037
+ dispatchContextUpdate(data);
1038
+ return;
1039
+ }
1040
+ if (isFileBrowserFetchContentRequestMessage(data)) {
1041
+ dispatchFileBrowserFetchContentRequest(
1042
+ data.requestId,
1043
+ data.subscriptionId,
1044
+ data.params
1045
+ );
1046
+ }
1047
+ };
1048
+ var projectProxy = createApiProxy("project");
1049
+ var projectApi = {
1050
+ design: {
1051
+ state: {
1052
+ getState: projectProxy.design.state.getState,
1053
+ subscribe: designStateApi.subscribe
1054
+ },
1055
+ api: projectProxy.design.api,
1056
+ createBatch: createProjectBatch
1057
+ },
1058
+ app: {
1059
+ state: {
1060
+ getState: projectProxy.app.state.getState,
1061
+ subscribe: appStateApi.subscribe
1062
+ },
1063
+ api: projectProxy.app.api
1064
+ }
1065
+ };
1066
+ var bridgeHandlers = {
1067
+ aiGenerator: aiGeneratorBridge.api,
1068
+ brandKit: createApiProxy("brandKit"),
1069
+ mockup: createApiProxy("mockup"),
1070
+ ai: createAIApiProxy(),
1071
+ context: contextApi,
1072
+ data: createApiProxy("data"),
1073
+ design: createApiProxy("design"),
1074
+ designStore: designStateApi,
1075
+ appStore: appStateApi,
1076
+ export: createApiProxy("export"),
1077
+ font: createApiProxy("font"),
1078
+ project: projectApi,
1079
+ state: createApiProxy("state"),
1080
+ upload: createApiProxy("upload"),
1081
+ fileBrowser: { getFiles: createApiProxy("fileBrowser").getFiles },
1082
+ fileBrowserRegistration: createFileBrowserApiProxy(),
1083
+ openMicroEditor: createApiProxy("openMicroEditor"),
1084
+ openMainEditor: createApiProxy("openMainEditor"),
1085
+ auth: authClient,
1086
+ stateless: statelessApi,
1087
+ createBatch,
1088
+ createProjectBatch
1089
+ };
1090
+
1091
+ // src/api/utils.ts
1092
+ function unwrapResult(result) {
1093
+ if (result.isOk) {
1094
+ return result.result;
1095
+ }
1096
+ throw result.error;
1097
+ }
1098
+
1099
+ // src/api/dragAndDrop/DragAndDropApi.ts
1100
+ var HIDDEN_DRAG_PREVIEW_OFFSET_PX = "-9999px";
1101
+ var DragAndDropApi = class {
1102
+ /**
1103
+ * Creates the drag-and-drop API from bridged SDK dependencies.
1104
+ */
1105
+ constructor(dependencies) {
1106
+ this.state = dependencies.state;
1107
+ this.context = dependencies.context;
1108
+ this.design = dependencies.design;
1109
+ this.upload = dependencies.upload;
1110
+ }
1111
+ /**
1112
+ * Handles the extension-side `dragstart` event and attaches a one-time
1113
+ * `dragend` listener that completes the Kittl drop flow.
1114
+ */
1115
+ startDragImageEvent(input) {
1116
+ const metrics = this.captureDragMetrics(input);
1117
+ this.applyNativeDragSetup(input.event.dataTransfer, input.img, metrics);
1118
+ const handleDragEnd = (event) => {
1119
+ void this.handleManagedDragEnd(metrics, event);
1120
+ };
1121
+ input.img.addEventListener("dragend", handleDragEnd, { once: true });
1122
+ }
1123
+ /**
1124
+ * Inserts the dropped image at the computed drop position. When
1125
+ * `input.persistImage === true`, fetches `src`, uploads it, and replaces
1126
+ * the inserted object with the uploaded asset.
1127
+ */
1128
+ async dropImage(input) {
1129
+ let objectId = null;
1130
+ try {
1131
+ const offset = unwrapResult(await this.context.get()).iframeOffset;
1132
+ const params = this.buildDropImageParams(input, offset);
1133
+ objectId = await this.addDroppedImage(params);
1134
+ if (input.persistImage) {
1135
+ await this.persistDroppedImage({
1136
+ objectId,
1137
+ src: input.src
1138
+ });
1139
+ }
1140
+ } catch {
1141
+ }
1142
+ return objectId;
1143
+ }
1144
+ /**
1145
+ * Adds the dropped image to the design and returns the inserted object id.
1146
+ */
1147
+ async addDroppedImage(params) {
1148
+ const result = await this.design.image.addImage(params);
1149
+ const insertedImage = unwrapResult(result);
1150
+ if (!insertedImage?.id) {
1151
+ throw new Error("Failed to add dropped image");
1152
+ }
1153
+ return insertedImage.id;
1154
+ }
1155
+ /**
1156
+ * Fetches `src`, uploads the bytes, and replaces the inserted object with
1157
+ * the uploaded Kittl asset when persistence succeeds.
1158
+ */
1159
+ async persistDroppedImage(input) {
1160
+ const response = await fetch(input.src);
1161
+ if (!response.ok) {
1162
+ throw new Error(`Failed to fetch dropped image: ${response.status}`);
1163
+ }
1164
+ const blob = await response.blob();
1165
+ const uploadResult = await this.upload.image.upload({ blob });
1166
+ const uploadedFiles = unwrapResult(uploadResult);
1167
+ if (uploadedFiles.length === 0) {
1168
+ throw new Error("Failed to upload dropped image");
1169
+ }
1170
+ await this.replaceWithUploadedImage({
1171
+ objectId: input.objectId,
1172
+ objectName: uploadedFiles[0].objectName
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Replaces the inserted image with the uploaded asset if the object still
1177
+ * exists.
1178
+ */
1179
+ async replaceWithUploadedImage(input) {
1180
+ const objectResult = await this.design.object.getObject({
1181
+ id: input.objectId
1182
+ });
1183
+ if (!objectResult.isOk) {
1184
+ return;
1185
+ }
1186
+ await this.design.image.updateImage({
1187
+ id: input.objectId,
1188
+ objectName: input.objectName
1189
+ });
1190
+ }
1191
+ /**
1192
+ * Converts iframe drag coordinates into `addImage(...)` params, applying host
1193
+ * offsets, grab offsets, and optional rendered size.
1194
+ */
1195
+ buildDropImageParams(input, offset) {
1196
+ const grabOffsetX = input.grabOffsetX ?? 0;
1197
+ const grabOffsetY = input.grabOffsetY ?? 0;
1198
+ const baseX = input.x + offset.left;
1199
+ const baseY = input.y + offset.top;
1200
+ const dropX = Math.floor(baseX - grabOffsetX);
1201
+ const dropY = Math.floor(baseY - grabOffsetY);
1202
+ const baseParams = {
1203
+ src: input.src.trim(),
1204
+ position: {
1205
+ relative: {
1206
+ to: "screen",
1207
+ coordinates: {
1208
+ x: dropX,
1209
+ y: dropY
1210
+ }
1211
+ }
1212
+ }
1213
+ };
1214
+ const { imgWidth, imgHeight } = input;
1215
+ if (typeof imgWidth !== "number" || typeof imgHeight !== "number") {
1216
+ return baseParams;
1217
+ }
1218
+ return {
1219
+ ...baseParams,
1220
+ size: {
1221
+ width: imgWidth,
1222
+ height: imgHeight,
1223
+ applyViewportScale: true
1224
+ }
1225
+ };
1226
+ }
1227
+ /**
1228
+ * Captures the rendered image size and pointer grab point at drag start so
1229
+ * the native drag preview and drop placement stay aligned.
1230
+ */
1231
+ captureDragMetrics(input) {
1232
+ const rect = input.img.getBoundingClientRect();
1233
+ const displayWidth = Math.floor(rect.width);
1234
+ const displayHeight = Math.floor(rect.height);
1235
+ const grabOffsetX = this.getGrabOffset(
1236
+ input.event.clientX - rect.left,
1237
+ displayWidth
1238
+ );
1239
+ const grabOffsetY = this.getGrabOffset(
1240
+ input.event.clientY - rect.top,
1241
+ displayHeight
1242
+ );
1243
+ return {
1244
+ displayWidth,
1245
+ displayHeight,
1246
+ grabOffsetX,
1247
+ grabOffsetY,
1248
+ src: input.img.src,
1249
+ persistImage: input.persistImage === true
1250
+ };
1251
+ }
1252
+ /**
1253
+ * Clamps a raw pointer offset into the rendered image bounds.
1254
+ */
1255
+ getGrabOffset(rawOffset, displaySize) {
1256
+ return this.clampFloor(rawOffset, 0, displaySize);
1257
+ }
1258
+ /**
1259
+ * Floors a number and clamps it into the provided inclusive range.
1260
+ */
1261
+ clampFloor(value, min, max) {
1262
+ return Math.min(Math.max(Math.floor(value), min), max);
1263
+ }
1264
+ /**
1265
+ * Configures the browser drag payload and drag preview image for the current
1266
+ * drag operation.
1267
+ */
1268
+ applyNativeDragSetup(dataTransfer, img, metrics) {
1269
+ if (!dataTransfer) {
1270
+ return;
1271
+ }
1272
+ const { displayWidth, displayHeight, grabOffsetX, grabOffsetY, src } = metrics;
1273
+ dataTransfer.setData("text/plain", src);
1274
+ dataTransfer.effectAllowed = "copy";
1275
+ const previewCanvas = this.getOrCreateDragPreviewCanvas();
1276
+ if (previewCanvas.canvas && previewCanvas.context) {
1277
+ previewCanvas.canvas.width = displayWidth;
1278
+ previewCanvas.canvas.height = displayHeight;
1279
+ previewCanvas.canvas.style.width = `${displayWidth}px`;
1280
+ previewCanvas.canvas.style.height = `${displayHeight}px`;
1281
+ previewCanvas.context.clearRect(0, 0, displayWidth, displayHeight);
1282
+ previewCanvas.context.drawImage(img, 0, 0, displayWidth, displayHeight);
1283
+ dataTransfer.setDragImage(previewCanvas.canvas, grabOffsetX, grabOffsetY);
1284
+ return;
1285
+ }
1286
+ dataTransfer.setDragImage(img, grabOffsetX, grabOffsetY);
1287
+ }
1288
+ /**
1289
+ * Creates and reuses the hidden canvas used as the native drag preview.
1290
+ * Reuse one canvas as a native drag image so we can control preview size exactly.
1291
+ * Browsers may auto-scale element drag ghosts, which shifts perceived cursor alignment.
1292
+ * Must be in the DOM - Chrome ignores setDragImage on detached elements and falls back
1293
+ * to a scaled ghost. Position it off-screen so it's invisible.
1294
+ */
1295
+ getOrCreateDragPreviewCanvas() {
1296
+ if (typeof document === "undefined" || !document.body) {
1297
+ return {
1298
+ canvas: null,
1299
+ context: null
1300
+ };
1301
+ }
1302
+ if (!this.dragPreviewCanvas) {
1303
+ this.dragPreviewCanvas = document.createElement("canvas");
1304
+ this.dragPreviewCanvas.style.position = "fixed";
1305
+ this.dragPreviewCanvas.style.left = HIDDEN_DRAG_PREVIEW_OFFSET_PX;
1306
+ this.dragPreviewCanvas.style.top = HIDDEN_DRAG_PREVIEW_OFFSET_PX;
1307
+ this.dragPreviewCanvas.style.pointerEvents = "none";
1308
+ }
1309
+ if (!this.dragPreviewCanvas.isConnected) {
1310
+ document.body.appendChild(this.dragPreviewCanvas);
1311
+ }
1312
+ if (this.dragPreviewCtx === void 0) {
1313
+ this.dragPreviewCtx = this.dragPreviewCanvas.getContext("2d");
1314
+ }
1315
+ return {
1316
+ canvas: this.dragPreviewCanvas,
1317
+ context: this.dragPreviewCtx ?? null
1318
+ };
1319
+ }
1320
+ /**
1321
+ * Completes the managed drag on `dragend` by ignoring cancelled/internal
1322
+ * drops, forwarding valid drops to `dropImage(...)`, and selecting the inserted
1323
+ * object when available.
1324
+ */
1325
+ async handleManagedDragEnd(metrics, event) {
1326
+ const dropInput = {
1327
+ x: event.clientX,
1328
+ y: event.clientY,
1329
+ src: metrics.src,
1330
+ imgWidth: metrics.displayWidth,
1331
+ imgHeight: metrics.displayHeight,
1332
+ grabOffsetX: metrics.grabOffsetX,
1333
+ grabOffsetY: metrics.grabOffsetY,
1334
+ persistImage: metrics.persistImage
1335
+ };
1336
+ try {
1337
+ if (event.clientX === 0 && event.clientY === 0) {
1338
+ return;
1339
+ }
1340
+ if (this.isInsideIframeViewport(event.clientX, event.clientY)) {
1341
+ return;
1342
+ }
1343
+ const objectId = await this.dropImage(dropInput);
1344
+ if (!objectId) {
1345
+ return;
1346
+ }
1347
+ await this.state.setSelectedObjectsIds([objectId]);
1348
+ } catch {
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Returns true when the final pointer position is still inside the iframe
1353
+ * viewport.
1354
+ */
1355
+ isInsideIframeViewport(x, y) {
1356
+ return x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight;
1357
+ }
1358
+ };
1359
+
1360
+ // src/createEditorSDKAPIs.ts
1361
+ function createEditorSDKAPIs() {
1362
+ const { project } = bridgeHandlers;
1363
+ const dragAndDrop = new DragAndDropApi({
1364
+ state: project.app.api,
1365
+ context: bridgeHandlers.context,
1366
+ design: project.design.api,
1367
+ upload: bridgeHandlers.upload
1368
+ });
1369
+ return {
1370
+ aiGenerator: bridgeHandlers.aiGenerator,
1371
+ mockup: bridgeHandlers.mockup,
1372
+ project,
1373
+ export: bridgeHandlers.export,
1374
+ helpers: { dragAndDrop },
1375
+ dragAndDrop,
1376
+ auth: bridgeHandlers.auth,
1377
+ upload: bridgeHandlers.upload,
1378
+ stateless: bridgeHandlers.stateless,
1379
+ font: bridgeHandlers.font,
1380
+ fileBrowser: bridgeHandlers.fileBrowser
1381
+ };
1382
+ }
1383
+
1384
+ // package.json
1385
+ var version = "1.0.0";
1386
+
1387
+ // src/utils/syncHtmlDataThemeFromHostContext.ts
1388
+ async function syncHtmlDataThemeFromHostContext(kittl2) {
1389
+ if (typeof document === "undefined") {
1390
+ return;
1391
+ }
1392
+ const parent = window.parent;
1393
+ if (!parent || parent === window) {
1394
+ return;
1395
+ }
1396
+ const contextResponse = await kittl2.context.get();
1397
+ if (contextResponse.isOk) {
1398
+ document.documentElement.dataset.theme = contextResponse.result.colorScheme;
1399
+ }
1400
+ await kittl2.context.subscribe((ctx) => {
1401
+ document.documentElement.dataset.theme = ctx.colorScheme;
1402
+ });
1403
+ }
1404
+
1405
+ // src/createKittlSDK.ts
1406
+ function createKittlSDK(apis) {
1407
+ const kittl2 = {
1408
+ onLoadedCallback: null,
1409
+ loaded: false,
1410
+ onReady: (callback) => {
1411
+ if (kittl2.loaded) {
1412
+ callback();
1413
+ return;
1414
+ }
1415
+ kittl2.onLoadedCallback = callback;
1416
+ },
1417
+ ...apis
1418
+ };
1419
+ const initSdk = () => {
1420
+ kittl2.loaded = true;
1421
+ window.addEventListener(
1422
+ "message",
1423
+ (event) => {
1424
+ handleIncomingMessage(event);
1425
+ }
1426
+ );
1427
+ const { context } = apis;
1428
+ const themeSynced = context?.get && context.subscribe ? syncHtmlDataThemeFromHostContext({
1429
+ context
1430
+ }) : Promise.resolve();
1431
+ void themeSynced.catch(() => void 0).then(() => {
1432
+ kittl2.onLoadedCallback?.();
1433
+ sendLoaded();
1434
+ });
1435
+ };
1436
+ if (typeof document !== "undefined" && typeof window !== "undefined") {
1437
+ setSDKVersion(version);
1438
+ window.kittl = kittl2;
1439
+ if (document.readyState === "loading") {
1440
+ document.addEventListener("DOMContentLoaded", initSdk);
1441
+ } else {
1442
+ initSdk();
1443
+ }
1444
+ }
1445
+ return kittl2;
1446
+ }
1447
+
1448
+ // src/editorContentPanel.ts
1449
+ var kittl = createKittlSDK({
1450
+ ...createEditorSDKAPIs(),
1451
+ context: bridgeHandlers.context,
1452
+ brandKit: bridgeHandlers.brandKit,
1453
+ fileBrowser: {
1454
+ getFiles: bridgeHandlers.fileBrowser.getFiles,
1455
+ // Keep existing content-panel extensions working while registration moves to sharedFileBrowser context.
1456
+ registerUploadBrowser: bridgeHandlers.fileBrowserRegistration.registerUploadBrowser
1457
+ }
1458
+ });
1459
+ export {
1460
+ kittl,
1461
+ unwrapResult
1462
+ };