-
Notifications
You must be signed in to change notification settings - Fork 94
/
bundler.ts
177 lines (165 loc) · 5.4 KB
/
bundler.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
import path from 'path';
import util from 'util';
import dedent from 'dedent';
import webpack from 'webpack';
import * as realFS from 'fs';
import * as memfs from 'memfs';
import * as unionfs from 'unionfs';
import { Logger } from '../logger';
/**
* Builds a V8 Isolate by bundling provided Workflows using webpack.
* Activities are replaced with stubs.
*
* @param nodeModulesPath node_modules path with required Workflow dependencies
* @param workflowsPath all Workflows found in path will be put in the bundle
* @param workflowInterceptorModules list of interceptor modules to register on Workflow creation
*/
export class WorkflowCodeBundler {
constructor(
public readonly logger: Logger,
public readonly nodeModulesPaths: string[],
public readonly workflowsPath: string,
public readonly workflowInterceptorModules: string[] = []
) {}
/**
* @return a string representation of the bundled Workflow code
*/
public async createBundle(): Promise<string> {
const vol = new memfs.Volume();
const ufs = new unionfs.Union();
/**
* readdir and exclude sourcemaps and d.ts files
*/
function readdir(...args: Parameters<typeof realFS.readdir>) {
// Help TS a bit because readdir has multiple signatures
const callback: (err: NodeJS.ErrnoException | null, files: string[]) => void = args.pop() as any;
const newArgs: Parameters<typeof realFS.readdir> = [
...args,
(err: Error | null, files: string[]) => {
if (err !== null) {
callback(err, []);
return;
}
callback(
null,
files.filter((f) => /\.[jt]s$/.test(path.extname(f)) && !f.endsWith('.d.ts'))
);
},
] as any;
return realFS.readdir(...newArgs);
}
// Cast because the type definitions are inaccurate
ufs.use(memfs.createFsFromVolume(vol) as any).use({ ...realFS, readdir: readdir as any });
const distDir = '/dist';
const entrypointPath = path.join('/src/main.js');
this.genEntrypoint(vol, entrypointPath);
await this.bundle(ufs, entrypointPath, distDir);
return ufs.readFileSync(path.join(distDir, 'main.js'), 'utf8');
}
/**
* Creates the main entrypoint for the generated webpack library.
*
* Exports all detected Workflow implementations and some workflow libraries to be used by the Worker.
*/
protected genEntrypoint(vol: typeof memfs.vol, target: string): void {
const interceptorCases = [...new Set(this.workflowInterceptorModules)]
.map(
(v) => dedent`
case ${JSON.stringify(v)}:
return import(/* webpackMode: "eager" */ ${JSON.stringify(v)});
`
)
.join('\n');
const code = dedent`
import * as api from '@temporalio/workflow/lib/worker-interface.js';
// Bundle all Workflows and interceptor modules for lazy evaluation
api.overrideGlobals();
api.setRequireFunc(
(path) => {
if (path === undefined) {
return import(/* webpackMode: "eager" */ ${JSON.stringify(this.workflowsPath)});
}
switch (path) {
${interceptorCases}
default:
throw new ReferenceError('Cannot load module: ' + path);
}
}
);
export const {
initRuntime,
activate,
concludeActivation,
inject,
resolveExternalDependencies,
getAndResetExternalCalls,
tryUnblockConditions,
} = api;
`;
try {
vol.mkdirSync(path.dirname(target), { recursive: true });
} catch (err: any) {
if (err.code !== 'EEXIST') throw err;
}
vol.writeFileSync(target, code);
}
/**
* Run webpack
*/
protected async bundle(filesystem: typeof unionfs.ufs, entry: string, distDir: string): Promise<void> {
const compiler = webpack({
resolve: {
modules: this.nodeModulesPaths,
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
],
},
entry: [entry],
mode: 'development',
// Recommended choice for development builds with high quality SourceMaps
devtool: 'eval-source-map',
output: {
path: distDir,
filename: 'main.js',
library: 'lib',
},
});
// Cast to any because the type declarations are inaccurate
compiler.inputFileSystem = filesystem as any;
compiler.outputFileSystem = filesystem as any;
try {
await new Promise<void>((resolve, reject) => {
compiler.run((err, stats) => {
if (stats !== undefined) {
const hasError = stats.hasErrors();
const lines = stats.toString({ chunks: false, colors: true }).split('\n');
for (const line of lines) {
this.logger[hasError ? 'error' : 'info'](line);
}
if (hasError) {
reject(
new Error(
"Webpack finished with errors, if you're unsure what went wrong, visit our troubleshooting page at https://docs.temporal.io/docs/typescript/troubleshooting#webpack-errors"
)
);
}
}
if (err) {
reject(err);
} else {
resolve();
}
});
});
} finally {
await util.promisify(compiler.close).bind(compiler)();
}
}
}