forked from SnailyCAD/snaily-cadv4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-images-domain.mjs
82 lines (62 loc) · 2.14 KB
/
create-images-domain.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import "dotenv/config";
import process from "node:process";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { readFile, writeFile } from "node:fs/promises";
import { format } from "prettier";
const UNIX_SLASHES_REGEX = /\/apps\/client/;
const WIN_SLASHES_REGEX = /\\apps\\client/;
function getNextConfigPath() {
let dir = join(process.cwd(), "apps", "client");
const unixMatch = process.cwd().match(UNIX_SLASHES_REGEX);
const winMatch = process.cwd().match(WIN_SLASHES_REGEX);
if (unixMatch || winMatch) {
dir = process.cwd();
}
const configFilePath = join(dir, "next.config.mjs");
return pathToFileURL(configFilePath);
}
async function loadNextConfig() {
const configFilePath = getNextConfigPath();
const data = await import(configFilePath);
const text = await readFile(configFilePath, "utf8");
return { data, text };
}
async function writeNextConfig(data) {
if (process.env.NODE_ENV === "development") return;
const configFilePath = getNextConfigPath();
return writeFile(
configFilePath,
await format(data, {
endOfLine: "auto",
semi: true,
trailingComma: "all",
singleQuote: false,
printWidth: 100,
tabWidth: 2,
parser: "typescript",
}),
);
}
function urlToDomain(fullUrl) {
try {
const url = new URL(fullUrl);
if (url.hostname === "api") {
return "localhost";
}
return `${url.hostname}`;
} catch {
return "localhost";
}
}
const domain = urlToDomain(process.env.NEXT_PUBLIC_PROD_ORIGIN);
const { text } = await loadNextConfig();
const stringArray = text.split("\n");
const imagesIndex = stringArray.findIndex((line) => line.includes("images: { // start images"));
const imagesEndIndex = stringArray.findIndex((line) => line.includes("}, // end images"));
let imagesData = stringArray.slice(imagesIndex, imagesEndIndex).join("\n");
imagesData = imagesData.replace(/, "localhost"/, `, "localhost", "${domain}"`);
stringArray.splice(imagesIndex, imagesEndIndex - imagesIndex, imagesData);
const config = stringArray.join("\n");
await writeNextConfig(config);
console.log("Image domain added to next.config.mjs");