@amplifyup/sdk 0.1.1 → 0.1.2

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