create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,279 @@
import { AsyncLocalStorage } from "async_hooks";
import { decorateServerError, getServerError } from "next/dist/compiled/@next/react-dev-overlay/dist/middleware";
import { COMPILER_NAMES, EDGE_UNSUPPORTED_NODE_APIS } from "../../../shared/lib/constants";
import { EdgeRuntime } from "next/dist/compiled/edge-runtime";
import { readFileSync, promises as fs } from "fs";
import { validateURL } from "../utils";
import { pick } from "../../../lib/pick";
import { fetchInlineAsset } from "./fetch-inline-assets";
const WEBPACK_HASH_REGEX = /__webpack_require__\.h = function\(\) \{ return "[0-9a-f]+"; \}/g;
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/ const moduleContexts = new Map();
/**
* For a given path a context, this function checks if there is any module
* context that contains the path with an older content and, if that's the
* case, removes the context from the cache.
*/ export function clearModuleContext(path, content) {
for (const [key, cache] of moduleContexts){
var ref;
const prev = (ref = cache == null ? void 0 : cache.paths.get(path)) == null ? void 0 : ref.replace(WEBPACK_HASH_REGEX, "");
if (typeof prev !== "undefined" && prev !== content.toString().replace(WEBPACK_HASH_REGEX, "")) {
moduleContexts.delete(key);
}
}
}
async function loadWasm(wasm) {
const modules = {};
await Promise.all(wasm.map(async (binding)=>{
const module = await WebAssembly.compile(await fs.readFile(binding.filePath));
modules[binding.name] = module;
}));
return modules;
}
function buildEnvironmentVariablesFrom(keys) {
const pairs = keys.map((key)=>[
key,
process.env[key]
]);
const env = Object.fromEntries(pairs);
env.NEXT_RUNTIME = "edge";
return env;
}
function throwUnsupportedAPIError(name) {
const error = new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`);
decorateServerError(error, COMPILER_NAMES.edgeServer);
throw error;
}
function createProcessPolyfill(options) {
const env = buildEnvironmentVariablesFrom(options.env);
const processPolyfill = {
env
};
const overridenValue = {};
for (const key of Object.keys(process)){
if (key === "env") continue;
Object.defineProperty(processPolyfill, key, {
get () {
if (overridenValue[key]) {
return overridenValue[key];
}
if (typeof process[key] === "function") {
return ()=>throwUnsupportedAPIError(`process.${key}`);
}
return undefined;
},
set (value) {
overridenValue[key] = value;
},
enumerable: false
});
}
return processPolyfill;
}
function addStub(context, name) {
Object.defineProperty(context, name, {
get () {
return function() {
throwUnsupportedAPIError(name);
};
},
enumerable: false
});
}
function getDecorateUnhandledError(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (error)=>{
if (error instanceof EdgeRuntimeError) {
decorateServerError(error, COMPILER_NAMES.edgeServer);
}
};
}
function getDecorateUnhandledRejection(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (rejected)=>{
if (rejected.reason instanceof EdgeRuntimeError) {
decorateServerError(rejected.reason, COMPILER_NAMES.edgeServer);
}
};
}
/**
* Create a module cache specific for the provided parameters. It includes
* a runtime context, require cache and paths cache.
*/ async function createModuleContext(options) {
const warnedEvals = new Set();
const warnedWasmCodegens = new Set();
const wasm = await loadWasm(options.edgeFunctionEntry.wasm ?? []);
const runtime = new EdgeRuntime({
codeGeneration: process.env.NODE_ENV !== "production" ? {
strings: true,
wasm: true
} : undefined,
extend: (context)=>{
context.process = createProcessPolyfill(options);
context.__next_eval__ = function __next_eval__(fn) {
const key = fn.toString();
if (!warnedEvals.has(key)) {
const warning = getServerError(new Error(`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer);
warning.name = "DynamicCodeEvaluationWarning";
Error.captureStackTrace(warning, __next_eval__);
warnedEvals.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn) {
const key = fn.toString();
if (!warnedWasmCodegens.has(key)) {
const warning = getServerError(new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer);
warning.name = "DynamicWasmCodeGenerationWarning";
Error.captureStackTrace(warning, __next_webassembly_compile__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn) {
const result = await fn();
// If a buffer is given, WebAssembly.instantiate returns an object
// containing both a module and an instance while it returns only an
// instance if a WASM module is given. Utilize the fact to determine
// if the WASM code generation happens.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code
const instantiatedFromBuffer = result.hasOwnProperty("module");
const key = fn.toString();
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError(new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer);
warning.name = "DynamicWasmCodeGenerationWarning";
Error.captureStackTrace(warning, __next_webassembly_instantiate__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return result;
};
const __fetch = context.fetch;
context.fetch = async (input, init = {})=>{
var ref;
const assetResponse = await fetchInlineAsset({
input,
assets: options.edgeFunctionEntry.assets,
distDir: options.distDir,
context
});
if (assetResponse) {
return assetResponse;
}
init.headers = new Headers(init.headers ?? {});
const prevs = ((ref = init.headers.get(`x-middleware-subrequest`)) == null ? void 0 : ref.split(":")) || [];
const value = prevs.concat(options.moduleName).join(":");
init.headers.set("x-middleware-subrequest", value);
if (!init.headers.has("user-agent")) {
init.headers.set(`user-agent`, `Next.js Middleware`);
}
if (typeof input === "object" && "url" in input) {
return __fetch(input.url, {
...pick(input, [
"method",
"body",
"cache",
"credentials",
"integrity",
"keepalive",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
]),
...init,
headers: {
...Object.fromEntries(input.headers),
...Object.fromEntries(init.headers)
}
});
}
return __fetch(String(input), init);
};
const __Request = context.Request;
context.Request = class extends __Request {
constructor(input, init){
const url = typeof input !== "string" && "url" in input ? input.url : String(input);
validateURL(url);
super(url, init);
this.next = init == null ? void 0 : init.next;
}
};
const __redirect = context.Response.redirect.bind(context.Response);
context.Response.redirect = (...args)=>{
validateURL(args[0]);
return __redirect(...args);
};
for (const name of EDGE_UNSUPPORTED_NODE_APIS){
addStub(context, name);
}
Object.assign(context, wasm);
context.AsyncLocalStorage = AsyncLocalStorage;
return context;
}
});
const decorateUnhandledError = getDecorateUnhandledError(runtime);
runtime.context.addEventListener("error", decorateUnhandledError);
const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime);
runtime.context.addEventListener("unhandledrejection", decorateUnhandledRejection);
return {
runtime,
paths: new Map(),
warnedEvals: new Set()
};
}
const pendingModuleCaches = new Map();
function getModuleContextShared(options) {
let deferredModuleContext = pendingModuleCaches.get(options.moduleName);
if (!deferredModuleContext) {
deferredModuleContext = createModuleContext(options);
pendingModuleCaches.set(options.moduleName, deferredModuleContext);
}
return deferredModuleContext;
}
/**
* For a given module name this function will get a cached module
* context or create it. It will return the module context along
* with a function that allows to run some code from a given
* filepath within the context.
*/ export async function getModuleContext(options) {
let moduleContext;
if (options.useCache) {
moduleContext = moduleContexts.get(options.moduleName) || await getModuleContextShared(options);
}
if (!moduleContext) {
moduleContext = await createModuleContext(options);
moduleContexts.set(options.moduleName, moduleContext);
}
const evaluateInContext = (filepath)=>{
if (!moduleContext.paths.has(filepath)) {
const content = readFileSync(filepath, "utf-8");
try {
moduleContext == null ? void 0 : moduleContext.runtime.evaluate(content);
moduleContext.paths.set(filepath, content);
} catch (error) {
if (options.useCache) {
moduleContext == null ? void 0 : moduleContext.paths.delete(options.moduleName);
}
throw error;
}
}
};
return {
...moduleContext,
evaluateInContext
};
}
//# sourceMappingURL=context.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { createReadStream, promises as fs } from "fs";
import { requestToBodyStream } from "../../body-streams";
import { resolve } from "path";
/**
* Short-circuits the `fetch` function
* to return a stream for a given asset, if a user used `new URL("file", import.meta.url)`.
* This allows to embed assets in Edge Runtime.
*/ export async function fetchInlineAsset(options) {
var ref;
const inputString = String(options.input);
if (!inputString.startsWith("blob:")) {
return;
}
const hash = inputString.replace("blob:", "");
const asset = (ref = options.assets) == null ? void 0 : ref.find((x)=>x.name === hash);
if (!asset) {
return;
}
const filePath = resolve(options.distDir, asset.filePath);
const fileIsReadable = await fs.access(filePath).then(()=>true, ()=>false);
if (fileIsReadable) {
const readStream = createReadStream(filePath);
return new options.context.Response(requestToBodyStream(options.context, Uint8Array, readStream));
}
}
//# sourceMappingURL=fetch-inline-assets.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/web/sandbox/fetch-inline-assets.ts"],"names":["createReadStream","promises","fs","requestToBodyStream","resolve","fetchInlineAsset","options","inputString","String","input","startsWith","hash","replace","asset","assets","find","x","name","filePath","distDir","fileIsReadable","access","then","readStream","context","Response","Uint8Array"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACrD,SAASC,mBAAmB,QAAQ,oBAAoB,CAAA;AACxD,SAASC,OAAO,QAAQ,MAAM,CAAA;AAE9B;;;;GAIG,CACH,OAAO,eAAeC,gBAAgB,CAACC,OAKtC,EAAiC;QAOlBA,GAAc;IAN5B,MAAMC,WAAW,GAAGC,MAAM,CAACF,OAAO,CAACG,KAAK,CAAC;IACzC,IAAI,CAACF,WAAW,CAACG,UAAU,CAAC,OAAO,CAAC,EAAE;QACpC,OAAM;KACP;IAED,MAAMC,IAAI,GAAGJ,WAAW,CAACK,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;IAC7C,MAAMC,KAAK,GAAGP,CAAAA,GAAc,GAAdA,OAAO,CAACQ,MAAM,SAAM,GAApBR,KAAAA,CAAoB,GAApBA,GAAc,CAAES,IAAI,CAAC,CAACC,CAAC,GAAKA,CAAC,CAACC,IAAI,KAAKN,IAAI,CAAC;IAC1D,IAAI,CAACE,KAAK,EAAE;QACV,OAAM;KACP;IAED,MAAMK,QAAQ,GAAGd,OAAO,CAACE,OAAO,CAACa,OAAO,EAAEN,KAAK,CAACK,QAAQ,CAAC;IACzD,MAAME,cAAc,GAAG,MAAMlB,EAAE,CAACmB,MAAM,CAACH,QAAQ,CAAC,CAACI,IAAI,CACnD,IAAM,IAAI,EACV,IAAM,KAAK,CACZ;IAED,IAAIF,cAAc,EAAE;QAClB,MAAMG,UAAU,GAAGvB,gBAAgB,CAACkB,QAAQ,CAAC;QAC7C,OAAO,IAAIZ,OAAO,CAACkB,OAAO,CAACC,QAAQ,CACjCtB,mBAAmB,CAACG,OAAO,CAACkB,OAAO,EAAEE,UAAU,EAAEH,UAAU,CAAC,CAC7D,CAAA;KACF;CACF"}

View File

@@ -0,0 +1,4 @@
export * from "./sandbox";
export { clearModuleContext } from "./context";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/web/sandbox/index.ts"],"names":["clearModuleContext"],"mappings":"AAAA,cAAc,WAAW,CAAA;AACzB,SAASA,kBAAkB,QAAQ,WAAW,CAAA"}

View File

@@ -0,0 +1,82 @@
import { getServerError } from "next/dist/compiled/@next/react-dev-overlay/dist/middleware";
import { getModuleContext } from "./context";
import { requestToBodyStream } from "../../body-streams";
export const ErrorSource = Symbol("SandboxError");
const FORBIDDEN_HEADERS = [
"content-length",
"content-encoding",
"transfer-encoding",
];
/**
* Decorates the runner function making sure all errors it can produce are
* tagged with `edge-server` so they can properly be rendered in dev.
*/ function withTaggedErrors(fn) {
return (params)=>{
return fn(params).then((result)=>{
var ref;
return {
...result,
waitUntil: result == null ? void 0 : (ref = result.waitUntil) == null ? void 0 : ref.catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, "edge-server");
})
};
}).catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, "edge-server");
});
};
}
export const getRuntimeContext = async (params)=>{
const { runtime , evaluateInContext } = await getModuleContext({
moduleName: params.name,
onWarning: params.onWarning ?? (()=>{}),
useCache: params.useCache !== false,
env: params.env,
edgeFunctionEntry: params.edgeFunctionEntry,
distDir: params.distDir
});
for (const paramPath of params.paths){
evaluateInContext(paramPath);
}
return runtime;
};
export const run = withTaggedErrors(async (params)=>{
var ref;
const runtime = await getRuntimeContext(params);
const subreq = params.request.headers[`x-middleware-subrequest`];
const subrequests = typeof subreq === "string" ? subreq.split(":") : [];
if (subrequests.includes(params.name)) {
return {
waitUntil: Promise.resolve(),
response: new runtime.context.Response(null, {
headers: {
"x-middleware-next": "1"
}
})
};
}
const edgeFunction = runtime.context._ENTRIES[`middleware_${params.name}`].default;
const cloned = ![
"HEAD",
"GET"
].includes(params.request.method) ? (ref = params.request.body) == null ? void 0 : ref.cloneBodyStream() : undefined;
const KUint8Array = runtime.evaluate("Uint8Array");
try {
const result = await edgeFunction({
request: {
...params.request,
body: cloned && requestToBodyStream(runtime.context, KUint8Array, cloned)
}
});
for (const headerName of FORBIDDEN_HEADERS){
result.response.headers.delete(headerName);
}
return result;
} finally{
var ref1;
await ((ref1 = params.request.body) == null ? void 0 : ref1.finalize());
}
});
//# sourceMappingURL=sandbox.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../server/web/sandbox/sandbox.ts"],"names":["getServerError","getModuleContext","requestToBodyStream","ErrorSource","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","params","then","result","waitUntil","catch","error","getRuntimeContext","runtime","evaluateInContext","moduleName","name","onWarning","useCache","env","edgeFunctionEntry","distDir","paramPath","paths","run","subreq","request","headers","subrequests","split","includes","Promise","resolve","response","context","Response","edgeFunction","_ENTRIES","default","cloned","method","body","cloneBodyStream","undefined","KUint8Array","evaluate","headerName","delete","finalize"],"mappings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