-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
platform.ts
272 lines (232 loc) · 7.54 KB
/
platform.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
264
265
266
267
268
269
270
271
272
import { logWarn } from '../../core/util/log';
import type {
OptimizerSystem,
SystemEnvironment,
TransformModuleInput,
TransformOutput,
} from './types';
import { createPath } from './path';
import { QWIK_BINDING_MAP } from './qwik-binding-map';
import { versions } from './versions';
export async function getSystem() {
const sysEnv = getEnv();
const sys: OptimizerSystem = {
dynamicImport: (path) => {
throw new Error(
`Qwik Optimizer sys.dynamicImport() not implemented, trying to import: "${path}"`
);
},
path: null as any,
cwd: () => '/',
os: 'unknown',
env: sysEnv,
};
sys.path = createPath(sys);
if (globalThis.IS_ESM) {
sys.dynamicImport = (path) => import(path);
}
if (globalThis.IS_CJS) {
if (sysEnv === 'node') {
// using this api object as a way to ensure bundlers
// do not try to inline or rewrite require()
sys.dynamicImport = (path) => require(path);
if (typeof TextEncoder === 'undefined') {
// TextEncoder/TextDecoder needs to be on the global scope for the WASM file
// https://nodejs.org/api/util.html#class-utiltextdecoder
const nodeUtil: typeof import('util') = await sys.dynamicImport('util');
global.TextEncoder = nodeUtil.TextEncoder;
global.TextDecoder = nodeUtil.TextDecoder;
}
} else if (sysEnv === 'webworker' || sysEnv === 'browsermain') {
sys.dynamicImport = async (path: string) => {
const cjsRsp = await fetch(path);
const cjsCode = await cjsRsp.text();
const cjsModule: any = { exports: {} };
const cjsRun = new Function('module', 'exports', cjsCode);
cjsRun(cjsModule, cjsModule.exports);
return cjsModule.exports;
};
}
}
if (sysEnv === 'node') {
sys.path = await sys.dynamicImport('path');
sys.cwd = () => process.cwd();
sys.os = process.platform;
}
return sys;
}
export const getPlatformInputFiles = async (sys: OptimizerSystem) => {
if (typeof sys.getInputFiles === 'function') {
return sys.getInputFiles;
}
if (sys.env === 'node') {
const fs: typeof import('fs') = await sys.dynamicImport('fs');
return async (rootDir: string) => {
const getChildFilePaths = async (dir: string): Promise<string[]> => {
const stats = await fs.promises.stat(dir);
const flatted = [];
if (stats.isDirectory()) {
const dirItems = await fs.promises.readdir(dir);
const files = await Promise.all(
dirItems.map(async (subdir: any) => {
const resolvedPath = sys.path.resolve(dir, subdir);
const stats = await fs.promises.stat(resolvedPath);
return stats.isDirectory() ? getChildFilePaths(resolvedPath) : [resolvedPath];
})
);
for (const file of files) {
flatted.push(...file);
}
} else {
flatted.push(dir);
}
return flatted.filter((a) => extensions[sys.path.extname(a)]);
};
const filePaths = await getChildFilePaths(rootDir);
const inputs = (
await Promise.all(
filePaths.map(async (filePath) => {
const input: TransformModuleInput = {
code: await fs.promises.readFile(filePath, 'utf8'),
path: filePath,
};
return input;
})
)
).sort((a, b) => {
if (a.path < b.path) return -1;
if (a.path > b.path) return 1;
return 0;
});
return inputs;
};
}
return null;
};
export async function loadPlatformBinding(sys: OptimizerSystem) {
const sysEnv = getEnv();
if (sysEnv === 'node') {
// NodeJS
const platform = (QWIK_BINDING_MAP as any)[process.platform];
if (platform) {
const triples = platform[process.arch];
if (triples) {
for (const triple of triples) {
// NodeJS - Native Binding
try {
const mod = await sys.dynamicImport(`./bindings/${triple.platformArchABI}`);
return mod;
} catch (e) {
logWarn(e);
}
}
}
}
}
if (globalThis.IS_CJS) {
// CJS WASM
if (sysEnv === 'node') {
// CJS WASM NodeJS
const wasmPath = sys.path.join(__dirname, 'bindings', 'qwik_wasm_bg.wasm');
const mod = await sys.dynamicImport(`./bindings/qwik.wasm.cjs`);
const fs: typeof import('fs') = await sys.dynamicImport('fs');
return new Promise<Buffer>((resolve, reject) => {
fs.readFile(wasmPath, (err, buf) => {
if (err != null) {
reject(err);
} else {
resolve(buf);
}
});
})
.then((buf) => WebAssembly.compile(buf))
.then((wasm) => mod.default(wasm))
.then(() => mod);
}
if (sysEnv === 'webworker' || sysEnv === 'browsermain') {
// CJS WASM Browser
const version = versions.qwik.split('-dev')[0];
const cachedCjsCode = `qwikWasmCjs${version}`;
const cachedWasmRsp = `qwikWasmRsp${version}`;
let cjsCode: string = (globalThis as any)[cachedCjsCode];
let wasmRsp: Response = (globalThis as any)[cachedWasmRsp];
if (!cjsCode || !wasmRsp) {
const cdnUrl = `https://cdn.jsdelivr.net/npm/@builder.io/qwik@${version}/bindings/`;
const cjsModuleUrl = new URL(`./qwik.wasm.cjs`, cdnUrl).href;
const wasmUrl = new URL(`./qwik_wasm_bg.wasm`, cdnUrl).href;
const rsps = await Promise.all([fetch(cjsModuleUrl), fetch(wasmUrl)]);
for (const rsp of rsps) {
if (!rsp.ok) {
throw new Error(`Unable to fetch Qwik WASM binding from ${rsp.url}`);
}
}
const cjsRsp = rsps[0];
(globalThis as any)[cachedCjsCode] = cjsCode = await cjsRsp.text();
(globalThis as any)[cachedWasmRsp] = wasmRsp = rsps[1];
}
const cjsModule: any = { exports: {} };
const cjsRun = new Function('module', 'exports', cjsCode);
cjsRun(cjsModule, cjsModule.exports);
const mod = cjsModule.exports;
// init
await mod.default(wasmRsp.clone());
return mod;
}
}
if (globalThis.IS_ESM) {
// ESM WASM
const module = await sys.dynamicImport(`./bindings/qwik.wasm.mjs`);
await module.default();
return module;
}
throw new Error(`Platform not supported`);
}
export interface PlatformBinding {
transform_fs?: (opts: any) => TransformOutput;
transform_modules: (opts: any) => TransformOutput;
}
const getEnv = (): SystemEnvironment => {
if (typeof Deno !== 'undefined') {
return 'deno';
}
if (
typeof process !== 'undefined' &&
typeof global !== 'undefined' &&
process.versions &&
process.versions.node
) {
return 'node';
}
if (
typeof self !== 'undefined' &&
typeof location !== 'undefined' &&
typeof navigator !== 'undefined' &&
typeof fetch === 'function' &&
typeof WorkerGlobalScope === 'function' &&
typeof (self as any).importScripts === 'function'
) {
return 'webworker';
}
if (
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
typeof location !== 'undefined' &&
typeof navigator !== 'undefined' &&
typeof Window === 'function' &&
typeof fetch === 'function'
) {
return 'browsermain';
}
return 'unknown';
};
const extensions: { [ext: string]: boolean } = {
'.js': true,
'.ts': true,
'.tsx': true,
'.jsx': true,
'.mjs': true,
};
declare const globalThis: { IS_CJS: boolean; IS_ESM: boolean };
declare const global: { [key: string]: any };
declare const WorkerGlobalScope: any;
declare const Deno: any;