2021-06-02 20:02:03 +03:00
|
|
|
const fs = require("fs");
|
|
|
|
|
2021-12-20 22:26:12 +03:00
|
|
|
async function run({
|
|
|
|
renderFunctionFilePath,
|
|
|
|
routePatterns,
|
|
|
|
apiRoutePatterns,
|
|
|
|
}) {
|
2021-12-18 22:23:12 +03:00
|
|
|
ensureDirSync("functions/render");
|
|
|
|
ensureDirSync("functions/server-render");
|
|
|
|
|
2021-06-02 20:02:03 +03:00
|
|
|
fs.copyFileSync(
|
|
|
|
renderFunctionFilePath,
|
|
|
|
"./functions/render/elm-pages-cli.js"
|
|
|
|
);
|
2021-12-17 07:37:32 +03:00
|
|
|
fs.copyFileSync(
|
|
|
|
renderFunctionFilePath,
|
|
|
|
"./functions/server-render/elm-pages-cli.js"
|
|
|
|
);
|
2021-12-17 22:14:29 +03:00
|
|
|
fs.writeFileSync("./functions/render/index.js", rendererCode(true));
|
|
|
|
fs.writeFileSync("./functions/server-render/index.js", rendererCode(false));
|
2021-06-02 20:02:03 +03:00
|
|
|
// TODO rename functions/render to functions/fallback-render
|
2021-06-02 21:02:35 +03:00
|
|
|
// TODO prepend instead of writing file
|
2021-12-17 22:14:29 +03:00
|
|
|
|
2021-12-21 21:01:42 +03:00
|
|
|
const apiServerRoutes = apiRoutePatterns.filter(isServerSide);
|
|
|
|
|
|
|
|
ensureValidRoutePatternsForNetlify(apiServerRoutes);
|
2021-12-20 22:26:12 +03:00
|
|
|
|
|
|
|
// TODO filter apiRoutePatterns on is server side
|
|
|
|
// TODO need information on whether api route is odb or serverless
|
2021-12-21 21:01:42 +03:00
|
|
|
const apiRouteRedirects = apiServerRoutes
|
2021-12-20 22:26:12 +03:00
|
|
|
.map((apiRoute) => {
|
2021-12-21 00:35:27 +03:00
|
|
|
if (apiRoute.kind === "prerender-with-fallback") {
|
2021-12-21 20:08:17 +03:00
|
|
|
return `${apiPatternToRedirectPattern(
|
|
|
|
apiRoute.pathPattern
|
2021-12-23 21:53:43 +03:00
|
|
|
)} /.netlify/builders/render 200`;
|
2021-12-21 00:35:27 +03:00
|
|
|
} else if (apiRoute.kind === "serverless") {
|
|
|
|
return `${apiPatternToRedirectPattern(
|
|
|
|
apiRoute.pathPattern
|
|
|
|
)} /.netlify/functions/server-render 200`;
|
|
|
|
} else {
|
|
|
|
throw "Unhandled 2";
|
|
|
|
}
|
2021-12-20 22:26:12 +03:00
|
|
|
})
|
|
|
|
.join("\n");
|
|
|
|
|
2021-12-16 02:39:35 +03:00
|
|
|
const redirectsFile =
|
|
|
|
routePatterns
|
|
|
|
.filter(isServerSide)
|
|
|
|
.map((route) => {
|
2021-12-16 02:44:48 +03:00
|
|
|
if (route.kind === "prerender-with-fallback") {
|
2021-12-23 21:53:43 +03:00
|
|
|
return `${route.pathPattern} /.netlify/builders/render 200
|
|
|
|
${route.pathPattern}/content.json /.netlify/builders/render 200`;
|
2021-12-16 02:39:35 +03:00
|
|
|
} else {
|
2021-12-16 23:05:18 +03:00
|
|
|
return `${route.pathPattern} /.netlify/functions/server-render 200
|
|
|
|
${route.pathPattern}/content.json /.netlify/functions/server-render 200`;
|
2021-12-16 02:39:35 +03:00
|
|
|
}
|
|
|
|
})
|
2021-12-21 00:35:27 +03:00
|
|
|
.join("\n") +
|
|
|
|
"\n" +
|
|
|
|
apiRouteRedirects +
|
|
|
|
"\n";
|
2021-06-02 20:02:03 +03:00
|
|
|
|
2021-12-16 02:39:35 +03:00
|
|
|
fs.writeFileSync("dist/_redirects", redirectsFile);
|
2021-06-02 20:02:03 +03:00
|
|
|
}
|
|
|
|
|
2021-12-20 22:26:12 +03:00
|
|
|
function ensureValidRoutePatternsForNetlify(apiRoutePatterns) {
|
|
|
|
const invalidNetlifyRoutes = apiRoutePatterns.filter((apiRoute) =>
|
|
|
|
apiRoute.pathPattern.some(({ kind }) => kind === "hybrid")
|
|
|
|
);
|
|
|
|
if (invalidNetlifyRoutes.length > 0) {
|
|
|
|
throw (
|
|
|
|
"Invalid Netlify routes!\n" +
|
|
|
|
invalidNetlifyRoutes
|
|
|
|
.map((value) => JSON.stringify(value, null, 2))
|
|
|
|
.join(", ")
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-16 02:39:35 +03:00
|
|
|
function isServerSide(route) {
|
|
|
|
return (
|
|
|
|
route.kind === "prerender-with-fallback" || route.kind === "serverless"
|
|
|
|
);
|
2021-06-02 20:02:03 +03:00
|
|
|
}
|
|
|
|
|
2021-12-21 21:01:42 +03:00
|
|
|
(async function () {
|
|
|
|
try {
|
|
|
|
await run({
|
|
|
|
renderFunctionFilePath: "./elm-stuff/elm-pages/elm.js",
|
|
|
|
routePatterns: JSON.parse(fs.readFileSync("dist/route-patterns.json")),
|
|
|
|
apiRoutePatterns: JSON.parse(fs.readFileSync("dist/api-patterns.json")),
|
|
|
|
});
|
|
|
|
console.log("Success - Adapter script complete");
|
|
|
|
} catch (error) {
|
|
|
|
console.error("ERROR - Adapter script failed");
|
|
|
|
console.error(error);
|
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
})();
|
2021-12-17 22:14:29 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {boolean} isOnDemand
|
|
|
|
*/
|
|
|
|
function rendererCode(isOnDemand) {
|
|
|
|
return `const path = require("path");
|
2021-12-29 02:35:56 +03:00
|
|
|
const cookie = require("cookie");
|
2021-12-30 00:02:45 +03:00
|
|
|
const busboy = require("busboy");
|
|
|
|
|
2021-12-17 22:14:29 +03:00
|
|
|
${
|
|
|
|
isOnDemand
|
|
|
|
? `const { builder } = require("@netlify/functions");
|
|
|
|
|
|
|
|
exports.handler = builder(render);`
|
|
|
|
: `
|
|
|
|
|
|
|
|
exports.handler = render;`
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {import('aws-lambda').APIGatewayProxyEvent} event
|
|
|
|
* @param {any} context
|
|
|
|
*/
|
|
|
|
async function render(event, context) {
|
2021-12-24 00:34:54 +03:00
|
|
|
const requestTime = new Date();
|
2021-12-17 22:14:29 +03:00
|
|
|
console.log(JSON.stringify(event));
|
|
|
|
global.staticHttpCache = {};
|
|
|
|
|
|
|
|
const compiledElmPath = path.join(__dirname, "elm-pages-cli.js");
|
|
|
|
const renderer = require("../../../../generator/src/render");
|
|
|
|
try {
|
|
|
|
const basePath = "/";
|
|
|
|
const mode = "build";
|
|
|
|
const addWatcher = () => {};
|
|
|
|
|
|
|
|
const renderResult = await renderer(
|
|
|
|
basePath,
|
|
|
|
require(compiledElmPath),
|
|
|
|
mode,
|
|
|
|
event.path,
|
2021-12-30 00:21:49 +03:00
|
|
|
await reqToJson(event, requestTime),
|
2021-12-30 04:18:37 +03:00
|
|
|
addWatcher,
|
|
|
|
false
|
2021-12-17 22:14:29 +03:00
|
|
|
);
|
2021-12-30 00:58:21 +03:00
|
|
|
console.log("@@@renderResult", JSON.stringify(renderResult, null, 2));
|
2021-12-17 22:14:29 +03:00
|
|
|
|
|
|
|
const statusCode = renderResult.is404 ? 404 : 200;
|
|
|
|
|
|
|
|
if (renderResult.kind === "json") {
|
|
|
|
return {
|
|
|
|
body: renderResult.contentJson,
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
"x-powered-by": "elm-pages",
|
2021-12-21 00:55:24 +03:00
|
|
|
},
|
|
|
|
statusCode,
|
|
|
|
};
|
|
|
|
} else if (renderResult.kind === "api-response") {
|
2021-12-21 01:45:18 +03:00
|
|
|
const serverResponse = renderResult.body;
|
2021-12-21 00:55:24 +03:00
|
|
|
return {
|
2021-12-21 01:45:18 +03:00
|
|
|
body: serverResponse.body,
|
2021-12-22 04:33:41 +03:00
|
|
|
multiValueHeaders: serverResponse.headers,
|
2021-12-21 01:45:18 +03:00
|
|
|
statusCode: serverResponse.statusCode,
|
2021-12-21 20:45:25 +03:00
|
|
|
isBase64Encoded: serverResponse.isBase64Encoded,
|
2021-12-17 22:14:29 +03:00
|
|
|
};
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
body: renderResult.htmlString,
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "text/html",
|
|
|
|
"x-powered-by": "elm-pages",
|
|
|
|
},
|
|
|
|
statusCode,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
return {
|
|
|
|
body: \`<body><h1>Error</h1><pre>\${error.toString()}</pre></body>\`,
|
|
|
|
statusCode: 500,
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "text/html",
|
|
|
|
"x-powered-by": "elm-pages",
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {import('aws-lambda').APIGatewayProxyEvent} req
|
2021-12-24 00:34:54 +03:00
|
|
|
* @param {Date} requestTime
|
2021-12-30 00:58:21 +03:00
|
|
|
* @returns {Promise<{ method: string; hostname: string; query: Record<string, string | undefined>; headers: Record<string, string>; host: string; pathname: string; port: number | null; protocol: string; rawUrl: string; }>}
|
2021-12-17 22:14:29 +03:00
|
|
|
*/
|
2021-12-24 00:34:54 +03:00
|
|
|
function reqToJson(req, requestTime) {
|
2021-12-30 00:02:45 +03:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
if (
|
2021-12-30 00:37:47 +03:00
|
|
|
req.httpMethod && req.httpMethod.toUpperCase() === "POST" &&
|
2021-12-30 00:02:45 +03:00
|
|
|
req.headers["content-type"] &&
|
|
|
|
req.headers["content-type"].includes("multipart/form-data") &&
|
|
|
|
req.body
|
|
|
|
) {
|
|
|
|
try {
|
2021-12-30 00:37:47 +03:00
|
|
|
console.log('@@@1');
|
2021-12-30 00:02:45 +03:00
|
|
|
const bb = busboy({
|
|
|
|
headers: req.headers,
|
|
|
|
});
|
|
|
|
let fields = {};
|
|
|
|
|
|
|
|
bb.on("file", (fieldname, file, info) => {
|
2021-12-30 00:37:47 +03:00
|
|
|
console.log('@@@2');
|
2021-12-30 00:02:45 +03:00
|
|
|
const { filename, encoding, mimeType } = info;
|
|
|
|
|
|
|
|
file.on("data", (data) => {
|
|
|
|
fields[fieldname] = {
|
|
|
|
filename,
|
|
|
|
mimeType,
|
|
|
|
body: data.toString(),
|
|
|
|
};
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
bb.on("field", (fieldName, value) => {
|
2021-12-30 00:28:20 +03:00
|
|
|
console.log("@@@field", fieldName, value);
|
2021-12-30 00:02:45 +03:00
|
|
|
fields[fieldName] = value;
|
|
|
|
});
|
|
|
|
|
|
|
|
// TODO skip parsing JSON and form data body if busboy doesn't run
|
|
|
|
bb.on("close", () => {
|
2021-12-30 00:37:47 +03:00
|
|
|
console.log('@@@3');
|
2021-12-30 00:28:20 +03:00
|
|
|
console.log("@@@close", fields);
|
2021-12-30 00:02:45 +03:00
|
|
|
resolve(toJsonHelper(req, requestTime, fields));
|
|
|
|
});
|
2021-12-30 00:37:47 +03:00
|
|
|
console.log('@@@4');
|
2021-12-30 01:25:46 +03:00
|
|
|
|
|
|
|
if (req.isBase64Encoded) {
|
|
|
|
bb.write(Buffer.from(req.body, 'base64').toString('utf8'));
|
|
|
|
} else {
|
|
|
|
bb.write(req.body);
|
|
|
|
}
|
2021-12-30 00:02:45 +03:00
|
|
|
} catch (error) {
|
2021-12-30 00:37:47 +03:00
|
|
|
console.error('@@@5', error);
|
2021-12-30 00:02:45 +03:00
|
|
|
resolve(toJsonHelper(req, requestTime, null));
|
|
|
|
}
|
|
|
|
} else {
|
2021-12-30 00:37:47 +03:00
|
|
|
console.log('@@@6');
|
2021-12-30 00:02:45 +03:00
|
|
|
resolve(toJsonHelper(req, requestTime, null));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2021-12-22 03:11:51 +03:00
|
|
|
|
2021-12-30 00:02:45 +03:00
|
|
|
function toJsonHelper(req, requestTime, multiPartFormData) {
|
|
|
|
let jsonBody = null;
|
2021-12-28 22:53:43 +03:00
|
|
|
try {
|
2021-12-30 00:28:14 +03:00
|
|
|
jsonBody = req.body && JSON.parse(req.body);
|
2021-12-28 22:53:43 +03:00
|
|
|
} catch (jsonParseError) {}
|
2021-12-17 22:14:29 +03:00
|
|
|
return {
|
|
|
|
method: req.httpMethod,
|
|
|
|
hostname: "TODO",
|
2021-12-28 22:53:43 +03:00
|
|
|
query: req.queryStringParameters || {},
|
2021-12-17 22:14:29 +03:00
|
|
|
headers: req.headers,
|
|
|
|
host: "", // TODO
|
|
|
|
pathname: req.path,
|
|
|
|
port: 80, // TODO
|
|
|
|
protocol: "https", // TODO
|
|
|
|
rawUrl: "", // TODO
|
2021-12-23 02:28:19 +03:00
|
|
|
body: req.body,
|
2021-12-24 00:34:54 +03:00
|
|
|
requestTime: Math.round(requestTime.getTime()),
|
2021-12-28 22:53:43 +03:00
|
|
|
cookies: cookie.parse(req.headers.cookie || ""),
|
|
|
|
// TODO skip parsing if content-type is not x-www-form-urlencoded
|
|
|
|
formData: paramsToObject(new URLSearchParams(req.body || "")),
|
2021-12-30 00:02:45 +03:00
|
|
|
multiPartFormData: multiPartFormData,
|
2021-12-28 22:53:43 +03:00
|
|
|
jsonBody: jsonBody,
|
2021-12-17 22:14:29 +03:00
|
|
|
};
|
|
|
|
}
|
2021-12-29 02:38:07 +03:00
|
|
|
|
|
|
|
function paramsToObject(entries) {
|
|
|
|
const result = {};
|
|
|
|
for (const [key, value] of entries) {
|
2021-12-30 00:58:21 +03:00
|
|
|
result[key] = value || "";
|
2021-12-29 02:38:07 +03:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
2021-12-17 22:14:29 +03:00
|
|
|
`;
|
|
|
|
}
|
2021-12-18 22:23:12 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {fs.PathLike} dirpath
|
|
|
|
*/
|
|
|
|
function ensureDirSync(dirpath) {
|
|
|
|
try {
|
|
|
|
fs.mkdirSync(dirpath, { recursive: true });
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code !== "EEXIST") throw err;
|
|
|
|
}
|
|
|
|
}
|
2021-12-20 22:26:12 +03:00
|
|
|
|
|
|
|
/** @typedef {{kind: 'dynamic'} | {kind: 'literal', value: string}} ApiSegment */
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {ApiSegment[]} pathPattern
|
|
|
|
*/
|
|
|
|
function apiPatternToRedirectPattern(pathPattern) {
|
2021-12-21 00:35:27 +03:00
|
|
|
return (
|
|
|
|
"/" +
|
|
|
|
pathPattern
|
|
|
|
.map((segment) => {
|
|
|
|
switch (segment.kind) {
|
|
|
|
case "literal": {
|
|
|
|
return segment.value;
|
|
|
|
}
|
|
|
|
case "dynamic": {
|
|
|
|
return ":dynamic"; // TODO need to assign different names for each dynamic segment?
|
|
|
|
}
|
|
|
|
default: {
|
|
|
|
throw "Unhandled segment: " + JSON.stringify(segment);
|
|
|
|
}
|
2021-12-20 22:26:12 +03:00
|
|
|
}
|
2021-12-21 00:35:27 +03:00
|
|
|
})
|
|
|
|
.join("/")
|
|
|
|
);
|
2021-12-20 22:26:12 +03:00
|
|
|
}
|