-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.ts
263 lines (229 loc) · 6.49 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
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
259
260
261
262
263
import fs, { pathExists } from 'fs-extra';
import path from 'path';
import execa from 'execa';
import {
glob,
createLambda,
download,
FileFsRef,
runShellScript,
BuildOptions,
DownloadedFiles,
Files,
debug,
} from '@now/build-utils';
import {
ensureDeno,
replaceBinDeno,
ensureBash,
replaceBootstrapBash,
} from './dev';
import { getWorkPath } from './util';
const DENO_LATEST = 'latest'
const DENO_VERSION = process.env.DENO_VERSION || DENO_LATEST;
const DOWNLOAD_URL = DENO_VERSION === DENO_LATEST ?
`https://github.com/hayd/deno-lambda/releases/latest/download/deno-lambda-layer.zip` :
`https://github.com/hayd/deno-lambda/releases/download/${DENO_VERSION}/deno-lambda-layer.zip`;
debug('Deno Version:', DENO_VERSION)
export const version = 3;
export async function build(opts: BuildOptions) {
const { files, entrypoint, workPath: wp, config, meta = {} } = opts;
const workPath = getWorkPath(wp, entrypoint);
await fs.mkdirp(workPath);
if (meta.isDev) {
debug('checking that deno is available');
ensureDeno();
debug('checking that bash is available');
ensureBash();
}
const lambdaFiles = await getDenoLambdaLayer(workPath, meta.isDev || false);
if (meta.isDev) {
debug('symlinking local deno to replace deno-lambda-layer bin/deno');
await replaceBinDeno(workPath);
}
debug('downloading source files');
const downloadedFiles = await download(
files,
path.join(workPath, 'src'),
meta
);
const entryPath = downloadedFiles[entrypoint].fsPath;
await runUserScripts(entryPath);
const extraFiles = await gatherExtraFiles(config.includeFiles, entryPath);
return buildDenoLambda(
opts,
downloadedFiles,
extraFiles,
lambdaFiles,
workPath
);
}
async function buildDenoLambda(
{ entrypoint }: BuildOptions,
downloadedFiles: DownloadedFiles,
extraFiles: DownloadedFiles,
layerFiles: Files,
workPath: string
) {
const unstable = !!process.env.DENO_UNSTABLE;
debug('building single file');
const entrypointPath = downloadedFiles[entrypoint].fsPath;
const entrypointDirname = path.dirname(entrypointPath);
const extname = path.extname(entrypointPath);
const binName = path.basename(entrypointPath).replace(extname, '');
const binPath = path.join(workPath, binName) + '.bundle.js';
const denoDir = path.join(workPath, 'layer', '.deno_dir');
debug('running `deno bundle`...');
try {
await execa(
path.join(workPath, 'layer', 'bin', 'deno'),
['bundle', entrypointPath, binPath, ...(unstable ? ['--unstable'] : [])],
{
env: {
DENO_DIR: denoDir,
},
cwd: entrypointDirname,
stdio: 'pipe',
}
);
} catch (err) {
debug('failed to `deno bundle`');
throw new Error(
'Failed to run `deno bundle`: ' + err.stdout + ' ' + err.stderr
);
}
const denoDirFiles = await getDenoDirFiles(denoDir);
const lambda = await createLambda({
files: {
...extraFiles,
...layerFiles,
...denoDirFiles,
[binName + '.bundle.js']: new FileFsRef({
mode: 0o755,
fsPath: binPath,
}),
},
handler: binName + '.handler',
runtime: 'provided',
environment: {
HANDLER_EXT: 'bundle.js',
PATH: process.env.PATH + ':./bin',
},
});
if (version === 3) {
return { output: lambda };
}
return {
[entrypoint]: lambda,
};
}
async function walk(dir: string): Promise<string[]> {
const f = await fs.readdir(dir);
const files = await Promise.all(
f.map(async file => {
const filePath = path.join(dir, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) return walk(filePath);
else if (stats.isFile()) return filePath;
throw 'File not dir or file: ' + filePath;
})
);
return files.flat();
}
async function getDenoDirFiles(denoDirPath: string): Promise<Files> {
const files: Files = {};
const dir = await walk(denoDirPath);
dir.forEach(file => {
const f = path.join('.deno_dir', file.replace(denoDirPath + '/', ''));
files[f] = new FileFsRef({ fsPath: file, mode: 0o755 });
});
return files;
}
async function getDenoLambdaLayer(
workPath: string,
isDev: boolean
): Promise<Files> {
const zipPath = path.join(workPath, 'deno-lambda-layer.zip');
if (!(await pathExists(zipPath))) {
debug('downloading ', DOWNLOAD_URL);
try {
await execa(
'curl',
[
'-o',
zipPath,
'-L',
DOWNLOAD_URL,
],
{
stdio: 'pipe',
}
);
} catch (err) {
debug('failed to download deno-lambda-layer');
throw new Error(
'Failed to download deno-lambda-layer.zip: ' +
err.stdout +
' ' +
err.stderr
);
}
}
const layerDir = path.join(workPath, 'layer');
const bootstrapPath = path.join(layerDir, 'bootstrap');
const denoPath = path.join(layerDir, 'bin/deno');
if (!(await pathExists(bootstrapPath)) || !(await pathExists(denoPath))) {
debug('unzipping `deno-lambda-layer.zip` into `layer`');
try {
await execa('unzip', [zipPath, '-d', layerDir], {
stdio: 'pipe',
});
} catch (err) {
debug('failed to unzip `deno-lambda-layer.zip` into `layer`');
throw new Error(
'Failed to unzip `deno-lambda-layer.zip` into `layer`: ' +
err.stdout +
' ' +
err.stderr
);
}
}
if (isDev) {
debug('using bash for bootstrap script');
await replaceBootstrapBash(bootstrapPath);
}
return {
bootstrap: new FileFsRef({
mode: 0o755,
fsPath: bootstrapPath,
}),
'bin/deno': new FileFsRef({
mode: 0o755,
fsPath: denoPath,
}),
};
}
async function runUserScripts(entrypoint: string) {
const entryDir = path.dirname(entrypoint);
const buildScriptPath = path.join(entryDir, 'build.sh');
const buildScriptExists = await fs.pathExists(buildScriptPath);
if (buildScriptExists) {
console.log('running `build.sh`...');
await runShellScript(buildScriptPath);
}
}
async function gatherExtraFiles(
globMatcher: string | string[] | undefined,
entrypoint: string
) {
if (!globMatcher) return {};
console.log('gathering extra files for the fs...');
const entryDir = path.dirname(entrypoint);
if (Array.isArray(globMatcher)) {
const allMatches = await Promise.all(
globMatcher.map(pattern => glob(pattern, entryDir))
);
return allMatches.reduce((acc, matches) => ({ ...acc, ...matches }), {});
}
return glob(globMatcher, entryDir);
}