@amplifyup/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js ADDED
@@ -0,0 +1,1398 @@
1
+ 'use strict';
2
+
3
+ /* @amplifyup/sdk - https://amplifyup.ai */
4
+
5
+ // src/adapters/aws.ts
6
+ var AWSAdapter = class {
7
+ constructor() {
8
+ this.initialized = false;
9
+ this.config = null;
10
+ this.apiGatewayUrl = "";
11
+ }
12
+ async init(config) {
13
+ if (typeof window === "undefined") {
14
+ console.warn("AmplifyUp SDK: Window object not available (SSR)");
15
+ return;
16
+ }
17
+ if (this.initialized) {
18
+ return;
19
+ }
20
+ this.config = {
21
+ trackingId: config.trackingId,
22
+ debug: config.debug,
23
+ dev: config.dev
24
+ };
25
+ this.apiGatewayUrl = config.apiGatewayUrl || "";
26
+ if (!this.apiGatewayUrl) {
27
+ console.warn("AmplifyUp SDK: AWS API Gateway URL not configured. Tracking disabled.");
28
+ return;
29
+ }
30
+ this.initialized = true;
31
+ if (config.debug) {
32
+ console.log("AmplifyUp SDK: AWS adapter initialized", {
33
+ apiGatewayUrl: this.apiGatewayUrl
34
+ });
35
+ }
36
+ }
37
+ isInitialized() {
38
+ return this.initialized;
39
+ }
40
+ async sendEvent(endpoint, eventData) {
41
+ if (!this.apiGatewayUrl) {
42
+ console.warn("AmplifyUp SDK: AWS configuration missing");
43
+ return;
44
+ }
45
+ const url = `${this.apiGatewayUrl}${endpoint}`;
46
+ try {
47
+ const response = await fetch(url, {
48
+ method: "POST",
49
+ headers: {
50
+ "Content-Type": "application/json"
51
+ },
52
+ body: JSON.stringify(eventData)
53
+ });
54
+ if (!response.ok) {
55
+ if (this.config.debug) {
56
+ console.warn(`AmplifyUp SDK: Event tracking failed: ${response.status} ${response.statusText}`);
57
+ }
58
+ } else if (this.config.debug) {
59
+ const result = await response.json().catch(() => ({}));
60
+ console.log("AmplifyUp SDK: Event tracked", result);
61
+ }
62
+ } catch (error) {
63
+ if (this.config.debug) {
64
+ console.error("AmplifyUp SDK: Event tracking error:", error);
65
+ }
66
+ }
67
+ }
68
+ page(properties) {
69
+ if (!this.initialized) {
70
+ return;
71
+ }
72
+ if (typeof window !== "undefined") {
73
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
74
+ return;
75
+ }
76
+ if (window.location.pathname.includes("/api/pages/proxy")) {
77
+ return;
78
+ }
79
+ const urlParams = new URLSearchParams(window.location.search);
80
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
81
+ return;
82
+ }
83
+ if (window.self !== window.top) {
84
+ return;
85
+ }
86
+ if (window.location.href.includes("preview=true") || window.location.href.includes("visualEditor=true")) {
87
+ return;
88
+ }
89
+ }
90
+ const eventData = {
91
+ type: "page",
92
+ anonymousId: properties.instanceId,
93
+ userId: properties.userId,
94
+ properties: {
95
+ path: properties.path || properties.url,
96
+ referrer: properties.referrer,
97
+ ...properties
98
+ },
99
+ context: {
100
+ page: {
101
+ path: properties.path || properties.url,
102
+ referrer: properties.referrer
103
+ }
104
+ },
105
+ timestamp: properties.timestamp || (/* @__PURE__ */ new Date()).toISOString()
106
+ };
107
+ this.sendEvent("/v1/page", eventData);
108
+ }
109
+ track(eventName, properties) {
110
+ if (!this.initialized) {
111
+ return;
112
+ }
113
+ if (typeof window !== "undefined") {
114
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
115
+ return;
116
+ }
117
+ if (window.location.pathname.includes("/api/pages/proxy")) {
118
+ return;
119
+ }
120
+ const urlParams = new URLSearchParams(window.location.search);
121
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
122
+ return;
123
+ }
124
+ if (window.self !== window.top) {
125
+ return;
126
+ }
127
+ if (window.location.href.includes("preview=true") || window.location.href.includes("visualEditor=true")) {
128
+ return;
129
+ }
130
+ }
131
+ const eventData = {
132
+ type: "track",
133
+ event: eventName,
134
+ anonymousId: properties.instanceId,
135
+ userId: properties.userId,
136
+ properties: {
137
+ ...properties
138
+ },
139
+ context: {
140
+ url: properties.url || (typeof window !== "undefined" ? window.location.href : "")
141
+ },
142
+ timestamp: properties.timestamp || (/* @__PURE__ */ new Date()).toISOString()
143
+ };
144
+ this.sendEvent("/v1/track", eventData);
145
+ }
146
+ identify(userId, traits) {
147
+ if (!this.initialized) {
148
+ console.warn("AmplifyUp SDK: Not initialized. Call init() first.");
149
+ return;
150
+ }
151
+ const eventData = {
152
+ type: "identify",
153
+ userId,
154
+ anonymousId: traits.instanceId,
155
+ traits: {
156
+ ...traits
157
+ },
158
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
159
+ };
160
+ this.sendEvent("/v1/track", eventData);
161
+ }
162
+ reset() {
163
+ if (this.config?.debug) {
164
+ console.log("AmplifyUp SDK: Reset called (identity cleared)");
165
+ }
166
+ }
167
+ };
168
+
169
+ // src/storage.ts
170
+ var INSTANCE_ID_KEY = "amplifyup_instance_id";
171
+ var USER_ID_KEY = "amplifyup_user_id";
172
+ function getInstanceId() {
173
+ if (typeof window === "undefined") {
174
+ return "";
175
+ }
176
+ const stored = localStorage.getItem(INSTANCE_ID_KEY);
177
+ if (stored) {
178
+ return stored;
179
+ }
180
+ const instanceId = `anon_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
181
+ localStorage.setItem(INSTANCE_ID_KEY, instanceId);
182
+ return instanceId;
183
+ }
184
+ function getUserId() {
185
+ if (typeof window === "undefined") {
186
+ return null;
187
+ }
188
+ return localStorage.getItem(USER_ID_KEY);
189
+ }
190
+ function setUserId(userId) {
191
+ if (typeof window === "undefined") {
192
+ return;
193
+ }
194
+ localStorage.setItem(USER_ID_KEY, userId);
195
+ }
196
+ function clearIds() {
197
+ if (typeof window === "undefined") {
198
+ return;
199
+ }
200
+ localStorage.removeItem(INSTANCE_ID_KEY);
201
+ localStorage.removeItem(USER_ID_KEY);
202
+ }
203
+
204
+ // src/index.ts
205
+ var PROD_API_URL = "https://api.amplifyup.ai" ;
206
+ var PROD_ORCHESTRATOR_URL = "https://amplifyup.ai" ;
207
+ var AmplifyUpSDK = class {
208
+ constructor(adapter) {
209
+ this.config = null;
210
+ // Internal URLs - set during init, not part of user config
211
+ this.apiGatewayUrl = "";
212
+ this.orchestratorUrl = "";
213
+ this.decisionApiUrl = "";
214
+ this.initialized = false;
215
+ this.highlightingEnabled = false;
216
+ this.componentRegistry = [];
217
+ this.messageListener = null;
218
+ this.mutationObserver = null;
219
+ this.isVisualEditorMode = false;
220
+ this.eventSelectionMode = false;
221
+ this.eventSelectionClickHandler = null;
222
+ this.eventTrackingConfig = [];
223
+ this.attachedEventListeners = [];
224
+ this.trackingIntervals = [];
225
+ this.trackingCleanup = null;
226
+ this.adapter = adapter || new AWSAdapter();
227
+ if (typeof window !== "undefined") {
228
+ this.isVisualEditorMode = this.detectVisualEditorMode();
229
+ if (this.isVisualEditorMode) {
230
+ this.setupHighlightingListener();
231
+ console.log("[AmplifyUp SDK] Visual editor mode detected - message listener enabled");
232
+ }
233
+ }
234
+ }
235
+ /**
236
+ * Detect if we're running in visual editor mode
237
+ * Returns true if:
238
+ * 1. Preview mode flag is set by proxy
239
+ * 2. We're in an iframe AND parent is from orchestrator domain
240
+ * 3. OR visualEditor/preview query parameter is present
241
+ */
242
+ detectVisualEditorMode() {
243
+ if (typeof window === "undefined") return false;
244
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
245
+ return true;
246
+ }
247
+ const urlParams = new URLSearchParams(window.location.search);
248
+ if (urlParams.get("visualEditor") === "true" || urlParams.get("preview") === "true") {
249
+ return true;
250
+ }
251
+ const inIframe = window.self !== window.top;
252
+ if (!inIframe) return false;
253
+ try {
254
+ if (document.referrer) {
255
+ const referrerUrl = new URL(document.referrer);
256
+ if (referrerUrl.hostname === "localhost" && referrerUrl.port === "5001" || referrerUrl.pathname.includes("/dashboard/composer") || referrerUrl.pathname.includes("/dashboard/routes/")) {
257
+ return true;
258
+ }
259
+ }
260
+ } catch (e) {
261
+ }
262
+ return false;
263
+ }
264
+ /**
265
+ * Check if we're in preview/composer mode (should disable tracking)
266
+ */
267
+ isPreviewMode() {
268
+ if (typeof window === "undefined") return false;
269
+ if (window.__AMPLIFYUP_PREVIEW_MODE__ === true) {
270
+ return true;
271
+ }
272
+ if (window.location.pathname.includes("/api/pages/proxy")) {
273
+ return true;
274
+ }
275
+ const urlParams = new URLSearchParams(window.location.search);
276
+ if (urlParams.get("preview") === "true" || urlParams.get("visualEditor") === "true") {
277
+ return true;
278
+ }
279
+ const fullUrl = window.location.href;
280
+ if (fullUrl.includes("preview=true") || fullUrl.includes("visualEditor=true")) {
281
+ return true;
282
+ }
283
+ if (window.self !== window.top) {
284
+ if (document.referrer) {
285
+ try {
286
+ const referrerUrl = new URL(document.referrer);
287
+ if (referrerUrl.hostname === "localhost" && referrerUrl.port === "5001" || referrerUrl.pathname.includes("/dashboard/composer") || referrerUrl.pathname.includes("/dashboard/routes/")) {
288
+ return true;
289
+ }
290
+ } catch {
291
+ }
292
+ }
293
+ return true;
294
+ }
295
+ return false;
296
+ }
297
+ /**
298
+ * Get production URLs
299
+ *
300
+ * URLs are baked in at build time via tsup.config.ts
301
+ *
302
+ * API Gateway endpoints:
303
+ * - /v1/track - Event tracking (ingestion)
304
+ * - /v1/page - Page view tracking (ingestion)
305
+ * - /v1/personalize - Decision engine (personalization)
306
+ */
307
+ getProductionUrls() {
308
+ return {
309
+ apiGatewayUrl: PROD_API_URL,
310
+ orchestratorUrl: PROD_ORCHESTRATOR_URL,
311
+ decisionApiUrl: `${PROD_API_URL}/v1/personalize`
312
+ };
313
+ }
314
+ /**
315
+ * Initialize the SDK
316
+ * Automatically reads env vars and sets up tracking
317
+ */
318
+ async init(config) {
319
+ if (!this.adapter) {
320
+ this.adapter = new AWSAdapter();
321
+ }
322
+ const isLocalhost = typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1");
323
+ if (isLocalhost || config.dev === true) {
324
+ this.apiGatewayUrl = "http://localhost:5001/api";
325
+ this.orchestratorUrl = "http://localhost:5001";
326
+ this.decisionApiUrl = "http://localhost:5001/api/v1/personalize";
327
+ } else {
328
+ const urls = this.getProductionUrls();
329
+ this.apiGatewayUrl = urls.apiGatewayUrl;
330
+ this.orchestratorUrl = urls.orchestratorUrl;
331
+ this.decisionApiUrl = urls.decisionApiUrl;
332
+ }
333
+ this.config = {
334
+ trackingId: config.trackingId,
335
+ debug: config.debug ?? true,
336
+ // Enable debug by default
337
+ dev: config.dev
338
+ };
339
+ try {
340
+ const adapterConfig = {
341
+ ...this.config,
342
+ apiGatewayUrl: this.apiGatewayUrl,
343
+ orchestratorUrl: this.orchestratorUrl,
344
+ decisionApiUrl: this.decisionApiUrl
345
+ };
346
+ await this.adapter.init(adapterConfig);
347
+ this.initialized = this.adapter.isInitialized();
348
+ if (typeof window !== "undefined") {
349
+ window.AmplifyUp = {
350
+ getInstanceId: () => this.getInstanceId(),
351
+ getUserId: () => this.getUserId(),
352
+ getTrackingId: () => this.getTrackingId(),
353
+ getDiagnostics: () => this.getDiagnostics(),
354
+ getStatus: () => {
355
+ console.log(this.getStatus());
356
+ return this.getDiagnostics();
357
+ },
358
+ testTracking: () => this.testTracking(),
359
+ verifyAWSConnection: () => {
360
+ const result = this.verifyAWSConnection();
361
+ console.log("AWS Connection Verification:", result.message);
362
+ console.log("Full details:", result);
363
+ return result;
364
+ },
365
+ isInitialized: () => this.isInitialized(),
366
+ // Re-export main tracking methods for convenience
367
+ page: (url, properties) => this.page(url, properties),
368
+ track: (eventName, properties) => this.track(eventName, properties),
369
+ identify: (userId, traits) => this.identify(userId, traits)
370
+ };
371
+ if (this.config?.debug) {
372
+ console.log("AmplifyUp SDK: Diagnostic methods available on window.AmplifyUp");
373
+ console.log("Try: AmplifyUp.getStatus() or AmplifyUp.verifyAWSConnection()");
374
+ }
375
+ }
376
+ this.clearTrackingIntervals();
377
+ if (this.isPreviewMode()) {
378
+ return;
379
+ }
380
+ if (typeof window !== "undefined" && this.initialized) {
381
+ await new Promise((resolve) => setTimeout(resolve, 200));
382
+ if (this.isPreviewMode()) {
383
+ return;
384
+ }
385
+ const url = window.location.pathname;
386
+ this.page(url);
387
+ }
388
+ if (this.config?.debug && this.initialized) {
389
+ console.log("AmplifyUp SDK: Initialized successfully", { trackingId: config.trackingId });
390
+ }
391
+ } catch (error) {
392
+ console.error("AmplifyUp SDK: Initialization failed", error);
393
+ throw error;
394
+ }
395
+ }
396
+ /**
397
+ * Check if SDK is initialized
398
+ */
399
+ isInitialized() {
400
+ return this.initialized && this.adapter.isInitialized();
401
+ }
402
+ /**
403
+ * Clear all tracking intervals and event listeners
404
+ */
405
+ clearTrackingIntervals() {
406
+ if (this.trackingCleanup) {
407
+ this.trackingCleanup();
408
+ this.trackingCleanup = null;
409
+ }
410
+ this.trackingIntervals.forEach((id) => clearInterval(id));
411
+ this.trackingIntervals = [];
412
+ }
413
+ /**
414
+ * Track a page view
415
+ */
416
+ page(url, properties) {
417
+ if (this.isPreviewMode()) {
418
+ return;
419
+ }
420
+ if (!this.isInitialized()) {
421
+ return;
422
+ }
423
+ const instanceId = getInstanceId();
424
+ const pageProperties = {
425
+ name: url,
426
+ path: url,
427
+ url: typeof window !== "undefined" ? window.location.href : url,
428
+ referrer: typeof document !== "undefined" ? document.referrer : void 0,
429
+ instanceId,
430
+ trackingId: this.config?.trackingId,
431
+ // Timestamp is included in event payload
432
+ ...properties
433
+ };
434
+ this.adapter.page(pageProperties);
435
+ }
436
+ /**
437
+ * Track an event
438
+ */
439
+ track(eventName, properties) {
440
+ if (this.isPreviewMode()) {
441
+ return;
442
+ }
443
+ if (!this.isInitialized()) {
444
+ return;
445
+ }
446
+ const instanceId = getInstanceId();
447
+ const trackProperties = {
448
+ instanceId,
449
+ trackingId: this.config?.trackingId,
450
+ url: typeof window !== "undefined" ? window.location.href : void 0,
451
+ // Timestamp is included in event payload
452
+ ...properties
453
+ };
454
+ this.adapter.track(eventName, trackProperties);
455
+ }
456
+ /**
457
+ * Track a button click or CTA interaction
458
+ */
459
+ trackClick(elementId, elementText, properties) {
460
+ this.track("Button Click", {
461
+ elementId,
462
+ elementText,
463
+ ...properties
464
+ });
465
+ }
466
+ /**
467
+ * Track form submission
468
+ */
469
+ trackFormSubmit(formId, formData) {
470
+ this.track("Form Submit", {
471
+ formId,
472
+ ...formData
473
+ });
474
+ }
475
+ /**
476
+ * Track form field interaction
477
+ */
478
+ trackFormFieldInteraction(fieldName, fieldValue) {
479
+ this.track("Form Field Interaction", {
480
+ fieldName,
481
+ fieldValue: fieldValue ? fieldValue.substring(0, 100) : void 0
482
+ // Truncate for privacy
483
+ });
484
+ }
485
+ /**
486
+ * Track product/content view
487
+ */
488
+ trackContentView(contentId, contentType, properties) {
489
+ this.track("Content View", {
490
+ contentId,
491
+ contentType,
492
+ ...properties
493
+ });
494
+ }
495
+ /**
496
+ * Identify user (when they sign up or log in)
497
+ */
498
+ identify(userId, traits) {
499
+ if (this.isPreviewMode()) {
500
+ if (this.config?.debug) {
501
+ console.log("AmplifyUp SDK: Identify tracking disabled in preview mode", { userId });
502
+ }
503
+ return;
504
+ }
505
+ if (!this.isInitialized()) {
506
+ if (this.config?.debug) {
507
+ console.warn("AmplifyUp SDK: Not initialized. Identify not called.");
508
+ }
509
+ return;
510
+ }
511
+ const instanceId = getInstanceId();
512
+ const identifyTraits = {
513
+ instanceId,
514
+ trackingId: this.config?.trackingId,
515
+ ...traits
516
+ };
517
+ this.adapter.identify(userId, identifyTraits);
518
+ setUserId(userId);
519
+ if (this.config?.debug) {
520
+ console.log("AmplifyUp SDK: User identified", { userId, instanceId });
521
+ }
522
+ }
523
+ /**
524
+ * Track content engagement (when user interacts with personalized content)
525
+ */
526
+ trackContentEngagement(contentId, engagementType) {
527
+ this.track("Content Engagement", {
528
+ contentId,
529
+ engagementType
530
+ });
531
+ if (this.orchestratorUrl) {
532
+ const instanceId = getInstanceId();
533
+ fetch(`${this.orchestratorUrl}/api/personalization/feedback`, {
534
+ method: "POST",
535
+ headers: { "Content-Type": "application/json" },
536
+ body: JSON.stringify({
537
+ instanceId,
538
+ trackingId: this.config?.trackingId,
539
+ contentId,
540
+ engagementType,
541
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
542
+ })
543
+ }).catch((err) => {
544
+ if (this.config?.debug) {
545
+ console.error("AmplifyUp SDK: Failed to send engagement feedback:", err);
546
+ }
547
+ });
548
+ }
549
+ }
550
+ /**
551
+ * Reset user identity (logout)
552
+ */
553
+ reset() {
554
+ this.adapter.reset();
555
+ clearIds();
556
+ if (this.config?.debug) {
557
+ console.log("AmplifyUp SDK: User identity reset");
558
+ }
559
+ }
560
+ /**
561
+ * Get instance ID (anonymous ID)
562
+ */
563
+ getInstanceId() {
564
+ return getInstanceId();
565
+ }
566
+ /**
567
+ * Get user ID
568
+ */
569
+ getUserId() {
570
+ return getUserId();
571
+ }
572
+ /**
573
+ * Get tracking ID
574
+ */
575
+ getTrackingId() {
576
+ return this.config?.trackingId;
577
+ }
578
+ /**
579
+ * Get diagnostic information
580
+ * Useful for debugging from browser console
581
+ */
582
+ getDiagnostics() {
583
+ const instanceId = getInstanceId();
584
+ const userId = getUserId();
585
+ return {
586
+ initialized: this.initialized,
587
+ instanceId,
588
+ userId,
589
+ trackingId: this.config?.trackingId,
590
+ config: {
591
+ apiGatewayUrl: this.apiGatewayUrl,
592
+ decisionApiUrl: this.decisionApiUrl,
593
+ orchestratorUrl: this.orchestratorUrl,
594
+ debug: this.config?.debug
595
+ }
596
+ };
597
+ }
598
+ /**
599
+ * Test tracking by sending a test event
600
+ */
601
+ testTracking() {
602
+ if (!this.initialized) {
603
+ console.warn("AmplifyUp SDK: Not initialized. Cannot test tracking.");
604
+ return;
605
+ }
606
+ const testEvent = {
607
+ eventName: "SDK Test Event",
608
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
609
+ test: true
610
+ };
611
+ console.log("AmplifyUp SDK: Sending test event...", testEvent);
612
+ this.track("SDK Test Event", {
613
+ ...testEvent,
614
+ instanceId: getInstanceId(),
615
+ trackingId: this.config?.trackingId
616
+ });
617
+ console.log("AmplifyUp SDK: Test event sent. Check AWS API Gateway to verify it was received.");
618
+ console.log("AmplifyUp SDK: Check Network tab for requests to:", this.apiGatewayUrl);
619
+ }
620
+ /**
621
+ * Verify AWS API Gateway connectivity
622
+ * Checks if AWS adapter is initialized and can send events
623
+ */
624
+ verifyAWSConnection() {
625
+ if (!this.apiGatewayUrl) {
626
+ return {
627
+ connected: false,
628
+ message: "AWS API Gateway URL not configured"
629
+ };
630
+ }
631
+ if (!this.initialized) {
632
+ return {
633
+ connected: false,
634
+ message: "SDK not initialized"
635
+ };
636
+ }
637
+ return {
638
+ connected: true,
639
+ message: "AWS adapter is connected and ready",
640
+ details: {
641
+ apiGatewayUrl: this.apiGatewayUrl,
642
+ decisionApiUrl: this.decisionApiUrl
643
+ }
644
+ };
645
+ }
646
+ /**
647
+ * Get status summary (for console debugging)
648
+ */
649
+ getStatus() {
650
+ const diag = this.getDiagnostics();
651
+ return `
652
+ AmplifyUp SDK Status:
653
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
654
+ Initialized: ${diag.initialized ? "\u2705 Yes" : "\u274C No"}
655
+ Instance ID: ${diag.instanceId}
656
+ User ID: ${diag.userId || "Not identified"}
657
+ Tracking ID: ${diag.trackingId || "Not set"}
658
+
659
+ Adapter:
660
+ Type: AWS (Pure AWS Architecture)
661
+
662
+ Config:
663
+ API Gateway: ${this.apiGatewayUrl || "Not set (required)"}
664
+ Decision API: ${this.decisionApiUrl || "Not set (using Orchestrator fallback)"}
665
+ Orchestrator: ${this.orchestratorUrl || "Not set"}
666
+ Debug: ${diag.config.debug ? "Enabled" : "Disabled"}
667
+
668
+ Available Console Commands:
669
+ AmplifyUp.getStatus() - Show this status
670
+ AmplifyUp.getDiagnostics() - Get full diagnostic object
671
+ AmplifyUp.getInstanceId() - Get instance ID (browser/session ID)
672
+ AmplifyUp.getUserId() - Get user ID if identified
673
+ AmplifyUp.testTracking() - Send a test event
674
+ AmplifyUp.verifyAWSConnection() - Verify AWS API Gateway connectivity
675
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
676
+ `.trim();
677
+ }
678
+ /**
679
+ * Get orchestrator URL
680
+ */
681
+ getOrchestratorUrl() {
682
+ return this.orchestratorUrl || void 0;
683
+ }
684
+ /**
685
+ * Get decision API URL
686
+ */
687
+ getDecisionApiUrl() {
688
+ return this.decisionApiUrl || void 0;
689
+ }
690
+ /**
691
+ * Build API URL for fetching page config from the Layout Provider
692
+ */
693
+ buildLayoutProviderUrl(route, preview = false) {
694
+ const orchestratorUrl = this.getOrchestratorUrl();
695
+ const trackingId = this.getTrackingId();
696
+ const instanceId = getInstanceId();
697
+ if (!orchestratorUrl || !trackingId) {
698
+ throw new Error("SDK not initialized. Call init() first.");
699
+ }
700
+ const isOnOrchestratorOrigin = typeof window !== "undefined" && window.location.origin === new URL(orchestratorUrl).origin;
701
+ const params = new URLSearchParams({
702
+ route,
703
+ trackingId,
704
+ instanceId
705
+ });
706
+ if (preview) {
707
+ params.set("preview", "true");
708
+ }
709
+ if (isOnOrchestratorOrigin) {
710
+ return `/api/layout/provider?${params.toString()}`;
711
+ }
712
+ return `${orchestratorUrl}/api/layout/provider?${params.toString()}`;
713
+ }
714
+ /**
715
+ * Fetch page configuration from orchestrator's Layout Provider
716
+ */
717
+ async fetchPageConfig(route, preview = false) {
718
+ const url = this.buildLayoutProviderUrl(route, preview);
719
+ const response = await fetch(url);
720
+ if (!response.ok) {
721
+ if (response.status === 404) {
722
+ return null;
723
+ }
724
+ throw new Error(`Failed to fetch page: ${response.statusText}`);
725
+ }
726
+ const data = await response.json();
727
+ const pageConfig = data.page;
728
+ if (pageConfig?.eventTracking) {
729
+ this.setupEventTracking(pageConfig.eventTracking);
730
+ }
731
+ return pageConfig;
732
+ }
733
+ /**
734
+ * Set up view-level event tracking based on configuration
735
+ */
736
+ setupEventTracking(eventConfig) {
737
+ if (typeof document === "undefined") return;
738
+ this.cleanupEventTracking();
739
+ this.eventTrackingConfig = eventConfig;
740
+ if (this.config?.debug) {
741
+ console.log("[AmplifyUp SDK] Setting up event tracking:", eventConfig.length, "events");
742
+ }
743
+ if (document.readyState === "loading") {
744
+ document.addEventListener("DOMContentLoaded", () => this.attachEventListeners());
745
+ } else {
746
+ setTimeout(() => this.attachEventListeners(), 100);
747
+ }
748
+ }
749
+ /**
750
+ * Attach event listeners to page elements based on view-level configuration
751
+ */
752
+ attachEventListeners() {
753
+ if (typeof document === "undefined") return;
754
+ this.eventTrackingConfig.forEach((eventConfig) => {
755
+ if (eventConfig.enabled === false) return;
756
+ let targetElements = [];
757
+ if (eventConfig.selector) {
758
+ try {
759
+ targetElements = document.querySelectorAll(eventConfig.selector);
760
+ } catch (e) {
761
+ if (this.config?.debug) {
762
+ console.warn(`[AmplifyUp SDK] Invalid selector: ${eventConfig.selector}`, e);
763
+ }
764
+ return;
765
+ }
766
+ } else {
767
+ if (this.config?.debug) {
768
+ console.warn(`[AmplifyUp SDK] Event ${eventConfig.eventName} has no selector, skipping`);
769
+ }
770
+ return;
771
+ }
772
+ if (targetElements.length === 0) {
773
+ if (this.config?.debug) {
774
+ console.log(`[AmplifyUp SDK] No elements found for selector: ${eventConfig.selector}`);
775
+ }
776
+ return;
777
+ }
778
+ targetElements.forEach((targetEl) => {
779
+ const htmlTargetEl = targetEl;
780
+ const domEventType = this.mapEventType(eventConfig.eventType);
781
+ const handler = (e) => {
782
+ this.handleTrackedEvent(e, eventConfig, htmlTargetEl);
783
+ };
784
+ if (eventConfig.eventType === "view") {
785
+ this.setupViewTracking(htmlTargetEl, eventConfig);
786
+ } else {
787
+ htmlTargetEl.addEventListener(domEventType, handler);
788
+ this.attachedEventListeners.push({
789
+ element: htmlTargetEl,
790
+ eventType: domEventType,
791
+ handler
792
+ });
793
+ }
794
+ if (this.config?.debug) {
795
+ console.log(`[AmplifyUp SDK] Attached ${eventConfig.eventType} listener for ${eventConfig.eventName} on selector: ${eventConfig.selector}`);
796
+ }
797
+ });
798
+ });
799
+ }
800
+ /**
801
+ * Map event type from config to DOM event type
802
+ */
803
+ mapEventType(eventType) {
804
+ const eventMap = {
805
+ "click": "click",
806
+ "submit": "submit",
807
+ "focus": "focus",
808
+ "blur": "blur",
809
+ "hover": "mouseenter",
810
+ "change": "change",
811
+ "scroll": "scroll",
812
+ "view": "view",
813
+ // Handled separately with IntersectionObserver
814
+ "custom": "custom"
815
+ };
816
+ return eventMap[eventType] || eventType;
817
+ }
818
+ /**
819
+ * Handle a tracked event and send to AWS API Gateway
820
+ */
821
+ handleTrackedEvent(event, config, element) {
822
+ const properties = {
823
+ eventType: config.eventType,
824
+ selector: config.selector
825
+ };
826
+ if (config.properties && config.properties.length > 0) {
827
+ config.properties.forEach((prop) => {
828
+ const dataAttrValue = element.getAttribute(`data-${prop}`);
829
+ if (dataAttrValue) {
830
+ properties[prop] = dataAttrValue;
831
+ return;
832
+ }
833
+ if (prop in element) {
834
+ const value = element[prop];
835
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
836
+ properties[prop] = value;
837
+ }
838
+ }
839
+ switch (prop) {
840
+ case "buttonText":
841
+ case "text":
842
+ properties[prop] = element.textContent?.trim().substring(0, 100);
843
+ break;
844
+ case "linkUrl":
845
+ case "href":
846
+ properties[prop] = element.getAttribute("href");
847
+ break;
848
+ case "formId":
849
+ case "id":
850
+ properties[prop] = element.id || element.getAttribute("name");
851
+ break;
852
+ case "value":
853
+ properties[prop] = element.value;
854
+ break;
855
+ case "tagName":
856
+ properties[prop] = element.tagName.toLowerCase();
857
+ break;
858
+ case "className":
859
+ properties[prop] = element.className;
860
+ break;
861
+ }
862
+ });
863
+ }
864
+ this.track(config.eventName, properties);
865
+ if (this.config?.debug) {
866
+ console.log(`[AmplifyUp SDK] Tracked event: ${config.eventName}`, properties);
867
+ }
868
+ }
869
+ /**
870
+ * Set up view tracking using IntersectionObserver
871
+ */
872
+ setupViewTracking(element, config) {
873
+ if (typeof IntersectionObserver === "undefined") return;
874
+ const observer = new IntersectionObserver(
875
+ (entries) => {
876
+ entries.forEach((entry) => {
877
+ if (entry.isIntersecting) {
878
+ this.handleTrackedEvent(
879
+ new CustomEvent("view"),
880
+ config,
881
+ element
882
+ );
883
+ observer.unobserve(element);
884
+ }
885
+ });
886
+ },
887
+ {
888
+ threshold: 0.5
889
+ // 50% visible
890
+ }
891
+ );
892
+ observer.observe(element);
893
+ element._amplifyupViewObserver = observer;
894
+ }
895
+ /**
896
+ * Clean up all attached event listeners
897
+ */
898
+ cleanupEventTracking() {
899
+ this.attachedEventListeners.forEach(({ element, eventType, handler }) => {
900
+ element.removeEventListener(eventType, handler);
901
+ });
902
+ this.attachedEventListeners = [];
903
+ if (typeof document !== "undefined") {
904
+ document.querySelectorAll("*").forEach((el) => {
905
+ const observer = el._amplifyupViewObserver;
906
+ if (observer) {
907
+ observer.disconnect();
908
+ delete el._amplifyupViewObserver;
909
+ }
910
+ });
911
+ }
912
+ this.eventTrackingConfig = [];
913
+ if (this.config?.debug) {
914
+ console.log("[AmplifyUp SDK] Cleaned up event tracking");
915
+ }
916
+ }
917
+ /**
918
+ * Manually trigger event tracking setup (useful after dynamic content loads)
919
+ */
920
+ refreshEventTracking() {
921
+ if (this.eventTrackingConfig.length > 0) {
922
+ this.cleanupEventTracking();
923
+ const config = [...this.eventTrackingConfig];
924
+ this.eventTrackingConfig = config;
925
+ this.attachEventListeners();
926
+ }
927
+ }
928
+ /**
929
+ * Set up postMessage listener for highlighting commands from orchestrator
930
+ */
931
+ setupHighlightingListener() {
932
+ if (this.messageListener) {
933
+ console.log("[AmplifyUp SDK] Message listener already set up");
934
+ return;
935
+ }
936
+ console.log("[AmplifyUp SDK] Setting up message listener...");
937
+ this.messageListener = (event) => {
938
+ console.log("[AmplifyUp SDK] Received message:", {
939
+ origin: event.origin,
940
+ currentOrigin: window.location.origin,
941
+ data: event.data
942
+ });
943
+ const allowedOrigins = [
944
+ "http://localhost:5001",
945
+ "http://localhost:3001",
946
+ "https://orchestrator.amplifyup.com"
947
+ ];
948
+ const isSameOrigin = event.origin === window.location.origin;
949
+ const isAllowedOrigin = allowedOrigins.some((origin) => event.origin.startsWith(origin));
950
+ if (!isSameOrigin && !isAllowedOrigin) {
951
+ console.warn("[AmplifyUp SDK] Rejected message from unauthorized origin:", {
952
+ eventOrigin: event.origin,
953
+ currentOrigin: window.location.origin,
954
+ allowedOrigins
955
+ });
956
+ return;
957
+ }
958
+ try {
959
+ if (event.data?.type === "COMPONENT_DELETABLE_STATUS") {
960
+ const { componentId, deletable, nodeId } = event.data;
961
+ const element = document.querySelector(`[data-component-id="${componentId}"]`);
962
+ if (element) {
963
+ const deleteButton = element._deleteButton;
964
+ if (deleteButton) {
965
+ if (deletable && nodeId) {
966
+ deleteButton.disabled = false;
967
+ deleteButton.style.opacity = "1";
968
+ deleteButton.style.cursor = "pointer";
969
+ element.setAttribute("data-node-id", nodeId);
970
+ } else {
971
+ deleteButton.disabled = true;
972
+ deleteButton.style.opacity = "0.5";
973
+ deleteButton.style.cursor = "not-allowed";
974
+ }
975
+ }
976
+ }
977
+ return;
978
+ }
979
+ if (event.data?.type === "DELETE_COMPONENT_REQUEST") {
980
+ if (window.parent && window.parent !== window) {
981
+ window.parent.postMessage(event.data, "*");
982
+ }
983
+ return;
984
+ }
985
+ if (event.data?.type === "GET_ELEMENT_POSITION") {
986
+ const { componentId, slotName } = event.data;
987
+ const selector = slotName ? `[data-amplifyup-slot="${slotName}"]` : `[data-amplifyup-component="${componentId}"], [data-component-id="${componentId}"]`;
988
+ console.log("[AmplifyUp SDK] Finding element position:", { selector, componentId, slotName });
989
+ const element = document.querySelector(selector);
990
+ if (element) {
991
+ const rect = element.getBoundingClientRect();
992
+ const position = {
993
+ x: rect.left + rect.width / 2,
994
+ // Center of element
995
+ y: rect.top - 50,
996
+ // Position above element
997
+ width: rect.width,
998
+ height: rect.height
999
+ };
1000
+ console.log("[AmplifyUp SDK] Element position calculated:", { rect, position });
1001
+ if (window.parent && window.parent !== window) {
1002
+ window.parent.postMessage({
1003
+ type: "ELEMENT_POSITION",
1004
+ componentId,
1005
+ slotName,
1006
+ position
1007
+ }, "*");
1008
+ console.log("[AmplifyUp SDK] Sent ELEMENT_POSITION message");
1009
+ }
1010
+ } else {
1011
+ console.warn("[AmplifyUp SDK] Element not found for selector:", selector);
1012
+ }
1013
+ return;
1014
+ }
1015
+ const message = event.data;
1016
+ if (!message || typeof message !== "object" || !message.type) {
1017
+ console.log("[AmplifyUp SDK] Message is not a highlighting message:", message);
1018
+ return;
1019
+ }
1020
+ console.log("[AmplifyUp SDK] Processing highlight message:", message.type);
1021
+ switch (message.type) {
1022
+ case "ENABLE_HIGHLIGHTING":
1023
+ case "UPDATE_HIGHLIGHTING":
1024
+ console.log("[AmplifyUp SDK] Enabling highlighting with registry:", message.componentRegistry?.length || 0, "components");
1025
+ this.enableHighlighting(
1026
+ message.componentRegistry || [],
1027
+ message.highlightComponents ?? true,
1028
+ message.showZones ?? false
1029
+ );
1030
+ break;
1031
+ case "DISABLE_HIGHLIGHTING":
1032
+ console.log("[AmplifyUp SDK] Disabling highlighting");
1033
+ this.disableHighlighting();
1034
+ break;
1035
+ case "SHOW_COMPONENT_TOOLTIP":
1036
+ case "HIDE_ALL_TOOLTIPS":
1037
+ break;
1038
+ case "ENABLE_EVENT_SELECTION":
1039
+ console.log("[AmplifyUp SDK] Enable event selection mode:", message.enabled);
1040
+ this.setEventSelectionMode(message.enabled || false);
1041
+ break;
1042
+ }
1043
+ } catch (error) {
1044
+ console.error("[AmplifyUp SDK] Error handling highlight message:", error);
1045
+ }
1046
+ };
1047
+ window.addEventListener("message", this.messageListener);
1048
+ console.log("[AmplifyUp SDK] Message listener attached to window");
1049
+ }
1050
+ /**
1051
+ * Enable/disable event selection mode
1052
+ * When enabled, clicks on elements send element info to parent for event configuration
1053
+ */
1054
+ setEventSelectionMode(enabled) {
1055
+ if (typeof document === "undefined") return;
1056
+ this.eventSelectionMode = enabled;
1057
+ if (this.eventSelectionClickHandler) {
1058
+ document.removeEventListener("click", this.eventSelectionClickHandler, true);
1059
+ this.eventSelectionClickHandler = null;
1060
+ }
1061
+ if (enabled) {
1062
+ this.eventSelectionClickHandler = (e) => {
1063
+ const target = e.target;
1064
+ if (!target) return;
1065
+ const selector = this.generateSelectorForElement(target);
1066
+ const tagName = target.tagName.toLowerCase();
1067
+ const text = target.textContent?.trim().substring(0, 50) || "";
1068
+ if (window.parent && window.parent !== window) {
1069
+ window.parent.postMessage({
1070
+ type: "ELEMENT_CLICKED_FOR_EVENT",
1071
+ selector,
1072
+ tagName,
1073
+ text
1074
+ }, "*");
1075
+ }
1076
+ if (tagName === "a") {
1077
+ e.preventDefault();
1078
+ }
1079
+ };
1080
+ document.addEventListener("click", this.eventSelectionClickHandler, true);
1081
+ if (this.config?.debug) {
1082
+ console.log("[AmplifyUp SDK] Event selection mode enabled - clicks will be captured");
1083
+ }
1084
+ } else {
1085
+ if (this.config?.debug) {
1086
+ console.log("[AmplifyUp SDK] Event selection mode disabled");
1087
+ }
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Generate a CSS selector for an element
1092
+ */
1093
+ generateSelectorForElement(el) {
1094
+ if (el.id) {
1095
+ return "#" + el.id;
1096
+ }
1097
+ const dataAttrs = Array.from(el.attributes).filter((a) => a.name.startsWith("data-"));
1098
+ if (dataAttrs.length > 0) {
1099
+ const attr = dataAttrs[0];
1100
+ return "[" + attr.name + '="' + attr.value + '"]';
1101
+ }
1102
+ if (el.className && typeof el.className === "string") {
1103
+ const classes = el.className.split(" ").filter(
1104
+ (c) => c && !c.startsWith("has-") && !c.includes("selectable") && !c.includes("selected")
1105
+ );
1106
+ if (classes.length > 0) {
1107
+ return el.tagName.toLowerCase() + "." + classes[0];
1108
+ }
1109
+ }
1110
+ if (el.type) {
1111
+ return el.tagName.toLowerCase() + '[type="' + el.type + '"]';
1112
+ }
1113
+ if (el.name) {
1114
+ return el.tagName.toLowerCase() + '[name="' + el.name + '"]';
1115
+ }
1116
+ return el.tagName.toLowerCase();
1117
+ }
1118
+ /**
1119
+ * Enable component highlighting
1120
+ */
1121
+ enableHighlighting(componentRegistry, highlightComponents, showZones) {
1122
+ if (typeof document === "undefined") return;
1123
+ this.componentRegistry = componentRegistry;
1124
+ this.highlightingEnabled = true;
1125
+ this.disableHighlighting();
1126
+ if (highlightComponents) {
1127
+ this.applyComponentHighlights();
1128
+ this.setupMutationObserver();
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Set up MutationObserver to watch for new components being added
1133
+ */
1134
+ setupMutationObserver() {
1135
+ if (typeof document === "undefined" || !window.MutationObserver) return;
1136
+ if (this.mutationObserver) {
1137
+ this.mutationObserver.disconnect();
1138
+ this.mutationObserver = null;
1139
+ }
1140
+ this.mutationObserver = new MutationObserver((mutations) => {
1141
+ let shouldReapply = false;
1142
+ mutations.forEach((mutation) => {
1143
+ mutation.addedNodes.forEach((node) => {
1144
+ if (node.nodeType === Node.ELEMENT_NODE) {
1145
+ const el = node;
1146
+ if (el.hasAttribute("data-amplifyup-component") || el.hasAttribute("data-component-id") || el.hasAttribute("data-amplifyup-slot") || el.querySelector("[data-amplifyup-component], [data-component-id], [data-amplifyup-slot]")) {
1147
+ shouldReapply = true;
1148
+ }
1149
+ }
1150
+ });
1151
+ if (mutation.type === "attributes") {
1152
+ const target = mutation.target;
1153
+ if (target.hasAttribute("data-amplifyup-slot") || target.hasAttribute("data-slot-empty")) {
1154
+ shouldReapply = true;
1155
+ }
1156
+ }
1157
+ });
1158
+ if (shouldReapply && this.highlightingEnabled) {
1159
+ setTimeout(() => {
1160
+ if (this.highlightingEnabled) {
1161
+ this.applyComponentHighlights();
1162
+ }
1163
+ }, 100);
1164
+ }
1165
+ });
1166
+ this.mutationObserver.observe(document.body, {
1167
+ childList: true,
1168
+ subtree: true,
1169
+ attributes: true,
1170
+ attributeFilter: ["data-amplifyup-component", "data-component-id", "data-amplifyup-slot", "data-slot-empty"]
1171
+ });
1172
+ }
1173
+ /**
1174
+ * Disable component highlighting
1175
+ */
1176
+ disableHighlighting() {
1177
+ if (typeof document === "undefined") return;
1178
+ this.highlightingEnabled = false;
1179
+ if (this.mutationObserver) {
1180
+ this.mutationObserver.disconnect();
1181
+ this.mutationObserver = null;
1182
+ }
1183
+ document.querySelectorAll(".amplifyup-component-highlight").forEach((el) => {
1184
+ const htmlEl = el;
1185
+ const handlers = htmlEl._amplifyupHandlers;
1186
+ if (handlers?.handleClick) {
1187
+ htmlEl.removeEventListener("click", handlers.handleClick);
1188
+ }
1189
+ delete htmlEl._amplifyupHandlers;
1190
+ htmlEl.classList.remove("amplifyup-component-highlight");
1191
+ });
1192
+ document.querySelectorAll(".amplifyup-slot-highlight").forEach((el) => {
1193
+ const htmlEl = el;
1194
+ const handlers = htmlEl._amplifyupSlotHandlers;
1195
+ if (handlers) {
1196
+ if (handlers.handleClick) htmlEl.removeEventListener("click", handlers.handleClick);
1197
+ if (handlers.handleDragOver) htmlEl.removeEventListener("dragover", handlers.handleDragOver);
1198
+ if (handlers.handleDrop) htmlEl.removeEventListener("drop", handlers.handleDrop);
1199
+ }
1200
+ delete htmlEl._amplifyupSlotHandlers;
1201
+ htmlEl.classList.remove("amplifyup-slot-highlight");
1202
+ });
1203
+ }
1204
+ /**
1205
+ * Build component hierarchy for ancestor selection
1206
+ */
1207
+ buildComponentHierarchy(element) {
1208
+ const hierarchy = [];
1209
+ let current = element;
1210
+ while (current) {
1211
+ if (current.hasAttribute("data-amplifyup-component") || current.hasAttribute("data-component-id") || current.hasAttribute("data-amplifyup-slot")) {
1212
+ hierarchy.push(current);
1213
+ }
1214
+ current = current.parentElement;
1215
+ }
1216
+ return hierarchy.reverse();
1217
+ }
1218
+ /**
1219
+ * Send selection message to orchestrator (includes element bounds for overlay positioning).
1220
+ */
1221
+ sendSelectionMessage(element, hierarchy, isEmpty) {
1222
+ if (!this.isVisualEditorMode) return;
1223
+ const componentId = element.getAttribute("data-amplifyup-component") || element.getAttribute("data-component-id");
1224
+ const slotName = element.getAttribute("data-amplifyup-slot");
1225
+ const componentName = element.getAttribute("data-component-name");
1226
+ const hierarchyInfo = hierarchy.map((el, index) => {
1227
+ const elComponentId = el.getAttribute("data-amplifyup-component") || el.getAttribute("data-component-id");
1228
+ const elSlotName = el.getAttribute("data-amplifyup-slot");
1229
+ const elComponentName = el.getAttribute("data-component-name");
1230
+ return {
1231
+ index,
1232
+ componentId: elComponentId,
1233
+ componentName: elComponentName,
1234
+ slotName: elSlotName,
1235
+ isSlot: !!elSlotName
1236
+ };
1237
+ });
1238
+ const rect = element.getBoundingClientRect ? element.getBoundingClientRect() : null;
1239
+ const bounds = rect ? { top: rect.top, left: rect.left, width: rect.width, height: rect.height } : void 0;
1240
+ const message = {
1241
+ type: "COMPONENT_SELECTED",
1242
+ componentId,
1243
+ componentName,
1244
+ slotName,
1245
+ hierarchy: hierarchyInfo,
1246
+ selectedIndex: hierarchy.length - 1,
1247
+ ...bounds && { bounds },
1248
+ ...isEmpty !== void 0 && { isEmpty }
1249
+ };
1250
+ if (window.parent && window.parent !== window) {
1251
+ window.parent.postMessage(message, "*");
1252
+ console.log("[AmplifyUp SDK] Sent selection message:", message);
1253
+ }
1254
+ }
1255
+ /**
1256
+ * Send component tree to orchestrator
1257
+ * Note: Component tree is now sent from AmplifyRenderer based on layoutTree from pageConfig
1258
+ * This method is kept for backwards compatibility but is no longer used
1259
+ */
1260
+ sendComponentTree() {
1261
+ console.log("[AmplifyUp SDK] sendComponentTree called but component tree is now sent from AmplifyRenderer");
1262
+ }
1263
+ /**
1264
+ * Apply component highlights
1265
+ */
1266
+ applyComponentHighlights() {
1267
+ if (typeof document === "undefined") return;
1268
+ if (!this.isVisualEditorMode) {
1269
+ return;
1270
+ }
1271
+ const doc = document;
1272
+ const win = window;
1273
+ const componentElements = doc.querySelectorAll("[data-amplifyup-component], [data-component-id]");
1274
+ console.log("[AmplifyUp SDK] Found", componentElements.length, "components to highlight");
1275
+ this.sendComponentTree();
1276
+ const slotElements = doc.querySelectorAll("[data-amplifyup-slot]");
1277
+ console.log("[AmplifyUp SDK] Found", slotElements.length, "slots to highlight");
1278
+ componentElements.forEach((el) => {
1279
+ const htmlEl = el;
1280
+ const componentId = htmlEl.getAttribute("data-amplifyup-component") || htmlEl.getAttribute("data-component-id");
1281
+ if (!componentId) return;
1282
+ if (htmlEl.classList.contains("amplifyup-component-highlight")) return;
1283
+ const component = this.componentRegistry.find((c) => c.component_id === componentId);
1284
+ htmlEl.classList.add("amplifyup-component-highlight");
1285
+ htmlEl.setAttribute("data-component-id", componentId);
1286
+ htmlEl.setAttribute("data-component-name", component?.component_name || componentId);
1287
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1288
+ const handleClick = (e) => {
1289
+ e.stopPropagation();
1290
+ this.sendSelectionMessage(htmlEl, hierarchy);
1291
+ if (window.parent && window.parent !== window) {
1292
+ window.parent.postMessage({ type: "CHECK_COMPONENT_DELETABLE", componentId }, "*");
1293
+ }
1294
+ };
1295
+ htmlEl.addEventListener("click", handleClick);
1296
+ htmlEl._amplifyupHandlers = { handleClick };
1297
+ });
1298
+ this.componentRegistry.forEach((component) => {
1299
+ if (!component.data_attribute) return;
1300
+ const elements = doc.querySelectorAll(`[${component.data_attribute}]`);
1301
+ elements.forEach((el) => {
1302
+ const htmlEl = el;
1303
+ if (htmlEl.classList.contains("amplifyup-component-highlight")) return;
1304
+ htmlEl.classList.add("amplifyup-component-highlight");
1305
+ htmlEl.setAttribute("data-component-id", component.component_id);
1306
+ htmlEl.setAttribute("data-component-name", component.component_name);
1307
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1308
+ const handleClick = (e) => {
1309
+ e.stopPropagation();
1310
+ this.sendSelectionMessage(htmlEl, hierarchy);
1311
+ if (window.parent && window.parent !== window) {
1312
+ window.parent.postMessage({ type: "CHECK_COMPONENT_DELETABLE", componentId: component.component_id }, "*");
1313
+ }
1314
+ };
1315
+ htmlEl.addEventListener("click", handleClick);
1316
+ htmlEl._amplifyupHandlers = { handleClick };
1317
+ });
1318
+ });
1319
+ slotElements.forEach((el) => {
1320
+ const htmlEl = el;
1321
+ const slotName = htmlEl.getAttribute("data-amplifyup-slot");
1322
+ const isEmpty = htmlEl.getAttribute("data-slot-empty") === "true";
1323
+ if (!slotName) return;
1324
+ if (htmlEl.classList.contains("amplifyup-slot-highlight")) return;
1325
+ htmlEl.classList.add("amplifyup-slot-highlight");
1326
+ const hierarchy = this.buildComponentHierarchy(htmlEl);
1327
+ const handleClick = (e) => {
1328
+ e.stopPropagation();
1329
+ this.sendSelectionMessage(htmlEl, hierarchy, isEmpty);
1330
+ };
1331
+ const handleDrop = (e) => {
1332
+ e.preventDefault();
1333
+ e.stopPropagation();
1334
+ try {
1335
+ const data = JSON.parse(e.dataTransfer.getData("application/json"));
1336
+ if (data.type === "component" && win.parent && win.parent !== win) {
1337
+ win.parent.postMessage({
1338
+ type: "COMPONENT_DROPPED",
1339
+ componentId: data.componentId,
1340
+ componentName: data.componentName,
1341
+ slotName,
1342
+ slotElement: { path: htmlEl.getAttribute("data-slot-path"), isEmpty }
1343
+ }, "*");
1344
+ }
1345
+ } catch (_err) {
1346
+ }
1347
+ };
1348
+ const handleDragOver = (e) => {
1349
+ e.preventDefault();
1350
+ e.stopPropagation();
1351
+ e.dataTransfer.dropEffect = "copy";
1352
+ };
1353
+ htmlEl.addEventListener("click", handleClick);
1354
+ htmlEl.addEventListener("dragover", handleDragOver);
1355
+ htmlEl.addEventListener("drop", handleDrop);
1356
+ htmlEl._amplifyupSlotHandlers = { handleClick, handleDragOver, handleDrop };
1357
+ });
1358
+ }
1359
+ /**
1360
+ * Cleanup: Remove message listener and observers
1361
+ */
1362
+ cleanup() {
1363
+ if (this.messageListener) {
1364
+ window.removeEventListener("message", this.messageListener);
1365
+ this.messageListener = null;
1366
+ }
1367
+ this.disableHighlighting();
1368
+ }
1369
+ };
1370
+ var sdkInstance = null;
1371
+ function getSDK(adapter) {
1372
+ if (!sdkInstance) {
1373
+ sdkInstance = new AmplifyUpSDK(adapter);
1374
+ }
1375
+ return sdkInstance;
1376
+ }
1377
+ getSDK();
1378
+
1379
+ // src/server.tsx
1380
+ async function fetchPageConfigServer(route, trackingId, preview = false) {
1381
+ const sdk = getSDK();
1382
+ const orchestratorUrl = typeof process !== "undefined" && process.env.NEXT_PUBLIC_ORCHESTRATOR_URL || "http://localhost:5001";
1383
+ const originalConfig = sdk.config;
1384
+ sdk.config = {
1385
+ trackingId,
1386
+ orchestratorUrl
1387
+ };
1388
+ try {
1389
+ const page = await sdk.fetchPageConfig(route, preview);
1390
+ return page;
1391
+ } finally {
1392
+ sdk.config = originalConfig;
1393
+ }
1394
+ }
1395
+
1396
+ exports.fetchPageConfigServer = fetchPageConfigServer;
1397
+ //# sourceMappingURL=server.js.map
1398
+ //# sourceMappingURL=server.js.map