-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
202 lines (166 loc) · 5.11 KB
/
index.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import path from "path";
import { existsSync, readFileSync, statSync, readdirSync } from "fs";
import {
glob,
download,
runNpmInstall,
runPackageJsonScript,
getNodeVersion,
getSpawnOptions,
createLambda,
Route,
BuildOptions,
Config,
FileFsRef,
Lambda,
} from "@now/build-utils";
interface PackageJson {
scripts?: {
[key: string]: string;
};
dependencies?: {
[key: string]: string;
};
devDependencies?: {
[key: string]: string;
};
}
interface Output {
[name: string]: FileFsRef | Lambda;
}
function validateDistDir(
distDir: string,
isDev: boolean | undefined,
config: Config
): void {
const distDirName = path.basename(distDir);
const exists = (): boolean => existsSync(distDir);
const isDirectory = (): boolean => statSync(distDir).isDirectory();
const isEmpty = (): boolean => readdirSync(distDir).length === 0;
const hash = isDev
? "#local-development"
: "#configuring-the-build-output-directory";
const docsUrl = `https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build${hash}`;
const info = config.zeroConfig
? "\nMore details: https://zeit.co/docs/v2/advanced/platform/frequently-asked-questions#missing-public-directory"
: `\nMake sure you configure the the correct distDir: ${docsUrl}`;
if (!exists()) {
throw new Error(`No output directory named "${distDirName}" found.${info}`);
}
if (!isDirectory()) {
throw new Error(
`Build failed because distDir is not a directory: "${distDirName}".${info}`
);
}
if (isEmpty()) {
throw new Error(
`Build failed because distDir is empty: "${distDirName}".${info}`
);
}
}
function getCommand(pkg: PackageJson, cmd: string): string {
const nowCmd = `now-${cmd}`;
const scripts = (pkg && pkg.scripts) || {};
if (scripts[nowCmd]) {
return nowCmd;
}
if (scripts[cmd]) {
return cmd;
}
return `npx frontity ${cmd}`;
}
export const version = 2;
export async function build({
files,
entrypoint,
workPath,
config,
meta = {},
}: BuildOptions): Promise<{ routes: object; output: Output }> {
console.log("Downloading user files...");
await download(files, workPath, meta);
const mountpoint = path.dirname(entrypoint);
const entrypointDir = path.join(workPath, mountpoint);
const distPath = path.join(
workPath,
mountpoint,
(config && (config.distDir as string)) || "build"
);
const entrypointName = path.basename(entrypoint);
if (entrypointName === "package.json") {
const pkgPath = path.join(workPath, entrypoint);
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
const minNodeRange: string | undefined = undefined;
const prefix = mountpoint === "." ? "" : `/${mountpoint}`;
const routes: Route[] = [
{
src: `${prefix}/static/(.*)`,
headers: { "cache-control": "public,max-age=31536000,immutable" },
dest: `/static/$1`,
},
{ src: `${prefix}/favicon.ico`, dest: "favicon.ico" },
{
src: `${prefix}($|/.*)`,
headers: { "cache-control": "s-maxage=1,stale-while-revalidate" },
dest: `/server.js`,
},
];
const nodeVersion = await getNodeVersion(entrypointDir, minNodeRange);
const spawnOpts = getSpawnOptions(meta, nodeVersion);
await runNpmInstall(entrypointDir, ["--prefer-offline"], spawnOpts);
const buildScript = getCommand(pkg, "build");
console.log(`Running "${buildScript}" script in "${entrypoint}"`);
const found = await runPackageJsonScript(
entrypointDir,
buildScript,
spawnOpts
);
if (!found) {
throw new Error(
`Missing required "${buildScript}" script in "${entrypoint}"`
);
}
validateDistDir(distPath, meta.isDev, config);
const statics = await glob("static/**", distPath);
const server = await glob("server.js", distPath);
const robotsTxt = await glob("robots.txt", workPath);
const adsTxt = await glob("ads.txt", workPath);
const favicon = await glob("favicon.ico", workPath);
if (!server["server.js"])
throw new Error(
"Something went wrong with the build. Please run `npx frontity dev --production` locally to find out."
);
if (robotsTxt["robots.txt"])
routes.unshift({ src: `${prefix}/robots.txt`, dest: "robots.txt" });
if (adsTxt["ads.txt"])
routes.unshift({ src: `${prefix}/ads.txt`, dest: "ads.txt" });
const launcherFiles = {
"now__bridge.js": new FileFsRef({
fsPath: require("@now/node-bridge"),
}),
"now__launcher.js": new FileFsRef({
fsPath: path.join(__dirname, "launcher.js"),
}),
};
const lambda = await createLambda({
runtime: "nodejs16.x",
handler: "now__launcher.launcher",
files: {
...launcherFiles,
"index.js": new FileFsRef({
fsPath: server["server.js"].fsPath,
}),
},
});
const output = {
...statics,
...robotsTxt,
...favicon,
...adsTxt,
"server.js": lambda,
};
console.log("Finished.");
return { routes, output };
}
throw new Error(`Build "src" is "${entrypoint}" but expected "package.json"`);
}