@edgeone/opennextjs-pages 0.0.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.
Files changed (35) hide show
  1. package/dist/build/advanced-api-routes.js +147 -0
  2. package/dist/build/cache.js +36 -0
  3. package/dist/build/content/next-shims/telemetry-storage.cjs +55 -0
  4. package/dist/build/content/prerendered.js +292 -0
  5. package/dist/build/content/server.js +236 -0
  6. package/dist/build/content/static.js +119 -0
  7. package/dist/build/functions/server.js +133 -0
  8. package/dist/build/plugin-context.js +367 -0
  9. package/dist/build/routes.js +127 -0
  10. package/dist/build/templates/handler-monorepo.tmpl.js +210 -0
  11. package/dist/build/templates/handler.tmpl.js +206 -0
  12. package/dist/esm-chunks/chunk-5J3FID2N.js +5551 -0
  13. package/dist/esm-chunks/chunk-6BT4RYQJ.js +43 -0
  14. package/dist/esm-chunks/chunk-FKDTZJRV.js +832 -0
  15. package/dist/esm-chunks/chunk-TLQCAGE2.js +1921 -0
  16. package/dist/index.js +50 -0
  17. package/dist/run/config.js +37 -0
  18. package/dist/run/constants.js +19 -0
  19. package/dist/run/handlers/cache.cjs +369 -0
  20. package/dist/run/handlers/request-context.cjs +148 -0
  21. package/dist/run/handlers/server.js +3213 -0
  22. package/dist/run/handlers/tags-handler.cjs +92 -0
  23. package/dist/run/handlers/tracer.cjs +916 -0
  24. package/dist/run/handlers/use-cache-handler.js +1538 -0
  25. package/dist/run/handlers/wait-until.cjs +39 -0
  26. package/dist/run/headers.js +81 -0
  27. package/dist/run/next.cjs +100 -0
  28. package/dist/run/revalidate.js +34 -0
  29. package/dist/run/storage/regional-blob-store.cjs +64 -0
  30. package/dist/run/storage/request-scoped-in-memory-cache.cjs +1496 -0
  31. package/dist/run/storage/storage.cjs +37 -0
  32. package/dist/shared/blob-types.cjs +37 -0
  33. package/dist/shared/blobkey.js +25 -0
  34. package/dist/shared/cache-types.cjs +33 -0
  35. package/package.json +55 -0
package/dist/index.js ADDED
@@ -0,0 +1,50 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import "./esm-chunks/chunk-6BT4RYQJ.js";
8
+
9
+ // src/index.ts
10
+ import { rm } from "node:fs/promises";
11
+ import { existsSync } from "node:fs";
12
+ import { copyPrerenderedContent } from "./build/content/prerendered.js";
13
+ import {
14
+ copyStaticAssets,
15
+ copyStaticContent,
16
+ copyStaticExport
17
+ } from "./build/content/static.js";
18
+ import { createServerHandler } from "./build/functions/server.js";
19
+ import { PluginContext } from "./build/plugin-context.js";
20
+ import { createRouteMeta } from "./build/routes.js";
21
+ var onPreBuild = async (options) => {
22
+ process.env.NEXT_PRIVATE_STANDALONE = "true";
23
+ };
24
+ var onBuild = async (options) => {
25
+ const ctx = new PluginContext(options);
26
+ await rm(ctx.staticDir, { recursive: true, force: true });
27
+ if (existsSync(ctx.serverHandlerDir)) {
28
+ await rm(ctx.serverHandlerDir, { recursive: true, force: true });
29
+ }
30
+ if (ctx.buildConfig.output === "export") {
31
+ return Promise.all([copyStaticExport(ctx)]);
32
+ }
33
+ await copyStaticAssets(ctx);
34
+ await Promise.all([
35
+ // copyStaticAssets(ctx),
36
+ copyStaticContent(ctx),
37
+ copyPrerenderedContent(ctx),
38
+ createServerHandler(ctx)
39
+ ]);
40
+ createRouteMeta(ctx);
41
+ };
42
+ var onPostBuild = async (options) => {
43
+ console.log("onPostBuild");
44
+ const ctx = new PluginContext(options);
45
+ };
46
+ export {
47
+ onBuild,
48
+ onPostBuild,
49
+ onPreBuild
50
+ };
@@ -0,0 +1,37 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import "../esm-chunks/chunk-6BT4RYQJ.js";
8
+
9
+ // src/run/config.ts
10
+ import { existsSync } from "node:fs";
11
+ import { readFile } from "node:fs/promises";
12
+ import { join, resolve } from "node:path";
13
+ import { PLUGIN_DIR, RUN_CONFIG_FILE } from "./constants.js";
14
+ import { setInMemoryCacheMaxSizeFromNextConfig } from "./storage/storage.cjs";
15
+ var getRunConfig = async () => {
16
+ return JSON.parse(await readFile(resolve(PLUGIN_DIR, RUN_CONFIG_FILE), "utf-8"));
17
+ };
18
+ var setRunConfig = (config) => {
19
+ const cacheHandler = join(PLUGIN_DIR, ".edgeone/dist/run/handlers/cache.cjs");
20
+ if (!existsSync(cacheHandler)) {
21
+ throw new Error(`Cache handler not found at ${cacheHandler}`);
22
+ }
23
+ config.experimental = {
24
+ ...config.experimental,
25
+ // Before Next.js 14.1.0 path to the cache handler was in experimental section, see NextConfigForMultipleVersions type
26
+ incrementalCacheHandlerPath: cacheHandler
27
+ };
28
+ config.cacheHandler = cacheHandler;
29
+ setInMemoryCacheMaxSizeFromNextConfig(
30
+ config.cacheMaxMemorySize ?? config.experimental?.isrMemoryCacheSize
31
+ );
32
+ process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(config);
33
+ };
34
+ export {
35
+ getRunConfig,
36
+ setRunConfig
37
+ };
@@ -0,0 +1,19 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import "../esm-chunks/chunk-6BT4RYQJ.js";
8
+
9
+ // src/run/constants.ts
10
+ import { resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
13
+ var PLUGIN_DIR = resolve(`${MODULE_DIR}../../..`);
14
+ var RUN_CONFIG_FILE = "run-config.json";
15
+ export {
16
+ MODULE_DIR,
17
+ PLUGIN_DIR,
18
+ RUN_CONFIG_FILE
19
+ };
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/run/handlers/cache.cts
31
+ var cache_exports = {};
32
+ __export(cache_exports, {
33
+ EdgeoneCacheHandler: () => EdgeoneCacheHandler,
34
+ default: () => cache_default
35
+ });
36
+ module.exports = __toCommonJS(cache_exports);
37
+ var import_node_buffer = require("node:buffer");
38
+ var import_node_path = require("node:path");
39
+ var import_posix = require("node:path/posix");
40
+ var import_constants = require("next/dist/lib/constants.js");
41
+ var import_cache_types = require("../../shared/cache-types.cjs");
42
+ var import_request_context = require("./request-context.cjs");
43
+ var import_tags_handler = require("./tags-handler.cjs");
44
+ var import_tracer = require("./tracer.cjs");
45
+ var memoizedPrerenderManifest;
46
+ var EdgeoneCacheHandler = class {
47
+ options;
48
+ revalidatedTags;
49
+ cacheStore;
50
+ tracer = (0, import_tracer.getTracer)();
51
+ constructor(options) {
52
+ this.options = options;
53
+ this.revalidatedTags = options.revalidatedTags;
54
+ this.cacheStore = {};
55
+ }
56
+ getTTL(blob) {
57
+ if (blob.value?.kind === "FETCH" || blob.value?.kind === "ROUTE" || blob.value?.kind === "APP_ROUTE" || blob.value?.kind === "PAGE" || blob.value?.kind === "PAGES" || blob.value?.kind === "APP_PAGE") {
58
+ const { revalidate } = blob.value;
59
+ if (typeof revalidate === "number") {
60
+ const revalidateAfter = revalidate * 1e3 + blob.lastModified;
61
+ return (revalidateAfter - Date.now()) / 1e3;
62
+ }
63
+ if (revalidate === false) {
64
+ return "PERMANENT";
65
+ }
66
+ }
67
+ return "NOT SET";
68
+ }
69
+ captureResponseCacheLastModified(cacheValue, key, getCacheKeySpan) {
70
+ if (cacheValue.value?.kind === "FETCH") {
71
+ return;
72
+ }
73
+ const requestContext = (0, import_request_context.getRequestContext)();
74
+ if (!requestContext) {
75
+ (0, import_tracer.recordWarning)(new Error("CacheHandler was called without a request context"), getCacheKeySpan);
76
+ return;
77
+ }
78
+ if (requestContext.responseCacheKey && requestContext.responseCacheKey !== key) {
79
+ requestContext.responseCacheGetLastModified = void 0;
80
+ (0, import_tracer.recordWarning)(
81
+ new Error(
82
+ `Multiple response cache keys used in single request: ["${requestContext.responseCacheKey}, "${key}"]`
83
+ ),
84
+ getCacheKeySpan
85
+ );
86
+ return;
87
+ }
88
+ requestContext.responseCacheKey = key;
89
+ if (cacheValue.lastModified) {
90
+ requestContext.responseCacheGetLastModified = cacheValue.lastModified;
91
+ }
92
+ }
93
+ captureRouteRevalidateAndRemoveFromObject(cacheValue) {
94
+ const { revalidate, ...restOfRouteValue } = cacheValue;
95
+ const requestContext = (0, import_request_context.getRequestContext)();
96
+ if (requestContext) {
97
+ requestContext.routeHandlerRevalidate = revalidate;
98
+ }
99
+ return restOfRouteValue;
100
+ }
101
+ captureCacheTags(cacheValue, key) {
102
+ const requestContext = (0, import_request_context.getRequestContext)();
103
+ if (!requestContext) {
104
+ return;
105
+ }
106
+ if (requestContext.responseCacheTags) {
107
+ return;
108
+ }
109
+ if (!cacheValue) {
110
+ const cacheTags = [`_N_T_${key === "/index" ? "/" : encodeURI(key)}`];
111
+ requestContext.responseCacheTags = cacheTags;
112
+ return;
113
+ }
114
+ if (cacheValue.kind === "PAGE" || cacheValue.kind === "PAGES" || cacheValue.kind === "APP_PAGE" || cacheValue.kind === "ROUTE" || cacheValue.kind === "APP_ROUTE") {
115
+ if (cacheValue.headers?.[import_constants.NEXT_CACHE_TAGS_HEADER]) {
116
+ const cacheTags = cacheValue.headers[import_constants.NEXT_CACHE_TAGS_HEADER].split(/,|%2c/gi);
117
+ requestContext.responseCacheTags = cacheTags;
118
+ } else if ((cacheValue.kind === "PAGE" || cacheValue.kind === "PAGES") && typeof cacheValue.pageData === "object") {
119
+ const cacheTags = [`_N_T_${key === "/index" ? "/" : encodeURI(key)}`];
120
+ requestContext.responseCacheTags = cacheTags;
121
+ }
122
+ }
123
+ }
124
+ async getPrerenderManifest(serverDistDir) {
125
+ if (memoizedPrerenderManifest) {
126
+ return memoizedPrerenderManifest;
127
+ }
128
+ const prerenderManifestPath = (0, import_node_path.join)(serverDistDir, "..", "prerender-manifest.json");
129
+ try {
130
+ const { loadManifest } = await import("next/dist/server/load-manifest.external.js");
131
+ memoizedPrerenderManifest = loadManifest(prerenderManifestPath);
132
+ } catch {
133
+ const { loadManifest } = await import("next/dist/server/load-manifest.js");
134
+ memoizedPrerenderManifest = loadManifest(prerenderManifestPath);
135
+ }
136
+ return memoizedPrerenderManifest;
137
+ }
138
+ async injectEntryToPrerenderManifest(key, { revalidate, cacheControl }) {
139
+ if (this.options.serverDistDir && (typeof revalidate === "number" || revalidate === false || typeof cacheControl !== "undefined")) {
140
+ try {
141
+ const prerenderManifest = await this.getPrerenderManifest(this.options.serverDistDir);
142
+ if (typeof cacheControl !== "undefined") {
143
+ try {
144
+ const { SharedCacheControls } = await import(
145
+ // @ts-expect-error supporting multiple next version, this module is not resolvable with currently used dev dependency
146
+ // eslint-disable-next-line import/no-unresolved, n/no-missing-import
147
+ "next/dist/server/lib/incremental-cache/shared-cache-controls.external.js"
148
+ );
149
+ const sharedCacheControls = new SharedCacheControls(prerenderManifest);
150
+ sharedCacheControls.set(key, cacheControl);
151
+ } catch {
152
+ const { SharedCacheControls } = await import(
153
+ // @ts-expect-error supporting multiple next version, this module is not resolvable with currently used dev dependency
154
+ // eslint-disable-next-line import/no-unresolved, n/no-missing-import
155
+ "next/dist/server/lib/incremental-cache/shared-cache-controls.js"
156
+ );
157
+ const sharedCacheControls = new SharedCacheControls(prerenderManifest);
158
+ sharedCacheControls.set(key, cacheControl);
159
+ }
160
+ } else if (typeof revalidate === "number" || revalidate === false) {
161
+ try {
162
+ const { normalizePagePath } = await import("next/dist/shared/lib/page-path/normalize-page-path.js");
163
+ prerenderManifest.routes[key] = {
164
+ experimentalPPR: void 0,
165
+ dataRoute: (0, import_posix.join)("/_next/data", `${normalizePagePath(key)}.json`),
166
+ srcRoute: null,
167
+ // FIXME: provide actual source route, however, when dynamically appending it doesn't really matter
168
+ initialRevalidateSeconds: revalidate,
169
+ // Pages routes do not have a prefetch data route.
170
+ prefetchDataRoute: void 0
171
+ };
172
+ } catch {
173
+ const { SharedRevalidateTimings } = await import("next/dist/server/lib/incremental-cache/shared-revalidate-timings.js");
174
+ const sharedRevalidateTimings = new SharedRevalidateTimings(prerenderManifest);
175
+ sharedRevalidateTimings.set(key, revalidate);
176
+ }
177
+ }
178
+ } catch {
179
+ }
180
+ }
181
+ }
182
+ async get(...args) {
183
+ return this.tracer.withActiveSpan("get cache key", async (span) => {
184
+ const [key, context = {}] = args;
185
+ (0, import_request_context.getLogger)();
186
+ span.setAttributes({ key });
187
+ const blob = null;
188
+ if (!blob) {
189
+ span.addEvent("Cache miss", { key });
190
+ return null;
191
+ }
192
+ const ttl = this.getTTL(blob);
193
+ if ((0, import_request_context.getRequestContext)()?.isBackgroundRevalidation && typeof ttl === "number" && ttl < 0) {
194
+ span.addEvent("Discarding stale entry due to SWR background revalidation request", {
195
+ key,
196
+ ttl
197
+ });
198
+ (0, import_request_context.getLogger)().withFields({
199
+ ttl,
200
+ key
201
+ });
202
+ return null;
203
+ }
204
+ const staleByTags = await this.checkCacheEntryStaleByTags(
205
+ blob,
206
+ context.tags,
207
+ context.softTags
208
+ );
209
+ if (staleByTags) {
210
+ span.addEvent("Stale", { staleByTags, key, ttl });
211
+ return null;
212
+ }
213
+ this.captureResponseCacheLastModified(blob, key, span);
214
+ const isDataRequest = Boolean(context.fetchUrl);
215
+ if (!isDataRequest) {
216
+ this.captureCacheTags(blob.value, key);
217
+ }
218
+ switch (blob.value?.kind) {
219
+ case "FETCH":
220
+ span.addEvent("FETCH", {
221
+ lastModified: blob.lastModified,
222
+ revalidate: context.revalidate,
223
+ ttl
224
+ });
225
+ return {
226
+ lastModified: blob.lastModified,
227
+ value: blob.value
228
+ };
229
+ case "ROUTE":
230
+ case "APP_ROUTE": {
231
+ span.addEvent(blob.value?.kind, {
232
+ lastModified: blob.lastModified,
233
+ status: blob.value.status,
234
+ revalidate: blob.value.revalidate,
235
+ ttl
236
+ });
237
+ const valueWithoutRevalidate = this.captureRouteRevalidateAndRemoveFromObject(blob.value);
238
+ return {
239
+ lastModified: blob.lastModified,
240
+ value: {
241
+ ...valueWithoutRevalidate,
242
+ body: import_node_buffer.Buffer.from(valueWithoutRevalidate.body, "base64")
243
+ }
244
+ };
245
+ }
246
+ case "PAGE":
247
+ case "PAGES": {
248
+ const { revalidate, ...restOfPageValue } = blob.value;
249
+ const requestContext = (0, import_request_context.getRequestContext)();
250
+ if (requestContext) {
251
+ requestContext.pageHandlerRevalidate = revalidate;
252
+ }
253
+ span.addEvent(blob.value?.kind, { lastModified: blob.lastModified, revalidate, ttl });
254
+ await this.injectEntryToPrerenderManifest(key, blob.value);
255
+ return {
256
+ lastModified: blob.lastModified,
257
+ value: restOfPageValue
258
+ };
259
+ }
260
+ case "APP_PAGE": {
261
+ const requestContext = (0, import_request_context.getRequestContext)();
262
+ if (requestContext && blob.value?.kind === "APP_PAGE") {
263
+ requestContext.isCacheableAppPage = true;
264
+ }
265
+ const { revalidate, rscData, ...restOfPageValue } = blob.value;
266
+ span.addEvent(blob.value?.kind, { lastModified: blob.lastModified, revalidate, ttl });
267
+ await this.injectEntryToPrerenderManifest(key, blob.value);
268
+ return {
269
+ lastModified: blob.lastModified,
270
+ value: {
271
+ ...restOfPageValue,
272
+ rscData: rscData ? import_node_buffer.Buffer.from(rscData, "base64") : void 0
273
+ }
274
+ };
275
+ }
276
+ default:
277
+ span.recordException(new Error(`Unknown cache entry kind: ${blob.value?.kind}`));
278
+ }
279
+ return null;
280
+ });
281
+ }
282
+ transformToStorableObject(data, context) {
283
+ if (!data) {
284
+ return null;
285
+ }
286
+ if ((0, import_cache_types.isCachedRouteValue)(data)) {
287
+ return {
288
+ ...data,
289
+ revalidate: context.revalidate ?? context.cacheControl?.revalidate,
290
+ cacheControl: context.cacheControl,
291
+ body: data.body.toString("base64")
292
+ };
293
+ }
294
+ if ((0, import_cache_types.isCachedPageValue)(data)) {
295
+ return {
296
+ ...data,
297
+ revalidate: context.revalidate ?? context.cacheControl?.revalidate,
298
+ cacheControl: context.cacheControl
299
+ };
300
+ }
301
+ if (data?.kind === "APP_PAGE") {
302
+ return {
303
+ ...data,
304
+ revalidate: context.revalidate ?? context.cacheControl?.revalidate,
305
+ cacheControl: context.cacheControl,
306
+ rscData: data.rscData?.toString("base64")
307
+ };
308
+ }
309
+ return data;
310
+ }
311
+ async set(...args) {
312
+ return {};
313
+ return this.tracer.withActiveSpan("set cache key", async (span) => {
314
+ const [key, data, context] = args;
315
+ const lastModified = Date.now();
316
+ span.setAttributes({ key, lastModified });
317
+ (0, import_request_context.getLogger)().debug(`[EdgeoneCacheHandler.set]: ${key}`);
318
+ const value = this.transformToStorableObject(data, context);
319
+ const isDataReq = Boolean(context.fetchUrl);
320
+ if (!isDataReq) {
321
+ this.captureCacheTags(value, key);
322
+ }
323
+ await this.cacheStore.set(key, { lastModified, value }, "blobStore.set");
324
+ if (data?.kind === "APP_PAGE") {
325
+ const requestContext = (0, import_request_context.getRequestContext)();
326
+ if (requestContext) {
327
+ requestContext.isCacheableAppPage = true;
328
+ }
329
+ }
330
+ if (!data && !isDataReq || data?.kind === "PAGE" || data?.kind === "PAGES") {
331
+ const requestContext = (0, import_request_context.getRequestContext)();
332
+ if (requestContext?.didPagesRouterOnDemandRevalidate) {
333
+ const tag = `_N_T_${key === "/index" ? "/" : encodeURI(key)}`;
334
+ requestContext?.trackBackgroundWork((0, import_tags_handler.purgeEdgeCache)(tag));
335
+ }
336
+ }
337
+ });
338
+ }
339
+ async revalidateTag(tagOrTags) {
340
+ return (0, import_tags_handler.markTagsAsStaleAndPurgeEdgeCache)(tagOrTags);
341
+ }
342
+ resetRequestCache() {
343
+ }
344
+ /**
345
+ * Checks if a cache entry is stale through on demand revalidated tags
346
+ */
347
+ checkCacheEntryStaleByTags(cacheEntry, tags = [], softTags = []) {
348
+ let cacheTags = [];
349
+ if (cacheEntry.value?.kind === "FETCH") {
350
+ cacheTags = [...tags, ...softTags];
351
+ } else if (cacheEntry.value?.kind === "PAGE" || cacheEntry.value?.kind === "PAGES" || cacheEntry.value?.kind === "APP_PAGE" || cacheEntry.value?.kind === "ROUTE" || cacheEntry.value?.kind === "APP_ROUTE") {
352
+ cacheTags = cacheEntry.value.headers?.[import_constants.NEXT_CACHE_TAGS_HEADER]?.split(/,|%2c/gi) || [];
353
+ } else {
354
+ return false;
355
+ }
356
+ if (this.revalidatedTags && this.revalidatedTags.length !== 0) {
357
+ for (const tag of this.revalidatedTags) {
358
+ if (cacheTags.includes(tag)) {
359
+ return true;
360
+ }
361
+ }
362
+ }
363
+ }
364
+ };
365
+ var cache_default = EdgeoneCacheHandler;
366
+ // Annotate the CommonJS export names for ESM import in node:
367
+ 0 && (module.exports = {
368
+ EdgeoneCacheHandler
369
+ });
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/run/handlers/request-context.cts
21
+ var request_context_exports = {};
22
+ __export(request_context_exports, {
23
+ createRequestContext: () => createRequestContext,
24
+ getLogger: () => getLogger,
25
+ getRequestContext: () => getRequestContext,
26
+ runWithRequestContext: () => runWithRequestContext
27
+ });
28
+ module.exports = __toCommonJS(request_context_exports);
29
+ var import_node_async_hooks = require("node:async_hooks");
30
+
31
+ // node_modules/@netlify/functions/dist/internal.js
32
+ var import_process = require("process");
33
+ var systemLogTag = "__nfSystemLog";
34
+ var serializeError = (error) => {
35
+ const cause = error?.cause instanceof Error ? serializeError(error.cause) : error.cause;
36
+ return {
37
+ error: error.message,
38
+ error_cause: cause,
39
+ error_stack: error.stack
40
+ };
41
+ };
42
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
43
+ LogLevel2[LogLevel2["Debug"] = 1] = "Debug";
44
+ LogLevel2[LogLevel2["Log"] = 2] = "Log";
45
+ LogLevel2[LogLevel2["Error"] = 3] = "Error";
46
+ return LogLevel2;
47
+ })(LogLevel || {});
48
+ var SystemLogger = class _SystemLogger {
49
+ fields;
50
+ logLevel;
51
+ constructor(fields = {}, logLevel = 2) {
52
+ this.fields = fields;
53
+ this.logLevel = logLevel;
54
+ }
55
+ doLog(logger, message) {
56
+ if (import_process.env.NETLIFY_DEV && !import_process.env.NETLIFY_ENABLE_SYSTEM_LOGGING) {
57
+ return;
58
+ }
59
+ logger(systemLogTag, JSON.stringify({ msg: message, fields: this.fields }));
60
+ }
61
+ log(message) {
62
+ if (this.logLevel > 2) {
63
+ return;
64
+ }
65
+ this.doLog(console.log, message);
66
+ }
67
+ debug(message) {
68
+ if (this.logLevel > 1) {
69
+ return;
70
+ }
71
+ this.doLog(console.debug, message);
72
+ }
73
+ error(message) {
74
+ if (this.logLevel > 3) {
75
+ return;
76
+ }
77
+ this.doLog(console.error, message);
78
+ }
79
+ withLogLevel(level) {
80
+ return new _SystemLogger(this.fields, level);
81
+ }
82
+ withFields(fields) {
83
+ return new _SystemLogger(
84
+ {
85
+ ...this.fields,
86
+ ...fields
87
+ },
88
+ this.logLevel
89
+ );
90
+ }
91
+ withError(error) {
92
+ const fields = error instanceof Error ? serializeError(error) : { error };
93
+ return this.withFields(fields);
94
+ }
95
+ };
96
+ var systemLogger = new SystemLogger();
97
+
98
+ // src/run/handlers/request-context.cts
99
+ var REQUEST_CONTEXT_GLOBAL_KEY = Symbol.for("nf-request-context-async-local-storage");
100
+ var REQUEST_COUNTER_KEY = Symbol.for("nf-request-counter");
101
+ var extendedGlobalThis = globalThis;
102
+ function createRequestContext(request, context) {
103
+ const backgroundWorkPromises = [];
104
+ const logger = systemLogger.withLogLevel(LogLevel.Log);
105
+ return {
106
+ isBackgroundRevalidation: false,
107
+ captureServerTiming: false,
108
+ trackBackgroundWork: (promise) => {
109
+ if (context?.waitUntil) {
110
+ context.waitUntil(promise);
111
+ } else {
112
+ backgroundWorkPromises.push(promise);
113
+ }
114
+ },
115
+ get backgroundWorkPromise() {
116
+ return Promise.allSettled(backgroundWorkPromises);
117
+ },
118
+ logger,
119
+ requestID: ""
120
+ };
121
+ }
122
+ var requestContextAsyncLocalStorage;
123
+ function getRequestContextAsyncLocalStorage() {
124
+ if (requestContextAsyncLocalStorage) {
125
+ return requestContextAsyncLocalStorage;
126
+ }
127
+ if (extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY]) {
128
+ return extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY];
129
+ }
130
+ const storage = new import_node_async_hooks.AsyncLocalStorage();
131
+ requestContextAsyncLocalStorage = storage;
132
+ extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY] = storage;
133
+ return storage;
134
+ }
135
+ var getRequestContext = () => getRequestContextAsyncLocalStorage().getStore();
136
+ function runWithRequestContext(requestContext, fn) {
137
+ return getRequestContextAsyncLocalStorage().run(requestContext, fn);
138
+ }
139
+ function getLogger() {
140
+ return getRequestContext()?.logger ?? systemLogger;
141
+ }
142
+ // Annotate the CommonJS export names for ESM import in node:
143
+ 0 && (module.exports = {
144
+ createRequestContext,
145
+ getLogger,
146
+ getRequestContext,
147
+ runWithRequestContext
148
+ });