-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
dev-builder.ts
258 lines (232 loc) · 7.01 KB
/
dev-builder.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/* disable this rule _here_ to avoid conflict with ongoing changes */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import bytes from 'bytes';
import chalk from 'chalk';
import { tmpdir } from 'os';
import { join, relative } from 'path';
import { createFunction } from '@zeit/fun';
import { readFile, mkdirp } from 'fs-extra';
import ignore, { Ignore } from '@zeit/dockerignore';
import { FileFsRef, download } from '@now/build-utils';
import { globBuilderInputs } from './glob';
import DevServer from './dev-server';
import IGNORED from '../../../util/ignored';
import { LambdaSizeExceededError } from '../../../util/errors-ts';
import { installBuilders, getBuilder } from './builder-cache';
import {
NowConfig,
BuildConfig,
BuildMatch,
BuildResult,
BuilderParamsBase,
BuilderInputs,
BuilderOutput,
BuilderOutputs,
BuiltLambda,
CacheOutputs,
PrepareCacheParams
} from './types';
const tmpDir = tmpdir();
const getWorkPath = () =>
join(
tmpDir,
'co.zeit.now',
'dev',
'workPaths',
Math.random()
.toString(32)
.slice(-8)
);
export async function executePrepareCache(
devServer: DevServer,
buildMatch: BuildMatch,
params: PrepareCacheParams
): Promise<CacheOutputs> {
const { builderWithPkg } = buildMatch;
if (!builderWithPkg) {
throw new Error('No builder');
}
const { builder } = builderWithPkg;
if (!builder.prepareCache) {
throw new Error('Builder has no `prepareCache()` function');
}
// Since the `prepareCache()` function may be computationally expensive, and
// its run in the same process as `now dev` (for now), defer executing it
// until after there has been time for the current HTTP request to complete.
await new Promise(r => setTimeout(r, 3000));
const startTime = Date.now();
const results = await builder.prepareCache(params);
const cacheTime = Date.now() - startTime;
devServer.output.debug(`\`prepareCache()\` took ${cacheTime}ms`);
return results;
}
export async function executeBuild(
nowJson: NowConfig,
devServer: DevServer,
files: BuilderInputs,
match: BuildMatch,
requestPath: string | null = null
): Promise<void> {
const {
builderWithPkg: { builder, package: pkg }
} = match;
const { cwd, env } = devServer;
const entrypoint = match.src;
const workPath = getWorkPath();
await mkdirp(workPath);
if (match.builderCachePromise) {
devServer.output.debug('Restoring build cache from previous build');
const builderCache = await match.builderCachePromise;
const startTime = Date.now();
await download(builderCache, workPath);
const cacheRestoreTime = Date.now() - startTime;
devServer.output.debug(`Restoring build cache took ${cacheRestoreTime}ms`);
}
devServer.output.debug(
`Building ${entrypoint} with "${match.use}"${
pkg.version ? ` v${pkg.version}` : ''
} (workPath = ${workPath})`
);
const builderConfig = builder.config || {};
const config = match.config || {};
let outputs: BuilderOutputs;
let result: BuildResult;
try {
devServer.applyBuildEnv(nowJson);
const r = await builder.build({
files,
entrypoint,
workPath,
config,
meta: { isDev: true, requestPath }
});
if (r.output) {
result = r as BuildResult;
} else {
// `BuilderOutputs` map was returned (Now Builder v1 behavior)
result = { output: r as BuilderOutputs };
}
outputs = result.output;
if (typeof builder.prepareCache === 'function') {
const cachePath = getWorkPath();
await mkdirp(cachePath);
match.builderCachePromise = executePrepareCache(devServer, match, {
files,
entrypoint,
workPath,
cachePath,
config,
meta: { isDev: true, requestPath }
});
}
} finally {
devServer.restoreOriginalEnv();
}
// enforce the lambda zip size soft watermark
const { maxLambdaSize = '5mb' } = { ...builderConfig, ...config };
let maxLambdaBytes: number;
if (typeof maxLambdaSize === 'string') {
maxLambdaBytes = bytes(maxLambdaSize);
} else {
maxLambdaBytes = maxLambdaSize;
}
for (const asset of Object.values(outputs)) {
if (asset.type === 'Lambda') {
const size = asset.zipBuffer.length;
if (size > maxLambdaBytes) {
throw new LambdaSizeExceededError(size, maxLambdaBytes);
}
}
}
await Promise.all(
Object.entries(outputs).map(async entry => {
const path: string = entry[0];
const asset: BuilderOutput = entry[1];
if (asset.type === 'Lambda') {
// Tear down the previous `fun` Lambda instance for this asset
const oldAsset = match.buildOutput && match.buildOutput[path];
if (oldAsset && oldAsset.type === 'Lambda' && oldAsset.fn) {
await oldAsset.fn.destroy();
}
asset.fn = await createFunction({
Code: { ZipFile: asset.zipBuffer },
Handler: asset.handler,
Runtime: asset.runtime,
MemorySize: 3008,
Environment: {
Variables: {
...nowJson.env,
...asset.environment,
...env,
NOW_REGION: 'dev1'
}
}
});
}
match.buildTimestamp = Date.now();
})
);
match.buildResults.set(requestPath, result);
Object.assign(match.buildOutput, outputs);
}
export async function getBuildMatches(
nowJson: NowConfig,
cwd: string
): Promise<BuildMatch[]> {
const matches: BuildMatch[] = [];
const builds = nowJson.builds || [{ src: '**', use: '@now/static' }];
for (const buildConfig of builds) {
let { src, use } = buildConfig;
if (src[0] === '/') {
// Remove a leading slash so that the globbing is relative to `cwd`
// instead of the root of the filesystem. This matches the behavior
// of Now deployments.
src = src.substring(1);
}
// TODO: use the `files` map from DevServer instead of hitting the filesystem
const entries = Object.values(await collectProjectFiles(src, cwd));
for (const fileRef of entries) {
src = relative(cwd, fileRef.fsPath);
const builderWithPkg = await getBuilder(use);
matches.push({
...buildConfig,
src,
builderWithPkg,
buildOutput: {},
buildResults: new Map(),
buildTimestamp: 0
});
}
}
return matches;
}
/**
* Collect project files, with `.nowignore` honored.
*/
export async function collectProjectFiles(
pattern: string,
cwd: string
): Promise<BuilderInputs> {
const ignore = await createIgnoreList(cwd);
const files = await globBuilderInputs(pattern, { cwd, ignore });
return files;
}
/**
* Create ignore list according `.nowignore` in cwd.
*/
export async function createIgnoreList(cwd: string): Promise<Ignore> {
const ig = ignore();
// Add the default ignored files
ig.add(IGNORED);
// Special case for now-cli's usage
ig.add('.nowignore');
try {
const nowignore = join(cwd, '.nowignore');
ig.add(await readFile(nowignore, 'utf8'));
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
return ig;
}