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