@templatical/core 0.0.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,2692 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/cloud/index.ts
31
+ var cloud_exports = {};
32
+ __export(cloud_exports, {
33
+ API_ROUTES: () => API_ROUTES,
34
+ ApiClient: () => ApiClient,
35
+ AuthManager: () => AuthManager,
36
+ WebSocketClient: () => WebSocketClient,
37
+ buildUrl: () => buildUrl,
38
+ createSdkAuthManager: () => createSdkAuthManager,
39
+ handleOperation: () => handleOperation,
40
+ performHealthCheck: () => performHealthCheck,
41
+ resolveWebSocketConfig: () => resolveWebSocketConfig,
42
+ useAiChat: () => useAiChat,
43
+ useAiConfig: () => useAiConfig,
44
+ useAiRewrite: () => useAiRewrite,
45
+ useCollaboration: () => useCollaboration,
46
+ useCommentListener: () => useCommentListener,
47
+ useComments: () => useComments,
48
+ useDesignReference: () => useDesignReference,
49
+ useEditor: () => useEditor,
50
+ useExport: () => useExport,
51
+ useMcpListener: () => useMcpListener,
52
+ usePlanConfig: () => usePlanConfig,
53
+ useSavedModules: () => useSavedModules,
54
+ useSnapshotHistory: () => useSnapshotHistory,
55
+ useTemplateScoring: () => useTemplateScoring,
56
+ useTestEmail: () => useTestEmail,
57
+ useWebSocket: () => useWebSocket
58
+ });
59
+ module.exports = __toCommonJS(cloud_exports);
60
+
61
+ // src/cloud/auth.ts
62
+ var import_types = require("@templatical/types");
63
+ var _AuthManager = class _AuthManager {
64
+ constructor(config) {
65
+ this.accessToken = null;
66
+ this.expiresAt = null;
67
+ this._projectId = null;
68
+ this._tenantId = null;
69
+ this._tenantSlug = null;
70
+ this._testEmailConfig = null;
71
+ this._userConfig = null;
72
+ this.refreshPromise = null;
73
+ this.url = config.url;
74
+ this.baseUrl = (config.baseUrl ?? _AuthManager.DEFAULT_BASE_URL).replace(
75
+ /\/$/,
76
+ ""
77
+ );
78
+ this.requestOptions = config.requestOptions ?? {};
79
+ this.onError = config.onError;
80
+ }
81
+ resolveUrl(path) {
82
+ if (path.startsWith("http://") || path.startsWith("https://")) {
83
+ return path;
84
+ }
85
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
86
+ return `${this.baseUrl}${normalizedPath}`;
87
+ }
88
+ get projectId() {
89
+ if (!this._projectId) {
90
+ throw new Error("Project ID not available. Call initialize() first.");
91
+ }
92
+ return this._projectId;
93
+ }
94
+ get tenantId() {
95
+ if (!this._tenantId) {
96
+ throw new Error("Tenant ID not available. Call initialize() first.");
97
+ }
98
+ return this._tenantId;
99
+ }
100
+ get tenantSlug() {
101
+ if (!this._tenantSlug) {
102
+ throw new Error("Tenant slug not available. Call initialize() first.");
103
+ }
104
+ return this._tenantSlug;
105
+ }
106
+ get testEmailConfig() {
107
+ return this._testEmailConfig;
108
+ }
109
+ get userConfig() {
110
+ return this._userConfig;
111
+ }
112
+ get accessTokenValue() {
113
+ return this.accessToken;
114
+ }
115
+ async initialize() {
116
+ await this.ensureToken();
117
+ }
118
+ async ensureToken() {
119
+ if (this.accessToken && !this.isTokenExpiringSoon()) {
120
+ return this.accessToken;
121
+ }
122
+ return this.refreshToken();
123
+ }
124
+ isTokenExpiringSoon() {
125
+ if (!this.expiresAt) {
126
+ return true;
127
+ }
128
+ const timeUntilExpiry = this.expiresAt.getTime() - Date.now();
129
+ return timeUntilExpiry < _AuthManager.REFRESH_THRESHOLD_MS;
130
+ }
131
+ async refreshToken() {
132
+ if (this.refreshPromise) {
133
+ return this.refreshPromise;
134
+ }
135
+ this.refreshPromise = this.performRefresh();
136
+ try {
137
+ const token = await this.refreshPromise;
138
+ return token;
139
+ } finally {
140
+ this.refreshPromise = null;
141
+ }
142
+ }
143
+ async performRefresh() {
144
+ try {
145
+ const method = this.requestOptions.method ?? "POST";
146
+ const headers = {
147
+ Accept: "application/json",
148
+ ...this.requestOptions.headers
149
+ };
150
+ const fetchOptions = {
151
+ method,
152
+ headers,
153
+ credentials: this.requestOptions.credentials ?? "include"
154
+ };
155
+ if (method === "POST" && this.requestOptions.body) {
156
+ headers["Content-Type"] = "application/json";
157
+ fetchOptions.body = JSON.stringify(this.requestOptions.body);
158
+ }
159
+ const response = await fetch(this.url, fetchOptions);
160
+ if (!response.ok) {
161
+ throw new import_types.SdkError(
162
+ `Token refresh failed: ${response.status}`,
163
+ response.status
164
+ );
165
+ }
166
+ const data = await response.json();
167
+ if (!data.token || !data.expires_at || !data.project_id || !data.tenant) {
168
+ throw new Error(
169
+ "Invalid token response: missing token, expires_at, project_id, or tenant"
170
+ );
171
+ }
172
+ this.accessToken = data.token;
173
+ this.expiresAt = new Date(data.expires_at * 1e3);
174
+ this._projectId = data.project_id;
175
+ this._tenantSlug = data.tenant;
176
+ if (data.test_email?.allowed_emails && data.test_email?.signature) {
177
+ this._testEmailConfig = {
178
+ allowedEmails: data.test_email.allowed_emails,
179
+ signature: data.test_email.signature
180
+ };
181
+ } else {
182
+ this._testEmailConfig = null;
183
+ }
184
+ if (data.user?.id && data.user?.name && data.user?.signature) {
185
+ this._userConfig = {
186
+ id: data.user.id,
187
+ name: data.user.name,
188
+ signature: data.user.signature
189
+ };
190
+ } else {
191
+ this._userConfig = null;
192
+ }
193
+ return this.accessToken;
194
+ } catch (error) {
195
+ const wrappedError = error instanceof Error ? error : new Error("Token refresh failed");
196
+ this.onError?.(wrappedError);
197
+ throw wrappedError;
198
+ }
199
+ }
200
+ async authenticatedFetch(url, options = {}) {
201
+ const token = await this.ensureToken();
202
+ const resolvedUrl = this.resolveUrl(url);
203
+ const makeRequest = async (authToken) => {
204
+ return fetch(resolvedUrl, {
205
+ ...options,
206
+ headers: {
207
+ ...options.headers,
208
+ Authorization: `Bearer ${authToken}`
209
+ }
210
+ });
211
+ };
212
+ let response = await makeRequest(token);
213
+ if (response.status === 401) {
214
+ const newToken = await this.refreshToken();
215
+ response = await makeRequest(newToken);
216
+ }
217
+ return response;
218
+ }
219
+ };
220
+ _AuthManager.DEFAULT_BASE_URL = "https://templatical.com";
221
+ _AuthManager.REFRESH_THRESHOLD_MS = 60 * 1e3;
222
+ var AuthManager = _AuthManager;
223
+ function createSdkAuthManager(config, onError) {
224
+ if (config.mode === "direct") {
225
+ const baseUrl = (config.baseUrl ?? "https://templatical.com").replace(
226
+ /\/$/,
227
+ ""
228
+ );
229
+ return new AuthManager({
230
+ url: `${baseUrl}/api/v1/auth/token`,
231
+ baseUrl: config.baseUrl,
232
+ requestOptions: {
233
+ method: "POST",
234
+ headers: {
235
+ "Content-Type": "application/json"
236
+ },
237
+ body: {
238
+ client_id: config.clientId,
239
+ client_secret: config.clientSecret,
240
+ tenant: config.tenant,
241
+ client_type: "sdk"
242
+ }
243
+ },
244
+ onError
245
+ });
246
+ }
247
+ return new AuthManager({
248
+ url: config.url,
249
+ baseUrl: config.baseUrl,
250
+ requestOptions: config.requestOptions,
251
+ onError
252
+ });
253
+ }
254
+
255
+ // src/cloud/api.ts
256
+ var import_types2 = require("@templatical/types");
257
+
258
+ // src/cloud/url-builder.ts
259
+ function buildUrl(template, params) {
260
+ return template.replace(
261
+ /\{(\w+)\}/g,
262
+ (_, key) => encodeURIComponent(params[key] ?? "")
263
+ );
264
+ }
265
+ var BASE = "/api/v1/projects/{project}/tenants/{tenant}";
266
+ var TEMPLATE = `${BASE}/templates/{template}`;
267
+ var AI = `${TEMPLATE}/ai`;
268
+ var MEDIA = `${BASE}/media`;
269
+ var FOLDERS = `${MEDIA}/folders`;
270
+ var MODULES = `${BASE}/saved-modules`;
271
+ var API_ROUTES = {
272
+ health: "/api/v1/health",
273
+ "projects.config": `${BASE}/config`,
274
+ "broadcasting.auth": `${BASE}/broadcasting/auth`,
275
+ "templates.store": `${BASE}/templates`,
276
+ "templates.show": `${TEMPLATE}`,
277
+ "templates.update": `${TEMPLATE}`,
278
+ "templates.destroy": `${TEMPLATE}`,
279
+ "templates.export": `${TEMPLATE}/export`,
280
+ "templates.importFromBeefree": `${BASE}/templates/import/from-beefree`,
281
+ "templates.sendTestEmail": `${TEMPLATE}/send-test-email`,
282
+ "snapshots.index": `${TEMPLATE}/snapshots`,
283
+ "snapshots.store": `${TEMPLATE}/snapshots`,
284
+ "snapshots.show": `${TEMPLATE}/snapshots/{snapshot}`,
285
+ "snapshots.restore": `${TEMPLATE}/snapshots/{snapshot}/restore`,
286
+ "comments.index": `${TEMPLATE}/comments`,
287
+ "comments.store": `${TEMPLATE}/comments`,
288
+ "comments.update": `${TEMPLATE}/comments/{comment}`,
289
+ "comments.destroy": `${TEMPLATE}/comments/{comment}`,
290
+ "comments.resolve": `${TEMPLATE}/comments/{comment}/resolve`,
291
+ "ai.generate": `${AI}/generate`,
292
+ "ai.conversationMessages": `${AI}/conversation-messages`,
293
+ "ai.suggestions": `${AI}/suggestions`,
294
+ "ai.rewriteText": `${AI}/rewrite-text`,
295
+ "ai.score": `${AI}/score`,
296
+ "ai.fixFinding": `${AI}/fix-finding`,
297
+ "ai.generateFromDesign": `${AI}/generate-from-design`,
298
+ "media.upload": `${MEDIA}/upload`,
299
+ "media.browse": `${MEDIA}/browse`,
300
+ "media.delete": `${MEDIA}/delete`,
301
+ "media.move": `${MEDIA}/move`,
302
+ "media.update": `${MEDIA}/{media}`,
303
+ "media.replace": `${MEDIA}/{media}/replace`,
304
+ "media.checkUsage": `${MEDIA}/check-usage`,
305
+ "media.frequentlyUsed": `${MEDIA}/frequently-used`,
306
+ "media.importFromUrl": `${MEDIA}/import-from-url`,
307
+ "folders.index": `${FOLDERS}`,
308
+ "folders.store": `${FOLDERS}`,
309
+ "folders.update": `${FOLDERS}/{mediaFolder}`,
310
+ "folders.destroy": `${FOLDERS}/{mediaFolder}`,
311
+ "savedModules.index": `${MODULES}`,
312
+ "savedModules.store": `${MODULES}`,
313
+ "savedModules.update": `${MODULES}/{savedModule}`,
314
+ "savedModules.destroy": `${MODULES}/{savedModule}`
315
+ };
316
+
317
+ // src/cloud/api.ts
318
+ var ApiClient = class {
319
+ constructor(authManager) {
320
+ this.authManager = authManager;
321
+ }
322
+ get projectId() {
323
+ return this.authManager.projectId;
324
+ }
325
+ get tenantSlug() {
326
+ return this.authManager.tenantSlug;
327
+ }
328
+ get baseParams() {
329
+ return { project: this.projectId, tenant: this.tenantSlug };
330
+ }
331
+ async request(path, options = {}) {
332
+ const response = await this.authManager.authenticatedFetch(path, {
333
+ ...options,
334
+ headers: {
335
+ "Content-Type": "application/json",
336
+ Accept: "application/json",
337
+ ...options.headers
338
+ }
339
+ });
340
+ if (!response.ok) {
341
+ const error = await response.json().catch(() => ({
342
+ message: `HTTP error ${response.status}`
343
+ }));
344
+ const errorMessage = this.extractFirstValidationError(error);
345
+ throw new import_types2.SdkError(errorMessage, response.status);
346
+ }
347
+ if (response.status === 204) {
348
+ return void 0;
349
+ }
350
+ const json = await response.json();
351
+ return json.data;
352
+ }
353
+ extractFirstValidationError(error) {
354
+ if (error.errors) {
355
+ const firstField = Object.keys(error.errors)[0];
356
+ if (firstField && error.errors[firstField]?.length > 0) {
357
+ return error.errors[firstField][0];
358
+ }
359
+ }
360
+ return error.message;
361
+ }
362
+ async createTemplate(content) {
363
+ return this.request(
364
+ buildUrl(API_ROUTES["templates.store"], this.baseParams),
365
+ {
366
+ method: "POST",
367
+ body: JSON.stringify({ content })
368
+ }
369
+ );
370
+ }
371
+ async getTemplate(id) {
372
+ return this.request(
373
+ buildUrl(API_ROUTES["templates.show"], {
374
+ ...this.baseParams,
375
+ template: id
376
+ })
377
+ );
378
+ }
379
+ async updateTemplate(id, content) {
380
+ return this.request(
381
+ buildUrl(API_ROUTES["templates.update"], {
382
+ ...this.baseParams,
383
+ template: id
384
+ }),
385
+ {
386
+ method: "PUT",
387
+ body: JSON.stringify({ content })
388
+ }
389
+ );
390
+ }
391
+ async createSnapshot(templateId, content) {
392
+ return this.request(
393
+ buildUrl(API_ROUTES["snapshots.store"], {
394
+ ...this.baseParams,
395
+ template: templateId
396
+ }),
397
+ {
398
+ method: "POST",
399
+ body: JSON.stringify({ content })
400
+ }
401
+ );
402
+ }
403
+ async deleteTemplate(id) {
404
+ return this.request(
405
+ buildUrl(API_ROUTES["templates.destroy"], {
406
+ ...this.baseParams,
407
+ template: id
408
+ }),
409
+ {
410
+ method: "DELETE"
411
+ }
412
+ );
413
+ }
414
+ async getSnapshots(templateId) {
415
+ return this.request(
416
+ buildUrl(API_ROUTES["snapshots.index"], {
417
+ ...this.baseParams,
418
+ template: templateId
419
+ })
420
+ );
421
+ }
422
+ async restoreSnapshot(templateId, snapshotId) {
423
+ return this.request(
424
+ buildUrl(API_ROUTES["snapshots.restore"], {
425
+ ...this.baseParams,
426
+ template: templateId,
427
+ snapshot: snapshotId
428
+ }),
429
+ {
430
+ method: "POST"
431
+ }
432
+ );
433
+ }
434
+ async exportTemplate(templateId, fontsPayload) {
435
+ const body = fontsPayload ? JSON.stringify({
436
+ custom_fonts: fontsPayload.customFonts,
437
+ default_fallback: fontsPayload.defaultFallback
438
+ }) : void 0;
439
+ return this.request(
440
+ buildUrl(API_ROUTES["templates.export"], {
441
+ ...this.baseParams,
442
+ template: templateId
443
+ }),
444
+ {
445
+ method: "POST",
446
+ body
447
+ }
448
+ );
449
+ }
450
+ async sendTestEmail(templateId, payload) {
451
+ await this.request(
452
+ buildUrl(API_ROUTES["templates.sendTestEmail"], {
453
+ ...this.baseParams,
454
+ template: templateId
455
+ }),
456
+ {
457
+ method: "POST",
458
+ body: JSON.stringify(payload)
459
+ }
460
+ );
461
+ }
462
+ commentsUrl(templateId, commentId) {
463
+ if (commentId) {
464
+ return buildUrl(API_ROUTES["comments.update"], {
465
+ ...this.baseParams,
466
+ template: templateId,
467
+ comment: commentId
468
+ });
469
+ }
470
+ return buildUrl(API_ROUTES["comments.index"], {
471
+ ...this.baseParams,
472
+ template: templateId
473
+ });
474
+ }
475
+ async getComments(templateId) {
476
+ return this.request(this.commentsUrl(templateId));
477
+ }
478
+ async createComment(templateId, data, headers) {
479
+ return this.request(this.commentsUrl(templateId), {
480
+ method: "POST",
481
+ body: JSON.stringify(data),
482
+ headers
483
+ });
484
+ }
485
+ async updateComment(templateId, commentId, data, headers) {
486
+ return this.request(this.commentsUrl(templateId, commentId), {
487
+ method: "PUT",
488
+ body: JSON.stringify(data),
489
+ headers
490
+ });
491
+ }
492
+ async deleteComment(templateId, commentId, data, headers) {
493
+ return this.request(this.commentsUrl(templateId, commentId), {
494
+ method: "DELETE",
495
+ body: JSON.stringify(data),
496
+ headers
497
+ });
498
+ }
499
+ async resolveComment(templateId, commentId, data, headers) {
500
+ return this.request(
501
+ buildUrl(API_ROUTES["comments.resolve"], {
502
+ ...this.baseParams,
503
+ template: templateId,
504
+ comment: commentId
505
+ }),
506
+ {
507
+ method: "POST",
508
+ body: JSON.stringify(data),
509
+ headers
510
+ }
511
+ );
512
+ }
513
+ async fetchConfig() {
514
+ return this.request(
515
+ buildUrl(API_ROUTES["projects.config"], this.baseParams)
516
+ );
517
+ }
518
+ async listModules(search) {
519
+ const url = buildUrl(API_ROUTES["savedModules.index"], this.baseParams);
520
+ const query = search ? `?search=${encodeURIComponent(search)}` : "";
521
+ return this.request(`${url}${query}`);
522
+ }
523
+ async createModule(data) {
524
+ return this.request(
525
+ buildUrl(API_ROUTES["savedModules.store"], this.baseParams),
526
+ {
527
+ method: "POST",
528
+ body: JSON.stringify(data)
529
+ }
530
+ );
531
+ }
532
+ async updateModule(id, data) {
533
+ return this.request(
534
+ buildUrl(API_ROUTES["savedModules.update"], {
535
+ ...this.baseParams,
536
+ savedModule: id
537
+ }),
538
+ {
539
+ method: "PUT",
540
+ body: JSON.stringify(data)
541
+ }
542
+ );
543
+ }
544
+ async deleteModule(id) {
545
+ return this.request(
546
+ buildUrl(API_ROUTES["savedModules.destroy"], {
547
+ ...this.baseParams,
548
+ savedModule: id
549
+ }),
550
+ {
551
+ method: "DELETE"
552
+ }
553
+ );
554
+ }
555
+ };
556
+
557
+ // src/cloud/websocket-client.ts
558
+ function resolveWebSocketConfig(serverConfig) {
559
+ return {
560
+ host: serverConfig.host,
561
+ port: serverConfig.port,
562
+ appKey: serverConfig.app_key
563
+ };
564
+ }
565
+ var WebSocketClient = class {
566
+ constructor(options) {
567
+ this.pusher = null;
568
+ this.authManager = options.authManager;
569
+ this.config = options.config;
570
+ this.onError = options.onError;
571
+ }
572
+ async connect() {
573
+ if (this.pusher) {
574
+ return;
575
+ }
576
+ const { default: Pusher } = await import("pusher-js");
577
+ const { host, port, appKey } = this.config;
578
+ const authEndpoint = this.authManager.resolveUrl(
579
+ buildUrl(API_ROUTES["broadcasting.auth"], {
580
+ project: this.authManager.projectId,
581
+ tenant: this.authManager.tenantSlug
582
+ })
583
+ );
584
+ this.pusher = new Pusher(appKey, {
585
+ wsHost: host,
586
+ wsPort: port,
587
+ wssPort: port,
588
+ forceTLS: true,
589
+ disableStats: true,
590
+ enabledTransports: ["ws", "wss"],
591
+ cluster: "",
592
+ channelAuthorization: {
593
+ transport: "ajax",
594
+ endpoint: authEndpoint,
595
+ headers: {
596
+ Authorization: `Bearer ${this.authManager.accessTokenValue}`,
597
+ Accept: "application/json"
598
+ },
599
+ params: {
600
+ user_id: this.authManager.userConfig?.id ?? "",
601
+ user_name: this.authManager.userConfig?.name ?? "",
602
+ user_signature: this.authManager.userConfig?.signature ?? ""
603
+ }
604
+ }
605
+ });
606
+ this.pusher.connection.bind("error", (error) => {
607
+ this.onError?.(
608
+ error instanceof Error ? error : new Error("WebSocket connection error")
609
+ );
610
+ });
611
+ }
612
+ subscribePresence(channelName) {
613
+ if (!this.pusher) {
614
+ throw new Error("WebSocketClient not connected. Call connect() first.");
615
+ }
616
+ return this.pusher.subscribe(channelName);
617
+ }
618
+ unsubscribe(channelName) {
619
+ this.pusher?.unsubscribe(channelName);
620
+ }
621
+ getChannel(channelName) {
622
+ return this.pusher?.channel(channelName);
623
+ }
624
+ disconnect() {
625
+ if (this.pusher) {
626
+ this.pusher.disconnect();
627
+ this.pusher = null;
628
+ }
629
+ }
630
+ getSocketId() {
631
+ return this.pusher?.connection.socket_id ?? null;
632
+ }
633
+ get isConnected() {
634
+ return this.pusher?.connection.state === "connected";
635
+ }
636
+ };
637
+
638
+ // src/cloud/mcp-operation-handler.ts
639
+ function handleOperation(editor, payload) {
640
+ const { operation, data } = payload;
641
+ switch (operation) {
642
+ case "add_block":
643
+ editor.addBlock(
644
+ data.block,
645
+ data.section_id,
646
+ data.column_index,
647
+ data.index
648
+ );
649
+ break;
650
+ case "update_block":
651
+ editor.updateBlock(
652
+ data.block_id,
653
+ data.updates
654
+ );
655
+ break;
656
+ case "delete_block":
657
+ editor.removeBlock(data.block_id);
658
+ break;
659
+ case "move_block":
660
+ editor.moveBlock(
661
+ data.block_id,
662
+ data.index,
663
+ data.section_id,
664
+ data.column_index
665
+ );
666
+ break;
667
+ case "update_settings":
668
+ editor.updateSettings(data.updates);
669
+ break;
670
+ case "set_content":
671
+ editor.setContent(data.content);
672
+ break;
673
+ case "update_block_style":
674
+ editor.updateBlock(
675
+ data.block_id,
676
+ {
677
+ styles: data.styles
678
+ }
679
+ );
680
+ break;
681
+ }
682
+ }
683
+
684
+ // src/cloud/editor.ts
685
+ var import_types3 = require("@templatical/types");
686
+ var import_types4 = require("@templatical/types");
687
+ var import_vue = require("vue");
688
+ function useEditor(options) {
689
+ const api = new ApiClient(options.authManager);
690
+ const state = (0, import_vue.reactive)({
691
+ template: null,
692
+ content: (0, import_types4.createDefaultTemplateContent)(
693
+ options.defaultFontFamily,
694
+ options.templateDefaults
695
+ ),
696
+ selectedBlockId: null,
697
+ viewport: "desktop",
698
+ darkMode: false,
699
+ previewMode: false,
700
+ isDirty: false,
701
+ isSaving: false,
702
+ isLoading: false
703
+ });
704
+ const content = (0, import_vue.computed)({
705
+ get: () => state.content,
706
+ set: (value) => {
707
+ state.content = value;
708
+ state.isDirty = true;
709
+ }
710
+ });
711
+ const selectedBlock = (0, import_vue.computed)(() => {
712
+ if (!state.selectedBlockId) return null;
713
+ return findBlockById(state.content.blocks, state.selectedBlockId);
714
+ });
715
+ const savedBlockIds = (0, import_vue.computed)(() => {
716
+ const ids = /* @__PURE__ */ new Set();
717
+ const blocks = state.template?.content?.blocks;
718
+ if (!blocks) {
719
+ return ids;
720
+ }
721
+ for (const block of blocks) {
722
+ ids.add(block.id);
723
+ if (block.type === "section") {
724
+ for (const column of block.children) {
725
+ for (const child of column) {
726
+ ids.add(child.id);
727
+ }
728
+ }
729
+ }
730
+ }
731
+ return ids;
732
+ });
733
+ function findBlockById(blocks, id) {
734
+ for (const block of blocks) {
735
+ if (block.id === id) return block;
736
+ if (block.type === "section") {
737
+ for (const column of block.children) {
738
+ const found = findBlockById(column, id);
739
+ if (found) return found;
740
+ }
741
+ }
742
+ }
743
+ return null;
744
+ }
745
+ function findBlockParent(blocks, id, parent = { blocks }) {
746
+ for (let i = 0; i < blocks.length; i++) {
747
+ const block = blocks[i];
748
+ if (block.id === id) return parent;
749
+ if (block.type === "section") {
750
+ for (let colIdx = 0; colIdx < block.children.length; colIdx++) {
751
+ const result = findBlockParent(block.children[colIdx], id, {
752
+ blocks: block.children[colIdx],
753
+ sectionId: block.id,
754
+ columnIndex: colIdx
755
+ });
756
+ if (result) return result;
757
+ }
758
+ }
759
+ }
760
+ return null;
761
+ }
762
+ function isBlockLocked(blockId) {
763
+ return options.lockedBlocks?.value.has(blockId) ?? false;
764
+ }
765
+ function setContent(newContent, markDirty2 = true) {
766
+ state.content = newContent;
767
+ if (markDirty2) {
768
+ state.isDirty = true;
769
+ }
770
+ }
771
+ function selectBlock(blockId) {
772
+ if (blockId && isBlockLocked(blockId)) {
773
+ return;
774
+ }
775
+ state.selectedBlockId = blockId;
776
+ }
777
+ function setViewport(viewport) {
778
+ state.viewport = viewport;
779
+ }
780
+ function setDarkMode(darkMode) {
781
+ state.darkMode = darkMode;
782
+ }
783
+ function setPreviewMode(previewMode) {
784
+ state.previewMode = previewMode;
785
+ if (previewMode) {
786
+ state.selectedBlockId = null;
787
+ }
788
+ }
789
+ function updateBlock(blockId, updates) {
790
+ if (isBlockLocked(blockId)) {
791
+ return;
792
+ }
793
+ const block = findBlockById(state.content.blocks, blockId);
794
+ if (block) {
795
+ Object.assign(block, updates);
796
+ state.isDirty = true;
797
+ }
798
+ }
799
+ function updateSettings(updates) {
800
+ state.content.settings = { ...state.content.settings, ...updates };
801
+ state.isDirty = true;
802
+ }
803
+ function addBlock(block, targetSectionId, columnIndex = 0, index) {
804
+ if (targetSectionId) {
805
+ const section = findBlockById(state.content.blocks, targetSectionId);
806
+ if (section && section.type === "section") {
807
+ section.children[columnIndex] = section.children[columnIndex] || [];
808
+ const targetArray = section.children[columnIndex];
809
+ if (index !== void 0 && index < targetArray.length) {
810
+ targetArray.splice(index, 0, block);
811
+ } else {
812
+ targetArray.push(block);
813
+ }
814
+ }
815
+ } else {
816
+ if (index !== void 0 && index < state.content.blocks.length) {
817
+ state.content.blocks.splice(index, 0, block);
818
+ } else {
819
+ state.content.blocks.push(block);
820
+ }
821
+ }
822
+ state.isDirty = true;
823
+ }
824
+ function removeBlock(blockId) {
825
+ if (isBlockLocked(blockId)) {
826
+ return;
827
+ }
828
+ const parent = findBlockParent(state.content.blocks, blockId);
829
+ if (parent) {
830
+ const index = parent.blocks.findIndex((b) => b.id === blockId);
831
+ if (index !== -1) {
832
+ parent.blocks.splice(index, 1);
833
+ if (state.selectedBlockId === blockId) {
834
+ state.selectedBlockId = null;
835
+ }
836
+ state.isDirty = true;
837
+ }
838
+ }
839
+ }
840
+ function moveBlock(blockId, newIndex, targetSectionId, columnIndex = 0) {
841
+ const parent = findBlockParent(state.content.blocks, blockId);
842
+ if (!parent) return;
843
+ const oldIndex = parent.blocks.findIndex((b) => b.id === blockId);
844
+ if (oldIndex === -1) return;
845
+ const [block] = parent.blocks.splice(oldIndex, 1);
846
+ if (targetSectionId) {
847
+ const section = findBlockById(state.content.blocks, targetSectionId);
848
+ if (section && section.type === "section") {
849
+ section.children[columnIndex] = section.children[columnIndex] || [];
850
+ section.children[columnIndex].splice(newIndex, 0, block);
851
+ }
852
+ } else {
853
+ state.content.blocks.splice(newIndex, 0, block);
854
+ }
855
+ state.isDirty = true;
856
+ }
857
+ async function create(content2) {
858
+ state.isLoading = true;
859
+ try {
860
+ if (content2) {
861
+ state.content = content2;
862
+ }
863
+ const template = await api.createTemplate(state.content);
864
+ state.template = template;
865
+ state.isDirty = false;
866
+ return template;
867
+ } catch (error) {
868
+ options.onError?.(error);
869
+ throw error;
870
+ } finally {
871
+ state.isLoading = false;
872
+ }
873
+ }
874
+ async function load(templateId) {
875
+ state.isLoading = true;
876
+ try {
877
+ const template = await api.getTemplate(templateId);
878
+ state.template = template;
879
+ state.content = template.content;
880
+ state.isDirty = false;
881
+ return template;
882
+ } catch (error) {
883
+ options.onError?.(error);
884
+ throw error;
885
+ } finally {
886
+ state.isLoading = false;
887
+ }
888
+ }
889
+ async function save() {
890
+ if (!state.template?.id) {
891
+ throw new import_types3.SdkError(
892
+ "No template loaded. Call create() or load() before saving."
893
+ );
894
+ }
895
+ state.isSaving = true;
896
+ try {
897
+ const template = await api.updateTemplate(
898
+ state.template.id,
899
+ state.content
900
+ );
901
+ state.template = template;
902
+ state.isDirty = false;
903
+ return template;
904
+ } catch (error) {
905
+ options.onError?.(error);
906
+ throw error;
907
+ } finally {
908
+ state.isSaving = false;
909
+ }
910
+ }
911
+ async function createSnapshot() {
912
+ if (!state.template?.id) {
913
+ return;
914
+ }
915
+ try {
916
+ await api.createSnapshot(state.template.id, state.content);
917
+ } catch (error) {
918
+ options.onError?.(error);
919
+ throw error;
920
+ }
921
+ }
922
+ function hasTemplate() {
923
+ return state.template?.id !== void 0;
924
+ }
925
+ function markDirty() {
926
+ state.isDirty = true;
927
+ }
928
+ return {
929
+ state: (0, import_vue.readonly)(state),
930
+ content,
931
+ selectedBlock,
932
+ savedBlockIds,
933
+ isBlockLocked,
934
+ setContent,
935
+ selectBlock,
936
+ setViewport,
937
+ setDarkMode,
938
+ setPreviewMode,
939
+ updateBlock,
940
+ updateSettings,
941
+ addBlock,
942
+ removeBlock,
943
+ moveBlock,
944
+ create,
945
+ load,
946
+ save,
947
+ createSnapshot,
948
+ hasTemplate,
949
+ markDirty
950
+ };
951
+ }
952
+
953
+ // src/cloud/ai-chat.ts
954
+ var import_vue2 = require("vue");
955
+ var messageIdCounter = 0;
956
+ function generateMessageId() {
957
+ return `msg_${Date.now()}_${++messageIdCounter}`;
958
+ }
959
+ function useAiChat(options) {
960
+ const { authManager, getTemplateId, onApply, onError } = options;
961
+ const messages = (0, import_vue2.ref)([]);
962
+ const isGenerating = (0, import_vue2.ref)(false);
963
+ const isLoadingHistory = (0, import_vue2.ref)(false);
964
+ const error = (0, import_vue2.ref)(null);
965
+ const failedPrompt = (0, import_vue2.ref)(null);
966
+ const conversationId = (0, import_vue2.ref)(null);
967
+ const lastApplyMessageId = (0, import_vue2.ref)(null);
968
+ const lastPreviousContent = (0, import_vue2.ref)(null);
969
+ const lastAppliedContent = (0, import_vue2.ref)(null);
970
+ const isLastChangeReverted = (0, import_vue2.ref)(false);
971
+ const suggestions = (0, import_vue2.ref)([]);
972
+ const isLoadingSuggestions = (0, import_vue2.ref)(false);
973
+ function updateMessage(msgId, updates) {
974
+ const idx = messages.value.findIndex((m) => m.id === msgId);
975
+ if (idx === -1) {
976
+ return;
977
+ }
978
+ const updated = { ...messages.value[idx], ...updates };
979
+ messages.value = [
980
+ ...messages.value.slice(0, idx),
981
+ updated,
982
+ ...messages.value.slice(idx + 1)
983
+ ];
984
+ }
985
+ async function loadConversation() {
986
+ const templateId = getTemplateId();
987
+ if (!templateId) {
988
+ return;
989
+ }
990
+ isLoadingHistory.value = true;
991
+ try {
992
+ const url = buildUrl(API_ROUTES["ai.conversationMessages"], {
993
+ project: authManager.projectId,
994
+ tenant: authManager.tenantSlug,
995
+ template: templateId
996
+ });
997
+ const response = await authManager.authenticatedFetch(url, {
998
+ method: "GET",
999
+ headers: {
1000
+ Accept: "application/json"
1001
+ }
1002
+ });
1003
+ if (!response.ok) {
1004
+ return;
1005
+ }
1006
+ const data = await response.json();
1007
+ if (data.conversation_id) {
1008
+ conversationId.value = data.conversation_id;
1009
+ }
1010
+ if (Array.isArray(data.data) && data.data.length > 0) {
1011
+ messages.value = data.data.map(
1012
+ (msg) => ({
1013
+ id: msg.id,
1014
+ role: msg.role,
1015
+ content: msg.content,
1016
+ timestamp: new Date(msg.created_at).getTime()
1017
+ })
1018
+ );
1019
+ }
1020
+ } catch {
1021
+ } finally {
1022
+ isLoadingHistory.value = false;
1023
+ }
1024
+ }
1025
+ async function loadSuggestions(currentContent, mergeTags) {
1026
+ const templateId = getTemplateId();
1027
+ if (!templateId) {
1028
+ return;
1029
+ }
1030
+ isLoadingSuggestions.value = true;
1031
+ try {
1032
+ const url = buildUrl(API_ROUTES["ai.suggestions"], {
1033
+ project: authManager.projectId,
1034
+ tenant: authManager.tenantSlug,
1035
+ template: templateId
1036
+ });
1037
+ const response = await authManager.authenticatedFetch(url, {
1038
+ method: "POST",
1039
+ headers: {
1040
+ "Content-Type": "application/json",
1041
+ Accept: "text/event-stream"
1042
+ },
1043
+ body: JSON.stringify({
1044
+ current_content: currentContent,
1045
+ merge_tags: mergeTags.map((p) => ({
1046
+ label: p.label,
1047
+ value: p.value
1048
+ }))
1049
+ })
1050
+ });
1051
+ if (!response.ok) {
1052
+ return;
1053
+ }
1054
+ const reader = response.body?.getReader();
1055
+ if (!reader) {
1056
+ return;
1057
+ }
1058
+ const decoder = new TextDecoder();
1059
+ let buffer = "";
1060
+ while (true) {
1061
+ const { done, value } = await reader.read();
1062
+ if (done) {
1063
+ break;
1064
+ }
1065
+ buffer += decoder.decode(value, { stream: true });
1066
+ const lines = buffer.split("\n");
1067
+ buffer = lines.pop() ?? "";
1068
+ for (const line of lines) {
1069
+ if (!line.startsWith("data: ")) {
1070
+ continue;
1071
+ }
1072
+ let event;
1073
+ try {
1074
+ event = JSON.parse(line.slice(6));
1075
+ } catch {
1076
+ continue;
1077
+ }
1078
+ if (event.type === "done" && Array.isArray(event.suggestions)) {
1079
+ suggestions.value = event.suggestions.slice(0, 3);
1080
+ }
1081
+ }
1082
+ }
1083
+ } catch {
1084
+ } finally {
1085
+ isLoadingSuggestions.value = false;
1086
+ }
1087
+ }
1088
+ async function sendPrompt(prompt, currentContent, mergeTags) {
1089
+ const templateId = getTemplateId();
1090
+ if (!templateId) {
1091
+ throw new Error("Template must be saved before using AI generation");
1092
+ }
1093
+ isGenerating.value = true;
1094
+ error.value = null;
1095
+ failedPrompt.value = null;
1096
+ suggestions.value = [];
1097
+ const userMsgId = generateMessageId();
1098
+ messages.value = [
1099
+ ...messages.value,
1100
+ {
1101
+ id: userMsgId,
1102
+ role: "user",
1103
+ content: prompt,
1104
+ timestamp: Date.now()
1105
+ }
1106
+ ];
1107
+ const assistantMsgId = generateMessageId();
1108
+ messages.value = [
1109
+ ...messages.value,
1110
+ {
1111
+ id: assistantMsgId,
1112
+ role: "assistant",
1113
+ content: "",
1114
+ timestamp: Date.now()
1115
+ }
1116
+ ];
1117
+ try {
1118
+ const url = buildUrl(API_ROUTES["ai.generate"], {
1119
+ project: authManager.projectId,
1120
+ tenant: authManager.tenantSlug,
1121
+ template: templateId
1122
+ });
1123
+ const response = await authManager.authenticatedFetch(url, {
1124
+ method: "POST",
1125
+ headers: {
1126
+ "Content-Type": "application/json",
1127
+ Accept: "text/event-stream"
1128
+ },
1129
+ body: JSON.stringify({
1130
+ prompt,
1131
+ current_content: currentContent,
1132
+ merge_tags: mergeTags.map((p) => ({
1133
+ label: p.label,
1134
+ value: p.value
1135
+ })),
1136
+ conversation_id: conversationId.value
1137
+ })
1138
+ });
1139
+ if (!response.ok) {
1140
+ const errorData = await response.json().catch(() => null);
1141
+ if (response.status === 403) {
1142
+ throw new Error("ai_generation_not_available");
1143
+ }
1144
+ throw new Error(errorData?.message || "Failed to generate template");
1145
+ }
1146
+ const reader = response.body?.getReader();
1147
+ if (!reader) {
1148
+ throw new Error("Failed to read stream");
1149
+ }
1150
+ const decoder = new TextDecoder();
1151
+ let buffer = "";
1152
+ let result = null;
1153
+ while (true) {
1154
+ const { done, value } = await reader.read();
1155
+ if (done) {
1156
+ break;
1157
+ }
1158
+ buffer += decoder.decode(value, { stream: true });
1159
+ const lines = buffer.split("\n");
1160
+ buffer = lines.pop() ?? "";
1161
+ for (const line of lines) {
1162
+ if (!line.startsWith("data: ")) {
1163
+ continue;
1164
+ }
1165
+ const jsonStr = line.slice(6);
1166
+ let event;
1167
+ try {
1168
+ event = JSON.parse(jsonStr);
1169
+ } catch {
1170
+ continue;
1171
+ }
1172
+ if (event.type === "text") {
1173
+ updateMessage(assistantMsgId, {
1174
+ content: (messages.value.find((m) => m.id === assistantMsgId)?.content ?? "") + event.text
1175
+ });
1176
+ } else if (event.type === "error") {
1177
+ throw new Error(event.message || "Failed to generate template");
1178
+ } else if (event.type === "done") {
1179
+ if (event.conversation_id) {
1180
+ conversationId.value = event.conversation_id;
1181
+ }
1182
+ updateMessage(assistantMsgId, {
1183
+ content: event.text
1184
+ });
1185
+ result = event.content ?? null;
1186
+ if (result) {
1187
+ lastPreviousContent.value = currentContent;
1188
+ lastAppliedContent.value = result;
1189
+ lastApplyMessageId.value = assistantMsgId;
1190
+ isLastChangeReverted.value = false;
1191
+ onApply?.(result);
1192
+ } else {
1193
+ error.value = "ai_apply_failed";
1194
+ }
1195
+ }
1196
+ }
1197
+ }
1198
+ return result;
1199
+ } catch (err) {
1200
+ const wrappedError = err instanceof Error ? err : new Error("Failed to generate template");
1201
+ error.value = wrappedError.message;
1202
+ failedPrompt.value = prompt;
1203
+ onError?.(wrappedError);
1204
+ messages.value = messages.value.filter(
1205
+ (m) => m.id !== userMsgId && m.id !== assistantMsgId
1206
+ );
1207
+ return null;
1208
+ } finally {
1209
+ isGenerating.value = false;
1210
+ }
1211
+ }
1212
+ function toggleLastRevert() {
1213
+ if (isLastChangeReverted.value) {
1214
+ if (lastAppliedContent.value) {
1215
+ onApply?.(lastAppliedContent.value);
1216
+ }
1217
+ isLastChangeReverted.value = false;
1218
+ } else {
1219
+ if (lastPreviousContent.value) {
1220
+ onApply?.(lastPreviousContent.value);
1221
+ }
1222
+ isLastChangeReverted.value = true;
1223
+ }
1224
+ }
1225
+ function clearChat() {
1226
+ messages.value = [];
1227
+ conversationId.value = null;
1228
+ error.value = null;
1229
+ lastApplyMessageId.value = null;
1230
+ lastPreviousContent.value = null;
1231
+ lastAppliedContent.value = null;
1232
+ isLastChangeReverted.value = false;
1233
+ }
1234
+ return {
1235
+ messages,
1236
+ isGenerating,
1237
+ isLoadingHistory,
1238
+ isLastChangeReverted,
1239
+ lastApplyMessageId,
1240
+ error,
1241
+ failedPrompt,
1242
+ suggestions,
1243
+ isLoadingSuggestions,
1244
+ sendPrompt,
1245
+ toggleLastRevert,
1246
+ loadConversation,
1247
+ loadSuggestions,
1248
+ clearChat
1249
+ };
1250
+ }
1251
+
1252
+ // src/cloud/ai-rewrite.ts
1253
+ var import_vue3 = require("vue");
1254
+ function useAiRewrite(options) {
1255
+ const { authManager, getTemplateId } = options;
1256
+ const isRewriting = (0, import_vue3.ref)(false);
1257
+ const streamingText = (0, import_vue3.ref)("");
1258
+ const previousContent = (0, import_vue3.ref)(null);
1259
+ const rewrittenContent = (0, import_vue3.ref)(null);
1260
+ const isReverted = (0, import_vue3.ref)(false);
1261
+ const error = (0, import_vue3.ref)(null);
1262
+ async function rewrite(content, instruction, mergeTags) {
1263
+ const templateId = getTemplateId();
1264
+ if (!templateId) {
1265
+ return null;
1266
+ }
1267
+ isRewriting.value = true;
1268
+ streamingText.value = "";
1269
+ error.value = null;
1270
+ try {
1271
+ const url = buildUrl(API_ROUTES["ai.rewriteText"], {
1272
+ project: authManager.projectId,
1273
+ tenant: authManager.tenantSlug,
1274
+ template: templateId
1275
+ });
1276
+ const response = await authManager.authenticatedFetch(url, {
1277
+ method: "POST",
1278
+ headers: {
1279
+ "Content-Type": "application/json",
1280
+ Accept: "text/event-stream"
1281
+ },
1282
+ body: JSON.stringify({
1283
+ content,
1284
+ instruction,
1285
+ merge_tags: mergeTags.map((p) => ({
1286
+ label: p.label,
1287
+ value: p.value
1288
+ }))
1289
+ })
1290
+ });
1291
+ if (!response.ok) {
1292
+ if (response.status === 403) {
1293
+ throw new Error("ai_generation_not_available");
1294
+ }
1295
+ const errorData = await response.json().catch(() => null);
1296
+ throw new Error(errorData?.message || "Failed to rewrite text");
1297
+ }
1298
+ const reader = response.body?.getReader();
1299
+ if (!reader) {
1300
+ throw new Error("Failed to read stream");
1301
+ }
1302
+ const decoder = new TextDecoder();
1303
+ let buffer = "";
1304
+ let result = null;
1305
+ while (true) {
1306
+ const { done, value } = await reader.read();
1307
+ if (done) {
1308
+ break;
1309
+ }
1310
+ buffer += decoder.decode(value, { stream: true });
1311
+ const lines = buffer.split("\n");
1312
+ buffer = lines.pop() ?? "";
1313
+ for (const line of lines) {
1314
+ if (!line.startsWith("data: ")) {
1315
+ continue;
1316
+ }
1317
+ let event;
1318
+ try {
1319
+ event = JSON.parse(line.slice(6));
1320
+ } catch {
1321
+ continue;
1322
+ }
1323
+ if (event.type === "text") {
1324
+ streamingText.value += event.text;
1325
+ } else if (event.type === "error") {
1326
+ throw new Error(event.message || "Failed to rewrite text");
1327
+ } else if (event.type === "done") {
1328
+ result = event.content ?? null;
1329
+ if (result) {
1330
+ previousContent.value = content;
1331
+ rewrittenContent.value = result;
1332
+ isReverted.value = false;
1333
+ }
1334
+ }
1335
+ }
1336
+ }
1337
+ return result;
1338
+ } catch (err) {
1339
+ error.value = err instanceof Error ? err.message : "Failed to rewrite text";
1340
+ return null;
1341
+ } finally {
1342
+ isRewriting.value = false;
1343
+ }
1344
+ }
1345
+ function undo() {
1346
+ if (!previousContent.value) {
1347
+ return null;
1348
+ }
1349
+ isReverted.value = true;
1350
+ return previousContent.value;
1351
+ }
1352
+ function redo() {
1353
+ if (!rewrittenContent.value) {
1354
+ return null;
1355
+ }
1356
+ isReverted.value = false;
1357
+ return rewrittenContent.value;
1358
+ }
1359
+ function reset() {
1360
+ isRewriting.value = false;
1361
+ streamingText.value = "";
1362
+ previousContent.value = null;
1363
+ rewrittenContent.value = null;
1364
+ isReverted.value = false;
1365
+ error.value = null;
1366
+ }
1367
+ return {
1368
+ isRewriting,
1369
+ streamingText,
1370
+ previousContent,
1371
+ rewrittenContent,
1372
+ isReverted,
1373
+ error,
1374
+ rewrite,
1375
+ undo,
1376
+ redo,
1377
+ reset
1378
+ };
1379
+ }
1380
+
1381
+ // src/cloud/ai-config.ts
1382
+ var import_vue4 = require("vue");
1383
+ function useAiConfig(config) {
1384
+ function isFeatureEnabled(feature) {
1385
+ if (config === false) {
1386
+ return false;
1387
+ }
1388
+ return config?.[feature] !== false;
1389
+ }
1390
+ const hasAnyMenuFeature = (0, import_vue4.computed)(
1391
+ () => isFeatureEnabled("chat") || isFeatureEnabled("scoring") || isFeatureEnabled("designToTemplate")
1392
+ );
1393
+ return {
1394
+ isFeatureEnabled,
1395
+ hasAnyMenuFeature
1396
+ };
1397
+ }
1398
+
1399
+ // src/cloud/template-scoring.ts
1400
+ var import_vue5 = require("vue");
1401
+ function useTemplateScoring(options) {
1402
+ const { authManager, getTemplateId } = options;
1403
+ const isScoring = (0, import_vue5.ref)(false);
1404
+ const scoringResult = (0, import_vue5.ref)(null);
1405
+ const error = (0, import_vue5.ref)(null);
1406
+ const fixingFindingId = (0, import_vue5.ref)(null);
1407
+ const fixStreamingText = (0, import_vue5.ref)("");
1408
+ const fixError = (0, import_vue5.ref)(null);
1409
+ async function score(content, mergeTags) {
1410
+ const templateId = getTemplateId();
1411
+ if (!templateId) {
1412
+ return null;
1413
+ }
1414
+ isScoring.value = true;
1415
+ error.value = null;
1416
+ scoringResult.value = null;
1417
+ try {
1418
+ const url = buildUrl(API_ROUTES["ai.score"], {
1419
+ project: authManager.projectId,
1420
+ tenant: authManager.tenantSlug,
1421
+ template: templateId
1422
+ });
1423
+ const response = await authManager.authenticatedFetch(url, {
1424
+ method: "POST",
1425
+ headers: {
1426
+ "Content-Type": "application/json",
1427
+ Accept: "text/event-stream"
1428
+ },
1429
+ body: JSON.stringify({
1430
+ current_content: content,
1431
+ merge_tags: mergeTags.map((p) => ({
1432
+ label: p.label,
1433
+ value: p.value
1434
+ }))
1435
+ })
1436
+ });
1437
+ if (!response.ok) {
1438
+ if (response.status === 403) {
1439
+ throw new Error("ai_generation_not_available");
1440
+ }
1441
+ const errorData = await response.json().catch(() => null);
1442
+ throw new Error(errorData?.message || "Failed to score template");
1443
+ }
1444
+ const reader = response.body?.getReader();
1445
+ if (!reader) {
1446
+ throw new Error("Failed to read stream");
1447
+ }
1448
+ const decoder = new TextDecoder();
1449
+ let buffer = "";
1450
+ let result = null;
1451
+ while (true) {
1452
+ const { done, value } = await reader.read();
1453
+ if (done) {
1454
+ break;
1455
+ }
1456
+ buffer += decoder.decode(value, { stream: true });
1457
+ const lines = buffer.split("\n");
1458
+ buffer = lines.pop() ?? "";
1459
+ for (const line of lines) {
1460
+ if (!line.startsWith("data: ")) {
1461
+ continue;
1462
+ }
1463
+ let event;
1464
+ try {
1465
+ event = JSON.parse(line.slice(6));
1466
+ } catch {
1467
+ continue;
1468
+ }
1469
+ if (event.type === "error") {
1470
+ throw new Error(event.message || "Failed to score template");
1471
+ }
1472
+ if (event.type === "done") {
1473
+ result = event.result ?? null;
1474
+ }
1475
+ }
1476
+ }
1477
+ if (result) {
1478
+ for (const [category, categoryData] of Object.entries(
1479
+ result.categories
1480
+ )) {
1481
+ for (const finding of categoryData.findings) {
1482
+ finding.category = category;
1483
+ }
1484
+ }
1485
+ }
1486
+ scoringResult.value = result;
1487
+ return result;
1488
+ } catch (err) {
1489
+ error.value = err instanceof Error ? err.message : "Failed to score template";
1490
+ return null;
1491
+ } finally {
1492
+ isScoring.value = false;
1493
+ }
1494
+ }
1495
+ async function fixFinding(blockContent, finding, mergeTags) {
1496
+ const templateId = getTemplateId();
1497
+ if (!templateId) {
1498
+ return null;
1499
+ }
1500
+ fixingFindingId.value = finding.id;
1501
+ fixStreamingText.value = "";
1502
+ fixError.value = null;
1503
+ try {
1504
+ const url = buildUrl(API_ROUTES["ai.fixFinding"], {
1505
+ project: authManager.projectId,
1506
+ tenant: authManager.tenantSlug,
1507
+ template: templateId
1508
+ });
1509
+ const response = await authManager.authenticatedFetch(url, {
1510
+ method: "POST",
1511
+ headers: {
1512
+ "Content-Type": "application/json",
1513
+ Accept: "text/event-stream"
1514
+ },
1515
+ body: JSON.stringify({
1516
+ content: blockContent,
1517
+ finding: {
1518
+ id: finding.id,
1519
+ message: finding.message,
1520
+ suggestion: finding.suggestion,
1521
+ category: finding.category
1522
+ },
1523
+ merge_tags: mergeTags.map((p) => ({
1524
+ label: p.label,
1525
+ value: p.value
1526
+ }))
1527
+ })
1528
+ });
1529
+ if (!response.ok) {
1530
+ if (response.status === 403) {
1531
+ throw new Error("ai_generation_not_available");
1532
+ }
1533
+ const errorData = await response.json().catch(() => null);
1534
+ throw new Error(errorData?.message || "Failed to fix finding");
1535
+ }
1536
+ const reader = response.body?.getReader();
1537
+ if (!reader) {
1538
+ throw new Error("Failed to read stream");
1539
+ }
1540
+ const decoder = new TextDecoder();
1541
+ let buffer = "";
1542
+ let result = null;
1543
+ while (true) {
1544
+ const { done, value } = await reader.read();
1545
+ if (done) {
1546
+ break;
1547
+ }
1548
+ buffer += decoder.decode(value, { stream: true });
1549
+ const lines = buffer.split("\n");
1550
+ buffer = lines.pop() ?? "";
1551
+ for (const line of lines) {
1552
+ if (!line.startsWith("data: ")) {
1553
+ continue;
1554
+ }
1555
+ let event;
1556
+ try {
1557
+ event = JSON.parse(line.slice(6));
1558
+ } catch {
1559
+ continue;
1560
+ }
1561
+ if (event.type === "text") {
1562
+ fixStreamingText.value += event.text;
1563
+ } else if (event.type === "error") {
1564
+ throw new Error(event.message || "Failed to fix finding");
1565
+ } else if (event.type === "done") {
1566
+ result = event.content ?? null;
1567
+ }
1568
+ }
1569
+ }
1570
+ return result;
1571
+ } catch (err) {
1572
+ fixError.value = err instanceof Error ? err.message : "Failed to fix finding";
1573
+ return null;
1574
+ } finally {
1575
+ fixingFindingId.value = null;
1576
+ }
1577
+ }
1578
+ function removeFinding(category, findingId) {
1579
+ if (!scoringResult.value) {
1580
+ return;
1581
+ }
1582
+ const cat = scoringResult.value.categories[category];
1583
+ if (!cat) {
1584
+ return;
1585
+ }
1586
+ cat.findings = cat.findings.filter((f) => f.id !== findingId);
1587
+ }
1588
+ function reset() {
1589
+ isScoring.value = false;
1590
+ scoringResult.value = null;
1591
+ error.value = null;
1592
+ fixingFindingId.value = null;
1593
+ fixStreamingText.value = "";
1594
+ fixError.value = null;
1595
+ }
1596
+ return {
1597
+ isScoring,
1598
+ scoringResult,
1599
+ error,
1600
+ fixingFindingId,
1601
+ fixStreamingText,
1602
+ fixError,
1603
+ score,
1604
+ fixFinding,
1605
+ removeFinding,
1606
+ reset
1607
+ };
1608
+ }
1609
+
1610
+ // src/cloud/design-reference.ts
1611
+ var import_vue6 = require("vue");
1612
+ function useDesignReference(options) {
1613
+ const { authManager, getTemplateId, onApply, onError } = options;
1614
+ const isGenerating = (0, import_vue6.ref)(false);
1615
+ const error = (0, import_vue6.ref)(null);
1616
+ async function generate(input) {
1617
+ const templateId = getTemplateId();
1618
+ if (!templateId) {
1619
+ throw new Error("Template must be saved before using design reference");
1620
+ }
1621
+ isGenerating.value = true;
1622
+ error.value = null;
1623
+ try {
1624
+ const formData = new FormData();
1625
+ if (input.prompt) {
1626
+ formData.append("prompt", input.prompt);
1627
+ }
1628
+ if (input.imageUpload) {
1629
+ formData.append("image_upload", input.imageUpload);
1630
+ }
1631
+ if (input.pdfUpload) {
1632
+ formData.append("pdf_upload", input.pdfUpload);
1633
+ }
1634
+ const url = buildUrl(API_ROUTES["ai.generateFromDesign"], {
1635
+ project: authManager.projectId,
1636
+ tenant: authManager.tenantSlug,
1637
+ template: templateId
1638
+ });
1639
+ const response = await authManager.authenticatedFetch(url, {
1640
+ method: "POST",
1641
+ headers: {
1642
+ Accept: "text/event-stream"
1643
+ },
1644
+ body: formData
1645
+ });
1646
+ if (!response.ok) {
1647
+ const errorData = await response.json().catch(() => null);
1648
+ if (response.status === 403) {
1649
+ throw new Error("ai_generation_not_available");
1650
+ }
1651
+ throw new Error(
1652
+ errorData?.message || "Failed to generate template from design"
1653
+ );
1654
+ }
1655
+ const reader = response.body?.getReader();
1656
+ if (!reader) {
1657
+ throw new Error("Failed to read stream");
1658
+ }
1659
+ const decoder = new TextDecoder();
1660
+ let buffer = "";
1661
+ let result = null;
1662
+ while (true) {
1663
+ const { done, value } = await reader.read();
1664
+ if (done) {
1665
+ break;
1666
+ }
1667
+ buffer += decoder.decode(value, { stream: true });
1668
+ const lines = buffer.split("\n");
1669
+ buffer = lines.pop() ?? "";
1670
+ for (const line of lines) {
1671
+ if (!line.startsWith("data: ")) {
1672
+ continue;
1673
+ }
1674
+ const jsonStr = line.slice(6);
1675
+ let event;
1676
+ try {
1677
+ event = JSON.parse(jsonStr);
1678
+ } catch {
1679
+ continue;
1680
+ }
1681
+ if (event.type === "error") {
1682
+ throw new Error(
1683
+ event.message || "Failed to generate template from design"
1684
+ );
1685
+ }
1686
+ if (event.type === "done") {
1687
+ result = event.content ?? null;
1688
+ if (result) {
1689
+ onApply?.(result);
1690
+ }
1691
+ }
1692
+ }
1693
+ }
1694
+ return result;
1695
+ } catch (err) {
1696
+ const wrappedError = err instanceof Error ? err : new Error("Failed to generate template from design");
1697
+ error.value = wrappedError.message;
1698
+ onError?.(wrappedError);
1699
+ return null;
1700
+ } finally {
1701
+ isGenerating.value = false;
1702
+ }
1703
+ }
1704
+ function reset() {
1705
+ isGenerating.value = false;
1706
+ error.value = null;
1707
+ }
1708
+ return {
1709
+ isGenerating,
1710
+ error,
1711
+ generate,
1712
+ reset
1713
+ };
1714
+ }
1715
+
1716
+ // src/cloud/comments.ts
1717
+ var import_vue7 = require("vue");
1718
+ function useComments(options) {
1719
+ const {
1720
+ authManager,
1721
+ getTemplateId,
1722
+ getSocketId,
1723
+ onComment,
1724
+ onError,
1725
+ hasCommentingFeature
1726
+ } = options;
1727
+ const api = new ApiClient(authManager);
1728
+ const comments = (0, import_vue7.ref)([]);
1729
+ const isLoading = (0, import_vue7.ref)(false);
1730
+ const isSubmitting = (0, import_vue7.ref)(false);
1731
+ const isEnabled = (0, import_vue7.computed)(() => {
1732
+ const featureAvailable = hasCommentingFeature?.() ?? false;
1733
+ return featureAvailable && authManager.userConfig !== null;
1734
+ });
1735
+ const totalCount = (0, import_vue7.computed)(() => {
1736
+ let count = 0;
1737
+ for (const thread of comments.value) {
1738
+ count += 1 + (thread.replies?.length ?? 0);
1739
+ }
1740
+ return count;
1741
+ });
1742
+ const unresolvedCount = (0, import_vue7.computed)(() => {
1743
+ return comments.value.filter((c) => !c.resolved_at).length;
1744
+ });
1745
+ const commentCountByBlock = (0, import_vue7.computed)(() => {
1746
+ const map = /* @__PURE__ */ new Map();
1747
+ for (const thread of comments.value) {
1748
+ if (thread.block_id) {
1749
+ map.set(
1750
+ thread.block_id,
1751
+ (map.get(thread.block_id) ?? 0) + 1 + (thread.replies?.length ?? 0)
1752
+ );
1753
+ }
1754
+ }
1755
+ return map;
1756
+ });
1757
+ function getUserPayload() {
1758
+ const user = authManager.userConfig;
1759
+ if (!user) {
1760
+ throw new Error("User config not available");
1761
+ }
1762
+ return {
1763
+ user_id: user.id,
1764
+ user_name: user.name,
1765
+ user_signature: user.signature
1766
+ };
1767
+ }
1768
+ function socketHeaders() {
1769
+ const socketId = getSocketId?.();
1770
+ if (!socketId) {
1771
+ return void 0;
1772
+ }
1773
+ return { "X-Socket-ID": socketId };
1774
+ }
1775
+ function emitEvent(type, comment) {
1776
+ onComment?.({ type, comment });
1777
+ }
1778
+ function findComment(commentId) {
1779
+ for (const thread of comments.value) {
1780
+ if (thread.id === commentId) {
1781
+ return thread;
1782
+ }
1783
+ for (const reply of thread.replies ?? []) {
1784
+ if (reply.id === commentId) {
1785
+ return reply;
1786
+ }
1787
+ }
1788
+ }
1789
+ return null;
1790
+ }
1791
+ async function loadComments() {
1792
+ const templateId = getTemplateId();
1793
+ if (!templateId) {
1794
+ return;
1795
+ }
1796
+ isLoading.value = true;
1797
+ try {
1798
+ comments.value = await api.getComments(templateId);
1799
+ } catch (err) {
1800
+ const wrappedError = err instanceof Error ? err : new Error("Failed to load comments");
1801
+ onError?.(wrappedError);
1802
+ } finally {
1803
+ isLoading.value = false;
1804
+ }
1805
+ }
1806
+ async function addComment(body, blockId, parentId) {
1807
+ const templateId = getTemplateId();
1808
+ if (!templateId) {
1809
+ return null;
1810
+ }
1811
+ isSubmitting.value = true;
1812
+ try {
1813
+ const comment = await api.createComment(
1814
+ templateId,
1815
+ {
1816
+ body,
1817
+ block_id: blockId,
1818
+ parent_id: parentId,
1819
+ ...getUserPayload()
1820
+ },
1821
+ socketHeaders()
1822
+ );
1823
+ if (parentId) {
1824
+ const parent = findComment(parentId);
1825
+ if (parent) {
1826
+ parent.replies = [...parent.replies ?? [], comment];
1827
+ }
1828
+ } else {
1829
+ comments.value = [...comments.value, comment];
1830
+ }
1831
+ emitEvent("created", comment);
1832
+ return comment;
1833
+ } catch (err) {
1834
+ const wrappedError = err instanceof Error ? err : new Error("Failed to create comment");
1835
+ onError?.(wrappedError);
1836
+ return null;
1837
+ } finally {
1838
+ isSubmitting.value = false;
1839
+ }
1840
+ }
1841
+ async function editComment(commentId, body) {
1842
+ const templateId = getTemplateId();
1843
+ if (!templateId) {
1844
+ return null;
1845
+ }
1846
+ isSubmitting.value = true;
1847
+ try {
1848
+ const updated = await api.updateComment(
1849
+ templateId,
1850
+ commentId,
1851
+ {
1852
+ body,
1853
+ ...getUserPayload()
1854
+ },
1855
+ socketHeaders()
1856
+ );
1857
+ updateCommentInState(commentId, updated);
1858
+ emitEvent("updated", updated);
1859
+ return updated;
1860
+ } catch (err) {
1861
+ const wrappedError = err instanceof Error ? err : new Error("Failed to update comment");
1862
+ onError?.(wrappedError);
1863
+ return null;
1864
+ } finally {
1865
+ isSubmitting.value = false;
1866
+ }
1867
+ }
1868
+ async function removeComment(commentId) {
1869
+ const templateId = getTemplateId();
1870
+ if (!templateId) {
1871
+ return false;
1872
+ }
1873
+ const comment = findComment(commentId);
1874
+ if (!comment) {
1875
+ return false;
1876
+ }
1877
+ const commentSnapshot = {
1878
+ ...comment,
1879
+ replies: [...comment.replies ?? []]
1880
+ };
1881
+ isSubmitting.value = true;
1882
+ try {
1883
+ await api.deleteComment(
1884
+ templateId,
1885
+ commentId,
1886
+ getUserPayload(),
1887
+ socketHeaders()
1888
+ );
1889
+ if (comment.parent_id) {
1890
+ const parent = findComment(comment.parent_id);
1891
+ if (parent) {
1892
+ parent.replies = (parent.replies ?? []).filter(
1893
+ (r) => r.id !== commentId
1894
+ );
1895
+ }
1896
+ } else {
1897
+ comments.value = comments.value.filter((c) => c.id !== commentId);
1898
+ }
1899
+ emitEvent("deleted", commentSnapshot);
1900
+ return true;
1901
+ } catch (err) {
1902
+ const wrappedError = err instanceof Error ? err : new Error("Failed to delete comment");
1903
+ onError?.(wrappedError);
1904
+ return false;
1905
+ } finally {
1906
+ isSubmitting.value = false;
1907
+ }
1908
+ }
1909
+ async function toggleResolve(commentId) {
1910
+ const templateId = getTemplateId();
1911
+ if (!templateId) {
1912
+ return null;
1913
+ }
1914
+ isSubmitting.value = true;
1915
+ try {
1916
+ const updated = await api.resolveComment(
1917
+ templateId,
1918
+ commentId,
1919
+ getUserPayload(),
1920
+ socketHeaders()
1921
+ );
1922
+ updateCommentInState(commentId, updated);
1923
+ const eventType = updated.resolved_at ? "resolved" : "unresolved";
1924
+ emitEvent(eventType, updated);
1925
+ return updated;
1926
+ } catch (err) {
1927
+ const wrappedError = err instanceof Error ? err : new Error("Failed to toggle comment resolution");
1928
+ onError?.(wrappedError);
1929
+ return null;
1930
+ } finally {
1931
+ isSubmitting.value = false;
1932
+ }
1933
+ }
1934
+ function applyRemoteCreate(comment) {
1935
+ if (comment.parent_id) {
1936
+ const parent = findComment(comment.parent_id);
1937
+ if (parent) {
1938
+ parent.replies = [...parent.replies ?? [], comment];
1939
+ }
1940
+ } else {
1941
+ comments.value = [...comments.value, comment];
1942
+ }
1943
+ emitEvent("created", comment);
1944
+ }
1945
+ function applyRemoteUpdate(comment) {
1946
+ updateCommentInState(comment.id, comment);
1947
+ emitEvent("updated", comment);
1948
+ }
1949
+ function applyRemoteDelete(commentId, parentId) {
1950
+ const comment = findComment(commentId);
1951
+ const snapshot = comment ? { ...comment, replies: [...comment.replies ?? []] } : null;
1952
+ if (parentId) {
1953
+ const parent = findComment(parentId);
1954
+ if (parent) {
1955
+ parent.replies = (parent.replies ?? []).filter(
1956
+ (r) => r.id !== commentId
1957
+ );
1958
+ }
1959
+ } else {
1960
+ comments.value = comments.value.filter((c) => c.id !== commentId);
1961
+ }
1962
+ if (snapshot) {
1963
+ emitEvent("deleted", snapshot);
1964
+ }
1965
+ }
1966
+ function updateCommentInState(commentId, updated) {
1967
+ for (let i = 0; i < comments.value.length; i++) {
1968
+ if (comments.value[i].id === commentId) {
1969
+ comments.value = [
1970
+ ...comments.value.slice(0, i),
1971
+ { ...updated, replies: comments.value[i].replies },
1972
+ ...comments.value.slice(i + 1)
1973
+ ];
1974
+ return;
1975
+ }
1976
+ const replies = comments.value[i].replies ?? [];
1977
+ for (let j = 0; j < replies.length; j++) {
1978
+ if (replies[j].id === commentId) {
1979
+ const newReplies = [
1980
+ ...replies.slice(0, j),
1981
+ updated,
1982
+ ...replies.slice(j + 1)
1983
+ ];
1984
+ comments.value = [
1985
+ ...comments.value.slice(0, i),
1986
+ { ...comments.value[i], replies: newReplies },
1987
+ ...comments.value.slice(i + 1)
1988
+ ];
1989
+ return;
1990
+ }
1991
+ }
1992
+ }
1993
+ }
1994
+ return {
1995
+ comments,
1996
+ isLoading,
1997
+ isSubmitting,
1998
+ isEnabled,
1999
+ commentCountByBlock,
2000
+ totalCount,
2001
+ unresolvedCount,
2002
+ loadComments,
2003
+ addComment,
2004
+ editComment,
2005
+ removeComment,
2006
+ toggleResolve,
2007
+ applyRemoteCreate,
2008
+ applyRemoteUpdate,
2009
+ applyRemoteDelete
2010
+ };
2011
+ }
2012
+
2013
+ // src/cloud/comment-listener.ts
2014
+ var import_vue8 = require("vue");
2015
+ function useCommentListener(options) {
2016
+ const { comments, channel } = options;
2017
+ (0, import_vue8.watch)(channel, (newChannel, oldChannel) => {
2018
+ if (oldChannel) {
2019
+ oldChannel.unbind("comment-broadcast");
2020
+ }
2021
+ if (newChannel) {
2022
+ newChannel.bind(
2023
+ "comment-broadcast",
2024
+ (payload) => {
2025
+ handleCommentBroadcast(comments, payload);
2026
+ }
2027
+ );
2028
+ }
2029
+ });
2030
+ }
2031
+ function handleCommentBroadcast(comments, payload) {
2032
+ switch (payload.action) {
2033
+ case "comment_created":
2034
+ comments.applyRemoteCreate(payload.comment);
2035
+ break;
2036
+ case "comment_updated":
2037
+ comments.applyRemoteUpdate(payload.comment);
2038
+ break;
2039
+ case "comment_deleted":
2040
+ comments.applyRemoteDelete(payload.comment.id, payload.comment.parent_id);
2041
+ break;
2042
+ case "comment_resolved":
2043
+ case "comment_unresolved":
2044
+ comments.applyRemoteUpdate(payload.comment);
2045
+ break;
2046
+ }
2047
+ }
2048
+
2049
+ // src/cloud/collaboration.ts
2050
+ var import_vue9 = require("vue");
2051
+ var COLLABORATOR_COLORS = [
2052
+ "#3b82f6",
2053
+ "#ef4444",
2054
+ "#10b981",
2055
+ "#f59e0b",
2056
+ "#8b5cf6",
2057
+ "#ec4899",
2058
+ "#06b6d4",
2059
+ "#f97316",
2060
+ "#6366f1",
2061
+ "#14b8a6"
2062
+ ];
2063
+ function useCollaboration(options) {
2064
+ const { authManager, editor, channel } = options;
2065
+ const collaborators = (0, import_vue9.ref)([]);
2066
+ const lockedBlocks = (0, import_vue9.ref)(/* @__PURE__ */ new Map());
2067
+ let colorIndex = 0;
2068
+ let isProcessingRemoteOperation = false;
2069
+ const myUserId = (0, import_vue9.computed)(() => authManager.userConfig?.id ?? "");
2070
+ function assignColor() {
2071
+ const color = COLLABORATOR_COLORS[colorIndex % COLLABORATOR_COLORS.length];
2072
+ colorIndex++;
2073
+ return color;
2074
+ }
2075
+ function addCollaborator(member) {
2076
+ if (member.id === myUserId.value) {
2077
+ return void 0;
2078
+ }
2079
+ if (collaborators.value.some((c) => c.id === member.id)) {
2080
+ return void 0;
2081
+ }
2082
+ const collaborator = {
2083
+ id: member.id,
2084
+ name: member.name,
2085
+ color: assignColor(),
2086
+ selectedBlockId: null
2087
+ };
2088
+ collaborators.value = [...collaborators.value, collaborator];
2089
+ return collaborator;
2090
+ }
2091
+ function removeCollaborator(memberId) {
2092
+ const newLockedBlocks = new Map(lockedBlocks.value);
2093
+ for (const [blockId, collaborator] of newLockedBlocks) {
2094
+ if (collaborator.id === memberId) {
2095
+ newLockedBlocks.delete(blockId);
2096
+ }
2097
+ }
2098
+ lockedBlocks.value = newLockedBlocks;
2099
+ collaborators.value = collaborators.value.filter((c) => c.id !== memberId);
2100
+ }
2101
+ function handleBlockLocked(data) {
2102
+ const collaborator = collaborators.value.find((c) => c.id === data.userId);
2103
+ if (!collaborator) {
2104
+ return;
2105
+ }
2106
+ collaborators.value = collaborators.value.map(
2107
+ (c) => c.id === data.userId ? { ...c, selectedBlockId: data.blockId } : c
2108
+ );
2109
+ const newLockedBlocks = new Map(lockedBlocks.value);
2110
+ for (const [blockId, holder] of newLockedBlocks) {
2111
+ if (holder.id === data.userId) {
2112
+ newLockedBlocks.delete(blockId);
2113
+ }
2114
+ }
2115
+ newLockedBlocks.set(data.blockId, {
2116
+ ...collaborator,
2117
+ selectedBlockId: data.blockId
2118
+ });
2119
+ lockedBlocks.value = newLockedBlocks;
2120
+ if (editor.state.selectedBlockId === data.blockId) {
2121
+ editor.selectBlock(null);
2122
+ }
2123
+ }
2124
+ function handleBlockUnlocked(data) {
2125
+ const newLockedBlocks = new Map(lockedBlocks.value);
2126
+ const holder = newLockedBlocks.get(data.blockId);
2127
+ newLockedBlocks.delete(data.blockId);
2128
+ lockedBlocks.value = newLockedBlocks;
2129
+ if (holder) {
2130
+ collaborators.value = collaborators.value.map(
2131
+ (c) => c.id === holder.id ? { ...c, selectedBlockId: null } : c
2132
+ );
2133
+ }
2134
+ }
2135
+ function handleRemoteOperation(payload) {
2136
+ isProcessingRemoteOperation = true;
2137
+ try {
2138
+ handleOperation(editor, payload);
2139
+ } finally {
2140
+ isProcessingRemoteOperation = false;
2141
+ }
2142
+ }
2143
+ function broadcastOperation(payload) {
2144
+ if (!channel.value || isProcessingRemoteOperation) {
2145
+ return;
2146
+ }
2147
+ channel.value.trigger("client-operation", payload);
2148
+ }
2149
+ function broadcastBlockLocked(blockId) {
2150
+ if (!channel.value) {
2151
+ return;
2152
+ }
2153
+ channel.value.trigger("client-block_locked", {
2154
+ blockId,
2155
+ userId: myUserId.value
2156
+ });
2157
+ }
2158
+ function broadcastBlockUnlocked(blockId) {
2159
+ if (!channel.value) {
2160
+ return;
2161
+ }
2162
+ channel.value.trigger("client-block_unlocked", { blockId });
2163
+ }
2164
+ (0, import_vue9.watch)(
2165
+ () => editor.state.selectedBlockId,
2166
+ (newBlockId, oldBlockId) => {
2167
+ if (isProcessingRemoteOperation) {
2168
+ return;
2169
+ }
2170
+ if (oldBlockId) {
2171
+ broadcastBlockUnlocked(oldBlockId);
2172
+ }
2173
+ if (newBlockId) {
2174
+ broadcastBlockLocked(newBlockId);
2175
+ }
2176
+ }
2177
+ );
2178
+ (0, import_vue9.watch)(channel, (newChannel, oldChannel) => {
2179
+ if (oldChannel) {
2180
+ oldChannel.unbind("pusher:member_added");
2181
+ oldChannel.unbind("pusher:member_removed");
2182
+ oldChannel.unbind("client-block_locked");
2183
+ oldChannel.unbind("client-block_unlocked");
2184
+ oldChannel.unbind("client-operation");
2185
+ oldChannel.unbind("mcp-operation");
2186
+ }
2187
+ if (!newChannel) {
2188
+ collaborators.value = [];
2189
+ lockedBlocks.value = /* @__PURE__ */ new Map();
2190
+ colorIndex = 0;
2191
+ return;
2192
+ }
2193
+ const members = newChannel.members;
2194
+ if (members) {
2195
+ members.each((member) => {
2196
+ addCollaborator(member.info);
2197
+ });
2198
+ }
2199
+ newChannel.bind(
2200
+ "pusher:member_added",
2201
+ (member) => {
2202
+ const collaborator = addCollaborator(member.info);
2203
+ if (collaborator) {
2204
+ options.onCollaboratorJoined?.(collaborator);
2205
+ }
2206
+ }
2207
+ );
2208
+ newChannel.bind(
2209
+ "pusher:member_removed",
2210
+ (member) => {
2211
+ const collaborator = collaborators.value.find(
2212
+ (c) => c.id === member.id
2213
+ );
2214
+ removeCollaborator(member.id);
2215
+ if (collaborator) {
2216
+ options.onCollaboratorLeft?.(collaborator);
2217
+ }
2218
+ }
2219
+ );
2220
+ newChannel.bind(
2221
+ "client-block_locked",
2222
+ (data) => {
2223
+ handleBlockLocked(data);
2224
+ const collaborator = collaborators.value.find(
2225
+ (c) => c.id === data.userId
2226
+ );
2227
+ if (collaborator) {
2228
+ options.onBlockLocked?.({
2229
+ blockId: data.blockId,
2230
+ collaborator
2231
+ });
2232
+ }
2233
+ }
2234
+ );
2235
+ newChannel.bind("client-block_unlocked", (data) => {
2236
+ const holder = lockedBlocks.value.get(data.blockId);
2237
+ handleBlockUnlocked(data);
2238
+ if (holder) {
2239
+ options.onBlockUnlocked?.({
2240
+ blockId: data.blockId,
2241
+ collaborator: holder
2242
+ });
2243
+ }
2244
+ });
2245
+ newChannel.bind("client-operation", (payload) => {
2246
+ handleRemoteOperation(payload);
2247
+ });
2248
+ newChannel.bind("mcp-operation", (payload) => {
2249
+ handleRemoteOperation(payload);
2250
+ });
2251
+ });
2252
+ return {
2253
+ collaborators,
2254
+ lockedBlocks,
2255
+ _broadcastOperation: broadcastOperation,
2256
+ _isProcessingRemoteOperation: () => isProcessingRemoteOperation
2257
+ };
2258
+ }
2259
+
2260
+ // src/cloud/web-socket.ts
2261
+ var import_vue10 = require("vue");
2262
+ function useWebSocket(options) {
2263
+ const { authManager, onError } = options;
2264
+ const channel = (0, import_vue10.ref)(
2265
+ null
2266
+ );
2267
+ const isConnected = (0, import_vue10.ref)(false);
2268
+ let wsClient = null;
2269
+ let channelName = null;
2270
+ async function connect(templateId, config) {
2271
+ if (wsClient) {
2272
+ return;
2273
+ }
2274
+ wsClient = new WebSocketClient({
2275
+ authManager,
2276
+ config,
2277
+ onError
2278
+ });
2279
+ await wsClient.connect();
2280
+ channelName = `presence-template.${templateId}`;
2281
+ const presenceChannel = wsClient.subscribePresence(channelName);
2282
+ presenceChannel.bind("pusher:subscription_succeeded", () => {
2283
+ isConnected.value = true;
2284
+ channel.value = presenceChannel;
2285
+ });
2286
+ presenceChannel.bind("pusher:subscription_error", (error) => {
2287
+ isConnected.value = false;
2288
+ channel.value = null;
2289
+ onError?.(
2290
+ error instanceof Error ? error : new Error("Failed to subscribe to template channel")
2291
+ );
2292
+ });
2293
+ }
2294
+ function disconnect() {
2295
+ if (channelName && wsClient) {
2296
+ wsClient.unsubscribe(channelName);
2297
+ }
2298
+ wsClient?.disconnect();
2299
+ wsClient = null;
2300
+ channelName = null;
2301
+ channel.value = null;
2302
+ isConnected.value = false;
2303
+ }
2304
+ function getSocketId() {
2305
+ return wsClient?.getSocketId() ?? null;
2306
+ }
2307
+ return {
2308
+ channel,
2309
+ isConnected,
2310
+ connect,
2311
+ disconnect,
2312
+ getSocketId
2313
+ };
2314
+ }
2315
+
2316
+ // src/cloud/saved-modules.ts
2317
+ var import_vue11 = require("vue");
2318
+ function useSavedModules(options) {
2319
+ const api = new ApiClient(options.authManager);
2320
+ const modules = (0, import_vue11.ref)([]);
2321
+ const isLoading = (0, import_vue11.ref)(false);
2322
+ async function loadModules(search) {
2323
+ isLoading.value = true;
2324
+ try {
2325
+ modules.value = await api.listModules(search);
2326
+ } catch (error) {
2327
+ options.onError?.(error);
2328
+ throw error;
2329
+ } finally {
2330
+ isLoading.value = false;
2331
+ }
2332
+ }
2333
+ async function createModule(name, content) {
2334
+ try {
2335
+ const module2 = await api.createModule({ name, content });
2336
+ modules.value = [module2, ...modules.value];
2337
+ return module2;
2338
+ } catch (error) {
2339
+ options.onError?.(error);
2340
+ throw error;
2341
+ }
2342
+ }
2343
+ async function updateModule(id, data) {
2344
+ try {
2345
+ const updated = await api.updateModule(id, data);
2346
+ modules.value = modules.value.map((m) => m.id === id ? updated : m);
2347
+ return updated;
2348
+ } catch (error) {
2349
+ options.onError?.(error);
2350
+ throw error;
2351
+ }
2352
+ }
2353
+ async function deleteModule(id) {
2354
+ try {
2355
+ await api.deleteModule(id);
2356
+ modules.value = modules.value.filter((m) => m.id !== id);
2357
+ } catch (error) {
2358
+ options.onError?.(error);
2359
+ throw error;
2360
+ }
2361
+ }
2362
+ return {
2363
+ modules,
2364
+ isLoading,
2365
+ loadModules,
2366
+ createModule,
2367
+ updateModule,
2368
+ deleteModule
2369
+ };
2370
+ }
2371
+
2372
+ // src/cloud/snapshots.ts
2373
+ var import_vue12 = require("vue");
2374
+ function useSnapshotHistory(options) {
2375
+ const api = new ApiClient(options.authManager);
2376
+ const snapshots = (0, import_vue12.ref)([]);
2377
+ const isLoading = (0, import_vue12.ref)(false);
2378
+ const isRestoring = (0, import_vue12.ref)(false);
2379
+ async function loadSnapshots() {
2380
+ isLoading.value = true;
2381
+ try {
2382
+ snapshots.value = await api.getSnapshots(options.templateId);
2383
+ } catch (error) {
2384
+ options.onError?.(error);
2385
+ throw error;
2386
+ } finally {
2387
+ isLoading.value = false;
2388
+ }
2389
+ }
2390
+ async function restoreSnapshot(snapshotId) {
2391
+ isRestoring.value = true;
2392
+ try {
2393
+ const template = await api.restoreSnapshot(
2394
+ options.templateId,
2395
+ snapshotId
2396
+ );
2397
+ options.onRestore?.(template);
2398
+ return template;
2399
+ } catch (error) {
2400
+ options.onError?.(error);
2401
+ throw error;
2402
+ } finally {
2403
+ isRestoring.value = false;
2404
+ }
2405
+ }
2406
+ return {
2407
+ snapshots,
2408
+ isLoading,
2409
+ isRestoring,
2410
+ loadSnapshots,
2411
+ restoreSnapshot
2412
+ };
2413
+ }
2414
+
2415
+ // src/cloud/test-email.ts
2416
+ var import_vue13 = require("vue");
2417
+ function useTestEmail(options) {
2418
+ const {
2419
+ authManager,
2420
+ getTemplateId,
2421
+ save,
2422
+ exportHtml,
2423
+ onError,
2424
+ isAuthReady,
2425
+ onBeforeTestEmail
2426
+ } = options;
2427
+ const api = new ApiClient(authManager);
2428
+ const isSending = (0, import_vue13.ref)(false);
2429
+ const error = (0, import_vue13.ref)(null);
2430
+ const testEmailConfig = (0, import_vue13.ref)(null);
2431
+ if (isAuthReady) {
2432
+ (0, import_vue13.watch)(
2433
+ isAuthReady,
2434
+ (ready) => {
2435
+ if (ready) {
2436
+ testEmailConfig.value = authManager.testEmailConfig;
2437
+ }
2438
+ },
2439
+ { immediate: true }
2440
+ );
2441
+ }
2442
+ const isEnabled = (0, import_vue13.computed)(() => testEmailConfig.value !== null);
2443
+ const allowedEmails = (0, import_vue13.computed)(
2444
+ () => testEmailConfig.value?.allowedEmails ?? []
2445
+ );
2446
+ async function sendTestEmail(recipient) {
2447
+ if (!testEmailConfig.value) {
2448
+ throw new Error("Test email is not enabled for this project");
2449
+ }
2450
+ const templateId = getTemplateId();
2451
+ if (!templateId) {
2452
+ throw new Error("Template must be saved before sending a test email");
2453
+ }
2454
+ isSending.value = true;
2455
+ error.value = null;
2456
+ try {
2457
+ await save();
2458
+ let { html } = await exportHtml(templateId);
2459
+ if (onBeforeTestEmail) {
2460
+ html = await onBeforeTestEmail(html);
2461
+ }
2462
+ await api.sendTestEmail(templateId, {
2463
+ recipient,
2464
+ html,
2465
+ allowed_emails: testEmailConfig.value.allowedEmails,
2466
+ signature: testEmailConfig.value.signature
2467
+ });
2468
+ } catch (err) {
2469
+ const wrappedError = err instanceof Error ? err : new Error("Failed to send test email");
2470
+ error.value = wrappedError.message;
2471
+ onError?.(wrappedError);
2472
+ throw wrappedError;
2473
+ } finally {
2474
+ isSending.value = false;
2475
+ }
2476
+ }
2477
+ return {
2478
+ isEnabled,
2479
+ allowedEmails,
2480
+ isSending,
2481
+ error,
2482
+ sendTestEmail
2483
+ };
2484
+ }
2485
+
2486
+ // src/cloud/export.ts
2487
+ function useExport(options) {
2488
+ const { authManager, getFontsConfig, canUseCustomFonts } = options;
2489
+ const api = new ApiClient(authManager);
2490
+ function getExportFontsPayload() {
2491
+ const fontsConfig = getFontsConfig?.();
2492
+ const customFontsAllowed = canUseCustomFonts?.() ?? true;
2493
+ return {
2494
+ customFonts: customFontsAllowed && fontsConfig?.customFonts ? fontsConfig.customFonts : [],
2495
+ defaultFallback: fontsConfig?.defaultFallback ?? "Arial, sans-serif"
2496
+ };
2497
+ }
2498
+ async function exportHtml(templateId) {
2499
+ const fontsPayload = getExportFontsPayload();
2500
+ const result = await api.exportTemplate(templateId, fontsPayload);
2501
+ return {
2502
+ html: result.html,
2503
+ mjml: result.mjml
2504
+ };
2505
+ }
2506
+ async function getMjmlSource(templateId) {
2507
+ const fontsPayload = getExportFontsPayload();
2508
+ const result = await api.exportTemplate(templateId, fontsPayload);
2509
+ return result.mjml;
2510
+ }
2511
+ return {
2512
+ exportHtml,
2513
+ getMjmlSource
2514
+ };
2515
+ }
2516
+
2517
+ // src/cloud/plan-config.ts
2518
+ var import_vue14 = require("vue");
2519
+ function usePlanConfig(options) {
2520
+ const { authManager, onError } = options;
2521
+ const config = (0, import_vue14.ref)(null);
2522
+ const isLoading = (0, import_vue14.ref)(false);
2523
+ const apiClient = new ApiClient(authManager);
2524
+ const features = (0, import_vue14.computed)(() => config.value?.features ?? null);
2525
+ function hasFeature(feature) {
2526
+ return config.value?.features[feature] ?? false;
2527
+ }
2528
+ async function fetchConfig() {
2529
+ if (isLoading.value) {
2530
+ return;
2531
+ }
2532
+ isLoading.value = true;
2533
+ try {
2534
+ config.value = await apiClient.fetchConfig();
2535
+ } catch (error) {
2536
+ onError?.(
2537
+ error instanceof Error ? error : new Error("Failed to fetch config")
2538
+ );
2539
+ } finally {
2540
+ isLoading.value = false;
2541
+ }
2542
+ }
2543
+ return {
2544
+ config,
2545
+ isLoading,
2546
+ hasFeature,
2547
+ features,
2548
+ fetchConfig
2549
+ };
2550
+ }
2551
+
2552
+ // src/cloud/health-check.ts
2553
+ var WS_HANDSHAKE_TIMEOUT = 5e3;
2554
+ function resolveHealthUrl(options) {
2555
+ if (options.authManager) {
2556
+ return options.authManager.resolveUrl(API_ROUTES.health);
2557
+ }
2558
+ const base = (options.baseUrl ?? "https://templatical.com").replace(
2559
+ /\/$/,
2560
+ ""
2561
+ );
2562
+ return `${base}${API_ROUTES.health}`;
2563
+ }
2564
+ async function checkApiAndAuth(url, authManager) {
2565
+ const start = performance.now();
2566
+ try {
2567
+ const response = authManager ? await authManager.authenticatedFetch(API_ROUTES.health, {
2568
+ method: "GET",
2569
+ headers: { Accept: "application/json" }
2570
+ }) : await fetch(url, {
2571
+ method: "GET",
2572
+ headers: { Accept: "application/json" }
2573
+ });
2574
+ const latency = Math.round(performance.now() - start);
2575
+ if (response.status === 401) {
2576
+ return {
2577
+ api: { ok: true, latency },
2578
+ auth: { ok: false, error: "HTTP 401" }
2579
+ };
2580
+ }
2581
+ if (!response.ok) {
2582
+ return {
2583
+ api: { ok: false, latency },
2584
+ auth: {
2585
+ ok: !authManager,
2586
+ error: authManager ? `HTTP ${response.status}` : void 0
2587
+ }
2588
+ };
2589
+ }
2590
+ const data = await response.json();
2591
+ return {
2592
+ api: { ok: data.status === "ok", latency },
2593
+ auth: { ok: true },
2594
+ wsConfig: data.websocket
2595
+ };
2596
+ } catch (error) {
2597
+ const latency = Math.round(performance.now() - start);
2598
+ return {
2599
+ api: { ok: false, latency },
2600
+ auth: {
2601
+ ok: !authManager,
2602
+ error: authManager ? error instanceof Error ? error.message : "Authentication check failed" : void 0
2603
+ }
2604
+ };
2605
+ }
2606
+ }
2607
+ async function checkWebSocket(wsConfig) {
2608
+ if (!wsConfig?.host || !wsConfig?.app_key) {
2609
+ return { ok: false, error: "WebSocket configuration not available" };
2610
+ }
2611
+ if (typeof WebSocket === "undefined") {
2612
+ return {
2613
+ ok: false,
2614
+ error: "WebSocket not supported in this environment"
2615
+ };
2616
+ }
2617
+ const protocol = wsConfig.port === 443 ? "wss" : "ws";
2618
+ const url = `${protocol}://${wsConfig.host}:${wsConfig.port}/app/${wsConfig.app_key}?protocol=7&client=js&version=8.4.0-rc2&flash=false`;
2619
+ return new Promise((resolve) => {
2620
+ const timeout = setTimeout(() => {
2621
+ ws.close();
2622
+ resolve({ ok: false, error: "WebSocket connection timed out" });
2623
+ }, WS_HANDSHAKE_TIMEOUT);
2624
+ const ws = new WebSocket(url);
2625
+ ws.onopen = () => {
2626
+ clearTimeout(timeout);
2627
+ ws.close();
2628
+ resolve({ ok: true });
2629
+ };
2630
+ ws.onerror = () => {
2631
+ clearTimeout(timeout);
2632
+ resolve({ ok: false, error: "WebSocket connection failed" });
2633
+ };
2634
+ });
2635
+ }
2636
+ async function performHealthCheck(options = {}) {
2637
+ const healthUrl = resolveHealthUrl(options);
2638
+ const result = await checkApiAndAuth(healthUrl, options.authManager);
2639
+ const wsResult = await checkWebSocket(result.wsConfig);
2640
+ return {
2641
+ api: result.api,
2642
+ websocket: wsResult,
2643
+ auth: result.auth,
2644
+ overall: result.api.ok && result.auth.ok
2645
+ };
2646
+ }
2647
+
2648
+ // src/cloud/mcp-listener.ts
2649
+ var import_vue15 = require("vue");
2650
+ function useMcpListener(options) {
2651
+ const { editor, channel, onOperation } = options;
2652
+ (0, import_vue15.watch)(channel, (newChannel, oldChannel) => {
2653
+ if (oldChannel) {
2654
+ oldChannel.unbind("mcp-operation");
2655
+ }
2656
+ if (newChannel) {
2657
+ newChannel.bind("mcp-operation", (payload) => {
2658
+ handleOperation(editor, payload);
2659
+ onOperation?.(payload);
2660
+ });
2661
+ }
2662
+ });
2663
+ }
2664
+ // Annotate the CommonJS export names for ESM import in node:
2665
+ 0 && (module.exports = {
2666
+ API_ROUTES,
2667
+ ApiClient,
2668
+ AuthManager,
2669
+ WebSocketClient,
2670
+ buildUrl,
2671
+ createSdkAuthManager,
2672
+ handleOperation,
2673
+ performHealthCheck,
2674
+ resolveWebSocketConfig,
2675
+ useAiChat,
2676
+ useAiConfig,
2677
+ useAiRewrite,
2678
+ useCollaboration,
2679
+ useCommentListener,
2680
+ useComments,
2681
+ useDesignReference,
2682
+ useEditor,
2683
+ useExport,
2684
+ useMcpListener,
2685
+ usePlanConfig,
2686
+ useSavedModules,
2687
+ useSnapshotHistory,
2688
+ useTemplateScoring,
2689
+ useTestEmail,
2690
+ useWebSocket
2691
+ });
2692
+ //# sourceMappingURL=index.cjs.map