@uniformdev/canvas 18.11.1-alpha.4 → 18.11.1-alpha.5

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,1534 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined")
12
+ return require.apply(this, arguments);
13
+ throw new Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __esm = (fn, res) => function __init() {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ };
18
+ var __commonJS = (cb, mod) => function __require2() {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ };
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, { get: all[name], enumerable: true });
24
+ };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") {
27
+ for (let key of __getOwnPropNames(from))
28
+ if (!__hasOwnProp.call(to, key) && key !== except)
29
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
+ mod
36
+ ));
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+ var __publicField = (obj, key, value) => {
39
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
40
+ return value;
41
+ };
42
+ var __accessCheck = (obj, member, msg) => {
43
+ if (!member.has(obj))
44
+ throw TypeError("Cannot " + msg);
45
+ };
46
+ var __privateGet = (obj, member, getter) => {
47
+ __accessCheck(obj, member, "read from private field");
48
+ return getter ? getter.call(obj) : member.get(obj);
49
+ };
50
+ var __privateAdd = (obj, member, value) => {
51
+ if (member.has(obj))
52
+ throw TypeError("Cannot add the same private member more than once");
53
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
54
+ };
55
+ var __privateSet = (obj, member, value, setter) => {
56
+ __accessCheck(obj, member, "write to private field");
57
+ setter ? setter.call(obj, value) : member.set(obj, value);
58
+ return value;
59
+ };
60
+ var __privateWrapper = (obj, member, setter, getter) => ({
61
+ set _(value) {
62
+ __privateSet(obj, member, value, setter);
63
+ },
64
+ get _() {
65
+ return __privateGet(obj, member, getter);
66
+ }
67
+ });
68
+
69
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
70
+ var require_retry_operation = __commonJS({
71
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
72
+ function RetryOperation(timeouts, options) {
73
+ if (typeof options === "boolean") {
74
+ options = { forever: options };
75
+ }
76
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
77
+ this._timeouts = timeouts;
78
+ this._options = options || {};
79
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
80
+ this._fn = null;
81
+ this._errors = [];
82
+ this._attempts = 1;
83
+ this._operationTimeout = null;
84
+ this._operationTimeoutCb = null;
85
+ this._timeout = null;
86
+ this._operationStart = null;
87
+ this._timer = null;
88
+ if (this._options.forever) {
89
+ this._cachedTimeouts = this._timeouts.slice(0);
90
+ }
91
+ }
92
+ module.exports = RetryOperation;
93
+ RetryOperation.prototype.reset = function() {
94
+ this._attempts = 1;
95
+ this._timeouts = this._originalTimeouts.slice(0);
96
+ };
97
+ RetryOperation.prototype.stop = function() {
98
+ if (this._timeout) {
99
+ clearTimeout(this._timeout);
100
+ }
101
+ if (this._timer) {
102
+ clearTimeout(this._timer);
103
+ }
104
+ this._timeouts = [];
105
+ this._cachedTimeouts = null;
106
+ };
107
+ RetryOperation.prototype.retry = function(err) {
108
+ if (this._timeout) {
109
+ clearTimeout(this._timeout);
110
+ }
111
+ if (!err) {
112
+ return false;
113
+ }
114
+ var currentTime = new Date().getTime();
115
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
116
+ this._errors.push(err);
117
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
118
+ return false;
119
+ }
120
+ this._errors.push(err);
121
+ var timeout = this._timeouts.shift();
122
+ if (timeout === void 0) {
123
+ if (this._cachedTimeouts) {
124
+ this._errors.splice(0, this._errors.length - 1);
125
+ timeout = this._cachedTimeouts.slice(-1);
126
+ } else {
127
+ return false;
128
+ }
129
+ }
130
+ var self = this;
131
+ this._timer = setTimeout(function() {
132
+ self._attempts++;
133
+ if (self._operationTimeoutCb) {
134
+ self._timeout = setTimeout(function() {
135
+ self._operationTimeoutCb(self._attempts);
136
+ }, self._operationTimeout);
137
+ if (self._options.unref) {
138
+ self._timeout.unref();
139
+ }
140
+ }
141
+ self._fn(self._attempts);
142
+ }, timeout);
143
+ if (this._options.unref) {
144
+ this._timer.unref();
145
+ }
146
+ return true;
147
+ };
148
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
149
+ this._fn = fn;
150
+ if (timeoutOps) {
151
+ if (timeoutOps.timeout) {
152
+ this._operationTimeout = timeoutOps.timeout;
153
+ }
154
+ if (timeoutOps.cb) {
155
+ this._operationTimeoutCb = timeoutOps.cb;
156
+ }
157
+ }
158
+ var self = this;
159
+ if (this._operationTimeoutCb) {
160
+ this._timeout = setTimeout(function() {
161
+ self._operationTimeoutCb();
162
+ }, self._operationTimeout);
163
+ }
164
+ this._operationStart = new Date().getTime();
165
+ this._fn(this._attempts);
166
+ };
167
+ RetryOperation.prototype.try = function(fn) {
168
+ console.log("Using RetryOperation.try() is deprecated");
169
+ this.attempt(fn);
170
+ };
171
+ RetryOperation.prototype.start = function(fn) {
172
+ console.log("Using RetryOperation.start() is deprecated");
173
+ this.attempt(fn);
174
+ };
175
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
176
+ RetryOperation.prototype.errors = function() {
177
+ return this._errors;
178
+ };
179
+ RetryOperation.prototype.attempts = function() {
180
+ return this._attempts;
181
+ };
182
+ RetryOperation.prototype.mainError = function() {
183
+ if (this._errors.length === 0) {
184
+ return null;
185
+ }
186
+ var counts = {};
187
+ var mainError = null;
188
+ var mainErrorCount = 0;
189
+ for (var i = 0; i < this._errors.length; i++) {
190
+ var error = this._errors[i];
191
+ var message = error.message;
192
+ var count = (counts[message] || 0) + 1;
193
+ counts[message] = count;
194
+ if (count >= mainErrorCount) {
195
+ mainError = error;
196
+ mainErrorCount = count;
197
+ }
198
+ }
199
+ return mainError;
200
+ };
201
+ }
202
+ });
203
+
204
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
205
+ var require_retry = __commonJS({
206
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
207
+ var RetryOperation = require_retry_operation();
208
+ exports.operation = function(options) {
209
+ var timeouts = exports.timeouts(options);
210
+ return new RetryOperation(timeouts, {
211
+ forever: options && (options.forever || options.retries === Infinity),
212
+ unref: options && options.unref,
213
+ maxRetryTime: options && options.maxRetryTime
214
+ });
215
+ };
216
+ exports.timeouts = function(options) {
217
+ if (options instanceof Array) {
218
+ return [].concat(options);
219
+ }
220
+ var opts = {
221
+ retries: 10,
222
+ factor: 2,
223
+ minTimeout: 1 * 1e3,
224
+ maxTimeout: Infinity,
225
+ randomize: false
226
+ };
227
+ for (var key in options) {
228
+ opts[key] = options[key];
229
+ }
230
+ if (opts.minTimeout > opts.maxTimeout) {
231
+ throw new Error("minTimeout is greater than maxTimeout");
232
+ }
233
+ var timeouts = [];
234
+ for (var i = 0; i < opts.retries; i++) {
235
+ timeouts.push(this.createTimeout(i, opts));
236
+ }
237
+ if (options && options.forever && !timeouts.length) {
238
+ timeouts.push(this.createTimeout(i, opts));
239
+ }
240
+ timeouts.sort(function(a, b) {
241
+ return a - b;
242
+ });
243
+ return timeouts;
244
+ };
245
+ exports.createTimeout = function(attempt, opts) {
246
+ var random = opts.randomize ? Math.random() + 1 : 1;
247
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
248
+ timeout = Math.min(timeout, opts.maxTimeout);
249
+ return timeout;
250
+ };
251
+ exports.wrap = function(obj, options, methods) {
252
+ if (options instanceof Array) {
253
+ methods = options;
254
+ options = null;
255
+ }
256
+ if (!methods) {
257
+ methods = [];
258
+ for (var key in obj) {
259
+ if (typeof obj[key] === "function") {
260
+ methods.push(key);
261
+ }
262
+ }
263
+ }
264
+ for (var i = 0; i < methods.length; i++) {
265
+ var method = methods[i];
266
+ var original = obj[method];
267
+ obj[method] = function retryWrapper(original2) {
268
+ var op = exports.operation(options);
269
+ var args = Array.prototype.slice.call(arguments, 1);
270
+ var callback = args.pop();
271
+ args.push(function(err) {
272
+ if (op.retry(err)) {
273
+ return;
274
+ }
275
+ if (err) {
276
+ arguments[0] = op.mainError();
277
+ }
278
+ callback.apply(this, arguments);
279
+ });
280
+ op.attempt(function() {
281
+ original2.apply(obj, args);
282
+ });
283
+ }.bind(obj, original);
284
+ obj[method].options = options;
285
+ }
286
+ };
287
+ }
288
+ });
289
+
290
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
291
+ var require_retry2 = __commonJS({
292
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
293
+ module.exports = require_retry();
294
+ }
295
+ });
296
+
297
+ // src/CanvasClient.ts
298
+ import { ApiClient } from "@uniformdev/context/api";
299
+
300
+ // ../../node_modules/.pnpm/p-retry@5.1.2/node_modules/p-retry/index.js
301
+ var import_retry = __toESM(require_retry2(), 1);
302
+ var networkErrorMsgs = /* @__PURE__ */ new Set([
303
+ "Failed to fetch",
304
+ "NetworkError when attempting to fetch resource.",
305
+ "The Internet connection appears to be offline.",
306
+ "Network request failed",
307
+ "fetch failed"
308
+ ]);
309
+ var AbortError = class extends Error {
310
+ constructor(message) {
311
+ super();
312
+ if (message instanceof Error) {
313
+ this.originalError = message;
314
+ ({ message } = message);
315
+ } else {
316
+ this.originalError = new Error(message);
317
+ this.originalError.stack = this.stack;
318
+ }
319
+ this.name = "AbortError";
320
+ this.message = message;
321
+ }
322
+ };
323
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
324
+ const retriesLeft = options.retries - (attemptNumber - 1);
325
+ error.attemptNumber = attemptNumber;
326
+ error.retriesLeft = retriesLeft;
327
+ return error;
328
+ };
329
+ var isNetworkError = (errorMessage) => networkErrorMsgs.has(errorMessage);
330
+ var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new Error(errorMessage) : new DOMException(errorMessage);
331
+ async function pRetry(input, options) {
332
+ return new Promise((resolve, reject) => {
333
+ options = {
334
+ onFailedAttempt() {
335
+ },
336
+ retries: 10,
337
+ ...options
338
+ };
339
+ const operation = import_retry.default.operation(options);
340
+ operation.attempt(async (attemptNumber) => {
341
+ try {
342
+ resolve(await input(attemptNumber));
343
+ } catch (error) {
344
+ if (!(error instanceof Error)) {
345
+ reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
346
+ return;
347
+ }
348
+ if (error instanceof AbortError) {
349
+ operation.stop();
350
+ reject(error.originalError);
351
+ } else if (error instanceof TypeError && !isNetworkError(error.message)) {
352
+ operation.stop();
353
+ reject(error);
354
+ } else {
355
+ decorateErrorWithCounts(error, attemptNumber, options);
356
+ try {
357
+ await options.onFailedAttempt(error);
358
+ } catch (error2) {
359
+ reject(error2);
360
+ return;
361
+ }
362
+ if (!operation.retry(error)) {
363
+ reject(operation.mainError());
364
+ }
365
+ }
366
+ }
367
+ });
368
+ if (options.signal && !options.signal.aborted) {
369
+ options.signal.addEventListener("abort", () => {
370
+ operation.stop();
371
+ const reason = options.signal.reason === void 0 ? getDOMException("The operation was aborted.") : options.signal.reason;
372
+ reject(reason instanceof Error ? reason : getDOMException(reason));
373
+ }, {
374
+ once: true
375
+ });
376
+ }
377
+ });
378
+ }
379
+
380
+ // ../../node_modules/.pnpm/p-throttle@5.0.0/node_modules/p-throttle/index.js
381
+ var AbortError2 = class extends Error {
382
+ constructor() {
383
+ super("Throttled function aborted");
384
+ this.name = "AbortError";
385
+ }
386
+ };
387
+ function pThrottle({ limit, interval, strict }) {
388
+ if (!Number.isFinite(limit)) {
389
+ throw new TypeError("Expected `limit` to be a finite number");
390
+ }
391
+ if (!Number.isFinite(interval)) {
392
+ throw new TypeError("Expected `interval` to be a finite number");
393
+ }
394
+ const queue = /* @__PURE__ */ new Map();
395
+ let currentTick = 0;
396
+ let activeCount = 0;
397
+ function windowedDelay() {
398
+ const now = Date.now();
399
+ if (now - currentTick > interval) {
400
+ activeCount = 1;
401
+ currentTick = now;
402
+ return 0;
403
+ }
404
+ if (activeCount < limit) {
405
+ activeCount++;
406
+ } else {
407
+ currentTick += interval;
408
+ activeCount = 1;
409
+ }
410
+ return currentTick - now;
411
+ }
412
+ const strictTicks = [];
413
+ function strictDelay() {
414
+ const now = Date.now();
415
+ if (strictTicks.length < limit) {
416
+ strictTicks.push(now);
417
+ return 0;
418
+ }
419
+ const earliestTime = strictTicks.shift() + interval;
420
+ if (now >= earliestTime) {
421
+ strictTicks.push(now);
422
+ return 0;
423
+ }
424
+ strictTicks.push(earliestTime);
425
+ return earliestTime - now;
426
+ }
427
+ const getDelay = strict ? strictDelay : windowedDelay;
428
+ return (function_) => {
429
+ const throttled = function(...args) {
430
+ if (!throttled.isEnabled) {
431
+ return (async () => function_.apply(this, args))();
432
+ }
433
+ let timeout;
434
+ return new Promise((resolve, reject) => {
435
+ const execute = () => {
436
+ resolve(function_.apply(this, args));
437
+ queue.delete(timeout);
438
+ };
439
+ timeout = setTimeout(execute, getDelay());
440
+ queue.set(timeout, reject);
441
+ });
442
+ };
443
+ throttled.abort = () => {
444
+ for (const timeout of queue.keys()) {
445
+ clearTimeout(timeout);
446
+ queue.get(timeout)(new AbortError2());
447
+ }
448
+ queue.clear();
449
+ strictTicks.splice(0, strictTicks.length);
450
+ };
451
+ throttled.isEnabled = true;
452
+ return throttled;
453
+ };
454
+ }
455
+
456
+ // src/enhancement/createLimitPolicy.ts
457
+ function createLimitPolicy({
458
+ throttle = { interval: 1e3, limit: 10 },
459
+ retry: retry2 = { retries: 1, factor: 1.66 }
460
+ }) {
461
+ const throttler = throttle ? pThrottle(throttle) : null;
462
+ return function limitPolicy(func) {
463
+ let currentFunc = async () => await func();
464
+ if (throttler) {
465
+ const throttleFunc = currentFunc;
466
+ currentFunc = throttler(throttleFunc);
467
+ }
468
+ if (retry2) {
469
+ const retryFunc = currentFunc;
470
+ currentFunc = () => pRetry(retryFunc, retry2);
471
+ }
472
+ return currentFunc();
473
+ };
474
+ }
475
+ var nullLimitPolicy = async (func) => await func();
476
+
477
+ // src/CanvasClient.ts
478
+ var CANVAS_URL = "/api/v1/canvas";
479
+ var CanvasClient = class extends ApiClient {
480
+ constructor(options) {
481
+ var _a;
482
+ if (!options.limitPolicy) {
483
+ options.limitPolicy = createLimitPolicy({});
484
+ }
485
+ super(options);
486
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
487
+ }
488
+ async getCompositionList(options) {
489
+ const { projectId } = this.options;
490
+ const fetchUri = this.createUrl(CANVAS_URL, { ...options, projectId });
491
+ return await this.apiClient(fetchUri);
492
+ }
493
+ getCompositionByNodePath(options) {
494
+ return this.getOneComposition(options);
495
+ }
496
+ unstable_getCompositionByNodePath(options) {
497
+ return this.getOneComposition(options);
498
+ }
499
+ getCompositionByNodeId(options) {
500
+ return this.getOneComposition(options);
501
+ }
502
+ unstable_getCompositionByNodeId(options) {
503
+ return this.getOneComposition(options);
504
+ }
505
+ getCompositionBySlug(options) {
506
+ return this.getOneComposition(options);
507
+ }
508
+ getCompositionById(options) {
509
+ return this.getOneComposition(options);
510
+ }
511
+ getOneComposition({
512
+ unstable_resolveData: resolveData,
513
+ unstable_dynamicVariables: dynamicVariables,
514
+ unstable_dataDiagnostics: dataDiagnostics,
515
+ ...params
516
+ }) {
517
+ const { projectId } = this.options;
518
+ if (!resolveData) {
519
+ return this.apiClient(this.createUrl(CANVAS_URL, { ...params, projectId }));
520
+ }
521
+ const edgeParams = {
522
+ ...params,
523
+ projectId,
524
+ ...dynamicVariables ? { dynamicVariables: JSON.stringify(dynamicVariables) } : {},
525
+ ...dataDiagnostics ? { dataDiagnostics: "true" } : {}
526
+ };
527
+ const edgeUrl = this.createUrl("/api/v1/composition", edgeParams, this.edgeApiHost);
528
+ return this.apiClient(edgeUrl);
529
+ }
530
+ async updateComposition(body) {
531
+ const fetchUri = this.createUrl(CANVAS_URL);
532
+ await this.apiClient(fetchUri, {
533
+ method: "PUT",
534
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
535
+ expectNoContent: true
536
+ });
537
+ }
538
+ async removeComposition(body) {
539
+ const fetchUri = this.createUrl(CANVAS_URL);
540
+ const { projectId } = this.options;
541
+ await this.apiClient(fetchUri, {
542
+ method: "DELETE",
543
+ body: JSON.stringify({ ...body, projectId }),
544
+ expectNoContent: true
545
+ });
546
+ }
547
+ async getComponentDefinitions(options) {
548
+ const { projectId } = this.options;
549
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions", { ...options, projectId });
550
+ return await this.apiClient(fetchUri);
551
+ }
552
+ async updateComponentDefinition(body) {
553
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
554
+ await this.apiClient(fetchUri, {
555
+ method: "PUT",
556
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
557
+ expectNoContent: true
558
+ });
559
+ }
560
+ async removeComponentDefinition(body) {
561
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
562
+ await this.apiClient(fetchUri, {
563
+ method: "DELETE",
564
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
565
+ expectNoContent: true
566
+ });
567
+ }
568
+ };
569
+ var UncachedCanvasClient = class extends CanvasClient {
570
+ constructor(options) {
571
+ super({ ...options, bypassCache: true });
572
+ }
573
+ };
574
+
575
+ // src/DataSourceClient.ts
576
+ import { ApiClient as ApiClient2 } from "@uniformdev/context/api";
577
+ var dataSourceUrl = "/api/v1/data-source";
578
+ var dataSourcesUrl = "/api/v1/data-sources";
579
+ var DataSourceClient = class extends ApiClient2 {
580
+ constructor(options) {
581
+ super(options);
582
+ }
583
+ async get(options) {
584
+ const { projectId } = this.options;
585
+ const fetchUri = this.createUrl(dataSourceUrl, { ...options, projectId });
586
+ return await this.apiClient(fetchUri);
587
+ }
588
+ async getList(options) {
589
+ const { projectId } = this.options;
590
+ const fetchUri = this.createUrl(dataSourcesUrl, { ...options, projectId });
591
+ return await this.apiClient(fetchUri);
592
+ }
593
+ async upsert(body) {
594
+ const fetchUri = this.createUrl(dataSourceUrl);
595
+ await this.apiClient(fetchUri, {
596
+ method: "PUT",
597
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
598
+ expectNoContent: true
599
+ });
600
+ }
601
+ async remove(body) {
602
+ const fetchUri = this.createUrl(dataSourceUrl);
603
+ await this.apiClient(fetchUri, {
604
+ method: "DELETE",
605
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
606
+ expectNoContent: true
607
+ });
608
+ }
609
+ };
610
+
611
+ // src/DataTypeClient.ts
612
+ import { ApiClient as ApiClient3 } from "@uniformdev/context/api";
613
+ var _url;
614
+ var _DataTypeClient = class extends ApiClient3 {
615
+ constructor(options) {
616
+ super(options);
617
+ }
618
+ async get(options) {
619
+ const { projectId } = this.options;
620
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url), { ...options, projectId });
621
+ return await this.apiClient(fetchUri);
622
+ }
623
+ async upsert(body) {
624
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url));
625
+ await this.apiClient(fetchUri, {
626
+ method: "PUT",
627
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
628
+ expectNoContent: true
629
+ });
630
+ }
631
+ async remove(body) {
632
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url));
633
+ await this.apiClient(fetchUri, {
634
+ method: "DELETE",
635
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
636
+ expectNoContent: true
637
+ });
638
+ }
639
+ };
640
+ var DataTypeClient = _DataTypeClient;
641
+ _url = new WeakMap();
642
+ __privateAdd(DataTypeClient, _url, "/api/v1/data-types");
643
+
644
+ // src/enhancement/batchEnhancer.ts
645
+ var BatchEntry = class {
646
+ constructor(_resolve, _reject, args) {
647
+ this._resolve = _resolve;
648
+ this._reject = _reject;
649
+ this.args = args;
650
+ this._isCompleted = false;
651
+ }
652
+ resolve(result) {
653
+ this._resolve(result);
654
+ this._isCompleted = true;
655
+ }
656
+ reject(reason) {
657
+ this._reject(reason);
658
+ this._isCompleted = true;
659
+ }
660
+ get isCompleted() {
661
+ return this._isCompleted;
662
+ }
663
+ };
664
+ function createBatchEnhancer({
665
+ handleBatch,
666
+ shouldQueue,
667
+ limitPolicy
668
+ }) {
669
+ let queue = [];
670
+ const batchedFn = async (options) => {
671
+ if (!shouldQueue || shouldQueue(options)) {
672
+ return new Promise((resolve, reject) => {
673
+ queue.push(new BatchEntry(resolve, reject, options));
674
+ });
675
+ } else {
676
+ return void 0;
677
+ }
678
+ };
679
+ const complete = async () => {
680
+ if (queue.length > 0) {
681
+ try {
682
+ await handleBatch(queue);
683
+ } catch (e) {
684
+ queue.forEach((entry) => entry.reject(e));
685
+ }
686
+ if (queue.some((entry) => !entry.isCompleted)) {
687
+ throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!");
688
+ }
689
+ }
690
+ const processed = queue.length;
691
+ queue = [];
692
+ return processed;
693
+ };
694
+ return { enhanceOne: batchedFn, completeAll: complete, limitPolicy };
695
+ }
696
+
697
+ // src/enhancement/compose.ts
698
+ var compose = (input, ...composers) => {
699
+ const composed = {
700
+ enhanceOne: (value) => {
701
+ let result = "enhanceOne" in input ? input.enhanceOne(value) : input(value);
702
+ for (const currentComposed of composers) {
703
+ const current = isPromise(result) ? result : Promise.resolve(result);
704
+ const enhanceOne = "enhanceOne" in currentComposed ? currentComposed.enhanceOne : currentComposed;
705
+ result = current.then(
706
+ (res) => enhanceOne({
707
+ ...value,
708
+ parameter: {
709
+ type: value.parameter.type,
710
+ value: res
711
+ }
712
+ })
713
+ );
714
+ }
715
+ return result;
716
+ },
717
+ completeAll: async () => {
718
+ var _a, _b;
719
+ for (const currentComposed of composers) {
720
+ if ("completeAll" in currentComposed) {
721
+ throw new Error(
722
+ "Only the first enhancer in a compose chain can use the completeAll function (batching)"
723
+ );
724
+ }
725
+ }
726
+ return (_b = "completeAll" in input ? (_a = input.completeAll) == null ? void 0 : _a.call(input) : 0) != null ? _b : 0;
727
+ }
728
+ };
729
+ return composed;
730
+ };
731
+ function isPromise(obj) {
732
+ return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
733
+ }
734
+
735
+ // src/enhancement/walkComponentTree.ts
736
+ function walkComponentTree(component, visitor, initialContext) {
737
+ var _a;
738
+ const componentQueue = [
739
+ {
740
+ ancestorsAndSelf: [{ component, parentSlot: void 0, parentSlotIndex: void 0 }],
741
+ context: initialContext
742
+ }
743
+ ];
744
+ const childContexts = /* @__PURE__ */ new Map();
745
+ do {
746
+ const currentQueueEntry = componentQueue.pop();
747
+ if (!currentQueueEntry)
748
+ continue;
749
+ const currentComponent = currentQueueEntry.ancestorsAndSelf[0];
750
+ let visitDescendants = true;
751
+ let descendantContext = (_a = childContexts.get(currentComponent.component)) != null ? _a : currentQueueEntry.context;
752
+ visitor(
753
+ currentComponent.component,
754
+ currentQueueEntry.ancestorsAndSelf,
755
+ {
756
+ replaceComponent: (replacementComponent) => {
757
+ Object.assign(currentComponent.component, replacementComponent);
758
+ const propertiesToCheck = [
759
+ "parameters",
760
+ "variant",
761
+ "slots",
762
+ "data",
763
+ "_pattern",
764
+ "_patternError"
765
+ ];
766
+ propertiesToCheck.forEach((property) => {
767
+ if (!replacementComponent[property]) {
768
+ delete currentComponent.component[property];
769
+ }
770
+ });
771
+ },
772
+ removeComponent: () => {
773
+ const { parentSlot, parentSlotIndex } = currentQueueEntry.ancestorsAndSelf[0];
774
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
775
+ if (parentSlot && typeof parentSlotIndex !== "undefined") {
776
+ parentComponent.component.slots[parentSlot].splice(parentSlotIndex, 1);
777
+ } else {
778
+ throw new Error("Unable to delete composition.");
779
+ }
780
+ },
781
+ insertAfter: (components) => {
782
+ const componentsToInsert = Array.isArray(components) ? components : [components];
783
+ const { parentSlot, parentSlotIndex } = currentQueueEntry.ancestorsAndSelf[0];
784
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
785
+ if (parentSlot && typeof parentSlotIndex !== "undefined") {
786
+ parentComponent.component.slots[parentSlot].splice(
787
+ parentSlotIndex + 1,
788
+ 0,
789
+ ...componentsToInsert
790
+ );
791
+ componentQueue.unshift(
792
+ ...componentsToInsert.map((enqueueingComponent) => ({
793
+ ancestorsAndSelf: [
794
+ {
795
+ component: enqueueingComponent,
796
+ parentSlot,
797
+ get parentSlotIndex() {
798
+ return parentComponent.component.slots[parentSlot].findIndex(
799
+ (x) => x === enqueueingComponent
800
+ );
801
+ }
802
+ },
803
+ ...currentQueueEntry.ancestorsAndSelf
804
+ ],
805
+ context: descendantContext
806
+ }))
807
+ );
808
+ } else {
809
+ throw new Error("Unable to insert after a component not in a slot.");
810
+ }
811
+ },
812
+ stopProcessingDescendants() {
813
+ visitDescendants = false;
814
+ },
815
+ setDescendantsContext(context) {
816
+ descendantContext = context;
817
+ },
818
+ setChildContext(child, context) {
819
+ childContexts.set(child, context);
820
+ }
821
+ },
822
+ descendantContext
823
+ );
824
+ const slots = currentComponent.component.slots;
825
+ if (visitDescendants && slots) {
826
+ const slotKeys = Object.keys(slots);
827
+ for (let slotIndex = slotKeys.length - 1; slotIndex >= 0; slotIndex--) {
828
+ const slotKey = slotKeys[slotIndex];
829
+ const components = slots[slotKey];
830
+ for (let componentIndex = components.length - 1; componentIndex >= 0; componentIndex--) {
831
+ const enqueueingComponent = components[componentIndex];
832
+ componentQueue.push({
833
+ ancestorsAndSelf: [
834
+ {
835
+ component: enqueueingComponent,
836
+ parentSlot: slotKey,
837
+ get parentSlotIndex() {
838
+ return currentComponent.component.slots[slotKey].findIndex(
839
+ (x) => x === enqueueingComponent
840
+ );
841
+ }
842
+ },
843
+ ...currentQueueEntry.ancestorsAndSelf
844
+ ],
845
+ context: descendantContext
846
+ });
847
+ }
848
+ }
849
+ }
850
+ } while (componentQueue.length > 0);
851
+ }
852
+ function getComponentPath(ancestorsAndSelf) {
853
+ const path = [];
854
+ for (let i = ancestorsAndSelf.length - 1; i >= 0; i--) {
855
+ const { parentSlot, parentSlotIndex } = ancestorsAndSelf[i];
856
+ if (parentSlot && parentSlotIndex !== void 0) {
857
+ path.push(`${parentSlot}[${parentSlotIndex}]`);
858
+ }
859
+ }
860
+ return `.${path.join(".")}`;
861
+ }
862
+ function getComponentJsonPointer(ancestorsAndSelf, { withSlots = false } = {}) {
863
+ const path = [];
864
+ for (let i = ancestorsAndSelf.length - 1; i >= 0; i--) {
865
+ const { parentSlot, parentSlotIndex } = ancestorsAndSelf[i];
866
+ if (parentSlot && parentSlotIndex !== void 0) {
867
+ path.push(`${parentSlot}/${parentSlotIndex}`);
868
+ }
869
+ }
870
+ return withSlots ? `/slots/${path.join("/slots/")}` : `/${path.join("/")}`;
871
+ }
872
+
873
+ // src/enhancement/enhance.ts
874
+ async function enhance({
875
+ composition,
876
+ enhancers,
877
+ context,
878
+ onErrors = (errors) => {
879
+ throw new Error(
880
+ errors.map(
881
+ (error) => `${error.message}
882
+ ${typeof error.error === "object" && "stack" in error.error ? error.error.stack : error.error}`
883
+ ).join("\n\n")
884
+ );
885
+ }
886
+ }) {
887
+ const promises = [];
888
+ const usedComponentEnhancers = /* @__PURE__ */ new Set();
889
+ const usedParameterEnhancers = /* @__PURE__ */ new Set();
890
+ walkComponentTree(composition, (currentComponent, componentContext) => {
891
+ var _a;
892
+ Object.entries((_a = currentComponent.parameters) != null ? _a : {}).forEach(([paramName, paramValue]) => {
893
+ const enhancer = enhancers.resolveParameterEnhancer(currentComponent, paramName, paramValue);
894
+ if (enhancer) {
895
+ usedParameterEnhancers.add(enhancer);
896
+ promises.push(
897
+ enhanceParameter(currentComponent, componentContext, paramName, paramValue, enhancer, context)
898
+ );
899
+ }
900
+ });
901
+ const componentEnhancers = enhancers.resolveComponentEnhancers(currentComponent);
902
+ promises.push(enhanceComponent(currentComponent, componentContext, componentEnhancers, context));
903
+ usedComponentEnhancers.add(componentEnhancers);
904
+ });
905
+ promises.push(
906
+ ...Array.from(usedComponentEnhancers).flatMap(
907
+ (enhancerSet) => Array.from(enhancerSet).map(async ([, enhancer]) => {
908
+ var _a;
909
+ try {
910
+ if (enhancer.completeAll) {
911
+ const limitPolicy = (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
912
+ await limitPolicy(() => enhancer.completeAll());
913
+ }
914
+ } catch (error) {
915
+ return {
916
+ error,
917
+ message: "Batch component enhancer failed. Individual failed components should receive their own rejections."
918
+ };
919
+ }
920
+ })
921
+ )
922
+ );
923
+ promises.push(
924
+ ...Array.from(usedParameterEnhancers).map(async (enhancer) => {
925
+ var _a;
926
+ try {
927
+ if (enhancer.completeAll) {
928
+ const limitPolicy = (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
929
+ await limitPolicy(() => enhancer.completeAll());
930
+ }
931
+ } catch (error) {
932
+ return {
933
+ error,
934
+ message: "Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."
935
+ };
936
+ }
937
+ })
938
+ );
939
+ const issues = (await Promise.all(promises)).flatMap((issue) => Array.isArray(issue) ? issue : [issue]).filter((issue) => issue);
940
+ if (issues.length) {
941
+ onErrors(issues);
942
+ }
943
+ }
944
+ async function enhanceComponent(component, componentContext, enhancers, context) {
945
+ if (enhancers.size) {
946
+ component.data = {};
947
+ }
948
+ return await Promise.all(
949
+ Array.from(enhancers).map(async ([enhancerName, enhancer]) => {
950
+ var _a;
951
+ try {
952
+ const limitPolicy = enhancer.completeAll ? nullLimitPolicy : (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
953
+ const result = await limitPolicy(async () => enhancer.enhanceOne({ component, context }));
954
+ if (result !== void 0 && result !== null) {
955
+ component.data[enhancerName] = result;
956
+ }
957
+ } catch (error) {
958
+ const message = `Component ${getComponentPath(componentContext)} (type: ${component.type}): data.${enhancerName} enhancer threw exception. Data key will not be present.`;
959
+ delete component.data[enhancerName];
960
+ return { message, error };
961
+ }
962
+ })
963
+ );
964
+ }
965
+ async function enhanceParameter(component, componentContext, parameterName, parameter, enhancer, context) {
966
+ var _a;
967
+ try {
968
+ const limitPolicy = enhancer.completeAll ? nullLimitPolicy : (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
969
+ const enhancedValue = await limitPolicy(
970
+ async () => enhancer.enhanceOne({ parameter, parameterName, component, context })
971
+ );
972
+ if (enhancedValue === null) {
973
+ delete component.parameters[parameterName];
974
+ } else if (typeof enhancedValue === "undefined") {
975
+ component.parameters[parameterName] = { ...parameter, value: parameter.value };
976
+ } else {
977
+ component.parameters[parameterName] = { ...parameter, value: enhancedValue };
978
+ }
979
+ } catch (error) {
980
+ const message = `Component ${getComponentPath(componentContext)} (type: ${component.type}): enhancing parameter ${parameterName} (type: ${parameter.type}) threw exception. Parameter will be removed.`;
981
+ delete component.parameters[parameterName];
982
+ return { message, error };
983
+ }
984
+ }
985
+
986
+ // src/enhancement/EnhancerBuilder.ts
987
+ var ChildEnhancerBuilder = class {
988
+ constructor() {
989
+ this._paramMatches = Array();
990
+ this._dataMatches = /* @__PURE__ */ new Map();
991
+ }
992
+ parameter(enhancer) {
993
+ this._paramMatches.push({ enhancer: this._resolveParameterEnhancer(enhancer) });
994
+ return this;
995
+ }
996
+ parameterName(name, enhancer) {
997
+ const names = Array.isArray(name) ? name : [name];
998
+ names.forEach(
999
+ (name2) => this._paramMatches.push({ name: name2, enhancer: this._resolveParameterEnhancer(enhancer) })
1000
+ );
1001
+ return this;
1002
+ }
1003
+ parameterType(type, enhancer) {
1004
+ const types = Array.isArray(type) ? type : [type];
1005
+ types.forEach(
1006
+ (type2) => this._paramMatches.push({ type: type2, enhancer: this._resolveParameterEnhancer(enhancer) })
1007
+ );
1008
+ return this;
1009
+ }
1010
+ data(name, enhancer) {
1011
+ if (this._dataMatches.has(name)) {
1012
+ throw new Error(`${name} enhancer data key has been used more than once. This will cause data loss.`);
1013
+ }
1014
+ this._dataMatches.set(name, typeof enhancer === "function" ? { enhanceOne: enhancer } : enhancer);
1015
+ return this;
1016
+ }
1017
+ resolveParameterEnhancer(parameterName, parameter) {
1018
+ var _a;
1019
+ return (_a = this._paramMatches.find(
1020
+ (m) => m.name && m.name === parameterName || m.type && m.type === parameter.type || !m.type && !m.name
1021
+ )) == null ? void 0 : _a.enhancer;
1022
+ }
1023
+ resolveComponentEnhancers() {
1024
+ return this._dataMatches;
1025
+ }
1026
+ _resolveParameterEnhancer(enhancer) {
1027
+ if (typeof enhancer === "function") {
1028
+ return { enhanceOne: enhancer };
1029
+ } else {
1030
+ return enhancer;
1031
+ }
1032
+ }
1033
+ };
1034
+ var EnhancerBuilder = class {
1035
+ constructor() {
1036
+ this._componentIndex = {};
1037
+ this._rootBuilder = new ChildEnhancerBuilder();
1038
+ }
1039
+ parameter(enhancer) {
1040
+ this._rootBuilder.parameter(enhancer);
1041
+ return this;
1042
+ }
1043
+ parameterName(name, enhancer) {
1044
+ this._rootBuilder.parameterName(name, enhancer);
1045
+ return this;
1046
+ }
1047
+ parameterType(type, enhancer) {
1048
+ this._rootBuilder.parameterType(type, enhancer);
1049
+ return this;
1050
+ }
1051
+ data(name, enhancer) {
1052
+ this._rootBuilder.data(name, enhancer);
1053
+ return this;
1054
+ }
1055
+ component(name, builder) {
1056
+ const names = Array.isArray(name) ? name : [name];
1057
+ names.forEach((name2) => {
1058
+ this._componentIndex[name2] = this._componentIndex[name2] || new ChildEnhancerBuilder();
1059
+ builder(this._componentIndex[name2]);
1060
+ });
1061
+ return this;
1062
+ }
1063
+ resolveParameterEnhancer(component, parameterName, parameter) {
1064
+ const eb = this._componentIndex[component.type];
1065
+ if (eb) {
1066
+ const targetedResolver = eb.resolveParameterEnhancer(parameterName, parameter);
1067
+ if (targetedResolver) {
1068
+ return targetedResolver;
1069
+ }
1070
+ }
1071
+ return this._rootBuilder.resolveParameterEnhancer(parameterName, parameter);
1072
+ }
1073
+ resolveComponentEnhancers(component) {
1074
+ let componentEnhancers = this._rootBuilder.resolveComponentEnhancers();
1075
+ const eb = this._componentIndex[component.type];
1076
+ if (eb) {
1077
+ componentEnhancers = new Map(componentEnhancers);
1078
+ for (const [key, value] of eb.resolveComponentEnhancers()) {
1079
+ componentEnhancers.set(key, value);
1080
+ }
1081
+ }
1082
+ return componentEnhancers;
1083
+ }
1084
+ };
1085
+
1086
+ // src/utils/constants.ts
1087
+ var CANVAS_PERSONALIZE_TYPE = "$personalization";
1088
+ var CANVAS_TEST_TYPE = "$test";
1089
+ var CANVAS_LOCALIZATION_TYPE = "$localization";
1090
+ var CANVAS_INTENT_TAG_PARAM = "intentTag";
1091
+ var CANVAS_LOCALE_TAG_PARAM = "locale";
1092
+ var CANVAS_PERSONALIZE_SLOT = "pz";
1093
+ var CANVAS_TEST_SLOT = "test";
1094
+ var CANVAS_LOCALIZATION_SLOT = "localized";
1095
+ var CANVAS_DRAFT_STATE = 0;
1096
+ var CANVAS_PUBLISHED_STATE = 64;
1097
+ var CANVAS_PERSONALIZATION_PARAM = "$pzCrit";
1098
+ var CANVAS_TEST_VARIANT_PARAM = "$tstVrnt";
1099
+ var CANVAS_ENRICHMENT_TAG_PARAM = "$enr";
1100
+ var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
1101
+ var IN_CONTEXT_EDITOR_COMPONENT_START_ROLE = "uniform-component-start";
1102
+ var IN_CONTEXT_EDITOR_EMBED_SCRIPT_ID = "uniform-canvas-preview-script";
1103
+ var PLACEHOLDER_ID = "placeholder";
1104
+ var EDGE_MIN_CACHE_TTL = 15;
1105
+ var EDGE_MAX_CACHE_TTL = 600;
1106
+ var EDGE_DEFAULT_CACHE_TTL = 30;
1107
+ var EDGE_CACHE_DISABLED = -1;
1108
+ var EDGE_MIN_L2_CACHE_TTL_IN_HOURS = 1;
1109
+ var EDGE_MAX_L2_CACHE_TTL_IN_HOURS = 4 * 7 * 24;
1110
+ var EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS = 24;
1111
+
1112
+ // src/enhancement/localize.ts
1113
+ function extractLocales({ component }) {
1114
+ var _a;
1115
+ const variations = {};
1116
+ const slot = (_a = component.slots) == null ? void 0 : _a[CANVAS_LOCALIZATION_SLOT];
1117
+ slot == null ? void 0 : slot.forEach((slotComponent) => {
1118
+ var _a2;
1119
+ const localeParameter = (_a2 = slotComponent.parameters) == null ? void 0 : _a2[CANVAS_LOCALE_TAG_PARAM];
1120
+ if ((localeParameter == null ? void 0 : localeParameter.value) && typeof localeParameter.value === "string") {
1121
+ variations[localeParameter.value] = variations[localeParameter.value] || [];
1122
+ variations[localeParameter.value].push(slotComponent);
1123
+ }
1124
+ });
1125
+ return variations;
1126
+ }
1127
+ function localize({
1128
+ composition,
1129
+ locale
1130
+ }) {
1131
+ walkComponentTree(composition, (currentComponent, _componentContext, actions) => {
1132
+ if (currentComponent.type === CANVAS_LOCALIZATION_TYPE) {
1133
+ const locales = extractLocales({ component: currentComponent });
1134
+ const resolvedLocale = typeof locale === "string" ? locale : locale({ component: currentComponent, locales });
1135
+ let replaceComponent;
1136
+ if (resolvedLocale) {
1137
+ replaceComponent = locales[resolvedLocale];
1138
+ }
1139
+ if (replaceComponent == null ? void 0 : replaceComponent.length) {
1140
+ const [first, ...rest] = replaceComponent;
1141
+ actions.replaceComponent(first);
1142
+ if (rest.length) {
1143
+ actions.insertAfter(rest);
1144
+ }
1145
+ } else {
1146
+ actions.removeComponent();
1147
+ }
1148
+ }
1149
+ });
1150
+ }
1151
+
1152
+ // src/enhancement/UniqueBatchEntries.ts
1153
+ var UniqueBatchEntries = class {
1154
+ constructor(entries, uniqueKeySelector) {
1155
+ this.groups = entries.reduce((acc, task) => {
1156
+ var _a;
1157
+ const key = uniqueKeySelector(task.args);
1158
+ acc[key] = (_a = acc[key]) != null ? _a : [];
1159
+ acc[key].push(task);
1160
+ return acc;
1161
+ }, {});
1162
+ }
1163
+ resolveKey(key, result) {
1164
+ this.groups[key].forEach((task) => task.resolve(result));
1165
+ }
1166
+ resolveRemaining(value) {
1167
+ Object.keys(this.groups).forEach((key) => {
1168
+ this.groups[key].forEach((task) => {
1169
+ if (!task.isCompleted) {
1170
+ task.resolve(value);
1171
+ }
1172
+ });
1173
+ });
1174
+ }
1175
+ };
1176
+
1177
+ // src/utils/hash.ts
1178
+ var generateHash = ({
1179
+ composition,
1180
+ secret
1181
+ }) => {
1182
+ if (!secret) {
1183
+ return void 0;
1184
+ }
1185
+ const str = `${JSON.stringify(composition)}-${secret}`;
1186
+ let hash = 0;
1187
+ for (let i = 0; i < str.length; i++) {
1188
+ const chr = str.charCodeAt(i);
1189
+ hash = (hash << 5) - hash + chr;
1190
+ hash |= 0;
1191
+ }
1192
+ return hash;
1193
+ };
1194
+
1195
+ // src/messaging/channel.ts
1196
+ var isSelectComponentMessage = (message) => {
1197
+ return message.type === "select-component" && message.id !== void 0;
1198
+ };
1199
+ var isReadyMessage = (message) => {
1200
+ return message.type === "ready";
1201
+ };
1202
+ var isUpdateCompositionMessage = (message) => {
1203
+ return message.type === "update-composition";
1204
+ };
1205
+ var isAddComponentMessage = (message) => {
1206
+ return message.type === "add-component";
1207
+ };
1208
+ var isMovingComponentMessage = (message) => {
1209
+ return message.type === "move-component";
1210
+ };
1211
+ var isDismissPlaceholderMessage = (message) => {
1212
+ return message.type === "dismiss-placeholder";
1213
+ };
1214
+ var createCanvasChannel = ({
1215
+ listenTo,
1216
+ broadcastTo
1217
+ }) => {
1218
+ let handlerCounter = 0;
1219
+ const handlers = {};
1220
+ const broadcastToItems = [...broadcastTo];
1221
+ const postMessage = (message) => {
1222
+ broadcastToItems.forEach((item) => item.postMessage(JSON.stringify(message), "*"));
1223
+ };
1224
+ const selectComponent = (id) => {
1225
+ const message = {
1226
+ type: "select-component",
1227
+ id
1228
+ };
1229
+ postMessage(message);
1230
+ };
1231
+ const ready = () => {
1232
+ var _a;
1233
+ if (typeof window === "undefined") {
1234
+ return;
1235
+ }
1236
+ const framework = (_a = window.__UNIFORM_CONTEXTUAL_EDITING__) == null ? void 0 : _a.framework;
1237
+ const message = {
1238
+ type: "ready",
1239
+ framework
1240
+ };
1241
+ postMessage(message);
1242
+ };
1243
+ const on = (types, handler) => {
1244
+ const handlerId = ++handlerCounter;
1245
+ handlers[handlerId] = {
1246
+ types: Array.isArray(types) ? types : [types],
1247
+ handler
1248
+ };
1249
+ return () => {
1250
+ delete handlers[handlerId];
1251
+ };
1252
+ };
1253
+ const updateComposition = (composition, secret) => {
1254
+ const message = {
1255
+ type: "update-composition",
1256
+ composition,
1257
+ hash: generateHash({
1258
+ composition,
1259
+ secret
1260
+ })
1261
+ };
1262
+ postMessage(message);
1263
+ };
1264
+ const addComponent = (options) => {
1265
+ const message = {
1266
+ ...options,
1267
+ type: "add-component"
1268
+ };
1269
+ postMessage(message);
1270
+ };
1271
+ const moveComponent = (options) => {
1272
+ const message = {
1273
+ ...options,
1274
+ type: "move-component"
1275
+ };
1276
+ postMessage(message);
1277
+ };
1278
+ const dismissPlaceholder = (options) => {
1279
+ const message = {
1280
+ ...options,
1281
+ type: "dismiss-placeholder"
1282
+ };
1283
+ postMessage(message);
1284
+ };
1285
+ const messageEventListener = (event) => {
1286
+ if (typeof event.data !== "string" || event.source === window) {
1287
+ return;
1288
+ }
1289
+ let message = null;
1290
+ try {
1291
+ const parsedMessage = JSON.parse(event.data);
1292
+ if (Object.hasOwn(parsedMessage, "type")) {
1293
+ message = parsedMessage;
1294
+ }
1295
+ } catch (e) {
1296
+ }
1297
+ if (!message) {
1298
+ return;
1299
+ }
1300
+ for (const handlerId in handlers) {
1301
+ const handler = handlers[handlerId];
1302
+ if (handler.types.includes(message.type)) {
1303
+ handler.handler(message, event);
1304
+ }
1305
+ }
1306
+ };
1307
+ listenTo.forEach((item) => item.addEventListener("message", messageEventListener));
1308
+ const destroy = () => {
1309
+ listenTo.forEach((item) => item.removeEventListener("message", messageEventListener));
1310
+ };
1311
+ return {
1312
+ ready,
1313
+ destroy,
1314
+ selectComponent,
1315
+ updateComposition,
1316
+ on,
1317
+ addComponent,
1318
+ moveComponent,
1319
+ dismissPlaceholder
1320
+ };
1321
+ };
1322
+
1323
+ // src/preview/createEventBus.ts
1324
+ var PUSHER_SRC = "https://js.pusher.com/7.0.3/pusher.min.js";
1325
+ async function loadPusher() {
1326
+ if (typeof document === "undefined" || typeof window === "undefined") {
1327
+ return;
1328
+ }
1329
+ if (window.Pusher) {
1330
+ return window.Pusher;
1331
+ }
1332
+ return new Promise((resolve, reject) => {
1333
+ const timeout = setTimeout(() => {
1334
+ if (window.Pusher) {
1335
+ resolve(window.Pusher);
1336
+ }
1337
+ reject(
1338
+ `Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${PUSHER_SRC}"><\/script> manually.`
1339
+ );
1340
+ }, 5e3);
1341
+ const pusher = document.createElement("script");
1342
+ pusher.src = PUSHER_SRC;
1343
+ pusher.addEventListener("load", () => {
1344
+ clearTimeout(timeout);
1345
+ resolve(window.Pusher);
1346
+ });
1347
+ document.head.appendChild(pusher);
1348
+ });
1349
+ }
1350
+ async function createEventBus() {
1351
+ const WindowPusher = await loadPusher();
1352
+ if (!WindowPusher) {
1353
+ return;
1354
+ }
1355
+ let bus = window.__UNIFORM_EVENT_BUS__;
1356
+ if (!bus) {
1357
+ const pusher = new WindowPusher("7b5f5abd160fea549ffe", {
1358
+ cluster: "mt1"
1359
+ });
1360
+ pusher.connect();
1361
+ console.log("[canvas] \u{1F525} preview connected");
1362
+ bus = window.__UNIFORM_EVENT_BUS__ = {
1363
+ subscribe: (channel) => {
1364
+ const channelObj = pusher.subscribe(channel);
1365
+ return {
1366
+ unsubscribe: () => pusher.unsubscribe(channel),
1367
+ addEventHandler: (eventName, handler) => {
1368
+ channelObj.bind(eventName, handler);
1369
+ return () => channelObj.unbind(eventName, handler);
1370
+ }
1371
+ };
1372
+ }
1373
+ };
1374
+ }
1375
+ return bus;
1376
+ }
1377
+
1378
+ // src/preview/getChannelName.ts
1379
+ function getChannelName(projectId, compositionId, state) {
1380
+ return `${projectId}.${compositionId}@${state}`;
1381
+ }
1382
+
1383
+ // src/preview/subscribeToComposition.ts
1384
+ function subscribeToComposition({
1385
+ projectId,
1386
+ compositionId,
1387
+ compositionState = 0,
1388
+ eventBus: { subscribe },
1389
+ callback,
1390
+ event = "updated"
1391
+ }) {
1392
+ const channelName = getChannelName(projectId, compositionId, compositionState);
1393
+ const channel = subscribe(channelName);
1394
+ const off = channel.addEventHandler(event, callback);
1395
+ return () => {
1396
+ off();
1397
+ channel.unsubscribe();
1398
+ };
1399
+ }
1400
+
1401
+ // src/utils/createApiEnhancer.ts
1402
+ var createUniformApiEnhancer = ({ apiUrl }) => {
1403
+ return async (message) => {
1404
+ const response = await fetch(apiUrl, {
1405
+ method: "post",
1406
+ body: JSON.stringify({
1407
+ composition: message.composition,
1408
+ hash: message.hash
1409
+ }),
1410
+ headers: {
1411
+ "Content-Type": "application/json"
1412
+ }
1413
+ });
1414
+ const json = await response.json();
1415
+ if (!response.ok) {
1416
+ throw new Error("Error reading enhanced composition");
1417
+ }
1418
+ const body = json;
1419
+ return body.composition;
1420
+ };
1421
+ };
1422
+
1423
+ // src/utils/isSystemComponentDefinition.ts
1424
+ var isSystemComponentDefinition = (componentType) => {
1425
+ return componentType.startsWith("$");
1426
+ };
1427
+
1428
+ // src/utils/mapSlotToPersonalizedVariations.ts
1429
+ function mapSlotToPersonalizedVariations(slot) {
1430
+ if (!slot)
1431
+ return [];
1432
+ return slot.map((v, i) => {
1433
+ var _a, _b;
1434
+ const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_PERSONALIZATION_PARAM]) == null ? void 0 : _b.value;
1435
+ const id = (contextTag == null ? void 0 : contextTag.name) || `pz-${i}-${v.type}`;
1436
+ return {
1437
+ ...v,
1438
+ id,
1439
+ pz: contextTag
1440
+ };
1441
+ });
1442
+ }
1443
+
1444
+ // src/utils/mapSlotToTestVariations.ts
1445
+ function mapSlotToTestVariations(slot) {
1446
+ if (!slot)
1447
+ return [];
1448
+ return slot.map((v, i) => {
1449
+ var _a, _b, _c;
1450
+ const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_TEST_VARIANT_PARAM]) == null ? void 0 : _b.value;
1451
+ const id = (_c = contextTag == null ? void 0 : contextTag.id) != null ? _c : "testId" in v ? v.testId : `ab-${i}-${v.type}`;
1452
+ return {
1453
+ ...v,
1454
+ id
1455
+ };
1456
+ });
1457
+ }
1458
+
1459
+ // src/index.ts
1460
+ import { ApiClientError } from "@uniformdev/context/api";
1461
+ var CanvasClientError = ApiClientError;
1462
+
1463
+ export {
1464
+ __require,
1465
+ __esm,
1466
+ __commonJS,
1467
+ __export,
1468
+ __toESM,
1469
+ __toCommonJS,
1470
+ __publicField,
1471
+ __privateGet,
1472
+ __privateAdd,
1473
+ __privateSet,
1474
+ __privateWrapper,
1475
+ createLimitPolicy,
1476
+ nullLimitPolicy,
1477
+ CanvasClient,
1478
+ UncachedCanvasClient,
1479
+ DataSourceClient,
1480
+ DataTypeClient,
1481
+ BatchEntry,
1482
+ createBatchEnhancer,
1483
+ compose,
1484
+ walkComponentTree,
1485
+ getComponentPath,
1486
+ getComponentJsonPointer,
1487
+ enhance,
1488
+ ChildEnhancerBuilder,
1489
+ EnhancerBuilder,
1490
+ CANVAS_PERSONALIZE_TYPE,
1491
+ CANVAS_TEST_TYPE,
1492
+ CANVAS_LOCALIZATION_TYPE,
1493
+ CANVAS_INTENT_TAG_PARAM,
1494
+ CANVAS_LOCALE_TAG_PARAM,
1495
+ CANVAS_PERSONALIZE_SLOT,
1496
+ CANVAS_TEST_SLOT,
1497
+ CANVAS_LOCALIZATION_SLOT,
1498
+ CANVAS_DRAFT_STATE,
1499
+ CANVAS_PUBLISHED_STATE,
1500
+ CANVAS_PERSONALIZATION_PARAM,
1501
+ CANVAS_TEST_VARIANT_PARAM,
1502
+ CANVAS_ENRICHMENT_TAG_PARAM,
1503
+ IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
1504
+ IN_CONTEXT_EDITOR_COMPONENT_START_ROLE,
1505
+ IN_CONTEXT_EDITOR_EMBED_SCRIPT_ID,
1506
+ PLACEHOLDER_ID,
1507
+ EDGE_MIN_CACHE_TTL,
1508
+ EDGE_MAX_CACHE_TTL,
1509
+ EDGE_DEFAULT_CACHE_TTL,
1510
+ EDGE_CACHE_DISABLED,
1511
+ EDGE_MIN_L2_CACHE_TTL_IN_HOURS,
1512
+ EDGE_MAX_L2_CACHE_TTL_IN_HOURS,
1513
+ EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS,
1514
+ extractLocales,
1515
+ localize,
1516
+ UniqueBatchEntries,
1517
+ generateHash,
1518
+ isSelectComponentMessage,
1519
+ isReadyMessage,
1520
+ isUpdateCompositionMessage,
1521
+ isAddComponentMessage,
1522
+ isMovingComponentMessage,
1523
+ isDismissPlaceholderMessage,
1524
+ createCanvasChannel,
1525
+ createEventBus,
1526
+ getChannelName,
1527
+ subscribeToComposition,
1528
+ createUniformApiEnhancer,
1529
+ isSystemComponentDefinition,
1530
+ mapSlotToPersonalizedVariations,
1531
+ mapSlotToTestVariations,
1532
+ ApiClientError,
1533
+ CanvasClientError
1534
+ };