@uniformdev/next-app-router 20.81.1-alpha.4.sha-de16ebeee7 → 20.81.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/edge.mjs DELETED
@@ -1,720 +0,0 @@
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 isIncontextEditingEnabled = ({
400
- isDraftModeEnabled,
401
- searchParams
402
- }) => {
403
- if (!isDraftModeEnabled) {
404
- return false;
405
- }
406
- const containsKey = searchParams.has(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM);
407
- return containsKey;
408
- };
409
-
410
- // src/utils/quirks.ts
411
- var buildQuirksFromHeaders = (headers) => {
412
- const headerToQuirkKey = {
413
- "x-vercel-ip-country": "vc-country",
414
- "x-vercel-ip-country-region": "vc-region",
415
- "x-vercel-ip-city": "vc-city"
416
- };
417
- return Object.entries(headerToQuirkKey).reduce((acc, [headerName, quirkKey]) => {
418
- const value = headers.get(headerName);
419
- if (value) {
420
- acc[quirkKey] = value;
421
- }
422
- return acc;
423
- }, {});
424
- };
425
-
426
- // src/middleware.ts
427
- var resolveUniformRequest = async ({
428
- request,
429
- ...options
430
- }) => {
431
- const draftModeEnabled = (await draftMode()).isEnabled;
432
- if (draftModeEnabled && isPlaygroundPath(request.nextUrl.pathname)) {
433
- return handlePlaygroundRequest({ request, options });
434
- }
435
- return resolveRouteRequest({ request, draftModeEnabled, options });
436
- };
437
- var isPlaygroundPath = (path) => {
438
- const { playgroundPath } = getServerConfig();
439
- if (!playgroundPath) {
440
- return false;
441
- }
442
- const PLAYGROUND_ID = "playground";
443
- const match = findRouteMatch(
444
- [
445
- {
446
- id: PLAYGROUND_ID,
447
- pattern: playgroundPath
448
- }
449
- ],
450
- path
451
- );
452
- return (match == null ? void 0 : match.route.id) === PLAYGROUND_ID;
453
- };
454
- var handlePlaygroundRequest = async ({
455
- request,
456
- options
457
- }) => {
458
- var _a, _b;
459
- const id = request.nextUrl.searchParams.get("id");
460
- if (!id) {
461
- return {
462
- type: "response",
463
- response: NextResponse.json({ error: "No id provided" }, { status: 400 })
464
- };
465
- }
466
- const playgroundPath = getPlaygroundPath();
467
- const pageState = {
468
- routePath: id,
469
- compositionState: CANVAS_EDITOR_STATE,
470
- keys: void 0,
471
- releaseId: (_a = options.release) == null ? void 0 : _a.id,
472
- defaultConsent: determineDefaultConsent({
473
- serverConfig: getServerConfig(),
474
- defaultConsent: options.defaultConsent
475
- }),
476
- previewMode: determinePreviewMode({
477
- searchParams: request.nextUrl.searchParams,
478
- isDraftModeEnabled: true
479
- }),
480
- locale: options.locale
481
- };
482
- const code = serializeEvaluationResult({ payload: pageState });
483
- const destination = await ((_b = options.rewriteDestinationPath) == null ? void 0 : _b.call(options, { code, pageState, source: "playground" })) || `${playgroundPath}${playgroundPath.endsWith("/") ? "" : "/"}${code}`;
484
- return {
485
- type: "response",
486
- response: NextResponse.rewrite(new URL(destination, request.nextUrl.origin))
487
- };
488
- };
489
- var resolveRouteRequest = async ({
490
- request,
491
- draftModeEnabled,
492
- options
493
- }) => {
494
- var _a, _b, _c, _d, _e;
495
- const releaseId = (_b = (_a = options.release) == null ? void 0 : _a.id) != null ? _b : draftModeEnabled ? request.nextUrl.searchParams.get("releaseId") || void 0 : void 0;
496
- const requestPath = (_d = await ((_c = options.rewriteRequestPath) == null ? void 0 : _c.call(options, {
497
- request,
498
- url: new URL(request.url)
499
- }))) != null ? _d : {
500
- path: `${request.nextUrl.pathname}${request.nextUrl.search}`
501
- };
502
- const defaultConsent = determineDefaultConsent({
503
- serverConfig: getServerConfig(),
504
- defaultConsent: options.defaultConsent
505
- });
506
- const pageState = {
507
- routePath: buildRoutePath({ path: requestPath.path, queryStrings: options.queryStrings }),
508
- compositionState: determineCompositionState({
509
- searchParams: request.nextUrl.searchParams,
510
- draftModeEnabled
511
- }),
512
- keys: requestPath.keys,
513
- releaseId,
514
- defaultConsent,
515
- previewMode: determinePreviewMode({
516
- searchParams: request.nextUrl.searchParams,
517
- isDraftModeEnabled: draftModeEnabled
518
- }),
519
- locale: options.locale
520
- };
521
- const code = serializeEvaluationResult({ payload: pageState });
522
- const destination = await ((_e = options.rewriteDestinationPath) == null ? void 0 : _e.call(options, { code, pageState, source: "route" })) || `/uniform/${code}`;
523
- const quirks = {
524
- ...buildQuirksFromHeaders(request.headers),
525
- ...options.quirks
526
- };
527
- const headers = new Headers();
528
- if (Object.keys(quirks).length > 0) {
529
- headers.append(
530
- "Set-Cookie",
531
- `${UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME}=${JSON.stringify(quirks)}; Path=/; SameSite=Lax; Max-Age=10`
532
- );
533
- }
534
- const createContext = async ({ manifest }) => {
535
- var _a2, _b2, _c2, _d2;
536
- const context = new Context({
537
- manifest,
538
- defaultConsent: defaultConsent != null ? defaultConsent : getDefaultConsent(),
539
- transitionStore: new CookieTransitionDataStore({
540
- serverCookieValue: (_b2 = (_a2 = request.cookies.get(UNIFORM_DEFAULT_COOKIE_NAME)) == null ? void 0 : _a2.value) != null ? _b2 : "",
541
- experimental_quirksEnabled: getQuirkSerialization(),
542
- quirkCookieValue: (_d2 = (_c2 = request.cookies.get(UNIFORM_DEFAULT_QUIRK_COOKIE_NAME)) == null ? void 0 : _c2.value) != null ? _d2 : ""
543
- })
544
- });
545
- await context.update({
546
- url: new URL(request.nextUrl.href),
547
- cookies: Object.fromEntries(request.cookies.getAll().map((cookie) => [cookie.name, cookie.value])),
548
- quirks
549
- });
550
- return context;
551
- };
552
- return {
553
- type: "rewrite",
554
- destination,
555
- pageState,
556
- code,
557
- headers,
558
- draftModeEnabled,
559
- createContext
560
- };
561
- };
562
- var buildRoutePath = ({
563
- path,
564
- queryStrings
565
- }) => {
566
- const [pathname = "", search] = path.split("?");
567
- if (!search || !queryStrings) {
568
- return pathname;
569
- }
570
- const patterns = Object.keys(queryStrings);
571
- const match = findRouteMatch(
572
- patterns.map((pattern) => ({ id: pattern, pattern })),
573
- pathname
574
- );
575
- const allowed = match ? queryStrings[match.route.id] : void 0;
576
- if (!(allowed == null ? void 0 : allowed.length)) {
577
- return pathname;
578
- }
579
- const requestSearchParams = new URLSearchParams(search);
580
- const searchParams = new URLSearchParams();
581
- [...allowed].sort().forEach((name) => {
582
- const value = requestSearchParams.get(name);
583
- if (value !== null) {
584
- searchParams.set(name, value);
585
- }
586
- });
587
- return searchParams.size ? `${pathname}?${searchParams.toString()}` : pathname;
588
- };
589
- var determineCompositionState = ({
590
- searchParams,
591
- draftModeEnabled
592
- }) => {
593
- if (!draftModeEnabled) {
594
- return CANVAS_PUBLISHED_STATE;
595
- }
596
- return isIncontextEditingEnabled({ isDraftModeEnabled: draftModeEnabled, searchParams }) ? CANVAS_EDITOR_STATE : CANVAS_DRAFT_STATE;
597
- };
598
- var determineDefaultConsent = ({
599
- serverConfig,
600
- defaultConsent
601
- }) => {
602
- return defaultConsent !== serverConfig.defaultConsent ? defaultConsent : void 0;
603
- };
604
- var determinePreviewMode = ({
605
- searchParams,
606
- isDraftModeEnabled
607
- }) => {
608
- if (!isDraftModeEnabled) {
609
- return void 0;
610
- }
611
- const queryStringSettings = searchParams.get(IN_CONTEXT_EDITOR_FORCED_SETTINGS_QUERY_STRING_PARAM);
612
- let previewSettings = void 0;
613
- if (queryStringSettings) {
614
- try {
615
- previewSettings = JSON.parse(queryStringSettings);
616
- } catch (e) {
617
- }
618
- }
619
- if (previewSettings == null ? void 0 : previewSettings.isVisualEditingDisabled) {
620
- return "preview";
621
- }
622
- const isInContextEditingEnabled = isIncontextEditingEnabled({ isDraftModeEnabled, searchParams });
623
- if (isInContextEditingEnabled) {
624
- return "editor";
625
- }
626
- return void 0;
627
- };
628
-
629
- // src/edge/uniformEdgeMiddleware.ts
630
- var UNIFORM_EDGE_ORIGIN_HEADER = "x-uniform-edge-origin";
631
- var uniformEdgeMiddleware = (options) => {
632
- return async (request) => {
633
- return handleUniformEdgeRoute({ request, ...options });
634
- };
635
- };
636
- var handleUniformEdgeRoute = async ({
637
- request,
638
- manifest,
639
- onError,
640
- ...options
641
- }) => {
642
- var _a;
643
- if (request.headers.has(UNIFORM_EDGE_ORIGIN_HEADER)) {
644
- return NextResponse2.next();
645
- }
646
- const result = await resolveUniformRequest({ request, ...options });
647
- if (result.type === "response") {
648
- return result.response;
649
- }
650
- const destination = new URL(result.destination, request.nextUrl.origin);
651
- if (result.draftModeEnabled || !isDocumentRequest(request)) {
652
- return NextResponse2.rewrite(destination, { headers: result.headers });
653
- }
654
- const [originResponse, context] = await Promise.all([
655
- fetch(destination, {
656
- headers: {
657
- cookie: (_a = request.headers.get("cookie")) != null ? _a : "",
658
- accept: "text/html",
659
- // Node's fetch decompresses the body but keeps the header, so ask for plain HTML.
660
- "accept-encoding": "identity",
661
- [UNIFORM_EDGE_ORIGIN_HEADER]: "1"
662
- }
663
- }),
664
- result.createContext({ manifest })
665
- ]);
666
- const headers = new Headers(originResponse.headers);
667
- headers.delete("content-length");
668
- headers.delete("content-encoding");
669
- headers.set("cache-control", "private, no-store");
670
- result.headers.forEach((value, key) => {
671
- headers.append(key, value);
672
- });
673
- return new Response(transformBody({ body: originResponse.body, context, onError }), {
674
- status: originResponse.status,
675
- statusText: originResponse.statusText,
676
- headers
677
- });
678
- };
679
- var isDocumentRequest = (request) => {
680
- var _a;
681
- return request.method === "GET" && !request.headers.has("rsc") && !request.headers.has("next-router-prefetch") && ((_a = request.headers.get("accept")) != null ? _a : "").includes("text/html");
682
- };
683
- var transformBody = ({
684
- body,
685
- context,
686
- onError
687
- }) => {
688
- if (!body) {
689
- return null;
690
- }
691
- const reader = body.getReader();
692
- const { readable, writable } = new TransformStream();
693
- const writer = writable.getWriter();
694
- void transformEdgeStream({
695
- context,
696
- decoder: new TextDecoder(),
697
- encoder: new TextEncoder(),
698
- reader: {
699
- read: async () => {
700
- const { done, value } = await reader.read();
701
- return { done, value };
702
- }
703
- },
704
- writer: {
705
- write: (value) => {
706
- void writer.write(value);
707
- },
708
- close: () => {
709
- return writer.close();
710
- }
711
- },
712
- onError
713
- });
714
- return readable;
715
- };
716
- export {
717
- UNIFORM_EDGE_ORIGIN_HEADER,
718
- handleUniformEdgeRoute,
719
- uniformEdgeMiddleware
720
- };