@uniformdev/next-app-router 20.81.0 → 20.81.1-alpha.10.sha-def425616f

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.
Files changed (48) hide show
  1. package/dist/{UniformComposition-DBO-oo7J.d.ts → UniformComposition-ChDH4dMd.d.ts} +12 -31
  2. package/dist/{UniformComposition-le6UEB_r.d.mts → UniformComposition-Doa1kKRm.d.mts} +12 -31
  3. package/dist/cache.d.mts +24 -6
  4. package/dist/cache.d.ts +24 -6
  5. package/dist/cache.js +396 -832
  6. package/dist/cache.mjs +391 -830
  7. package/dist/compat.d.mts +2 -4
  8. package/dist/compat.d.ts +2 -4
  9. package/dist/component.d.mts +10 -1
  10. package/dist/component.d.ts +10 -1
  11. package/dist/component.js +113 -617
  12. package/dist/component.mjs +112 -640
  13. package/dist/composition-CGU7iH-k.d.mts +37 -0
  14. package/dist/composition-CGU7iH-k.d.ts +37 -0
  15. package/dist/config/default.js +0 -1
  16. package/dist/config/default.mjs +0 -1
  17. package/dist/createCachedManifestProvider-2-2u3PYd.d.mts +84 -0
  18. package/dist/createCachedManifestProvider-BoorKD15.d.ts +84 -0
  19. package/dist/edge.d.mts +80 -0
  20. package/dist/edge.d.ts +80 -0
  21. package/dist/edge.js +1225 -0
  22. package/dist/edge.mjs +1191 -0
  23. package/dist/handler.d.mts +15 -2
  24. package/dist/handler.d.ts +15 -2
  25. package/dist/handler.js +134 -628
  26. package/dist/handler.mjs +132 -626
  27. package/dist/index.d.mts +81 -41
  28. package/dist/index.d.ts +81 -41
  29. package/dist/index.esm.js +2051 -5614
  30. package/dist/index.js +2092 -5651
  31. package/dist/index.mjs +2051 -5614
  32. package/dist/middleware.d.mts +60 -13
  33. package/dist/middleware.d.ts +60 -13
  34. package/dist/middleware.js +415 -5746
  35. package/dist/middleware.mjs +422 -5776
  36. package/dist/models-C8OdCO44.d.mts +72 -0
  37. package/dist/models-C8OdCO44.d.ts +72 -0
  38. package/dist/resolveRouteFromPath-CnfnaxY2.d.ts +80 -0
  39. package/dist/resolveRouteFromPath-_rauUskz.d.mts +80 -0
  40. package/dist/vercel.d.mts +37 -0
  41. package/dist/vercel.d.ts +37 -0
  42. package/dist/vercel.js +788 -0
  43. package/dist/vercel.mjs +759 -0
  44. package/package.json +37 -9
  45. package/dist/client-BElN_CWD.d.mts +0 -786
  46. package/dist/client-BElN_CWD.d.ts +0 -786
  47. package/dist/resolveRouteFromCode-BOvjIvM2.d.ts +0 -18
  48. package/dist/resolveRouteFromCode-CuJ4JHeb.d.mts +0 -18
package/dist/edge.mjs ADDED
@@ -0,0 +1,1191 @@
1
+ // src/edge/uniformEdgeMiddleware.ts
2
+ import { transformEdgeStream } from "@uniformdev/context-edge";
3
+ import { NextResponse as NextResponse2 } from "next/server";
4
+
5
+ // ../canvas/dist/index.mjs
6
+ import { ApiClient } from "@uniformdev/context/api";
7
+ import { ApiClientError } from "@uniformdev/context/api";
8
+ import { ApiClientError as ApiClientError2 } from "@uniformdev/context/api";
9
+ import { ApiClient as ApiClient2 } from "@uniformdev/context/api";
10
+ import { rewriteFiltersForApi } from "@uniformdev/context/api";
11
+ import { rewriteFiltersForApi as rewriteFiltersForApi2 } from "@uniformdev/context/api";
12
+ import { ApiClientError as ApiClientError3 } from "@uniformdev/context/api";
13
+ import { rewriteFiltersForApi as rewriteFiltersForApi3 } from "@uniformdev/context/api";
14
+ import { ApiClientError as ApiClientError4 } from "@uniformdev/context/api";
15
+ import { rewriteFiltersForApi as rewriteFiltersForApi4 } from "@uniformdev/context/api";
16
+ import { ApiClient as ApiClient3, rewriteFiltersForApi as rewriteFiltersForApi5 } from "@uniformdev/context/api";
17
+ import { ApiClient as ApiClient4, rewriteFiltersForApi as rewriteFiltersForApi6 } from "@uniformdev/context/api";
18
+ import { ApiClient as ApiClient5 } from "@uniformdev/context/api";
19
+ import { ApiClient as ApiClient6 } from "@uniformdev/context/api";
20
+ import { ApiClient as ApiClient7 } from "@uniformdev/context/api";
21
+ import { ApiClient as ApiClient8 } from "@uniformdev/context/api";
22
+ import { ApiClient as ApiClient9 } from "@uniformdev/context/api";
23
+ import { ApiClient as ApiClient10 } from "@uniformdev/context/api";
24
+ import { ApiClient as ApiClient11 } from "@uniformdev/context/api";
25
+ import { ApiClient as ApiClient12 } from "@uniformdev/context/api";
26
+ import { ApiClient as ApiClient13 } from "@uniformdev/context/api";
27
+ import { ApiClient as ApiClient14 } from "@uniformdev/context/api";
28
+ import { ApiClient as ApiClient15 } from "@uniformdev/context/api";
29
+ import { ApiClient as ApiClient16 } from "@uniformdev/context/api";
30
+ import { ApiClient as ApiClient17 } from "@uniformdev/context/api";
31
+ import { ApiClientError as ApiClientError5 } from "@uniformdev/context/api";
32
+ import { ApiClient as ApiClient18 } from "@uniformdev/context/api";
33
+ var __typeError = (msg) => {
34
+ throw TypeError(msg);
35
+ };
36
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
37
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
38
+ 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);
39
+ var SELECT_QUERY_PREFIX = "select.";
40
+ function appendCsv(out, key, values) {
41
+ if (values === void 0) {
42
+ return;
43
+ }
44
+ out[key] = values.join(",");
45
+ }
46
+ function projectionToQuery(spec) {
47
+ const out = {};
48
+ if (!spec) {
49
+ return out;
50
+ }
51
+ const { fields, fieldTypes, slots } = spec;
52
+ const p = SELECT_QUERY_PREFIX;
53
+ if (fields) {
54
+ appendCsv(out, `${p}fields[only]`, fields.only);
55
+ appendCsv(out, `${p}fields[except]`, fields.except);
56
+ appendCsv(out, `${p}fields[locales]`, fields.locales);
57
+ if (fields.blockDepth === "preserveAll" || typeof fields.blockDepth === "number") {
58
+ out[`${p}fields[blockDepth]`] = String(fields.blockDepth);
59
+ }
60
+ }
61
+ if (fieldTypes) {
62
+ appendCsv(out, `${p}fieldTypes[only]`, fieldTypes.only);
63
+ appendCsv(out, `${p}fieldTypes[except]`, fieldTypes.except);
64
+ }
65
+ if (slots) {
66
+ appendCsv(out, `${p}slots[only]`, slots.only);
67
+ appendCsv(out, `${p}slots[except]`, slots.except);
68
+ if (typeof slots.depth === "number") {
69
+ out[`${p}slots[depth]`] = String(slots.depth);
70
+ }
71
+ if (slots.named) {
72
+ const slotNames = Object.keys(slots.named).sort();
73
+ for (const slotName of slotNames) {
74
+ const named = slots.named[slotName];
75
+ if (named && typeof named.depth === "number") {
76
+ out[`${p}slots.${slotName}[depth]`] = String(named.depth);
77
+ }
78
+ }
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+ var CANVAS_DRAFT_STATE = 0;
84
+ var CANVAS_PUBLISHED_STATE = 64;
85
+ var CANVAS_EDITOR_STATE = 63;
86
+ var CANVAS_INTERNAL_PARAM_PREFIX = "$internal_";
87
+ var CANVAS_COMPONENT_DISPLAY_NAME_PARAM = `${CANVAS_INTERNAL_PARAM_PREFIX}displayName`;
88
+ var CANVAS_HYPOTHESIS_PARAM = `${CANVAS_INTERNAL_PARAM_PREFIX}hypothesis`;
89
+ var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
90
+ var IN_CONTEXT_EDITOR_FORCED_SETTINGS_QUERY_STRING_PARAM = "is_incontext_editing_forced_settings";
91
+ var EDGE_MAX_CACHE_TTL = 24 * 60 * 60;
92
+ var _contentTypesUrl;
93
+ var _entriesUrl;
94
+ var _ContentClient = class _ContentClient2 extends ApiClient4 {
95
+ constructor(options) {
96
+ var _a;
97
+ super(options);
98
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
99
+ }
100
+ getContentTypes(options) {
101
+ const { projectId } = this.options;
102
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl), { ...options, projectId });
103
+ return this.apiClient(fetchUri);
104
+ }
105
+ getEntries(options) {
106
+ const { projectId } = this.options;
107
+ const { skipDataResolution, filters, select, ...params } = options;
108
+ const rewrittenFilters = rewriteFiltersForApi6(filters);
109
+ const rewrittenSelect = projectionToQuery(select);
110
+ if (skipDataResolution) {
111
+ const url = this.createUrl(__privateGet(_ContentClient2, _entriesUrl), {
112
+ ...params,
113
+ ...rewrittenFilters,
114
+ ...rewrittenSelect,
115
+ projectId
116
+ });
117
+ return this.apiClient(url);
118
+ }
119
+ const edgeUrl = this.createUrl(
120
+ __privateGet(_ContentClient2, _entriesUrl),
121
+ { ...this.getEdgeOptions(params), ...rewrittenFilters, ...rewrittenSelect },
122
+ this.edgeApiHost
123
+ );
124
+ return this.apiClient(
125
+ edgeUrl,
126
+ this.options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0
127
+ );
128
+ }
129
+ /** Fetches historical versions of an entry */
130
+ async getEntryHistory(options) {
131
+ const historyUrl = this.createUrl("/api/v1/entries-history", {
132
+ ...options,
133
+ projectId: this.options.projectId
134
+ });
135
+ return this.apiClient(historyUrl);
136
+ }
137
+ async upsertContentType(body, opts = {}) {
138
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl));
139
+ if (typeof body.contentType.slugSettings === "object" && body.contentType.slugSettings !== null && Object.keys(body.contentType.slugSettings).length === 0) {
140
+ delete body.contentType.slugSettings;
141
+ }
142
+ await this.apiClient(fetchUri, {
143
+ method: "PUT",
144
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
145
+ expectNoContent: true,
146
+ headers: opts.autogenerateDataTypes ? { "x-uniform-autogenerate-data-types": "true" } : {}
147
+ });
148
+ }
149
+ async upsertEntry(body, options) {
150
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _entriesUrl));
151
+ const headers = {};
152
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
153
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
154
+ }
155
+ const { response } = await this.apiClientWithResponse(fetchUri, {
156
+ method: "PUT",
157
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
158
+ expectNoContent: true,
159
+ headers
160
+ });
161
+ return { modified: response.headers.get("x-modified-at") };
162
+ }
163
+ async deleteContentType(body) {
164
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl));
165
+ await this.apiClient(fetchUri, {
166
+ method: "DELETE",
167
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
168
+ expectNoContent: true
169
+ });
170
+ }
171
+ async deleteEntry(body) {
172
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _entriesUrl));
173
+ await this.apiClient(fetchUri, {
174
+ method: "DELETE",
175
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
176
+ expectNoContent: true
177
+ });
178
+ }
179
+ getEdgeOptions(options) {
180
+ const { projectId } = this.options;
181
+ const { skipDataResolution, ...params } = options;
182
+ return {
183
+ projectId,
184
+ ...params,
185
+ diagnostics: typeof options.diagnostics === "boolean" ? options.diagnostics : options.diagnostics === "no-data" ? "no-data" : void 0
186
+ };
187
+ }
188
+ };
189
+ _contentTypesUrl = /* @__PURE__ */ new WeakMap();
190
+ _entriesUrl = /* @__PURE__ */ new WeakMap();
191
+ __privateAdd(_ContentClient, _contentTypesUrl, "/api/v1/content-types");
192
+ __privateAdd(_ContentClient, _entriesUrl, "/api/v1/entries");
193
+ var _url;
194
+ var _DataTypeClient = class _DataTypeClient2 extends ApiClient6 {
195
+ constructor(options) {
196
+ super(options);
197
+ }
198
+ /** Fetches a list of DataTypes for a project */
199
+ async list(options) {
200
+ const { projectId } = this.options;
201
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url), { ...options, projectId });
202
+ return await this.apiClient(fetchUri);
203
+ }
204
+ /** @deprecated Use {@link list} instead. */
205
+ async get(options) {
206
+ return this.list(options);
207
+ }
208
+ /** Updates or creates (based on id) a DataType */
209
+ async save(body) {
210
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url));
211
+ await this.apiClient(fetchUri, {
212
+ method: "PUT",
213
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
214
+ expectNoContent: true
215
+ });
216
+ }
217
+ /** @deprecated Use {@link save} instead. */
218
+ async upsert(body) {
219
+ return this.save(body);
220
+ }
221
+ /** Deletes a DataType */
222
+ async remove(body) {
223
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url));
224
+ await this.apiClient(fetchUri, {
225
+ method: "DELETE",
226
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
227
+ expectNoContent: true
228
+ });
229
+ }
230
+ };
231
+ _url = /* @__PURE__ */ new WeakMap();
232
+ __privateAdd(_DataTypeClient, _url, "/api/v1/data-types");
233
+ var _baseUrl;
234
+ var _IntegrationPropertyEditorsClient = class _IntegrationPropertyEditorsClient2 extends ApiClient8 {
235
+ constructor(options) {
236
+ super(options);
237
+ this.teamId = options.teamId;
238
+ }
239
+ /**
240
+ * Gets a list of property type and hook names for the current team, including public integrations' hooks.
241
+ */
242
+ get(options) {
243
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl), {
244
+ ...options,
245
+ teamId: this.teamId
246
+ });
247
+ return this.apiClient(fetchUri);
248
+ }
249
+ /**
250
+ * Creates or updates a custom AI property editor on a Mesh app.
251
+ */
252
+ async deploy(body) {
253
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl));
254
+ await this.apiClient(fetchUri, {
255
+ method: "PUT",
256
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
257
+ expectNoContent: true
258
+ });
259
+ }
260
+ /**
261
+ * Removes a custom AI property editor from a Mesh app.
262
+ */
263
+ async delete(body) {
264
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl));
265
+ await this.apiClient(fetchUri, {
266
+ method: "DELETE",
267
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
268
+ expectNoContent: true
269
+ });
270
+ }
271
+ };
272
+ _baseUrl = /* @__PURE__ */ new WeakMap();
273
+ __privateAdd(_IntegrationPropertyEditorsClient, _baseUrl, "/api/v1/integration-property-editors");
274
+ var _url2;
275
+ var _projectsUrl;
276
+ var _ProjectClient = class _ProjectClient2 extends ApiClient12 {
277
+ constructor(options) {
278
+ super({ ...options, bypassCache: true });
279
+ }
280
+ /** Fetches single Project */
281
+ async get(options) {
282
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2), { ...options });
283
+ return await this.apiClient(fetchUri);
284
+ }
285
+ /**
286
+ * Fetches projects grouped by team.
287
+ * When teamId is provided, returns a single team with its projects.
288
+ * When omitted, returns all accessible teams and their projects.
289
+ */
290
+ async list(options) {
291
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _projectsUrl), options ? { ...options } : {});
292
+ return await this.apiClient(fetchUri);
293
+ }
294
+ /** @deprecated Use {@link list} instead. */
295
+ async getProjects(options) {
296
+ return this.list(options);
297
+ }
298
+ /** Updates or creates (based on id) a Project */
299
+ async save(body) {
300
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2));
301
+ return await this.apiClient(fetchUri, {
302
+ method: "PUT",
303
+ body: JSON.stringify({ ...body })
304
+ });
305
+ }
306
+ /** @deprecated Use {@link save} instead. */
307
+ async upsert(body) {
308
+ return this.save(body);
309
+ }
310
+ /** Deletes a Project */
311
+ async remove(body) {
312
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2));
313
+ await this.apiClient(fetchUri, {
314
+ method: "DELETE",
315
+ body: JSON.stringify({ ...body }),
316
+ expectNoContent: true
317
+ });
318
+ }
319
+ /** @deprecated Use {@link remove} instead. */
320
+ async delete(body) {
321
+ return this.remove(body);
322
+ }
323
+ };
324
+ _url2 = /* @__PURE__ */ new WeakMap();
325
+ _projectsUrl = /* @__PURE__ */ new WeakMap();
326
+ __privateAdd(_ProjectClient, _url2, "/api/v1/project");
327
+ __privateAdd(_ProjectClient, _projectsUrl, "/api/v1/projects");
328
+
329
+ // src/middleware.ts
330
+ import {
331
+ Context,
332
+ CookieTransitionDataStore,
333
+ UNIFORM_DEFAULT_COOKIE_NAME,
334
+ UNIFORM_DEFAULT_QUIRK_COOKIE_NAME
335
+ } from "@uniformdev/context";
336
+ import {
337
+ serializeEvaluationResult,
338
+ UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME
339
+ } from "@uniformdev/next-app-router-shared";
340
+ import { draftMode } from "next/headers";
341
+ import { NextResponse } from "next/server";
342
+
343
+ // src/config/helpers.ts
344
+ import config from "@uniformdev/next-app-router/config/resolved";
345
+ var getServerConfig = () => {
346
+ return config;
347
+ };
348
+ var getDefaultConsent = () => {
349
+ if (typeof config.defaultConsent === "boolean") {
350
+ return config.defaultConsent;
351
+ }
352
+ return false;
353
+ };
354
+ var getQuirkSerialization = () => {
355
+ if (typeof config.quirkSerialization === "boolean") {
356
+ return config.quirkSerialization;
357
+ }
358
+ return true;
359
+ };
360
+ var getPlaygroundPath = () => {
361
+ if (typeof config.playgroundPath === "string") {
362
+ return config.playgroundPath;
363
+ }
364
+ return "/uniform/playground";
365
+ };
366
+
367
+ // src/data/routes.ts
368
+ var findRouteMatch = (routes, path) => {
369
+ const pieces = path.split("/").filter(Boolean);
370
+ for (const route of routes) {
371
+ const patternPieces = route.pattern.split("/").filter(Boolean);
372
+ if (patternPieces.length !== pieces.length) {
373
+ continue;
374
+ }
375
+ let match = true;
376
+ const params = {};
377
+ for (let i = 0; i < patternPieces.length; i++) {
378
+ const patternPiece = patternPieces[i];
379
+ const piece = pieces[i];
380
+ if (patternPiece.startsWith(":")) {
381
+ const paramName = patternPiece.slice(1);
382
+ params[paramName] = piece;
383
+ } else if (patternPiece !== piece) {
384
+ match = false;
385
+ break;
386
+ }
387
+ }
388
+ if (match) {
389
+ return {
390
+ route,
391
+ params
392
+ };
393
+ }
394
+ }
395
+ return void 0;
396
+ };
397
+
398
+ // src/utils/draft.ts
399
+ var isDraftModeEnabled = ({
400
+ draftModeEnabled
401
+ }) => {
402
+ return draftModeEnabled;
403
+ };
404
+ var isIncontextEditingEnabled = ({
405
+ isDraftModeEnabled: isDraftModeEnabled2,
406
+ searchParams
407
+ }) => {
408
+ if (!isDraftModeEnabled2) {
409
+ return false;
410
+ }
411
+ const containsKey = searchParams.has(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM);
412
+ return containsKey;
413
+ };
414
+ var isDevelopmentEnvironment = () => {
415
+ return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
416
+ };
417
+
418
+ // src/utils/quirks.ts
419
+ var buildQuirksFromHeaders = (headers) => {
420
+ const headerToQuirkKey = {
421
+ "x-vercel-ip-country": "vc-country",
422
+ "x-vercel-ip-country-region": "vc-region",
423
+ "x-vercel-ip-city": "vc-city"
424
+ };
425
+ return Object.entries(headerToQuirkKey).reduce((acc, [headerName, quirkKey]) => {
426
+ const value = headers.get(headerName);
427
+ if (value) {
428
+ acc[quirkKey] = value;
429
+ }
430
+ return acc;
431
+ }, {});
432
+ };
433
+
434
+ // src/middleware.ts
435
+ var resolveUniformRequest = async ({
436
+ request,
437
+ edgeMode,
438
+ ...options
439
+ }) => {
440
+ const draftModeEnabled = (await draftMode()).isEnabled;
441
+ if (draftModeEnabled && isPlaygroundPath(request.nextUrl.pathname)) {
442
+ return handlePlaygroundRequest({ request, options });
443
+ }
444
+ return resolveRouteRequest({ request, draftModeEnabled, edgeMode, options });
445
+ };
446
+ var isPlaygroundPath = (path) => {
447
+ const { playgroundPath } = getServerConfig();
448
+ if (!playgroundPath) {
449
+ return false;
450
+ }
451
+ const PLAYGROUND_ID = "playground";
452
+ const match = findRouteMatch(
453
+ [
454
+ {
455
+ id: PLAYGROUND_ID,
456
+ pattern: playgroundPath
457
+ }
458
+ ],
459
+ path
460
+ );
461
+ return (match == null ? void 0 : match.route.id) === PLAYGROUND_ID;
462
+ };
463
+ var handlePlaygroundRequest = async ({
464
+ request,
465
+ options
466
+ }) => {
467
+ var _a, _b;
468
+ const id = request.nextUrl.searchParams.get("id");
469
+ if (!id) {
470
+ return {
471
+ type: "response",
472
+ response: NextResponse.json({ error: "No id provided" }, { status: 400 })
473
+ };
474
+ }
475
+ const playgroundPath = getPlaygroundPath();
476
+ const pageState = {
477
+ routePath: id,
478
+ compositionState: CANVAS_EDITOR_STATE,
479
+ keys: void 0,
480
+ releaseId: (_a = options.release) == null ? void 0 : _a.id,
481
+ defaultConsent: determineDefaultConsent({
482
+ serverConfig: getServerConfig(),
483
+ defaultConsent: options.defaultConsent
484
+ }),
485
+ previewMode: determinePreviewMode({
486
+ searchParams: request.nextUrl.searchParams,
487
+ isDraftModeEnabled: true
488
+ }),
489
+ locale: options.locale
490
+ };
491
+ const code = serializeEvaluationResult({ payload: pageState });
492
+ const destination = await ((_b = options.rewriteDestinationPath) == null ? void 0 : _b.call(options, { code, pageState, source: "playground" })) || `${playgroundPath}${playgroundPath.endsWith("/") ? "" : "/"}${code}`;
493
+ return {
494
+ type: "response",
495
+ response: NextResponse.rewrite(new URL(destination, request.nextUrl.origin))
496
+ };
497
+ };
498
+ var resolveRouteRequest = async ({
499
+ request,
500
+ draftModeEnabled,
501
+ edgeMode,
502
+ options
503
+ }) => {
504
+ var _a, _b, _c, _d, _e;
505
+ const releaseId = (_b = (_a = options.release) == null ? void 0 : _a.id) != null ? _b : draftModeEnabled ? request.nextUrl.searchParams.get("releaseId") || void 0 : void 0;
506
+ const requestPath = (_d = await ((_c = options.rewriteRequestPath) == null ? void 0 : _c.call(options, {
507
+ request,
508
+ url: new URL(request.url)
509
+ }))) != null ? _d : {
510
+ path: `${request.nextUrl.pathname}${request.nextUrl.search}`
511
+ };
512
+ const defaultConsent = determineDefaultConsent({
513
+ serverConfig: getServerConfig(),
514
+ defaultConsent: options.defaultConsent
515
+ });
516
+ const pageState = {
517
+ routePath: buildRoutePath({ path: requestPath.path, queryStrings: options.queryStrings }),
518
+ compositionState: determineCompositionState({
519
+ searchParams: request.nextUrl.searchParams,
520
+ draftModeEnabled
521
+ }),
522
+ keys: requestPath.keys,
523
+ releaseId,
524
+ defaultConsent,
525
+ previewMode: determinePreviewMode({
526
+ searchParams: request.nextUrl.searchParams,
527
+ isDraftModeEnabled: draftModeEnabled
528
+ }),
529
+ locale: options.locale
530
+ };
531
+ if (edgeMode && pageState.compositionState === CANVAS_PUBLISHED_STATE && await edgeMode({ pageState })) {
532
+ pageState.edgeMode = true;
533
+ }
534
+ const code = serializeEvaluationResult({ payload: pageState });
535
+ const destination = await ((_e = options.rewriteDestinationPath) == null ? void 0 : _e.call(options, { code, pageState, source: "route" })) || `/uniform/${code}`;
536
+ const quirks = {
537
+ ...buildQuirksFromHeaders(request.headers),
538
+ ...options.quirks
539
+ };
540
+ const headers = new Headers();
541
+ if (Object.keys(quirks).length > 0) {
542
+ headers.append(
543
+ "Set-Cookie",
544
+ `${UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME}=${JSON.stringify(quirks)}; Path=/; SameSite=Lax; Max-Age=10`
545
+ );
546
+ }
547
+ const createContext = async ({ manifest }) => {
548
+ var _a2, _b2, _c2, _d2;
549
+ const context = new Context({
550
+ manifest,
551
+ defaultConsent: defaultConsent != null ? defaultConsent : getDefaultConsent(),
552
+ transitionStore: new CookieTransitionDataStore({
553
+ serverCookieValue: (_b2 = (_a2 = request.cookies.get(UNIFORM_DEFAULT_COOKIE_NAME)) == null ? void 0 : _a2.value) != null ? _b2 : "",
554
+ experimental_quirksEnabled: getQuirkSerialization(),
555
+ quirkCookieValue: (_d2 = (_c2 = request.cookies.get(UNIFORM_DEFAULT_QUIRK_COOKIE_NAME)) == null ? void 0 : _c2.value) != null ? _d2 : ""
556
+ })
557
+ });
558
+ await context.update({
559
+ url: new URL(request.nextUrl.href),
560
+ cookies: Object.fromEntries(request.cookies.getAll().map((cookie) => [cookie.name, cookie.value])),
561
+ quirks
562
+ });
563
+ return context;
564
+ };
565
+ return {
566
+ type: "rewrite",
567
+ destination,
568
+ pageState,
569
+ code,
570
+ headers,
571
+ draftModeEnabled,
572
+ createContext
573
+ };
574
+ };
575
+ var buildRoutePath = ({
576
+ path,
577
+ queryStrings
578
+ }) => {
579
+ const [pathname = "", search] = path.split("?");
580
+ if (!search || !queryStrings) {
581
+ return pathname;
582
+ }
583
+ const patterns = Object.keys(queryStrings);
584
+ const match = findRouteMatch(
585
+ patterns.map((pattern) => ({ id: pattern, pattern })),
586
+ pathname
587
+ );
588
+ const allowed = match ? queryStrings[match.route.id] : void 0;
589
+ if (!(allowed == null ? void 0 : allowed.length)) {
590
+ return pathname;
591
+ }
592
+ const requestSearchParams = new URLSearchParams(search);
593
+ const searchParams = new URLSearchParams();
594
+ [...allowed].sort().forEach((name) => {
595
+ const value = requestSearchParams.get(name);
596
+ if (value !== null) {
597
+ searchParams.set(name, value);
598
+ }
599
+ });
600
+ return searchParams.size ? `${pathname}?${searchParams.toString()}` : pathname;
601
+ };
602
+ var determineCompositionState = ({
603
+ searchParams,
604
+ draftModeEnabled
605
+ }) => {
606
+ if (!draftModeEnabled) {
607
+ return CANVAS_PUBLISHED_STATE;
608
+ }
609
+ return isIncontextEditingEnabled({ isDraftModeEnabled: draftModeEnabled, searchParams }) ? CANVAS_EDITOR_STATE : CANVAS_DRAFT_STATE;
610
+ };
611
+ var determineDefaultConsent = ({
612
+ serverConfig,
613
+ defaultConsent
614
+ }) => {
615
+ return defaultConsent !== serverConfig.defaultConsent ? defaultConsent : void 0;
616
+ };
617
+ var determinePreviewMode = ({
618
+ searchParams,
619
+ isDraftModeEnabled: isDraftModeEnabled2
620
+ }) => {
621
+ if (!isDraftModeEnabled2) {
622
+ return void 0;
623
+ }
624
+ const queryStringSettings = searchParams.get(IN_CONTEXT_EDITOR_FORCED_SETTINGS_QUERY_STRING_PARAM);
625
+ let previewSettings = void 0;
626
+ if (queryStringSettings) {
627
+ try {
628
+ previewSettings = JSON.parse(queryStringSettings);
629
+ } catch (e) {
630
+ }
631
+ }
632
+ if (previewSettings == null ? void 0 : previewSettings.isVisualEditingDisabled) {
633
+ return "preview";
634
+ }
635
+ const isInContextEditingEnabled = isIncontextEditingEnabled({ isDraftModeEnabled: isDraftModeEnabled2, searchParams });
636
+ if (isInContextEditingEnabled) {
637
+ return "editor";
638
+ }
639
+ return void 0;
640
+ };
641
+
642
+ // src/edge/uniformEdgeMiddleware.ts
643
+ var UNIFORM_EDGE_ORIGIN_HEADER = "x-uniform-edge-origin";
644
+ var uniformEdgeMiddleware = (options) => {
645
+ return async (request, event) => {
646
+ return handleUniformEdgeRoute({
647
+ request,
648
+ waitUntil: event ? (promise) => event.waitUntil(promise) : void 0,
649
+ ...options
650
+ });
651
+ };
652
+ };
653
+ var handleUniformEdgeRoute = async ({
654
+ request,
655
+ manifest,
656
+ onError,
657
+ filter,
658
+ waitUntil = ignorePromise,
659
+ ...options
660
+ }) => {
661
+ var _a;
662
+ if (request.headers.has(UNIFORM_EDGE_ORIGIN_HEADER)) {
663
+ return NextResponse2.next();
664
+ }
665
+ const result = await resolveUniformRequest({
666
+ request,
667
+ ...options,
668
+ edgeMode: ({ pageState }) => filter ? filter.shouldProcess({ pageState, waitUntil }) : true
669
+ });
670
+ if (result.type === "response") {
671
+ return result.response;
672
+ }
673
+ const destination = new URL(result.destination, request.nextUrl.origin);
674
+ if (!result.pageState.edgeMode || !isDocumentRequest(request)) {
675
+ return NextResponse2.rewrite(destination, { headers: result.headers });
676
+ }
677
+ const [originResponse, context] = await Promise.all([
678
+ fetch(destination, {
679
+ // A page that calls `redirect()` answers with a redirect, which belongs to the visitor.
680
+ redirect: "manual",
681
+ headers: {
682
+ cookie: (_a = request.headers.get("cookie")) != null ? _a : "",
683
+ accept: "text/html",
684
+ // Node's fetch decompresses the body but keeps the header, so ask for plain HTML.
685
+ "accept-encoding": "identity",
686
+ [UNIFORM_EDGE_ORIGIN_HEADER]: "1"
687
+ }
688
+ }),
689
+ resolveManifest({ manifest, waitUntil, onError }).then(
690
+ (resolved) => result.createContext({ manifest: resolved })
691
+ )
692
+ ]);
693
+ const headers = new Headers(originResponse.headers);
694
+ result.headers.forEach((value, key) => {
695
+ headers.append(key, value);
696
+ });
697
+ if (originResponse.status >= 300 && originResponse.status < 400) {
698
+ return new Response(originResponse.body, {
699
+ status: originResponse.status,
700
+ statusText: originResponse.statusText,
701
+ headers
702
+ });
703
+ }
704
+ headers.delete("content-length");
705
+ headers.delete("content-encoding");
706
+ headers.set("cache-control", "private, no-store");
707
+ const observe = filter == null ? void 0 : filter.observe;
708
+ const onComplete = observe && originResponse.status === 200 ? (hasPlacements) => observe({ pageState: result.pageState, hasPlacements, waitUntil }) : void 0;
709
+ return new Response(transformBody({ body: originResponse.body, context, onError, onComplete }), {
710
+ status: originResponse.status,
711
+ statusText: originResponse.statusText,
712
+ headers
713
+ });
714
+ };
715
+ var ignorePromise = (promise) => {
716
+ promise.catch(() => {
717
+ });
718
+ };
719
+ var EMPTY_MANIFEST = { project: {} };
720
+ var resolveManifest = async ({
721
+ manifest,
722
+ waitUntil,
723
+ onError
724
+ }) => {
725
+ if (typeof manifest !== "function") {
726
+ return manifest;
727
+ }
728
+ try {
729
+ return await manifest({ waitUntil });
730
+ } catch (error) {
731
+ onError == null ? void 0 : onError({ error });
732
+ return EMPTY_MANIFEST;
733
+ }
734
+ };
735
+ var isDocumentRequest = (request) => {
736
+ const accept = request.headers.get("accept");
737
+ return request.method === "GET" && !request.headers.has("rsc") && !request.headers.has("next-router-prefetch") && (!accept || accept.includes("text/html") || accept.includes("*/*"));
738
+ };
739
+ var transformBody = ({
740
+ body,
741
+ context,
742
+ onError,
743
+ onComplete
744
+ }) => {
745
+ if (!body) {
746
+ return null;
747
+ }
748
+ const reader = body.getReader();
749
+ const { readable, writable } = new TransformStream();
750
+ const writer = writable.getWriter();
751
+ let hasPlacements = false;
752
+ let complete = true;
753
+ writer.closed.catch(() => {
754
+ complete = false;
755
+ return reader.cancel();
756
+ }).catch(() => {
757
+ });
758
+ void transformEdgeStream({
759
+ context,
760
+ decoder: new TextDecoder(),
761
+ encoder: new TextEncoder(),
762
+ reader: {
763
+ read: async () => {
764
+ await writer.ready.catch(() => {
765
+ });
766
+ const { done, value } = await reader.read();
767
+ return { done, value };
768
+ }
769
+ },
770
+ writer: {
771
+ // Write and close fail only after the visitor disconnects, which `writer.closed` handles.
772
+ write: (value) => {
773
+ writer.write(value).catch(() => {
774
+ });
775
+ },
776
+ close: () => {
777
+ return writer.close().catch(() => {
778
+ });
779
+ }
780
+ },
781
+ onError: (details) => {
782
+ complete = false;
783
+ if (onError) {
784
+ onError(details);
785
+ } else {
786
+ console.error("[transformEdgeStream]", details.error);
787
+ }
788
+ },
789
+ onPlacement: () => {
790
+ hasPlacements = true;
791
+ }
792
+ }).then(() => {
793
+ if (complete) {
794
+ onComplete == null ? void 0 : onComplete(hasPlacements);
795
+ }
796
+ });
797
+ return readable;
798
+ };
799
+
800
+ // src/utils/env.ts
801
+ var env = {
802
+ getProjectId: () => {
803
+ return process.env.UNIFORM_PROJECT_ID;
804
+ },
805
+ getApiKey: () => {
806
+ return process.env.UNIFORM_API_KEY;
807
+ },
808
+ getApiHost: () => {
809
+ return process.env.UNIFORM_API_HOST || process.env.UNIFORM_CLI_BASE_URL;
810
+ },
811
+ getEdgeApiHost: () => {
812
+ return process.env.UNIFORM_EDGE_API_HOST || process.env.UNIFORM_CLI_BASE_EDGE_URL;
813
+ }
814
+ };
815
+
816
+ // src/utils/tag.ts
817
+ var encodePathForTag = (path) => path.split("/").map((segment) => /[^\x00-\x7F]/.test(segment) ? encodeURIComponent(segment) : segment).join("/");
818
+ var buildPathTag = (path) => {
819
+ const actualPath = path.startsWith("/") ? path : `/${path}`;
820
+ return `path:${encodePathForTag(actualPath)}`.toLowerCase();
821
+ };
822
+
823
+ // src/edgeRouteFilter/createLearnedEdgeRouteFilter.ts
824
+ var createLearnedEdgeRouteFilter = ({
825
+ cache,
826
+ ttl = 3600,
827
+ maxAge = 10,
828
+ maxEntries = 1e3
829
+ } = {}) => {
830
+ const memory = /* @__PURE__ */ new Map();
831
+ const pending = /* @__PURE__ */ new Map();
832
+ const remember = (key, hasPlacements) => {
833
+ memory.delete(key);
834
+ memory.set(key, { hasPlacements, checkedAt: Date.now() });
835
+ if (memory.size > maxEntries) {
836
+ const oldest = memory.keys().next().value;
837
+ if (oldest !== void 0) {
838
+ memory.delete(oldest);
839
+ }
840
+ }
841
+ };
842
+ const read = async (key) => {
843
+ const stored = await (cache == null ? void 0 : cache.get(key).catch(() => void 0));
844
+ const hasPlacements = isRecord(stored) ? stored.hasPlacements : void 0;
845
+ remember(key, hasPlacements);
846
+ return hasPlacements;
847
+ };
848
+ return {
849
+ shouldProcess: async ({ pageState }) => {
850
+ var _a, _b;
851
+ const key = buildKey(pageState);
852
+ const known = memory.get(key);
853
+ if (known && Date.now() - known.checkedAt < maxAge * 1e3) {
854
+ return (_a = known.hasPlacements) != null ? _a : true;
855
+ }
856
+ let lookup = pending.get(key);
857
+ if (!lookup) {
858
+ lookup = read(key).finally(() => {
859
+ pending.delete(key);
860
+ });
861
+ pending.set(key, lookup);
862
+ }
863
+ return (_b = await lookup) != null ? _b : true;
864
+ },
865
+ observe: ({ pageState, hasPlacements, waitUntil }) => {
866
+ var _a, _b;
867
+ const key = buildKey(pageState);
868
+ if (((_a = memory.get(key)) == null ? void 0 : _a.hasPlacements) === hasPlacements) {
869
+ return;
870
+ }
871
+ remember(key, hasPlacements);
872
+ if (cache) {
873
+ const tags = [buildPathTag((_b = pageState.routePath.split("?")[0]) != null ? _b : "")];
874
+ waitUntil(cache.set(key, { hasPlacements }, { ttl, tags }).catch(() => {
875
+ }));
876
+ }
877
+ }
878
+ };
879
+ };
880
+ var buildKey = (pageState) => {
881
+ var _a, _b;
882
+ return `uniform-edge-route-${(_a = env.getProjectId()) != null ? _a : ""}-${(_b = pageState.locale) != null ? _b : ""}-${pageState.routePath}`;
883
+ };
884
+ var isRecord = (value) => typeof value === "object" && value !== null && "hasPlacements" in value && typeof value.hasPlacements === "boolean";
885
+
886
+ // src/edgeRouteFilter/createStaticEdgeRouteFilter.ts
887
+ var createStaticEdgeRouteFilter = ({
888
+ paths
889
+ }) => {
890
+ const routes = paths.map((pattern) => ({ id: pattern, pattern }));
891
+ return {
892
+ shouldProcess: ({ pageState }) => Boolean(findRouteMatch(routes, stripQuery(pageState.routePath)))
893
+ };
894
+ };
895
+ var stripQuery = (routePath) => {
896
+ var _a;
897
+ return (_a = routePath.split("?")[0]) != null ? _a : "";
898
+ };
899
+
900
+ // src/clients/manifest.ts
901
+ import "server-only";
902
+ import { ManifestClient } from "@uniformdev/context/api";
903
+
904
+ // src/clients/cache.ts
905
+ var isSpecificCacheMode = (options) => {
906
+ return "cache" in options;
907
+ };
908
+ var isStateCacheMode = (options) => {
909
+ return "state" in options;
910
+ };
911
+ var isDetectCacheMode = (options) => {
912
+ return "searchParams" in options && "draftModeEnabled" in options;
913
+ };
914
+ var resolveManifestCache = (options) => {
915
+ return resolveCache({
916
+ options
917
+ });
918
+ };
919
+ var resolveCache = ({
920
+ options
921
+ }) => {
922
+ let cache = void 0;
923
+ if (options) {
924
+ if (isSpecificCacheMode(options)) {
925
+ cache = options.cache;
926
+ } else if (isStateCacheMode(options)) {
927
+ if (options.state === CANVAS_DRAFT_STATE || options.state === CANVAS_EDITOR_STATE) {
928
+ cache = {
929
+ type: "no-cache",
930
+ bypassCache: true
931
+ };
932
+ }
933
+ } else if (isDetectCacheMode(options)) {
934
+ const { disabled } = shouldCacheBeDisabled(options);
935
+ if (disabled) {
936
+ cache = {
937
+ type: "no-cache",
938
+ bypassCache: true
939
+ };
940
+ }
941
+ }
942
+ }
943
+ return cache || {
944
+ type: "force-cache"
945
+ };
946
+ };
947
+ var shouldCacheBeDisabled = (options) => {
948
+ if (isDraftModeEnabled(options)) {
949
+ return { disabled: true, reason: "DRAFT" };
950
+ }
951
+ if (isIncontextEditingEnabled({
952
+ isDraftModeEnabled: options.draftModeEnabled,
953
+ searchParams: options.searchParams
954
+ })) {
955
+ return { disabled: true, reason: "INCONTEXT" };
956
+ }
957
+ if (isDevelopmentEnvironment()) {
958
+ return { disabled: true, reason: "DEV" };
959
+ }
960
+ return {
961
+ disabled: false,
962
+ reason: void 0
963
+ };
964
+ };
965
+ var determineFetchCacheOptions = (mode) => {
966
+ let cache = void 0;
967
+ let revalidate = void 0;
968
+ if (mode.type === "revalidate") {
969
+ cache = void 0;
970
+ revalidate = mode.interval;
971
+ } else {
972
+ cache = mode.type;
973
+ }
974
+ return {
975
+ cache,
976
+ revalidate
977
+ };
978
+ };
979
+
980
+ // src/clients/retry.ts
981
+ import { ApiClientError as ApiClientError6 } from "@uniformdev/context/api";
982
+ function createThrottler(limit, interval) {
983
+ let available = limit;
984
+ let refillScheduled = false;
985
+ const waiting = [];
986
+ function scheduleRefill() {
987
+ if (refillScheduled) return;
988
+ refillScheduled = true;
989
+ setTimeout(() => {
990
+ refillScheduled = false;
991
+ available = limit;
992
+ while (available > 0 && waiting.length > 0) {
993
+ available--;
994
+ const next = waiting.shift();
995
+ next();
996
+ }
997
+ if (waiting.length > 0) {
998
+ scheduleRefill();
999
+ }
1000
+ }, interval);
1001
+ }
1002
+ return async function throttle(fn) {
1003
+ if (available > 0) {
1004
+ available--;
1005
+ if (!refillScheduled) {
1006
+ scheduleRefill();
1007
+ }
1008
+ return fn();
1009
+ }
1010
+ return new Promise((resolve, reject) => {
1011
+ waiting.push(() => {
1012
+ fn().then(resolve, reject);
1013
+ });
1014
+ scheduleRefill();
1015
+ });
1016
+ };
1017
+ }
1018
+ function createLimiter(concurrency) {
1019
+ let active = 0;
1020
+ const queue = [];
1021
+ return async function limit(fn) {
1022
+ return new Promise((resolve, reject) => {
1023
+ const run = async () => {
1024
+ active++;
1025
+ try {
1026
+ const result = await fn();
1027
+ resolve(result);
1028
+ } catch (error) {
1029
+ reject(error);
1030
+ } finally {
1031
+ active--;
1032
+ if (queue.length > 0) {
1033
+ const next = queue.shift();
1034
+ next();
1035
+ }
1036
+ }
1037
+ };
1038
+ if (active < concurrency) {
1039
+ run();
1040
+ } else {
1041
+ queue.push(run);
1042
+ }
1043
+ });
1044
+ };
1045
+ }
1046
+ async function retry(fn, options) {
1047
+ let lastError;
1048
+ let delay = 1e3;
1049
+ for (let attempt = 1; attempt <= options.retries + 1; attempt++) {
1050
+ try {
1051
+ return await fn();
1052
+ } catch (error) {
1053
+ lastError = error;
1054
+ const attemptError = Object.assign(error, { attemptNumber: attempt });
1055
+ if (options.onFailedAttempt) {
1056
+ await options.onFailedAttempt(attemptError);
1057
+ }
1058
+ if (attempt > options.retries) {
1059
+ throw error;
1060
+ }
1061
+ await new Promise((resolve) => setTimeout(resolve, delay));
1062
+ delay *= options.factor;
1063
+ }
1064
+ }
1065
+ throw lastError;
1066
+ }
1067
+ function createLimitPolicy({
1068
+ throttle = { interval: 1e3, limit: 10 },
1069
+ retry: retryOptions = { retries: 1, factor: 1.66 },
1070
+ limit = 10
1071
+ }) {
1072
+ const throttler = throttle ? createThrottler(throttle.limit, throttle.interval) : null;
1073
+ const limiter = limit ? createLimiter(limit) : null;
1074
+ return function limitPolicy(func) {
1075
+ let currentFunc = async () => await func();
1076
+ if (throttler) {
1077
+ const throttleFunc = currentFunc;
1078
+ currentFunc = () => throttler(throttleFunc);
1079
+ }
1080
+ if (limiter) {
1081
+ const limitFunc = currentFunc;
1082
+ currentFunc = () => limiter(limitFunc);
1083
+ }
1084
+ if (retryOptions) {
1085
+ const retryFunc = currentFunc;
1086
+ currentFunc = () => retry(retryFunc, {
1087
+ ...retryOptions,
1088
+ onFailedAttempt: async (error) => {
1089
+ if (retryOptions.onFailedAttempt) {
1090
+ await retryOptions.onFailedAttempt(error);
1091
+ }
1092
+ if (error instanceof ApiClientError6 && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
1093
+ throw error;
1094
+ }
1095
+ }
1096
+ });
1097
+ }
1098
+ return currentFunc();
1099
+ };
1100
+ }
1101
+
1102
+ // src/clients/tags.ts
1103
+ var generateManifestCacheTags = () => {
1104
+ return ["manifest"];
1105
+ };
1106
+
1107
+ // src/clients/manifest.ts
1108
+ var getManifestClient = (options) => {
1109
+ const cache = resolveManifestCache(options);
1110
+ const manifestClient = new ManifestClient({
1111
+ apiHost: env.getApiHost(),
1112
+ apiKey: env.getApiKey(),
1113
+ projectId: env.getProjectId(),
1114
+ limitPolicy: createLimitPolicy({
1115
+ limit: 6
1116
+ }),
1117
+ fetch: (req, init) => {
1118
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache);
1119
+ return fetch(req, {
1120
+ ...init,
1121
+ headers: {
1122
+ ...init == null ? void 0 : init.headers,
1123
+ "x-bypass-cache": typeof cache.bypassCache !== "undefined" ? cache.bypassCache.toString() : "false"
1124
+ },
1125
+ cache: fetchCache,
1126
+ next: {
1127
+ revalidate,
1128
+ tags: generateManifestCacheTags()
1129
+ }
1130
+ });
1131
+ }
1132
+ });
1133
+ return manifestClient;
1134
+ };
1135
+
1136
+ // src/manifest/createCachedManifestProvider.ts
1137
+ var createCachedManifestProvider = ({
1138
+ cache,
1139
+ fallback,
1140
+ ttl = 3600,
1141
+ maxAge = 10,
1142
+ fetchManifest = fetchPublishedManifest
1143
+ } = {}) => {
1144
+ let current;
1145
+ let pending;
1146
+ const load = async ({ waitUntil }) => {
1147
+ var _a;
1148
+ const key = `uniform-manifest-${(_a = env.getProjectId()) != null ? _a : ""}`;
1149
+ const cached = await (cache == null ? void 0 : cache.get(key).catch(() => void 0));
1150
+ if (isManifest(cached)) {
1151
+ return cached;
1152
+ }
1153
+ const manifest = await fetchManifest();
1154
+ if (cache) {
1155
+ waitUntil(cache.set(key, manifest, { ttl, tags: generateManifestCacheTags() }).catch(() => {
1156
+ }));
1157
+ }
1158
+ return manifest;
1159
+ };
1160
+ return async (options) => {
1161
+ var _a;
1162
+ if (current && Date.now() - current.loadedAt < maxAge * 1e3) {
1163
+ return current.manifest;
1164
+ }
1165
+ pending != null ? pending : pending = load(options).then((manifest) => {
1166
+ current = { manifest, loadedAt: Date.now() };
1167
+ return manifest;
1168
+ }).finally(() => {
1169
+ pending = void 0;
1170
+ });
1171
+ try {
1172
+ return await pending;
1173
+ } catch (error) {
1174
+ const known = (_a = current == null ? void 0 : current.manifest) != null ? _a : fallback;
1175
+ if (known) {
1176
+ return known;
1177
+ }
1178
+ throw error;
1179
+ }
1180
+ };
1181
+ };
1182
+ var fetchPublishedManifest = () => getManifestClient({ cache: { type: "no-store" } }).get({ preview: false });
1183
+ var isManifest = (value) => typeof value === "object" && value !== null && "project" in value;
1184
+ export {
1185
+ UNIFORM_EDGE_ORIGIN_HEADER,
1186
+ createCachedManifestProvider,
1187
+ createLearnedEdgeRouteFilter,
1188
+ createStaticEdgeRouteFilter,
1189
+ handleUniformEdgeRoute,
1190
+ uniformEdgeMiddleware
1191
+ };