@uniformdev/next-app-router 20.7.1-alpha.118

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,2648 @@
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 __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js
28
+ var require_yocto_queue = __commonJS({
29
+ "../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js"(exports, module) {
30
+ "use strict";
31
+ var Node = class {
32
+ /// value;
33
+ /// next;
34
+ constructor(value) {
35
+ this.value = value;
36
+ this.next = void 0;
37
+ }
38
+ };
39
+ var Queue = class {
40
+ // TODO: Use private class fields when targeting Node.js 12.
41
+ // #_head;
42
+ // #_tail;
43
+ // #_size;
44
+ constructor() {
45
+ this.clear();
46
+ }
47
+ enqueue(value) {
48
+ const node = new Node(value);
49
+ if (this._head) {
50
+ this._tail.next = node;
51
+ this._tail = node;
52
+ } else {
53
+ this._head = node;
54
+ this._tail = node;
55
+ }
56
+ this._size++;
57
+ }
58
+ dequeue() {
59
+ const current = this._head;
60
+ if (!current) {
61
+ return;
62
+ }
63
+ this._head = this._head.next;
64
+ this._size--;
65
+ return current.value;
66
+ }
67
+ clear() {
68
+ this._head = void 0;
69
+ this._tail = void 0;
70
+ this._size = 0;
71
+ }
72
+ get size() {
73
+ return this._size;
74
+ }
75
+ *[Symbol.iterator]() {
76
+ let current = this._head;
77
+ while (current) {
78
+ yield current.value;
79
+ current = current.next;
80
+ }
81
+ }
82
+ };
83
+ module.exports = Queue;
84
+ }
85
+ });
86
+
87
+ // ../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js
88
+ var require_p_limit = __commonJS({
89
+ "../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js"(exports, module) {
90
+ "use strict";
91
+ var Queue = require_yocto_queue();
92
+ var pLimit2 = (concurrency) => {
93
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
94
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
95
+ }
96
+ const queue = new Queue();
97
+ let activeCount = 0;
98
+ const next = () => {
99
+ activeCount--;
100
+ if (queue.size > 0) {
101
+ queue.dequeue()();
102
+ }
103
+ };
104
+ const run = async (fn, resolve, ...args) => {
105
+ activeCount++;
106
+ const result = (async () => fn(...args))();
107
+ resolve(result);
108
+ try {
109
+ await result;
110
+ } catch (e) {
111
+ }
112
+ next();
113
+ };
114
+ const enqueue = (fn, resolve, ...args) => {
115
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
116
+ (async () => {
117
+ await Promise.resolve();
118
+ if (activeCount < concurrency && queue.size > 0) {
119
+ queue.dequeue()();
120
+ }
121
+ })();
122
+ };
123
+ const generator = (fn, ...args) => new Promise((resolve) => {
124
+ enqueue(fn, resolve, ...args);
125
+ });
126
+ Object.defineProperties(generator, {
127
+ activeCount: {
128
+ get: () => activeCount
129
+ },
130
+ pendingCount: {
131
+ get: () => queue.size
132
+ },
133
+ clearQueue: {
134
+ value: () => {
135
+ queue.clear();
136
+ }
137
+ }
138
+ });
139
+ return generator;
140
+ };
141
+ module.exports = pLimit2;
142
+ }
143
+ });
144
+
145
+ // ../context/dist/api/api.mjs
146
+ var import_p_limit = __toESM(require_p_limit(), 1);
147
+ var __defProp2 = Object.defineProperty;
148
+ var __typeError = (msg) => {
149
+ throw TypeError(msg);
150
+ };
151
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
152
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
153
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
154
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
155
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
156
+ var defaultLimitPolicy = (0, import_p_limit.default)(6);
157
+ var ApiClientError = class _ApiClientError extends Error {
158
+ constructor(errorMessage, fetchMethod, fetchUri, statusCode, statusText, requestId) {
159
+ super(
160
+ `${errorMessage}
161
+ ${statusCode}${statusText ? " " + statusText : ""} (${fetchMethod} ${fetchUri}${requestId ? ` Request ID: ${requestId}` : ""})`
162
+ );
163
+ this.errorMessage = errorMessage;
164
+ this.fetchMethod = fetchMethod;
165
+ this.fetchUri = fetchUri;
166
+ this.statusCode = statusCode;
167
+ this.statusText = statusText;
168
+ this.requestId = requestId;
169
+ Object.setPrototypeOf(this, _ApiClientError.prototype);
170
+ }
171
+ };
172
+ var ApiClient = class _ApiClient {
173
+ constructor(options) {
174
+ __publicField(this, "options");
175
+ var _a, _b, _c, _d, _e;
176
+ if (!options.apiKey && !options.bearerToken) {
177
+ throw new Error("You must provide an API key or a bearer token");
178
+ }
179
+ let leFetch = options.fetch;
180
+ if (!leFetch) {
181
+ if (typeof window !== "undefined") {
182
+ leFetch = window.fetch.bind(window);
183
+ } else if (typeof fetch !== "undefined") {
184
+ leFetch = fetch;
185
+ } else {
186
+ throw new Error("You must provide or polyfill a fetch implementation when not in a browser");
187
+ }
188
+ }
189
+ this.options = {
190
+ ...options,
191
+ fetch: leFetch,
192
+ apiHost: this.ensureApiHost(options.apiHost),
193
+ apiKey: (_a = options.apiKey) != null ? _a : null,
194
+ projectId: (_b = options.projectId) != null ? _b : null,
195
+ bearerToken: (_c = options.bearerToken) != null ? _c : null,
196
+ limitPolicy: (_d = options.limitPolicy) != null ? _d : defaultLimitPolicy,
197
+ bypassCache: (_e = options.bypassCache) != null ? _e : false
198
+ };
199
+ }
200
+ async apiClient(fetchUri, options) {
201
+ return (await this.apiClientWithResponse(fetchUri, options)).body;
202
+ }
203
+ async apiClientWithResponse(fetchUri, options) {
204
+ return this.options.limitPolicy(async () => {
205
+ var _a;
206
+ const coreHeaders = this.options.apiKey ? {
207
+ "x-api-key": this.options.apiKey
208
+ } : {
209
+ Authorization: `Bearer ${this.options.bearerToken}`
210
+ };
211
+ if (this.options.bypassCache) {
212
+ coreHeaders["x-bypass-cache"] = "true";
213
+ }
214
+ const { fetch: fetch2, signal } = this.options;
215
+ const callApi = () => fetch2(fetchUri.toString(), {
216
+ ...options,
217
+ signal,
218
+ headers: {
219
+ ...options == null ? void 0 : options.headers,
220
+ ...coreHeaders
221
+ }
222
+ });
223
+ const apiResponse = await handleRateLimits(callApi);
224
+ if (!apiResponse.ok) {
225
+ let message = "";
226
+ try {
227
+ const responseText = await apiResponse.text();
228
+ try {
229
+ const parsed = JSON.parse(responseText);
230
+ if (parsed.errorMessage) {
231
+ message = Array.isArray(parsed.errorMessage) ? parsed.errorMessage.join(", ") : parsed.errorMessage;
232
+ } else {
233
+ message = responseText;
234
+ }
235
+ } catch (e) {
236
+ message = responseText;
237
+ }
238
+ } catch (e) {
239
+ message = `General error`;
240
+ }
241
+ throw new ApiClientError(
242
+ message,
243
+ (_a = options == null ? void 0 : options.method) != null ? _a : "GET",
244
+ fetchUri.toString(),
245
+ apiResponse.status,
246
+ apiResponse.statusText,
247
+ _ApiClient.getRequestId(apiResponse)
248
+ );
249
+ }
250
+ if (options == null ? void 0 : options.expectNoContent) {
251
+ return { response: apiResponse, body: null };
252
+ }
253
+ return {
254
+ response: apiResponse,
255
+ body: await apiResponse.json()
256
+ };
257
+ });
258
+ }
259
+ createUrl(path, queryParams, hostOverride) {
260
+ const url = new URL(`${hostOverride != null ? hostOverride : this.options.apiHost}${path}`);
261
+ Object.entries(queryParams != null ? queryParams : {}).forEach(([key, value]) => {
262
+ var _a;
263
+ if (typeof value !== "undefined" && value !== null) {
264
+ url.searchParams.append(key, Array.isArray(value) ? value.join(",") : (_a = value == null ? void 0 : value.toString()) != null ? _a : "");
265
+ }
266
+ });
267
+ return url;
268
+ }
269
+ ensureApiHost(apiHost) {
270
+ if (!apiHost) return "https://uniform.app";
271
+ if (!(apiHost == null ? void 0 : apiHost.startsWith("http"))) {
272
+ throw new Error('Your apiHost must start with "http"');
273
+ }
274
+ if (apiHost.indexOf("/", 8) > -1) {
275
+ throw new Error("Your apiHost must not contain a path element after the domain");
276
+ }
277
+ if (apiHost.indexOf("?") > -1) {
278
+ throw new Error("Your apiHost must not contain a query string");
279
+ }
280
+ if (apiHost == null ? void 0 : apiHost.endsWith("/")) {
281
+ apiHost = apiHost.substring(0, apiHost.length - 1);
282
+ }
283
+ return apiHost;
284
+ }
285
+ static getRequestId(response) {
286
+ const apigRequestId = response.headers.get("apigw-requestid");
287
+ if (apigRequestId) {
288
+ return apigRequestId;
289
+ }
290
+ return void 0;
291
+ }
292
+ };
293
+ async function handleRateLimits(callApi) {
294
+ var _a;
295
+ const backoffRetries = 5;
296
+ let backoffRetriesLeft = backoffRetries;
297
+ let response;
298
+ while (backoffRetriesLeft > 0) {
299
+ response = await callApi();
300
+ if (response.status !== 429) {
301
+ break;
302
+ }
303
+ let resetWait = 0;
304
+ try {
305
+ const responseClone = response.clone();
306
+ const dateHeader = responseClone.headers.get("date");
307
+ const serverTime = dateHeader ? new Date(dateHeader).getTime() : void 0;
308
+ const body = await responseClone.json();
309
+ const resetTime = (_a = body == null ? void 0 : body.info) == null ? void 0 : _a.reset;
310
+ if (typeof serverTime === "number" && typeof resetTime === "number") {
311
+ resetWait = Math.max(0, Math.min(Math.round(1.1 * (resetTime - serverTime)), 1e4));
312
+ }
313
+ } catch (e) {
314
+ }
315
+ const base = Math.pow(2, backoffRetries - backoffRetriesLeft) * 333;
316
+ const backoffWait = base + Math.round(Math.random() * (base / 2)) * (Math.random() > 0.5 ? 1 : -1);
317
+ await new Promise((resolve) => setTimeout(resolve, resetWait + backoffWait));
318
+ backoffRetriesLeft -= 1;
319
+ }
320
+ return response;
321
+ }
322
+ var _url;
323
+ var _AggregateClient = class _AggregateClient2 extends ApiClient {
324
+ constructor(options) {
325
+ super(options);
326
+ }
327
+ /** Fetches all aggregates for a project */
328
+ async get(options) {
329
+ const { projectId } = this.options;
330
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url), { ...options, projectId });
331
+ return await this.apiClient(fetchUri);
332
+ }
333
+ /** Updates or creates (based on id) an Aggregate */
334
+ async upsert(body) {
335
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url));
336
+ await this.apiClient(fetchUri, {
337
+ method: "PUT",
338
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
339
+ expectNoContent: true
340
+ });
341
+ }
342
+ /** Deletes an Aggregate */
343
+ async remove(body) {
344
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url));
345
+ await this.apiClient(fetchUri, {
346
+ method: "DELETE",
347
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
348
+ expectNoContent: true
349
+ });
350
+ }
351
+ };
352
+ _url = /* @__PURE__ */ new WeakMap();
353
+ __privateAdd(_AggregateClient, _url, "/api/v2/aggregate");
354
+ var _url2;
355
+ var _DimensionClient = class _DimensionClient2 extends ApiClient {
356
+ constructor(options) {
357
+ super(options);
358
+ }
359
+ /** Fetches the known score dimensions for a project */
360
+ async get(options) {
361
+ const { projectId } = this.options;
362
+ const fetchUri = this.createUrl(__privateGet(_DimensionClient2, _url2), { ...options, projectId });
363
+ return await this.apiClient(fetchUri);
364
+ }
365
+ };
366
+ _url2 = /* @__PURE__ */ new WeakMap();
367
+ __privateAdd(_DimensionClient, _url2, "/api/v2/dimension");
368
+ var _url3;
369
+ var _valueUrl;
370
+ var _EnrichmentClient = class _EnrichmentClient2 extends ApiClient {
371
+ constructor(options) {
372
+ super(options);
373
+ }
374
+ /** Fetches all enrichments and values for a project, grouped by category */
375
+ async get(options) {
376
+ const { projectId } = this.options;
377
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3), { ...options, projectId });
378
+ return await this.apiClient(fetchUri);
379
+ }
380
+ /** Updates or creates (based on id) an enrichment category */
381
+ async upsertCategory(body) {
382
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3));
383
+ await this.apiClient(fetchUri, {
384
+ method: "PUT",
385
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
386
+ expectNoContent: true
387
+ });
388
+ }
389
+ /** Deletes an enrichment category */
390
+ async removeCategory(body) {
391
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3));
392
+ await this.apiClient(fetchUri, {
393
+ method: "DELETE",
394
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
395
+ expectNoContent: true
396
+ });
397
+ }
398
+ /** Updates or creates (based on id) an enrichment value within an enrichment category */
399
+ async upsertValue(body) {
400
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _valueUrl));
401
+ await this.apiClient(fetchUri, {
402
+ method: "PUT",
403
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
404
+ expectNoContent: true
405
+ });
406
+ }
407
+ /** Deletes an enrichment value within an enrichment category. The category is left alone. */
408
+ async removeValue(body) {
409
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _valueUrl));
410
+ await this.apiClient(fetchUri, {
411
+ method: "DELETE",
412
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
413
+ expectNoContent: true
414
+ });
415
+ }
416
+ };
417
+ _url3 = /* @__PURE__ */ new WeakMap();
418
+ _valueUrl = /* @__PURE__ */ new WeakMap();
419
+ __privateAdd(_EnrichmentClient, _url3, "/api/v1/enrichments");
420
+ __privateAdd(_EnrichmentClient, _valueUrl, "/api/v1/enrichment-values");
421
+ var _url4;
422
+ var _ManifestClient = class _ManifestClient2 extends ApiClient {
423
+ constructor(options) {
424
+ super(options);
425
+ }
426
+ /** Fetches the Context manifest for a project */
427
+ async get(options) {
428
+ const { projectId } = this.options;
429
+ const fetchUri = this.createUrl(__privateGet(_ManifestClient2, _url4), { ...options, projectId });
430
+ return await this.apiClient(fetchUri);
431
+ }
432
+ /** Publishes the Context manifest for a project */
433
+ async publish() {
434
+ const { projectId } = this.options;
435
+ const fetchUri = this.createUrl("/api/v1/publish", { siteId: projectId });
436
+ await this.apiClient(fetchUri, {
437
+ method: "POST",
438
+ expectNoContent: true
439
+ });
440
+ }
441
+ };
442
+ _url4 = /* @__PURE__ */ new WeakMap();
443
+ __privateAdd(_ManifestClient, _url4, "/api/v2/manifest");
444
+ var _url5;
445
+ var _QuirkClient = class _QuirkClient2 extends ApiClient {
446
+ constructor(options) {
447
+ super(options);
448
+ }
449
+ /** Fetches all Quirks for a project */
450
+ async get(options) {
451
+ const { projectId } = this.options;
452
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5), { ...options, projectId });
453
+ return await this.apiClient(fetchUri);
454
+ }
455
+ /** Updates or creates (based on id) a Quirk */
456
+ async upsert(body) {
457
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5));
458
+ await this.apiClient(fetchUri, {
459
+ method: "PUT",
460
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
461
+ expectNoContent: true
462
+ });
463
+ }
464
+ /** Deletes a Quirk */
465
+ async remove(body) {
466
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5));
467
+ await this.apiClient(fetchUri, {
468
+ method: "DELETE",
469
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
470
+ expectNoContent: true
471
+ });
472
+ }
473
+ };
474
+ _url5 = /* @__PURE__ */ new WeakMap();
475
+ __privateAdd(_QuirkClient, _url5, "/api/v2/quirk");
476
+ var _url6;
477
+ var _SignalClient = class _SignalClient2 extends ApiClient {
478
+ constructor(options) {
479
+ super(options);
480
+ }
481
+ /** Fetches all Signals for a project */
482
+ async get(options) {
483
+ const { projectId } = this.options;
484
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6), { ...options, projectId });
485
+ return await this.apiClient(fetchUri);
486
+ }
487
+ /** Updates or creates (based on id) a Signal */
488
+ async upsert(body) {
489
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6));
490
+ await this.apiClient(fetchUri, {
491
+ method: "PUT",
492
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
493
+ expectNoContent: true
494
+ });
495
+ }
496
+ /** Deletes a Signal */
497
+ async remove(body) {
498
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6));
499
+ await this.apiClient(fetchUri, {
500
+ method: "DELETE",
501
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
502
+ expectNoContent: true
503
+ });
504
+ }
505
+ };
506
+ _url6 = /* @__PURE__ */ new WeakMap();
507
+ __privateAdd(_SignalClient, _url6, "/api/v2/signal");
508
+ var _url7;
509
+ var _TestClient = class _TestClient2 extends ApiClient {
510
+ constructor(options) {
511
+ super(options);
512
+ }
513
+ /** Fetches all Tests for a project */
514
+ async get(options) {
515
+ const { projectId } = this.options;
516
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7), { ...options, projectId });
517
+ return await this.apiClient(fetchUri);
518
+ }
519
+ /** Updates or creates (based on id) a Test */
520
+ async upsert(body) {
521
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7));
522
+ await this.apiClient(fetchUri, {
523
+ method: "PUT",
524
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
525
+ expectNoContent: true
526
+ });
527
+ }
528
+ /** Deletes a Test */
529
+ async remove(body) {
530
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7));
531
+ await this.apiClient(fetchUri, {
532
+ method: "DELETE",
533
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
534
+ expectNoContent: true
535
+ });
536
+ }
537
+ };
538
+ _url7 = /* @__PURE__ */ new WeakMap();
539
+ __privateAdd(_TestClient, _url7, "/api/v2/test");
540
+
541
+ // ../canvas/dist/index.mjs
542
+ var __create2 = Object.create;
543
+ var __defProp3 = Object.defineProperty;
544
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
545
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
546
+ var __getProtoOf2 = Object.getPrototypeOf;
547
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
548
+ var __typeError2 = (msg) => {
549
+ throw TypeError(msg);
550
+ };
551
+ var __commonJS2 = (cb, mod) => function __require() {
552
+ return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
553
+ };
554
+ var __copyProps2 = (to, from, except, desc) => {
555
+ if (from && typeof from === "object" || typeof from === "function") {
556
+ for (let key of __getOwnPropNames2(from))
557
+ if (!__hasOwnProp2.call(to, key) && key !== except)
558
+ __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
559
+ }
560
+ return to;
561
+ };
562
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
563
+ // If the importer is in node compatibility mode or this is not an ESM
564
+ // file that has been converted to a CommonJS file using a Babel-
565
+ // compatible transform (i.e. "__esModule" has not been set), then set
566
+ // "default" to the CommonJS "module.exports" for node compatibility.
567
+ isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
568
+ mod
569
+ ));
570
+ var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
571
+ var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
572
+ var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
573
+ var require_yocto_queue2 = __commonJS2({
574
+ "../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js"(exports, module) {
575
+ "use strict";
576
+ var Node = class {
577
+ /// value;
578
+ /// next;
579
+ constructor(value) {
580
+ this.value = value;
581
+ this.next = void 0;
582
+ }
583
+ };
584
+ var Queue = class {
585
+ // TODO: Use private class fields when targeting Node.js 12.
586
+ // #_head;
587
+ // #_tail;
588
+ // #_size;
589
+ constructor() {
590
+ this.clear();
591
+ }
592
+ enqueue(value) {
593
+ const node = new Node(value);
594
+ if (this._head) {
595
+ this._tail.next = node;
596
+ this._tail = node;
597
+ } else {
598
+ this._head = node;
599
+ this._tail = node;
600
+ }
601
+ this._size++;
602
+ }
603
+ dequeue() {
604
+ const current = this._head;
605
+ if (!current) {
606
+ return;
607
+ }
608
+ this._head = this._head.next;
609
+ this._size--;
610
+ return current.value;
611
+ }
612
+ clear() {
613
+ this._head = void 0;
614
+ this._tail = void 0;
615
+ this._size = 0;
616
+ }
617
+ get size() {
618
+ return this._size;
619
+ }
620
+ *[Symbol.iterator]() {
621
+ let current = this._head;
622
+ while (current) {
623
+ yield current.value;
624
+ current = current.next;
625
+ }
626
+ }
627
+ };
628
+ module.exports = Queue;
629
+ }
630
+ });
631
+ var require_p_limit2 = __commonJS2({
632
+ "../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js"(exports, module) {
633
+ "use strict";
634
+ var Queue = require_yocto_queue2();
635
+ var pLimit2 = (concurrency) => {
636
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
637
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
638
+ }
639
+ const queue = new Queue();
640
+ let activeCount = 0;
641
+ const next = () => {
642
+ activeCount--;
643
+ if (queue.size > 0) {
644
+ queue.dequeue()();
645
+ }
646
+ };
647
+ const run = async (fn, resolve, ...args) => {
648
+ activeCount++;
649
+ const result = (async () => fn(...args))();
650
+ resolve(result);
651
+ try {
652
+ await result;
653
+ } catch (e) {
654
+ }
655
+ next();
656
+ };
657
+ const enqueue = (fn, resolve, ...args) => {
658
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
659
+ (async () => {
660
+ await Promise.resolve();
661
+ if (activeCount < concurrency && queue.size > 0) {
662
+ queue.dequeue()();
663
+ }
664
+ })();
665
+ };
666
+ const generator = (fn, ...args) => new Promise((resolve) => {
667
+ enqueue(fn, resolve, ...args);
668
+ });
669
+ Object.defineProperties(generator, {
670
+ activeCount: {
671
+ get: () => activeCount
672
+ },
673
+ pendingCount: {
674
+ get: () => queue.size
675
+ },
676
+ clearQueue: {
677
+ value: () => {
678
+ queue.clear();
679
+ }
680
+ }
681
+ });
682
+ return generator;
683
+ };
684
+ module.exports = pLimit2;
685
+ }
686
+ });
687
+ var require_retry_operation = __commonJS2({
688
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
689
+ "use strict";
690
+ function RetryOperation(timeouts, options) {
691
+ if (typeof options === "boolean") {
692
+ options = { forever: options };
693
+ }
694
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
695
+ this._timeouts = timeouts;
696
+ this._options = options || {};
697
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
698
+ this._fn = null;
699
+ this._errors = [];
700
+ this._attempts = 1;
701
+ this._operationTimeout = null;
702
+ this._operationTimeoutCb = null;
703
+ this._timeout = null;
704
+ this._operationStart = null;
705
+ this._timer = null;
706
+ if (this._options.forever) {
707
+ this._cachedTimeouts = this._timeouts.slice(0);
708
+ }
709
+ }
710
+ module.exports = RetryOperation;
711
+ RetryOperation.prototype.reset = function() {
712
+ this._attempts = 1;
713
+ this._timeouts = this._originalTimeouts.slice(0);
714
+ };
715
+ RetryOperation.prototype.stop = function() {
716
+ if (this._timeout) {
717
+ clearTimeout(this._timeout);
718
+ }
719
+ if (this._timer) {
720
+ clearTimeout(this._timer);
721
+ }
722
+ this._timeouts = [];
723
+ this._cachedTimeouts = null;
724
+ };
725
+ RetryOperation.prototype.retry = function(err) {
726
+ if (this._timeout) {
727
+ clearTimeout(this._timeout);
728
+ }
729
+ if (!err) {
730
+ return false;
731
+ }
732
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
733
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
734
+ this._errors.push(err);
735
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
736
+ return false;
737
+ }
738
+ this._errors.push(err);
739
+ var timeout = this._timeouts.shift();
740
+ if (timeout === void 0) {
741
+ if (this._cachedTimeouts) {
742
+ this._errors.splice(0, this._errors.length - 1);
743
+ timeout = this._cachedTimeouts.slice(-1);
744
+ } else {
745
+ return false;
746
+ }
747
+ }
748
+ var self = this;
749
+ this._timer = setTimeout(function() {
750
+ self._attempts++;
751
+ if (self._operationTimeoutCb) {
752
+ self._timeout = setTimeout(function() {
753
+ self._operationTimeoutCb(self._attempts);
754
+ }, self._operationTimeout);
755
+ if (self._options.unref) {
756
+ self._timeout.unref();
757
+ }
758
+ }
759
+ self._fn(self._attempts);
760
+ }, timeout);
761
+ if (this._options.unref) {
762
+ this._timer.unref();
763
+ }
764
+ return true;
765
+ };
766
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
767
+ this._fn = fn;
768
+ if (timeoutOps) {
769
+ if (timeoutOps.timeout) {
770
+ this._operationTimeout = timeoutOps.timeout;
771
+ }
772
+ if (timeoutOps.cb) {
773
+ this._operationTimeoutCb = timeoutOps.cb;
774
+ }
775
+ }
776
+ var self = this;
777
+ if (this._operationTimeoutCb) {
778
+ this._timeout = setTimeout(function() {
779
+ self._operationTimeoutCb();
780
+ }, self._operationTimeout);
781
+ }
782
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
783
+ this._fn(this._attempts);
784
+ };
785
+ RetryOperation.prototype.try = function(fn) {
786
+ console.log("Using RetryOperation.try() is deprecated");
787
+ this.attempt(fn);
788
+ };
789
+ RetryOperation.prototype.start = function(fn) {
790
+ console.log("Using RetryOperation.start() is deprecated");
791
+ this.attempt(fn);
792
+ };
793
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
794
+ RetryOperation.prototype.errors = function() {
795
+ return this._errors;
796
+ };
797
+ RetryOperation.prototype.attempts = function() {
798
+ return this._attempts;
799
+ };
800
+ RetryOperation.prototype.mainError = function() {
801
+ if (this._errors.length === 0) {
802
+ return null;
803
+ }
804
+ var counts = {};
805
+ var mainError = null;
806
+ var mainErrorCount = 0;
807
+ for (var i = 0; i < this._errors.length; i++) {
808
+ var error = this._errors[i];
809
+ var message = error.message;
810
+ var count = (counts[message] || 0) + 1;
811
+ counts[message] = count;
812
+ if (count >= mainErrorCount) {
813
+ mainError = error;
814
+ mainErrorCount = count;
815
+ }
816
+ }
817
+ return mainError;
818
+ };
819
+ }
820
+ });
821
+ var require_retry = __commonJS2({
822
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
823
+ "use strict";
824
+ var RetryOperation = require_retry_operation();
825
+ exports.operation = function(options) {
826
+ var timeouts = exports.timeouts(options);
827
+ return new RetryOperation(timeouts, {
828
+ forever: options && (options.forever || options.retries === Infinity),
829
+ unref: options && options.unref,
830
+ maxRetryTime: options && options.maxRetryTime
831
+ });
832
+ };
833
+ exports.timeouts = function(options) {
834
+ if (options instanceof Array) {
835
+ return [].concat(options);
836
+ }
837
+ var opts = {
838
+ retries: 10,
839
+ factor: 2,
840
+ minTimeout: 1 * 1e3,
841
+ maxTimeout: Infinity,
842
+ randomize: false
843
+ };
844
+ for (var key in options) {
845
+ opts[key] = options[key];
846
+ }
847
+ if (opts.minTimeout > opts.maxTimeout) {
848
+ throw new Error("minTimeout is greater than maxTimeout");
849
+ }
850
+ var timeouts = [];
851
+ for (var i = 0; i < opts.retries; i++) {
852
+ timeouts.push(this.createTimeout(i, opts));
853
+ }
854
+ if (options && options.forever && !timeouts.length) {
855
+ timeouts.push(this.createTimeout(i, opts));
856
+ }
857
+ timeouts.sort(function(a, b) {
858
+ return a - b;
859
+ });
860
+ return timeouts;
861
+ };
862
+ exports.createTimeout = function(attempt, opts) {
863
+ var random = opts.randomize ? Math.random() + 1 : 1;
864
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
865
+ timeout = Math.min(timeout, opts.maxTimeout);
866
+ return timeout;
867
+ };
868
+ exports.wrap = function(obj, options, methods) {
869
+ if (options instanceof Array) {
870
+ methods = options;
871
+ options = null;
872
+ }
873
+ if (!methods) {
874
+ methods = [];
875
+ for (var key in obj) {
876
+ if (typeof obj[key] === "function") {
877
+ methods.push(key);
878
+ }
879
+ }
880
+ }
881
+ for (var i = 0; i < methods.length; i++) {
882
+ var method = methods[i];
883
+ var original = obj[method];
884
+ obj[method] = function retryWrapper(original2) {
885
+ var op = exports.operation(options);
886
+ var args = Array.prototype.slice.call(arguments, 1);
887
+ var callback = args.pop();
888
+ args.push(function(err) {
889
+ if (op.retry(err)) {
890
+ return;
891
+ }
892
+ if (err) {
893
+ arguments[0] = op.mainError();
894
+ }
895
+ callback.apply(this, arguments);
896
+ });
897
+ op.attempt(function() {
898
+ original2.apply(obj, args);
899
+ });
900
+ }.bind(obj, original);
901
+ obj[method].options = options;
902
+ }
903
+ };
904
+ }
905
+ });
906
+ var require_retry2 = __commonJS2({
907
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
908
+ "use strict";
909
+ module.exports = require_retry();
910
+ }
911
+ });
912
+ var import_p_limit2 = __toESM2(require_p_limit2());
913
+ var import_retry = __toESM2(require_retry2(), 1);
914
+ var networkErrorMsgs = /* @__PURE__ */ new Set([
915
+ "Failed to fetch",
916
+ // Chrome
917
+ "NetworkError when attempting to fetch resource.",
918
+ // Firefox
919
+ "The Internet connection appears to be offline.",
920
+ // Safari
921
+ "Network request failed",
922
+ // `cross-fetch`
923
+ "fetch failed"
924
+ // Undici (Node.js)
925
+ ]);
926
+ var AbortError = class extends Error {
927
+ constructor(message) {
928
+ super();
929
+ if (message instanceof Error) {
930
+ this.originalError = message;
931
+ ({ message } = message);
932
+ } else {
933
+ this.originalError = new Error(message);
934
+ this.originalError.stack = this.stack;
935
+ }
936
+ this.name = "AbortError";
937
+ this.message = message;
938
+ }
939
+ };
940
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
941
+ const retriesLeft = options.retries - (attemptNumber - 1);
942
+ error.attemptNumber = attemptNumber;
943
+ error.retriesLeft = retriesLeft;
944
+ return error;
945
+ };
946
+ var isNetworkError = (errorMessage) => networkErrorMsgs.has(errorMessage);
947
+ var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new Error(errorMessage) : new DOMException(errorMessage);
948
+ async function pRetry(input, options) {
949
+ return new Promise((resolve, reject) => {
950
+ options = {
951
+ onFailedAttempt() {
952
+ },
953
+ retries: 10,
954
+ ...options
955
+ };
956
+ const operation = import_retry.default.operation(options);
957
+ operation.attempt(async (attemptNumber) => {
958
+ try {
959
+ resolve(await input(attemptNumber));
960
+ } catch (error) {
961
+ if (!(error instanceof Error)) {
962
+ reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
963
+ return;
964
+ }
965
+ if (error instanceof AbortError) {
966
+ operation.stop();
967
+ reject(error.originalError);
968
+ } else if (error instanceof TypeError && !isNetworkError(error.message)) {
969
+ operation.stop();
970
+ reject(error);
971
+ } else {
972
+ decorateErrorWithCounts(error, attemptNumber, options);
973
+ try {
974
+ await options.onFailedAttempt(error);
975
+ } catch (error2) {
976
+ reject(error2);
977
+ return;
978
+ }
979
+ if (!operation.retry(error)) {
980
+ reject(operation.mainError());
981
+ }
982
+ }
983
+ }
984
+ });
985
+ if (options.signal && !options.signal.aborted) {
986
+ options.signal.addEventListener("abort", () => {
987
+ operation.stop();
988
+ const reason = options.signal.reason === void 0 ? getDOMException("The operation was aborted.") : options.signal.reason;
989
+ reject(reason instanceof Error ? reason : getDOMException(reason));
990
+ }, {
991
+ once: true
992
+ });
993
+ }
994
+ });
995
+ }
996
+ var AbortError2 = class extends Error {
997
+ constructor() {
998
+ super("Throttled function aborted");
999
+ this.name = "AbortError";
1000
+ }
1001
+ };
1002
+ function pThrottle({ limit, interval, strict }) {
1003
+ if (!Number.isFinite(limit)) {
1004
+ throw new TypeError("Expected `limit` to be a finite number");
1005
+ }
1006
+ if (!Number.isFinite(interval)) {
1007
+ throw new TypeError("Expected `interval` to be a finite number");
1008
+ }
1009
+ const queue = /* @__PURE__ */ new Map();
1010
+ let currentTick = 0;
1011
+ let activeCount = 0;
1012
+ function windowedDelay() {
1013
+ const now = Date.now();
1014
+ if (now - currentTick > interval) {
1015
+ activeCount = 1;
1016
+ currentTick = now;
1017
+ return 0;
1018
+ }
1019
+ if (activeCount < limit) {
1020
+ activeCount++;
1021
+ } else {
1022
+ currentTick += interval;
1023
+ activeCount = 1;
1024
+ }
1025
+ return currentTick - now;
1026
+ }
1027
+ const strictTicks = [];
1028
+ function strictDelay() {
1029
+ const now = Date.now();
1030
+ if (strictTicks.length < limit) {
1031
+ strictTicks.push(now);
1032
+ return 0;
1033
+ }
1034
+ const earliestTime = strictTicks.shift() + interval;
1035
+ if (now >= earliestTime) {
1036
+ strictTicks.push(now);
1037
+ return 0;
1038
+ }
1039
+ strictTicks.push(earliestTime);
1040
+ return earliestTime - now;
1041
+ }
1042
+ const getDelay = strict ? strictDelay : windowedDelay;
1043
+ return (function_) => {
1044
+ const throttled = function(...args) {
1045
+ if (!throttled.isEnabled) {
1046
+ return (async () => function_.apply(this, args))();
1047
+ }
1048
+ let timeout;
1049
+ return new Promise((resolve, reject) => {
1050
+ const execute = () => {
1051
+ resolve(function_.apply(this, args));
1052
+ queue.delete(timeout);
1053
+ };
1054
+ timeout = setTimeout(execute, getDelay());
1055
+ queue.set(timeout, reject);
1056
+ });
1057
+ };
1058
+ throttled.abort = () => {
1059
+ for (const timeout of queue.keys()) {
1060
+ clearTimeout(timeout);
1061
+ queue.get(timeout)(new AbortError2());
1062
+ }
1063
+ queue.clear();
1064
+ strictTicks.splice(0, strictTicks.length);
1065
+ };
1066
+ throttled.isEnabled = true;
1067
+ return throttled;
1068
+ };
1069
+ }
1070
+ function createLimitPolicy({
1071
+ throttle = { interval: 1e3, limit: 10 },
1072
+ retry: retry2 = { retries: 1, factor: 1.66 },
1073
+ limit = 10
1074
+ }) {
1075
+ const throttler = throttle ? pThrottle(throttle) : null;
1076
+ const limiter = limit ? (0, import_p_limit2.default)(limit) : null;
1077
+ return function limitPolicy(func) {
1078
+ let currentFunc = async () => await func();
1079
+ if (throttler) {
1080
+ const throttleFunc = currentFunc;
1081
+ currentFunc = throttler(throttleFunc);
1082
+ }
1083
+ if (limiter) {
1084
+ const limitFunc = currentFunc;
1085
+ currentFunc = () => limiter(limitFunc);
1086
+ }
1087
+ if (retry2) {
1088
+ const retryFunc = currentFunc;
1089
+ currentFunc = () => pRetry(retryFunc, {
1090
+ ...retry2,
1091
+ onFailedAttempt: async (error) => {
1092
+ if (retry2.onFailedAttempt) {
1093
+ await retry2.onFailedAttempt(error);
1094
+ }
1095
+ if (error instanceof ApiClientError && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
1096
+ throw error;
1097
+ }
1098
+ }
1099
+ });
1100
+ }
1101
+ return currentFunc();
1102
+ };
1103
+ }
1104
+ var isPlainObject = (obj) => typeof obj === "object" && obj !== null && !Array.isArray(obj);
1105
+ function rewriteFilters(filters) {
1106
+ return Object.entries(filters != null ? filters : {}).reduce(
1107
+ (acc, [key, value]) => {
1108
+ const lhs = `filters.${key}` + (isPlainObject(value) ? `[${Object.keys(value)[0]}]` : "");
1109
+ const rhs = isPlainObject(value) ? Object.values(value)[0] : value;
1110
+ return {
1111
+ ...acc,
1112
+ [lhs]: Array.isArray(rhs) ? rhs.map((v) => `${v}`.trim()).join(",") : `${rhs}`.trim()
1113
+ };
1114
+ },
1115
+ {}
1116
+ );
1117
+ }
1118
+ var CANVAS_URL = "/api/v1/canvas";
1119
+ var CanvasClient = class extends ApiClient {
1120
+ constructor(options) {
1121
+ var _a;
1122
+ if (!options.limitPolicy) {
1123
+ options.limitPolicy = createLimitPolicy({});
1124
+ }
1125
+ super(options);
1126
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
1127
+ this.edgeApiRequestInit = options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0;
1128
+ }
1129
+ /** Fetches lists of Canvas compositions, optionally by type */
1130
+ async getCompositionList(params = {}) {
1131
+ const { projectId } = this.options;
1132
+ const { resolveData, filters, ...originParams } = params;
1133
+ const rewrittenFilters = rewriteFilters(filters);
1134
+ if (!resolveData) {
1135
+ const fetchUri = this.createUrl(CANVAS_URL, { ...originParams, projectId, ...rewrittenFilters });
1136
+ return this.apiClient(fetchUri);
1137
+ }
1138
+ const edgeParams = {
1139
+ ...originParams,
1140
+ projectId,
1141
+ diagnostics: typeof params.diagnostics === "boolean" ? params.diagnostics : params.diagnostics === "no-data" ? "no-data" : void 0,
1142
+ ...rewrittenFilters
1143
+ };
1144
+ const edgeUrl = this.createUrl("/api/v1/compositions", edgeParams, this.edgeApiHost);
1145
+ return this.apiClient(edgeUrl, this.edgeApiRequestInit);
1146
+ }
1147
+ getCompositionByNodePath(options) {
1148
+ return this.getOneComposition(options);
1149
+ }
1150
+ getCompositionByNodeId(options) {
1151
+ return this.getOneComposition(options);
1152
+ }
1153
+ getCompositionBySlug(options) {
1154
+ return this.getOneComposition(options);
1155
+ }
1156
+ getCompositionById(options) {
1157
+ return this.getOneComposition(options);
1158
+ }
1159
+ getCompositionDefaults(options) {
1160
+ return this.getOneComposition(options);
1161
+ }
1162
+ /** Fetches historical versions of a composition or pattern */
1163
+ async getCompositionHistory(options) {
1164
+ const historyUrl = this.createUrl("/api/v1/canvas-history", {
1165
+ ...options,
1166
+ projectId: this.options.projectId
1167
+ });
1168
+ return this.apiClient(historyUrl);
1169
+ }
1170
+ getOneComposition({
1171
+ skipDataResolution,
1172
+ diagnostics,
1173
+ ...params
1174
+ }) {
1175
+ const { projectId } = this.options;
1176
+ if (skipDataResolution) {
1177
+ return this.apiClient(this.createUrl(CANVAS_URL, { ...params, projectId }));
1178
+ }
1179
+ const edgeParams = {
1180
+ ...params,
1181
+ projectId,
1182
+ diagnostics: typeof diagnostics === "boolean" ? diagnostics : diagnostics === "no-data" ? "no-data" : void 0
1183
+ };
1184
+ const edgeUrl = this.createUrl("/api/v1/composition", edgeParams, this.edgeApiHost);
1185
+ return this.apiClient(edgeUrl, this.edgeApiRequestInit);
1186
+ }
1187
+ /** Updates or creates a Canvas component definition */
1188
+ async updateComposition(body, options) {
1189
+ const fetchUri = this.createUrl(CANVAS_URL);
1190
+ const headers = {};
1191
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
1192
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1193
+ }
1194
+ const { response } = await this.apiClientWithResponse(fetchUri, {
1195
+ method: "PUT",
1196
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1197
+ expectNoContent: true,
1198
+ headers
1199
+ });
1200
+ return { modified: response.headers.get("x-modified-at") };
1201
+ }
1202
+ /** Deletes a Canvas component definition */
1203
+ async removeComposition(body) {
1204
+ const fetchUri = this.createUrl(CANVAS_URL);
1205
+ const { projectId } = this.options;
1206
+ await this.apiClient(fetchUri, {
1207
+ method: "DELETE",
1208
+ body: JSON.stringify({ ...body, projectId }),
1209
+ expectNoContent: true
1210
+ });
1211
+ }
1212
+ /** Fetches all Canvas component definitions */
1213
+ async getComponentDefinitions(options) {
1214
+ const { projectId } = this.options;
1215
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions", { ...options, projectId });
1216
+ return this.apiClient(fetchUri);
1217
+ }
1218
+ /** Updates or creates a Canvas component definition */
1219
+ async updateComponentDefinition(body) {
1220
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
1221
+ await this.apiClient(fetchUri, {
1222
+ method: "PUT",
1223
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1224
+ expectNoContent: true
1225
+ });
1226
+ }
1227
+ /** Deletes a Canvas component definition */
1228
+ async removeComponentDefinition(body) {
1229
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
1230
+ await this.apiClient(fetchUri, {
1231
+ method: "DELETE",
1232
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1233
+ expectNoContent: true
1234
+ });
1235
+ }
1236
+ };
1237
+ var _contentTypesUrl;
1238
+ var _entriesUrl;
1239
+ var _ContentClient = class _ContentClient2 extends ApiClient {
1240
+ constructor(options) {
1241
+ var _a;
1242
+ super(options);
1243
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
1244
+ }
1245
+ getContentTypes(options) {
1246
+ const { projectId } = this.options;
1247
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl), { ...options, projectId });
1248
+ return this.apiClient(fetchUri);
1249
+ }
1250
+ getEntries(options) {
1251
+ const { projectId } = this.options;
1252
+ const { skipDataResolution, filters, ...params } = options;
1253
+ const rewrittenFilters = rewriteFilters(filters);
1254
+ if (skipDataResolution) {
1255
+ const url = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl), { ...params, ...rewrittenFilters, projectId });
1256
+ return this.apiClient(url);
1257
+ }
1258
+ const edgeUrl = this.createUrl(
1259
+ __privateGet2(_ContentClient2, _entriesUrl),
1260
+ { ...this.getEdgeOptions(params), ...rewrittenFilters },
1261
+ this.edgeApiHost
1262
+ );
1263
+ return this.apiClient(
1264
+ edgeUrl,
1265
+ this.options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0
1266
+ );
1267
+ }
1268
+ /** Fetches historical versions of an entry */
1269
+ async getEntryHistory(options) {
1270
+ const historyUrl = this.createUrl("/api/v1/entries-history", {
1271
+ ...options,
1272
+ projectId: this.options.projectId
1273
+ });
1274
+ return this.apiClient(historyUrl);
1275
+ }
1276
+ async upsertContentType(body, opts = {}) {
1277
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl));
1278
+ if (typeof body.contentType.slugSettings === "object" && body.contentType.slugSettings !== null && Object.keys(body.contentType.slugSettings).length === 0) {
1279
+ delete body.contentType.slugSettings;
1280
+ }
1281
+ await this.apiClient(fetchUri, {
1282
+ method: "PUT",
1283
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1284
+ expectNoContent: true,
1285
+ headers: opts.autogenerateDataTypes ? { "x-uniform-autogenerate-data-types": "true" } : {}
1286
+ });
1287
+ }
1288
+ async upsertEntry(body, options) {
1289
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl));
1290
+ const headers = {};
1291
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
1292
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1293
+ }
1294
+ const { response } = await this.apiClientWithResponse(fetchUri, {
1295
+ method: "PUT",
1296
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1297
+ expectNoContent: true,
1298
+ headers
1299
+ });
1300
+ return { modified: response.headers.get("x-modified-at") };
1301
+ }
1302
+ async deleteContentType(body) {
1303
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl));
1304
+ await this.apiClient(fetchUri, {
1305
+ method: "DELETE",
1306
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1307
+ expectNoContent: true
1308
+ });
1309
+ }
1310
+ async deleteEntry(body) {
1311
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl));
1312
+ await this.apiClient(fetchUri, {
1313
+ method: "DELETE",
1314
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1315
+ expectNoContent: true
1316
+ });
1317
+ }
1318
+ getEdgeOptions(options) {
1319
+ const { projectId } = this.options;
1320
+ const { skipDataResolution, ...params } = options;
1321
+ return {
1322
+ projectId,
1323
+ ...params,
1324
+ diagnostics: typeof options.diagnostics === "boolean" ? options.diagnostics : options.diagnostics === "no-data" ? "no-data" : void 0
1325
+ };
1326
+ }
1327
+ };
1328
+ _contentTypesUrl = /* @__PURE__ */ new WeakMap();
1329
+ _entriesUrl = /* @__PURE__ */ new WeakMap();
1330
+ __privateAdd2(_ContentClient, _contentTypesUrl, "/api/v1/content-types");
1331
+ __privateAdd2(_ContentClient, _entriesUrl, "/api/v1/entries");
1332
+ var _url8;
1333
+ var _DataTypeClient = class _DataTypeClient2 extends ApiClient {
1334
+ constructor(options) {
1335
+ super(options);
1336
+ }
1337
+ /** Fetches all DataTypes for a project */
1338
+ async get(options) {
1339
+ const { projectId } = this.options;
1340
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8), { ...options, projectId });
1341
+ return await this.apiClient(fetchUri);
1342
+ }
1343
+ /** Updates or creates (based on id) a DataType */
1344
+ async upsert(body) {
1345
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8));
1346
+ await this.apiClient(fetchUri, {
1347
+ method: "PUT",
1348
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1349
+ expectNoContent: true
1350
+ });
1351
+ }
1352
+ /** Deletes a DataType */
1353
+ async remove(body) {
1354
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8));
1355
+ await this.apiClient(fetchUri, {
1356
+ method: "DELETE",
1357
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1358
+ expectNoContent: true
1359
+ });
1360
+ }
1361
+ };
1362
+ _url8 = /* @__PURE__ */ new WeakMap();
1363
+ __privateAdd2(_DataTypeClient, _url8, "/api/v1/data-types");
1364
+ var CANVAS_DRAFT_STATE = 0;
1365
+ var CANVAS_EDITOR_STATE = 63;
1366
+ var SECRET_QUERY_STRING_PARAM = "secret";
1367
+ var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
1368
+ var IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM = "is_incontext_editing_playground";
1369
+ var EDGE_MAX_CACHE_TTL = 24 * 60 * 60;
1370
+ var escapeCharacter = "\\";
1371
+ var variablePrefix = "${";
1372
+ var variableSuffix = "}";
1373
+ function parseVariableExpression(serialized, onToken) {
1374
+ if (typeof serialized !== "string") {
1375
+ throw new TypeError("Variable expression must be a string");
1376
+ }
1377
+ let bufferStartIndex = 0;
1378
+ let bufferEndIndex = 0;
1379
+ let tokenCount = 0;
1380
+ const handleToken = (token, type) => {
1381
+ tokenCount++;
1382
+ return onToken == null ? void 0 : onToken(token, type);
1383
+ };
1384
+ let state = "text";
1385
+ for (let index = 0; index < serialized.length; index++) {
1386
+ const char = serialized[index];
1387
+ if (bufferStartIndex > bufferEndIndex) {
1388
+ bufferEndIndex = bufferStartIndex;
1389
+ }
1390
+ if (char === variablePrefix[0] && serialized[index + 1] === variablePrefix[1]) {
1391
+ if (serialized[index - 1] === escapeCharacter) {
1392
+ bufferEndIndex -= escapeCharacter.length;
1393
+ if (handleToken(serialized.substring(bufferStartIndex, bufferEndIndex), "text") === false) {
1394
+ return tokenCount;
1395
+ }
1396
+ bufferStartIndex = index;
1397
+ bufferEndIndex = index + 1;
1398
+ continue;
1399
+ }
1400
+ state = "variable";
1401
+ if (bufferEndIndex > bufferStartIndex) {
1402
+ if (handleToken(serialized.substring(bufferStartIndex, bufferEndIndex), "text") === false) {
1403
+ return tokenCount;
1404
+ }
1405
+ bufferStartIndex = bufferEndIndex;
1406
+ }
1407
+ index += variablePrefix.length - 1;
1408
+ bufferStartIndex += variablePrefix.length;
1409
+ continue;
1410
+ }
1411
+ if (char === variableSuffix && state === "variable") {
1412
+ if (serialized[index - 1] === escapeCharacter) {
1413
+ bufferEndIndex++;
1414
+ continue;
1415
+ }
1416
+ state = "text";
1417
+ if (bufferEndIndex > bufferStartIndex) {
1418
+ const unescapedVariableName = serialized.substring(bufferStartIndex, bufferEndIndex).replace(/\\([${}])/g, "$1");
1419
+ if (handleToken(unescapedVariableName, "variable") === false) {
1420
+ return tokenCount;
1421
+ }
1422
+ bufferStartIndex = bufferEndIndex + variableSuffix.length;
1423
+ }
1424
+ continue;
1425
+ }
1426
+ bufferEndIndex++;
1427
+ }
1428
+ if (bufferEndIndex > bufferStartIndex) {
1429
+ if (state === "variable") {
1430
+ state = "text";
1431
+ bufferStartIndex -= variablePrefix.length;
1432
+ }
1433
+ handleToken(serialized.substring(bufferStartIndex), state);
1434
+ }
1435
+ return tokenCount;
1436
+ }
1437
+ function createVariableReference(variableName) {
1438
+ return `\${${variableName.replace(/([${}])/g, "\\$1")}}`;
1439
+ }
1440
+ var _baseUrl;
1441
+ var _IntegrationPropertyEditorsClient = class _IntegrationPropertyEditorsClient2 extends ApiClient {
1442
+ constructor(options) {
1443
+ super(options);
1444
+ this.teamId = options.teamId;
1445
+ }
1446
+ /**
1447
+ * Gets a list of property type and hook names for the current team, including public integrations' hooks.
1448
+ */
1449
+ get(options) {
1450
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl), {
1451
+ ...options,
1452
+ teamId: this.teamId
1453
+ });
1454
+ return this.apiClient(fetchUri);
1455
+ }
1456
+ /**
1457
+ * Creates or updates a custom AI property editor on a Mesh app.
1458
+ */
1459
+ async deploy(body) {
1460
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl));
1461
+ await this.apiClient(fetchUri, {
1462
+ method: "PUT",
1463
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
1464
+ expectNoContent: true
1465
+ });
1466
+ }
1467
+ /**
1468
+ * Removes a custom AI property editor from a Mesh app.
1469
+ */
1470
+ async delete(body) {
1471
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl));
1472
+ await this.apiClient(fetchUri, {
1473
+ method: "DELETE",
1474
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
1475
+ expectNoContent: true
1476
+ });
1477
+ }
1478
+ };
1479
+ _baseUrl = /* @__PURE__ */ new WeakMap();
1480
+ __privateAdd2(_IntegrationPropertyEditorsClient, _baseUrl, "/api/v1/integration-property-editors");
1481
+ var _url22;
1482
+ var _ProjectClient = class _ProjectClient2 extends ApiClient {
1483
+ constructor(options) {
1484
+ super({ ...options, bypassCache: true });
1485
+ }
1486
+ /** Fetches single Project */
1487
+ async get(options) {
1488
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22), { ...options });
1489
+ return await this.apiClient(fetchUri);
1490
+ }
1491
+ /** Updates or creates (based on id) a Project */
1492
+ async upsert(body) {
1493
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22));
1494
+ return await this.apiClient(fetchUri, {
1495
+ method: "PUT",
1496
+ body: JSON.stringify({ ...body })
1497
+ });
1498
+ }
1499
+ /** Deletes a Project */
1500
+ async delete(body) {
1501
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22));
1502
+ await this.apiClient(fetchUri, {
1503
+ method: "DELETE",
1504
+ body: JSON.stringify({ ...body }),
1505
+ expectNoContent: true
1506
+ });
1507
+ }
1508
+ };
1509
+ _url22 = /* @__PURE__ */ new WeakMap();
1510
+ __privateAdd2(_ProjectClient, _url22, "/api/v1/project");
1511
+ var isAllowedReferrer = (referrer) => {
1512
+ return Boolean(referrer == null ? void 0 : referrer.match(/(^https:\/\/|\.)(uniform.app|uniform.wtf|localhost:\d{4})\//));
1513
+ };
1514
+
1515
+ // src/handler/createPreviewGETRouteHandler.ts
1516
+ import { cookies, draftMode } from "next/headers";
1517
+ import { redirect } from "next/navigation";
1518
+ import { NextResponse } from "next/server";
1519
+
1520
+ // src/config/helpers.ts
1521
+ import serverConfig from "uniform.server.config";
1522
+ var getServerConfig = () => {
1523
+ return serverConfig;
1524
+ };
1525
+
1526
+ // src/handler/createPreviewGETRouteHandler.ts
1527
+ var BASE_URL_EXAMPLE = "https://example.com";
1528
+ var getQueryParam = (req, paramName) => {
1529
+ const value = req.nextUrl.searchParams.get(paramName);
1530
+ if (typeof value === "undefined") {
1531
+ return void 0;
1532
+ }
1533
+ return Array.isArray(value) ? value[0] : value;
1534
+ };
1535
+ var contextualEditingQueryParams = [
1536
+ IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
1537
+ IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM
1538
+ ];
1539
+ var createPreviewGETRouteHandler = (options) => {
1540
+ return async (request) => {
1541
+ const isConfigCheck = getQueryParam(request, "is_config_check") === "true";
1542
+ const { playgroundPath } = getServerConfig();
1543
+ if (isConfigCheck) {
1544
+ return Response.json(
1545
+ {
1546
+ hasPlayground: Boolean(playgroundPath),
1547
+ isUsingCustomFullPathResolver: false
1548
+ },
1549
+ {
1550
+ headers: {
1551
+ "Access-Control-Allow-Origin": process.env.UNIFORM_CLI_BASE_URL || "https://uniform.app"
1552
+ }
1553
+ }
1554
+ );
1555
+ }
1556
+ if (request.headers.get("sec-fetch-mode") === "no-cors") {
1557
+ return new Response(null, { status: 204 });
1558
+ }
1559
+ if (!process.env.UNIFORM_PREVIEW_SECRET) {
1560
+ return new Response("No preview secret is configured", { status: 401 });
1561
+ }
1562
+ const { searchParams } = new URL(request.url);
1563
+ const id = getQueryParam(request, compositionQueryParam.id);
1564
+ const path = getQueryParam(request, compositionQueryParam.path);
1565
+ const isPlayground = searchParams.get(IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM) === "true" || id && !path;
1566
+ const locale = getQueryParam(request, compositionQueryParam.locale);
1567
+ let pathToRedirectTo;
1568
+ if (isPlayground) {
1569
+ if (!playgroundPath) {
1570
+ return new Response("No playground path is configured", { status: 401 });
1571
+ }
1572
+ pathToRedirectTo = playgroundPath;
1573
+ if (options == null ? void 0 : options.processPlaygroundPath) {
1574
+ const processedPath = options.processPlaygroundPath({ playgroundPath, locale });
1575
+ if (processedPath) {
1576
+ pathToRedirectTo = processedPath;
1577
+ }
1578
+ }
1579
+ }
1580
+ const slug = getQueryParam(request, compositionQueryParam.slug);
1581
+ const disable = getQueryParam(request, "disable");
1582
+ const secret = getQueryParam(request, SECRET_QUERY_STRING_PARAM);
1583
+ const referer = request.headers.get("referer");
1584
+ const isUniformContextualEditing = getQueryParam(request, IN_CONTEXT_EDITOR_QUERY_STRING_PARAM) === "true" && isAllowedReferrer(referer || void 0);
1585
+ const releaseId = getQueryParam(request, "releaseId");
1586
+ if (typeof pathToRedirectTo === "undefined") {
1587
+ const resolveFullPath = (options == null ? void 0 : options.resolveFullPath) || resolveFullPathDefault;
1588
+ pathToRedirectTo = resolveFullPath({ id, slug, path, locale });
1589
+ }
1590
+ validateLocalRedirectUrl(pathToRedirectTo);
1591
+ if (!pathToRedirectTo) {
1592
+ return new Response("Could not resolve the full path of the preview page", { status: 400 });
1593
+ }
1594
+ if (disable) {
1595
+ (await draftMode()).disable();
1596
+ redirect(pathToRedirectTo);
1597
+ return;
1598
+ }
1599
+ if (secret !== process.env.UNIFORM_PREVIEW_SECRET) {
1600
+ return new Response("Invalid preview secret", { status: 401 });
1601
+ }
1602
+ const draft = await draftMode();
1603
+ draft.enable();
1604
+ const cookieStore = await cookies();
1605
+ const draftCookie = cookieStore.get("__prerender_bypass");
1606
+ if (draftCookie == null ? void 0 : draftCookie.value) {
1607
+ cookieStore.set({
1608
+ name: "__prerender_bypass",
1609
+ value: draftCookie.value,
1610
+ httpOnly: true,
1611
+ path: "/",
1612
+ secure: true,
1613
+ sameSite: "none"
1614
+ // Allow cookie in cross-origin iframes
1615
+ });
1616
+ }
1617
+ const redirectionUrl = new URL(pathToRedirectTo, BASE_URL_EXAMPLE);
1618
+ assignRequestQueryToSearchParams(redirectionUrl.searchParams, searchParams);
1619
+ if (isPlayground) {
1620
+ redirectionUrl.searchParams.set("id", searchParams.get("id") || "");
1621
+ if (locale) {
1622
+ redirectionUrl.searchParams.set("locale", locale);
1623
+ }
1624
+ if (releaseId) {
1625
+ redirectionUrl.searchParams.set("releaseId", releaseId);
1626
+ }
1627
+ }
1628
+ if (releaseId) {
1629
+ redirectionUrl.searchParams.set("releaseId", releaseId);
1630
+ }
1631
+ if (!isUniformContextualEditing) {
1632
+ contextualEditingQueryParams.forEach((param) => {
1633
+ redirectionUrl.searchParams.delete(param);
1634
+ });
1635
+ }
1636
+ const fullPathToRedirectTo = redirectionUrl.href.replace(BASE_URL_EXAMPLE, "");
1637
+ return NextResponse.redirect(new URL(fullPathToRedirectTo, request.url), {
1638
+ status: 307
1639
+ });
1640
+ };
1641
+ };
1642
+ function validateLocalRedirectUrl(pathToRedirectTo) {
1643
+ if (pathToRedirectTo == null ? void 0 : pathToRedirectTo.match(/^[a-z]+:\/\//g)) {
1644
+ throw new Error("Tried to redirect to absolute URL with protocol. Disallowing open redirect.");
1645
+ }
1646
+ }
1647
+ var resolveFullPathDefault = ({ slug, path }) => {
1648
+ return path || slug;
1649
+ };
1650
+ var compositionQueryParam = {
1651
+ id: "id",
1652
+ slug: "slug",
1653
+ path: "path",
1654
+ locale: "locale"
1655
+ };
1656
+ var assignRequestQueryToSearchParams = (searchParams, query) => {
1657
+ const compositionQueryParamNames = Object.values(compositionQueryParam);
1658
+ for (const [name, value] of query.entries()) {
1659
+ if (name === SECRET_QUERY_STRING_PARAM) {
1660
+ continue;
1661
+ }
1662
+ if (compositionQueryParamNames.includes(name)) {
1663
+ continue;
1664
+ }
1665
+ if (typeof value === "undefined") {
1666
+ continue;
1667
+ }
1668
+ searchParams.append(name, value);
1669
+ }
1670
+ };
1671
+
1672
+ // src/handler/createPreviewOPTIONSRouteHandler.ts
1673
+ var createPreviewOPTIONSRouteHandler = () => {
1674
+ return async () => {
1675
+ return new Response(null, {
1676
+ headers: {
1677
+ "Access-Control-Allow-Origin": process.env.UNIFORM_CLI_BASE_URL || "https://uniform.app",
1678
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
1679
+ "Access-Control-Allow-Headers": "*"
1680
+ }
1681
+ });
1682
+ };
1683
+ };
1684
+
1685
+ // src/handler/createPreviewPOSTRouteHandler.ts
1686
+ import { getCache } from "@vercel/functions";
1687
+ import { revalidatePath, revalidateTag } from "next/cache";
1688
+
1689
+ // src/handler/helpers.ts
1690
+ import { Webhook } from "svix";
1691
+
1692
+ // src/clients/canvas.ts
1693
+ import "server-only";
1694
+
1695
+ // src/utils/env.ts
1696
+ var env = {
1697
+ getProjectId: () => {
1698
+ return process.env.UNIFORM_PROJECT_ID;
1699
+ },
1700
+ getApiKey: () => {
1701
+ return process.env.UNIFORM_API_KEY;
1702
+ },
1703
+ getApiHost: () => {
1704
+ return process.env.UNIFORM_API_HOST || process.env.UNIFORM_CLI_BASE_URL;
1705
+ },
1706
+ getEdgeApiHost: () => {
1707
+ return process.env.UNIFORM_EDGE_API_HOST || process.env.UNIFORM_CLI_BASE_EDGE_URL;
1708
+ }
1709
+ };
1710
+
1711
+ // src/utils/tag.ts
1712
+ var buildPathTag = (path) => {
1713
+ const actualPath = path.startsWith("/") ? path : `/${path}`;
1714
+ return `path:${actualPath}`.toLowerCase();
1715
+ };
1716
+ var buildCompositionTag = (compositionId) => {
1717
+ return `composition:${compositionId}`.toLowerCase();
1718
+ };
1719
+
1720
+ // src/utils/draft.ts
1721
+ var isDraftModeEnabled = ({
1722
+ draftModeEnabled
1723
+ }) => {
1724
+ return draftModeEnabled;
1725
+ };
1726
+ var isIncontextEditingEnabled = ({ searchParams }) => {
1727
+ const containsKey = searchParams.has(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM);
1728
+ return containsKey;
1729
+ };
1730
+ var isDevelopmentEnvironment = () => {
1731
+ return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
1732
+ };
1733
+
1734
+ // src/clients/cache.ts
1735
+ var isSpecificCacheMode = (options) => {
1736
+ return "cache" in options;
1737
+ };
1738
+ var isStateCacheMode = (options) => {
1739
+ return "state" in options;
1740
+ };
1741
+ var isDetectCacheMode = (options) => {
1742
+ return "searchParams" in options && "draftModeEnabled" in options;
1743
+ };
1744
+ var resolveCanvasCache = (options) => {
1745
+ return resolveCache({
1746
+ options,
1747
+ defaultCache: getServerConfig().canvasCache
1748
+ });
1749
+ };
1750
+ var resolveProjectMapCache = (options) => {
1751
+ return resolveCache({
1752
+ options,
1753
+ defaultCache: getServerConfig().projectMapCache
1754
+ });
1755
+ };
1756
+ var resolveCache = ({
1757
+ options,
1758
+ defaultCache
1759
+ }) => {
1760
+ let cache = defaultCache;
1761
+ if (options) {
1762
+ if (isSpecificCacheMode(options)) {
1763
+ cache = options.cache;
1764
+ } else if (isStateCacheMode(options)) {
1765
+ if (options.state === CANVAS_DRAFT_STATE || options.state === CANVAS_EDITOR_STATE) {
1766
+ cache = {
1767
+ type: "no-cache",
1768
+ bypassCache: true
1769
+ };
1770
+ }
1771
+ } else if (isDetectCacheMode(options)) {
1772
+ const { disabled } = shouldCacheBeDisabled(options);
1773
+ if (disabled) {
1774
+ cache = {
1775
+ type: "no-cache",
1776
+ bypassCache: true
1777
+ };
1778
+ }
1779
+ }
1780
+ }
1781
+ return cache || {
1782
+ type: "force-cache"
1783
+ };
1784
+ };
1785
+ var shouldCacheBeDisabled = (options) => {
1786
+ if (isDraftModeEnabled(options)) {
1787
+ return { disabled: true, reason: "DRAFT" };
1788
+ }
1789
+ if (isIncontextEditingEnabled(options)) {
1790
+ return { disabled: true, reason: "INCONTEXT" };
1791
+ }
1792
+ if (isDevelopmentEnvironment()) {
1793
+ return { disabled: true, reason: "DEV" };
1794
+ }
1795
+ return {
1796
+ disabled: false,
1797
+ reason: void 0
1798
+ };
1799
+ };
1800
+ var determineFetchCacheOptions = (mode) => {
1801
+ let cache = void 0;
1802
+ let revalidate = void 0;
1803
+ if (mode.type === "revalidate") {
1804
+ cache = void 0;
1805
+ revalidate = mode.interval;
1806
+ } else {
1807
+ cache = mode.type;
1808
+ }
1809
+ return {
1810
+ cache,
1811
+ revalidate
1812
+ };
1813
+ };
1814
+
1815
+ // src/clients/retry.ts
1816
+ function createThrottler(limit, interval) {
1817
+ let available = limit;
1818
+ let refillScheduled = false;
1819
+ const waiting = [];
1820
+ function scheduleRefill() {
1821
+ if (refillScheduled) return;
1822
+ refillScheduled = true;
1823
+ setTimeout(() => {
1824
+ refillScheduled = false;
1825
+ available = limit;
1826
+ while (available > 0 && waiting.length > 0) {
1827
+ available--;
1828
+ const next = waiting.shift();
1829
+ next();
1830
+ }
1831
+ if (waiting.length > 0) {
1832
+ scheduleRefill();
1833
+ }
1834
+ }, interval);
1835
+ }
1836
+ return async function throttle(fn) {
1837
+ if (available > 0) {
1838
+ available--;
1839
+ if (!refillScheduled) {
1840
+ scheduleRefill();
1841
+ }
1842
+ return fn();
1843
+ }
1844
+ return new Promise((resolve, reject) => {
1845
+ waiting.push(() => {
1846
+ fn().then(resolve, reject);
1847
+ });
1848
+ scheduleRefill();
1849
+ });
1850
+ };
1851
+ }
1852
+ function createLimiter(concurrency) {
1853
+ let active = 0;
1854
+ const queue = [];
1855
+ return async function limit(fn) {
1856
+ return new Promise((resolve, reject) => {
1857
+ const run = async () => {
1858
+ active++;
1859
+ try {
1860
+ const result = await fn();
1861
+ resolve(result);
1862
+ } catch (error) {
1863
+ reject(error);
1864
+ } finally {
1865
+ active--;
1866
+ if (queue.length > 0) {
1867
+ const next = queue.shift();
1868
+ next();
1869
+ }
1870
+ }
1871
+ };
1872
+ if (active < concurrency) {
1873
+ run();
1874
+ } else {
1875
+ queue.push(run);
1876
+ }
1877
+ });
1878
+ };
1879
+ }
1880
+ async function retry(fn, options) {
1881
+ let lastError;
1882
+ let delay = 1e3;
1883
+ for (let attempt = 1; attempt <= options.retries + 1; attempt++) {
1884
+ try {
1885
+ return await fn();
1886
+ } catch (error) {
1887
+ lastError = error;
1888
+ const attemptError = Object.assign(error, { attemptNumber: attempt });
1889
+ if (options.onFailedAttempt) {
1890
+ await options.onFailedAttempt(attemptError);
1891
+ }
1892
+ if (attempt > options.retries) {
1893
+ throw error;
1894
+ }
1895
+ await new Promise((resolve) => setTimeout(resolve, delay));
1896
+ delay *= options.factor;
1897
+ }
1898
+ }
1899
+ throw lastError;
1900
+ }
1901
+ function createLimitPolicy2({
1902
+ throttle = { interval: 1e3, limit: 10 },
1903
+ retry: retryOptions = { retries: 1, factor: 1.66 },
1904
+ limit = 10
1905
+ }) {
1906
+ const throttler = throttle ? createThrottler(throttle.limit, throttle.interval) : null;
1907
+ const limiter = limit ? createLimiter(limit) : null;
1908
+ return function limitPolicy(func) {
1909
+ let currentFunc = async () => await func();
1910
+ if (throttler) {
1911
+ const throttleFunc = currentFunc;
1912
+ currentFunc = () => throttler(throttleFunc);
1913
+ }
1914
+ if (limiter) {
1915
+ const limitFunc = currentFunc;
1916
+ currentFunc = () => limiter(limitFunc);
1917
+ }
1918
+ if (retryOptions) {
1919
+ const retryFunc = currentFunc;
1920
+ currentFunc = () => retry(retryFunc, {
1921
+ ...retryOptions,
1922
+ onFailedAttempt: async (error) => {
1923
+ if (retryOptions.onFailedAttempt) {
1924
+ await retryOptions.onFailedAttempt(error);
1925
+ }
1926
+ if (error instanceof ApiClientError && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
1927
+ throw error;
1928
+ }
1929
+ }
1930
+ });
1931
+ }
1932
+ return currentFunc();
1933
+ };
1934
+ }
1935
+
1936
+ // src/clients/canvas.ts
1937
+ var getCanvasClient = (options) => {
1938
+ const cache = resolveCanvasCache(options);
1939
+ return new CanvasClient({
1940
+ projectId: env.getProjectId(),
1941
+ apiHost: env.getApiHost(),
1942
+ apiKey: env.getApiKey(),
1943
+ edgeApiHost: env.getEdgeApiHost(),
1944
+ disableSWR: typeof cache.disableSWR !== "undefined" ? cache.disableSWR : true,
1945
+ limitPolicy: createLimitPolicy2({
1946
+ limit: 6
1947
+ }),
1948
+ fetch: (req, init) => {
1949
+ let requestedUrl;
1950
+ if (typeof req === "string") {
1951
+ requestedUrl = new URL(req);
1952
+ } else if (req instanceof URL) {
1953
+ requestedUrl = req;
1954
+ } else {
1955
+ requestedUrl = new URL(req.url);
1956
+ }
1957
+ const tags = [];
1958
+ if (requestedUrl) {
1959
+ const compositionIdKey = "compositionId";
1960
+ const compositionIdsKey = "compositionIDs";
1961
+ const compositionId = requestedUrl.searchParams.get(compositionIdKey);
1962
+ const compositionIds = requestedUrl.searchParams.get(compositionIdsKey);
1963
+ if (compositionId) {
1964
+ tags.push(buildCompositionTag(compositionId));
1965
+ }
1966
+ if (compositionIds) {
1967
+ const ids = compositionIds.split(",");
1968
+ for (let i = 0; i < ids.length; i++) {
1969
+ tags.push(buildCompositionTag(ids[i]));
1970
+ }
1971
+ }
1972
+ }
1973
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache);
1974
+ return fetch(req, {
1975
+ ...init,
1976
+ cache: fetchCache,
1977
+ headers: {
1978
+ ...init == null ? void 0 : init.headers,
1979
+ "x-bypass-cache": typeof cache.bypassCache !== "undefined" ? cache.bypassCache.toString() : "false"
1980
+ },
1981
+ next: {
1982
+ revalidate,
1983
+ tags: tags.length ? tags : void 0
1984
+ }
1985
+ });
1986
+ }
1987
+ });
1988
+ };
1989
+
1990
+ // src/clients/projectMap.ts
1991
+ import "server-only";
1992
+
1993
+ // ../project-map/dist/index.mjs
1994
+ var __typeError3 = (msg) => {
1995
+ throw TypeError(msg);
1996
+ };
1997
+ var __accessCheck3 = (obj, member, msg) => member.has(obj) || __typeError3("Cannot " + msg);
1998
+ var __privateGet3 = (obj, member, getter) => (__accessCheck3(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
1999
+ var __privateAdd3 = (obj, member, value) => member.has(obj) ? __typeError3("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2000
+ var __privateSet = (obj, member, value, setter) => (__accessCheck3(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
2001
+ var __privateMethod = (obj, member, method) => (__accessCheck3(obj, member, "access private method"), method);
2002
+ var ProjectMapClient = class extends ApiClient {
2003
+ constructor(options) {
2004
+ super(options);
2005
+ this.getProjectMapDefinitions = async () => {
2006
+ const { projectId } = this.options;
2007
+ const fetchUri = this.createUrl("/api/v1/project-map", { projectId });
2008
+ return await this.apiClient(fetchUri);
2009
+ };
2010
+ this.getProjectMapDefinition = async (options2) => {
2011
+ const { projectId } = this.options;
2012
+ const fetchUri = this.createUrl("/api/v1/project-map", {
2013
+ ...options2,
2014
+ projectId
2015
+ });
2016
+ return await this.apiClient(fetchUri);
2017
+ };
2018
+ this.upsertProjectMap = async (options2) => {
2019
+ const { projectId } = this.options;
2020
+ const fetchUri = this.createUrl("/api/v1/project-map");
2021
+ const result = await this.apiClient(fetchUri, {
2022
+ method: "PUT",
2023
+ body: JSON.stringify({ ...options2, projectId })
2024
+ });
2025
+ return result.projectMapId;
2026
+ };
2027
+ this.deleteProjectMap = async (options2) => {
2028
+ const { projectId } = this.options;
2029
+ const fetchUri = this.createUrl("/api/v1/project-map");
2030
+ await this.apiClient(fetchUri, {
2031
+ method: "DELETE",
2032
+ body: JSON.stringify({ ...options2, projectId }),
2033
+ expectNoContent: true
2034
+ });
2035
+ };
2036
+ this.upsertProjectMapNodes = async (options2) => {
2037
+ const { projectId } = this.options;
2038
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes");
2039
+ await this.apiClient(fetchUri, {
2040
+ method: "PUT",
2041
+ body: JSON.stringify({
2042
+ ...options2,
2043
+ projectId,
2044
+ nodes: options2.nodes.map((n) => {
2045
+ return {
2046
+ ...n,
2047
+ node: { ...this.cleanProjectMapNode(n.node) }
2048
+ };
2049
+ })
2050
+ }),
2051
+ expectNoContent: true
2052
+ });
2053
+ };
2054
+ this.deleteProjectMapNode = async (options2) => {
2055
+ const { projectId } = this.options;
2056
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes");
2057
+ await this.apiClient(fetchUri, {
2058
+ method: "DELETE",
2059
+ body: JSON.stringify({
2060
+ ...options2,
2061
+ projectId
2062
+ }),
2063
+ expectNoContent: true
2064
+ });
2065
+ };
2066
+ this.getSubtree = async (options2) => {
2067
+ var _a;
2068
+ const fetchOptions = this.setFetchOptions(options2);
2069
+ fetchOptions["tree"] = "true";
2070
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes", fetchOptions);
2071
+ const result = await this.apiClient(fetchUri);
2072
+ const root = {
2073
+ ...result.tree
2074
+ };
2075
+ const nodes = [root];
2076
+ while (nodes && nodes.length > 0) {
2077
+ const currentNode = nodes.pop();
2078
+ let lastChild = void 0;
2079
+ (_a = currentNode == null ? void 0 : currentNode.children) == null ? void 0 : _a.forEach((child) => {
2080
+ child.parent = cutReferences(currentNode);
2081
+ child.previousSibling = cutReferences(lastChild);
2082
+ if (lastChild) {
2083
+ lastChild.nextSibling = cutReferences(child);
2084
+ }
2085
+ lastChild = child;
2086
+ nodes.push(child);
2087
+ });
2088
+ }
2089
+ return root;
2090
+ };
2091
+ this.getNodes = async (options2) => {
2092
+ const fetchOptions = this.setFetchOptions(options2);
2093
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes", fetchOptions);
2094
+ return await this.apiClient(fetchUri);
2095
+ };
2096
+ }
2097
+ setFetchOptions(options) {
2098
+ const { projectId } = this.options;
2099
+ const fetchOptions = {
2100
+ projectId
2101
+ };
2102
+ Object.entries(options).forEach(([key, value]) => {
2103
+ if (value === void 0) {
2104
+ return;
2105
+ }
2106
+ if (typeof value === "boolean") {
2107
+ if (!value) {
2108
+ return;
2109
+ }
2110
+ fetchOptions[key] = "true";
2111
+ return;
2112
+ }
2113
+ if (typeof value === "number") {
2114
+ fetchOptions[key] = value.toString(10);
2115
+ return;
2116
+ }
2117
+ fetchOptions[key] = value;
2118
+ });
2119
+ return fetchOptions;
2120
+ }
2121
+ cleanProjectMapNode(node) {
2122
+ var _a, _b, _c;
2123
+ return {
2124
+ id: ((_c = (_b = (_a = node.id) == null ? void 0 : _a.match(/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i)) == null ? void 0 : _b.length) != null ? _c : 0) == 1 ? node.id : void 0,
2125
+ path: node.path,
2126
+ name: node.name,
2127
+ type: node.type,
2128
+ order: node.order,
2129
+ data: node.data,
2130
+ compositionId: node.compositionId,
2131
+ description: node.description,
2132
+ locales: node.locales
2133
+ };
2134
+ }
2135
+ };
2136
+ var cutReferences = (node) => node ? {
2137
+ ...node,
2138
+ parent: void 0,
2139
+ children: void 0
2140
+ } : void 0;
2141
+ var _routeInfo;
2142
+ var _Route_static;
2143
+ var parseRouteOrPath_fn;
2144
+ var isDynamicRouteSegment_fn;
2145
+ var _Route = class _Route2 {
2146
+ constructor(route) {
2147
+ this.route = route;
2148
+ __privateAdd3(this, _routeInfo);
2149
+ var _a;
2150
+ __privateSet(this, _routeInfo, __privateMethod(_a = _Route2, _Route_static, parseRouteOrPath_fn).call(_a, this.route));
2151
+ }
2152
+ get dynamicSegmentCount() {
2153
+ return __privateGet3(this, _routeInfo).segments.reduce(
2154
+ (count, segment) => {
2155
+ var _a;
2156
+ return __privateMethod(_a = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_a, segment) ? count + 1 : count;
2157
+ },
2158
+ 0
2159
+ );
2160
+ }
2161
+ /** Tests if an incoming path matches this route */
2162
+ matches(path) {
2163
+ var _a, _b;
2164
+ const { segments: pathSegments, queryParams: pathQuery } = __privateMethod(_a = _Route2, _Route_static, parseRouteOrPath_fn).call(_a, path);
2165
+ const { segments: routeSegments } = __privateGet3(this, _routeInfo);
2166
+ if (pathSegments.length !== routeSegments.length) {
2167
+ return { match: false };
2168
+ }
2169
+ const possibleMatch = {
2170
+ match: true,
2171
+ dynamicSegmentCount: 0,
2172
+ pathParams: {},
2173
+ queryParams: {}
2174
+ };
2175
+ for (let i = 0; i < routeSegments.length; i++) {
2176
+ const routeSegment = routeSegments[i];
2177
+ const pathSegment = pathSegments[i];
2178
+ if (__privateMethod(_b = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_b, routeSegment)) {
2179
+ const key = routeSegment.slice(1);
2180
+ possibleMatch.pathParams[key] = pathSegment;
2181
+ possibleMatch.dynamicSegmentCount++;
2182
+ } else if (routeSegment !== pathSegment) {
2183
+ return { match: false };
2184
+ }
2185
+ }
2186
+ for (const [key, value] of __privateGet3(this, _routeInfo).queryParams) {
2187
+ possibleMatch.queryParams[key] = pathQuery.has(key) ? pathQuery.get(key) : value;
2188
+ }
2189
+ return possibleMatch;
2190
+ }
2191
+ /**
2192
+ * Creates an expanded path value for this route given dynamic input values and allowed query string values
2193
+ */
2194
+ expand(options) {
2195
+ const { dynamicInputValues = {}, allowedQueryParams = [], doNotEscapeVariables = false } = options != null ? options : {};
2196
+ const path = __privateGet3(this, _routeInfo).segments.map((segment) => {
2197
+ const dynamicSegmentName = _Route2.getDynamicRouteSegmentName(segment);
2198
+ if (!dynamicSegmentName) {
2199
+ return segment;
2200
+ }
2201
+ const dynamicSegmentValue = dynamicInputValues[dynamicSegmentName];
2202
+ if (!dynamicSegmentValue) {
2203
+ return segment;
2204
+ }
2205
+ return encodeRouteComponent(dynamicSegmentValue, doNotEscapeVariables);
2206
+ }).join("/");
2207
+ const queries = allowedQueryParams.filter((qs) => {
2208
+ const type = typeof dynamicInputValues[qs];
2209
+ return type === "string" || type === "number" || type === "boolean";
2210
+ }).map(
2211
+ (qs) => `${encodeRouteComponent(qs, doNotEscapeVariables)}=${encodeRouteComponent(
2212
+ dynamicInputValues[qs],
2213
+ doNotEscapeVariables
2214
+ )}`
2215
+ );
2216
+ const query = queries.length ? `?${queries.join("&")}` : "";
2217
+ return `/${path}${query}`;
2218
+ }
2219
+ static getDynamicRouteSegmentName(segment) {
2220
+ var _a;
2221
+ if (!__privateMethod(_a = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_a, segment)) {
2222
+ return void 0;
2223
+ }
2224
+ return segment.slice(_Route2.dynamicSegmentPrefix.length);
2225
+ }
2226
+ };
2227
+ _routeInfo = /* @__PURE__ */ new WeakMap();
2228
+ _Route_static = /* @__PURE__ */ new WeakSet();
2229
+ parseRouteOrPath_fn = function(path) {
2230
+ if (!path.startsWith("/") || path === "") {
2231
+ throw new Error(`Path must start with a slash: ${path}`);
2232
+ }
2233
+ const [pathname, queryString] = path.split("?");
2234
+ const pathSegments = pathname.substring(1).split("/");
2235
+ if (pathSegments[pathSegments.length - 1] === "") {
2236
+ pathSegments.pop();
2237
+ }
2238
+ const queryParams = new URLSearchParams(queryString);
2239
+ return { segments: pathSegments, queryParams };
2240
+ };
2241
+ isDynamicRouteSegment_fn = function(segment) {
2242
+ if (!segment) {
2243
+ return false;
2244
+ }
2245
+ return segment.startsWith(_Route.dynamicSegmentPrefix);
2246
+ };
2247
+ __privateAdd3(_Route, _Route_static);
2248
+ _Route.dynamicSegmentPrefix = ":";
2249
+ function encodeRouteComponent(value, doNotEscapeVariables) {
2250
+ if (!doNotEscapeVariables) {
2251
+ return encodeURIComponent(value);
2252
+ }
2253
+ const result = [];
2254
+ parseVariableExpression(value.toString(10), (token, type) => {
2255
+ if (type === "variable") {
2256
+ result.push(createVariableReference(token));
2257
+ } else {
2258
+ result.push(encodeURIComponent(token));
2259
+ }
2260
+ });
2261
+ return result.join("");
2262
+ }
2263
+
2264
+ // src/clients/projectMap.ts
2265
+ var getProjectMapClient = (options) => {
2266
+ const cache = resolveProjectMapCache(options);
2267
+ const manifestClient = new ProjectMapClient({
2268
+ apiHost: env.getApiHost(),
2269
+ apiKey: env.getApiKey(),
2270
+ projectId: env.getProjectId(),
2271
+ limitPolicy: createLimitPolicy2({
2272
+ limit: 6
2273
+ }),
2274
+ fetch: (req, init) => {
2275
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache);
2276
+ return fetch(req, {
2277
+ ...init,
2278
+ headers: {
2279
+ ...init == null ? void 0 : init.headers,
2280
+ "x-bypass-cache": typeof cache.bypassCache !== "undefined" ? cache.bypassCache.toString() : "false"
2281
+ },
2282
+ cache: fetchCache,
2283
+ next: {
2284
+ revalidate
2285
+ }
2286
+ });
2287
+ }
2288
+ });
2289
+ return manifestClient;
2290
+ };
2291
+
2292
+ // src/handler/helpers.ts
2293
+ var isSvixMessage = async (request) => {
2294
+ const requiredHeaders = ["svix-id", "svix-timestamp", "svix-signature"];
2295
+ const hasAllRequiredHeaders = requiredHeaders.every((header) => request.headers.has(header));
2296
+ if (!hasAllRequiredHeaders) {
2297
+ return {
2298
+ looksLikeMessage: false,
2299
+ validation: false
2300
+ };
2301
+ }
2302
+ if (typeof process.env.UNIFORM_WEBHOOK_SECRET !== "undefined") {
2303
+ const payload = await request.clone().text();
2304
+ const headers = Object.fromEntries(request.headers.entries());
2305
+ const wh = new Webhook(process.env.UNIFORM_WEBHOOK_SECRET);
2306
+ try {
2307
+ wh.verify(payload, headers);
2308
+ } catch (e) {
2309
+ return {
2310
+ looksLikeMessage: true,
2311
+ validation: false
2312
+ };
2313
+ }
2314
+ }
2315
+ return {
2316
+ looksLikeMessage: true,
2317
+ validation: true
2318
+ };
2319
+ };
2320
+ var processCompositionChange = async (compositionId) => {
2321
+ const projectMapClient = getProjectMapClient({
2322
+ cache: {
2323
+ type: "no-cache"
2324
+ }
2325
+ });
2326
+ const [{ nodes }, composition] = await Promise.all([
2327
+ projectMapClient.getNodes({
2328
+ compositionId
2329
+ }),
2330
+ getComposition({ compositionId })
2331
+ ]);
2332
+ const tags = [];
2333
+ const paths = [];
2334
+ if (composition == null ? void 0 : composition.pattern) {
2335
+ tags.push("route");
2336
+ }
2337
+ if (nodes) {
2338
+ for (let i = 0; i < nodes.length; i++) {
2339
+ const node = nodes[i];
2340
+ const result = buildProjectMapNodePaths(node.path);
2341
+ tags.push(...result.tags);
2342
+ if (result.paths) {
2343
+ paths.push(...result.paths);
2344
+ }
2345
+ }
2346
+ }
2347
+ tags.push(buildCompositionTag(compositionId));
2348
+ return {
2349
+ tags,
2350
+ paths
2351
+ };
2352
+ };
2353
+ var getComposition = async ({ compositionId }) => {
2354
+ const canvasClient = getCanvasClient({
2355
+ cache: {
2356
+ type: "no-cache"
2357
+ }
2358
+ });
2359
+ try {
2360
+ const composition = await canvasClient.getCompositionById({
2361
+ compositionId
2362
+ });
2363
+ return composition;
2364
+ } catch (err) {
2365
+ if (err instanceof ApiClientError && err.statusCode === 404) {
2366
+ return null;
2367
+ }
2368
+ throw err;
2369
+ }
2370
+ };
2371
+ var buildProjectMapNodePaths = (path) => {
2372
+ const tags = [];
2373
+ const paths = [];
2374
+ const isDynamic = path.includes(":");
2375
+ if (!isDynamic) {
2376
+ tags.push(buildPathTag(path));
2377
+ paths.push(path);
2378
+ } else {
2379
+ const pieces = path.split("/");
2380
+ const invalidatePieces = [];
2381
+ for (let j = 0; j < pieces.length; j++) {
2382
+ const piece = pieces[j];
2383
+ if (piece.startsWith(":")) {
2384
+ break;
2385
+ }
2386
+ invalidatePieces.push(piece);
2387
+ }
2388
+ const toInvalidate = invalidatePieces.join("/");
2389
+ tags.push(buildPathTag(toInvalidate));
2390
+ paths.push(toInvalidate);
2391
+ }
2392
+ return {
2393
+ tags,
2394
+ paths
2395
+ };
2396
+ };
2397
+ var getPathName = (url) => {
2398
+ try {
2399
+ const { pathname } = new URL(url);
2400
+ return pathname;
2401
+ } catch (e) {
2402
+ return url;
2403
+ }
2404
+ };
2405
+ var processRedirectChange = async (sourceUrl) => {
2406
+ const tags = [];
2407
+ const pathName = getPathName(sourceUrl);
2408
+ tags.push(buildPathTag(pathName));
2409
+ return {
2410
+ tags,
2411
+ paths: [pathName]
2412
+ };
2413
+ };
2414
+
2415
+ // src/handler/messages/handleCompositionChanged.ts
2416
+ import { CompositionChangedDefinition } from "@uniformdev/webhooks";
2417
+ var handleCompositionChanged = async (body) => {
2418
+ const parsed = CompositionChangedDefinition.schema.safeParse(body);
2419
+ if (!parsed.success) {
2420
+ return void 0;
2421
+ }
2422
+ return processCompositionChange(parsed.data.id);
2423
+ };
2424
+
2425
+ // src/handler/messages/handleCompositionDeleted.ts
2426
+ import { CompositionDeletedDefinition } from "@uniformdev/webhooks";
2427
+ var handleCompositionDeleted = async (body) => {
2428
+ const parsed = CompositionDeletedDefinition.schema.safeParse(body);
2429
+ if (!parsed.success) {
2430
+ return void 0;
2431
+ }
2432
+ return processCompositionChange(parsed.data.id);
2433
+ };
2434
+
2435
+ // src/handler/messages/handleCompositionPublished.ts
2436
+ import { CompositionPublishedDefinition } from "@uniformdev/webhooks";
2437
+ var handleCompositionPublished = async (body) => {
2438
+ const parsed = CompositionPublishedDefinition.schema.safeParse(body);
2439
+ if (!parsed.success) {
2440
+ return void 0;
2441
+ }
2442
+ return processCompositionChange(parsed.data.id);
2443
+ };
2444
+
2445
+ // src/handler/messages/handleManifestPublished.ts
2446
+ import { ManifestPublishedDefinition } from "@uniformdev/webhooks";
2447
+ var handleManifestPublished = async (body) => {
2448
+ const parsed = ManifestPublishedDefinition.schema.safeParse(body);
2449
+ if (!parsed.success) {
2450
+ return void 0;
2451
+ }
2452
+ return {
2453
+ tags: ["manifest"]
2454
+ };
2455
+ };
2456
+
2457
+ // src/handler/messages/handleProjectMapNodeDelete.ts
2458
+ import { ProjectMapNodeDeleteDefinition } from "@uniformdev/webhooks";
2459
+ var handleProjectMapNodeDelete = async (body) => {
2460
+ const parsed = ProjectMapNodeDeleteDefinition.schema.safeParse(body);
2461
+ if (!parsed.success) {
2462
+ return void 0;
2463
+ }
2464
+ const tags = [];
2465
+ const paths = [];
2466
+ const result = buildProjectMapNodePaths(parsed.data.path);
2467
+ tags.push(...result.tags);
2468
+ if (result.paths) {
2469
+ paths.push(...result.paths);
2470
+ }
2471
+ return {
2472
+ tags,
2473
+ paths
2474
+ };
2475
+ };
2476
+
2477
+ // src/handler/messages/handleProjectMapNodeInsert.ts
2478
+ import { ProjectMapNodeInsertDefinition } from "@uniformdev/webhooks";
2479
+ var handleProjectMapNodeInsert = async (body) => {
2480
+ const parsed = ProjectMapNodeInsertDefinition.schema.safeParse(body);
2481
+ if (!parsed.success) {
2482
+ return void 0;
2483
+ }
2484
+ const tags = [];
2485
+ const paths = [];
2486
+ const result = buildProjectMapNodePaths(parsed.data.path);
2487
+ tags.push(...result.tags);
2488
+ if (result.paths) {
2489
+ paths.push(...result.paths);
2490
+ }
2491
+ return {
2492
+ tags,
2493
+ paths
2494
+ };
2495
+ };
2496
+
2497
+ // src/handler/messages/handleProjectMapNodeUpdate.ts
2498
+ import { ProjectMapNodeUpdateDefinition } from "@uniformdev/webhooks";
2499
+ var handleProjectMapNodeUpdate = async (body) => {
2500
+ const parsed = ProjectMapNodeUpdateDefinition.schema.safeParse(body);
2501
+ if (!parsed.success) {
2502
+ return void 0;
2503
+ }
2504
+ const tags = [];
2505
+ const paths = [];
2506
+ const currentResult = buildProjectMapNodePaths(parsed.data.path);
2507
+ tags.push(...currentResult.tags);
2508
+ if (currentResult.paths) {
2509
+ paths.push(...currentResult.paths);
2510
+ }
2511
+ const previousResult = buildProjectMapNodePaths(parsed.data.previous_path);
2512
+ tags.push(...previousResult.tags);
2513
+ if (previousResult.paths) {
2514
+ paths.push(...previousResult.paths);
2515
+ }
2516
+ return {
2517
+ tags,
2518
+ paths
2519
+ };
2520
+ };
2521
+
2522
+ // src/handler/messages/handleRedirectDelete.ts
2523
+ import { RedirectDeleteDefinition } from "@uniformdev/webhooks";
2524
+ var handleRedirectDelete = async (body) => {
2525
+ const parsed = RedirectDeleteDefinition.schema.safeParse(body);
2526
+ if (!parsed.success) {
2527
+ return void 0;
2528
+ }
2529
+ return processRedirectChange(parsed.data.source_url);
2530
+ };
2531
+
2532
+ // src/handler/messages/handleRedirectInsert.ts
2533
+ import { RedirectInsertDefinition } from "@uniformdev/webhooks";
2534
+ var handleRedirectInsert = async (body) => {
2535
+ const parsed = RedirectInsertDefinition.schema.safeParse(body);
2536
+ if (!parsed.success) {
2537
+ return void 0;
2538
+ }
2539
+ return processRedirectChange(parsed.data.source_url);
2540
+ };
2541
+
2542
+ // src/handler/messages/handleRedirectUpdate.ts
2543
+ import { RedirectUpdateDefinition } from "@uniformdev/webhooks";
2544
+ var handleRedirectUpdate = async (body) => {
2545
+ const parsed = RedirectUpdateDefinition.schema.safeParse(body);
2546
+ if (!parsed.success) {
2547
+ return void 0;
2548
+ }
2549
+ return processRedirectChange(parsed.data.source_url);
2550
+ };
2551
+
2552
+ // src/handler/createPreviewPOSTRouteHandler.ts
2553
+ var createPreviewPOSTRouteHandler = () => {
2554
+ return async (request) => {
2555
+ let previewSecretPassed = false;
2556
+ if (process.env.UNIFORM_PREVIEW_SECRET) {
2557
+ const secretValue = request.nextUrl.searchParams.get(SECRET_QUERY_STRING_PARAM);
2558
+ if (secretValue !== process.env.UNIFORM_PREVIEW_SECRET) {
2559
+ console.warn(
2560
+ "The preview secret passed in the query string does not match the UNIFORM_PREVIEW_SECRET env var."
2561
+ );
2562
+ } else {
2563
+ previewSecretPassed = true;
2564
+ }
2565
+ } else {
2566
+ if (!process.env.UNIFORM_WEBHOOK_SECRET) {
2567
+ console.warn("Both UNIFORM_PREVIEW_SECRET and UNIFORM_WEBHOOK_SECRET are not set.");
2568
+ }
2569
+ previewSecretPassed = true;
2570
+ }
2571
+ if (!previewSecretPassed) {
2572
+ return new Response("The request could not be validated.", {
2573
+ status: 401
2574
+ });
2575
+ }
2576
+ const { looksLikeMessage, validation } = await isSvixMessage(request);
2577
+ if (looksLikeMessage) {
2578
+ if (!validation) {
2579
+ return new Response("This looks like a webhook request but the validation failed.", { status: 401 });
2580
+ }
2581
+ return handleSvixMessage(request);
2582
+ }
2583
+ return new Response("This is not a webhook request.", { status: 401 });
2584
+ };
2585
+ };
2586
+ var handleSvixMessage = async (request) => {
2587
+ var _a;
2588
+ const handlers = [
2589
+ handleProjectMapNodeUpdate,
2590
+ handleProjectMapNodeInsert,
2591
+ handleProjectMapNodeDelete,
2592
+ handleCompositionDeleted,
2593
+ handleCompositionChanged,
2594
+ handleCompositionPublished,
2595
+ handleRedirectInsert,
2596
+ handleRedirectUpdate,
2597
+ handleRedirectDelete,
2598
+ handleManifestPublished
2599
+ ];
2600
+ let tags = void 0;
2601
+ let paths = void 0;
2602
+ let jsonBody;
2603
+ try {
2604
+ jsonBody = await request.json();
2605
+ } catch (err) {
2606
+ console.error("Error parsing the request body as JSON.", err);
2607
+ return new Response("Error parsing the request body as JSON.", {
2608
+ status: 400
2609
+ });
2610
+ }
2611
+ for (let i = 0; i < handlers.length; i++) {
2612
+ const handler = handlers[i];
2613
+ const result = await handler(jsonBody);
2614
+ if (result) {
2615
+ tags = result.tags;
2616
+ paths = result.paths;
2617
+ break;
2618
+ }
2619
+ }
2620
+ if (tags == null ? void 0 : tags.length) {
2621
+ const cache = ((_a = getServerConfig().experimental) == null ? void 0 : _a.middlewareRuntimeCache) ? getCache() : void 0;
2622
+ for (let i = 0; i < tags.length; i++) {
2623
+ const tag = tags[i];
2624
+ revalidateTag(tag, "max");
2625
+ if (cache) {
2626
+ await cache.expireTag(tag);
2627
+ }
2628
+ }
2629
+ }
2630
+ if (paths == null ? void 0 : paths.length) {
2631
+ for (let i = 0; i < paths.length; i++) {
2632
+ const path = paths[i];
2633
+ revalidatePath(path);
2634
+ }
2635
+ }
2636
+ return new Response(
2637
+ JSON.stringify({
2638
+ handled: typeof tags !== "undefined" || typeof paths !== "undefined",
2639
+ tags,
2640
+ paths
2641
+ })
2642
+ );
2643
+ };
2644
+ export {
2645
+ createPreviewGETRouteHandler,
2646
+ createPreviewOPTIONSRouteHandler,
2647
+ createPreviewPOSTRouteHandler
2648
+ };