Skip to content

Commit 209d5f0

Browse files
authored
refactor: run optimizer/server in web worker env (#386)
1 parent a58f9b8 commit 209d5f0

File tree

22 files changed

+246
-138
lines changed

22 files changed

+246
-138
lines changed

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,9 @@
127127
"qwikloader.debug.js",
128128
"qwikloader.optimize.js",
129129
"qwikloader.optimize.debug.js",
130-
"server/index.cjs",
131-
"server/index.mjs",
132-
"server/index.d.ts",
130+
"server.cjs",
131+
"server.mjs",
132+
"server.d.ts",
133133
"server/package.json",
134134
"testing/index.cjs",
135135
"testing/index.mjs",

scripts/api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export function apiExtractor(config: BuildConfig) {
1111
// Run the api extractor for each of the submodules
1212
createTypesApi(config, 'core', 'core.d.ts', './core');
1313
createTypesApi(config, 'optimizer', 'optimizer.d.ts', './core');
14-
createTypesApi(config, 'server', 'server/index.d.ts', '../core');
14+
createTypesApi(config, 'server', 'server.d.ts', './core');
1515
createTypesApi(config, 'testing', 'testing/index.d.ts', '../core');
1616
createTypesApi(config, 'build', 'build/index.d.ts', '../core');
1717

scripts/cli.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { BuildConfig, copyFile, emptyDir, importPath, mkdir, stat } from './util';
2-
import { banner, readdir, watcher } from './util';
32
import { build } from 'esbuild';
43
import { basename, join } from 'path';
4+
import { getBanner, readdir, watcher } from './util';
55
import { readPackageJson, writePackageJson } from './package-json';
66
import semver from 'semver';
77

@@ -42,7 +42,7 @@ async function bundleCli(config: BuildConfig, distCliDir: string) {
4242
minify: !config.dev,
4343
plugins: [importPath(/api$/, './index.js')],
4444
banner: {
45-
js: `#! /usr/bin/env node\n${banner.js}`,
45+
js: `#! /usr/bin/env node\n${getBanner('create-qwik')}`,
4646
},
4747
watch: watcher(config),
4848
});
@@ -56,7 +56,7 @@ async function bundleCli(config: BuildConfig, distCliDir: string) {
5656
platform: 'node',
5757
minify: !config.dev,
5858
banner: {
59-
js: banner.js,
59+
js: getBanner('create-qwik'),
6060
},
6161
watch: watcher(config),
6262
});

scripts/package-json.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,17 @@ export async function generatePackageJson(config: BuildConfig) {
4646
import: './loader/index.mjs',
4747
require: './loader/index.cjs',
4848
},
49+
'./optimizer.cjs': './optimizer.cjs',
50+
'./optimizer.mjs': './optimizer.mjs',
4951
'./optimizer': {
5052
import: './optimizer.mjs',
5153
require: './optimizer.cjs',
5254
},
53-
'./server/index.cjs': './server/index.cjs',
55+
'./server.cjs': './server.cjs',
56+
'./server.mjs': './server.mjs',
5457
'./server': {
55-
import: './server/index.mjs',
56-
require: './server/index.cjs',
58+
import: './server.mjs',
59+
require: './server.cjs',
5760
},
5861
'./testing': {
5962
import: './testing/index.mjs',
@@ -81,6 +84,7 @@ export async function generatePackageJson(config: BuildConfig) {
8184
await generateLegacyCjsSubmodule(config, 'core');
8285
await generateLegacyCjsSubmodule(config, 'jsx-runtime');
8386
await generateLegacyCjsSubmodule(config, 'optimizer');
87+
await generateLegacyCjsSubmodule(config, 'server');
8488

8589
console.log(`🐷 generated package.json`);
8690
}
@@ -109,6 +113,7 @@ export async function readPackageJson(pkgJsonDir: string) {
109113
}
110114

111115
export async function writePackageJson(pkgJsonDir: string, pkgJson: PackageJSON) {
116+
ensureDir(pkgJsonDir);
112117
const pkgJsonPath = join(pkgJsonDir, 'package.json');
113118
const pkgJsonStr = JSON.stringify(pkgJson, null, 2) + '\n';
114119
await writeFile(pkgJsonPath, pkgJsonStr);

scripts/submodule-core.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { BuildConfig, injectGlobalThisPoly, rollupOnWarn } from './util';
2-
import { banner, fileSize, readFile, target, watcher, writeFile } from './util';
32
import { build, BuildOptions } from 'esbuild';
3+
import { getBanner, fileSize, readFile, target, watcher, writeFile } from './util';
44
import { InputOptions, OutputOptions, rollup } from 'rollup';
55
import { join } from 'path';
66
import { minify } from 'terser';
@@ -47,18 +47,27 @@ async function submoduleCoreProd(config: BuildConfig) {
4747
format: 'es',
4848
entryFileNames: 'core.mjs',
4949
sourcemap: true,
50+
banner: getBanner('@builder.io/qwik'),
5051
};
5152

53+
const cjsIntro = [
54+
,
55+
/**
56+
* Quick and dirty polyfill so globalThis is a global (really only needed for cjs and Node10)
57+
* and globalThis is only needed so globalThis.qDev can be set, and for dev dead code removal
58+
*/
59+
readFileSync(injectGlobalThisPoly(config), 'utf-8'),
60+
`globalThis.qwikCore = (function (exports) {`,
61+
].join('');
62+
5263
const cjsOutput: OutputOptions = {
5364
dir: join(config.distPkgDir),
5465
format: 'cjs',
5566
entryFileNames: 'core.cjs',
5667
sourcemap: true,
57-
/**
58-
* Quick and dirty polyfill so globalThis is a global (really only needed for cjs and Node10)
59-
* and globalThis is only needed so globalThis.qDev can be set, and for dev dead code removal
60-
*/
61-
intro: readFileSync(join(config.scriptsDir, 'shim', 'globalthis.js'), 'utf-8'),
68+
banner: getBanner('@builder.io/qwik'),
69+
intro: cjsIntro,
70+
outro: `return exports; })(typeof exports === 'object' ? exports : {});`,
6271
};
6372

6473
const build = await rollup(input);
@@ -83,7 +92,7 @@ async function submoduleCoreProd(config: BuildConfig) {
8392
},
8493
format: {
8594
comments: false,
86-
preamble: banner.js,
95+
preamble: getBanner('@builder.io/qwik'),
8796
ecma: 2018,
8897
},
8998
});
@@ -123,7 +132,6 @@ async function submoduleCoreDev(config: BuildConfig) {
123132
bundle: true,
124133
sourcemap: 'external',
125134
target,
126-
banner,
127135
define: {
128136
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
129137
},

scripts/submodule-optimizer.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
import { build, BuildOptions } from 'esbuild';
22
import {
3+
access,
34
BuildConfig,
4-
banner,
5+
getBanner,
6+
injectGlobalThisPoly,
57
nodeTarget,
8+
readFile,
69
target,
710
watcher,
811
writeFile,
9-
readFile,
10-
access,
1112
} from './util';
1213
import { join } from 'path';
1314
import { minify } from 'terser';
1415
import { platformArchTriples } from '@napi-rs/triples';
1516
import { readPackageJson } from './package-json';
1617
import { watch } from 'rollup';
17-
import { constants } from 'fs';
18+
import { constants, readFileSync } from 'fs';
1819
import { inlineQwikScriptsEsBuild } from './submodule-qwikloader';
1920

2021
/**
@@ -33,7 +34,6 @@ export async function submoduleOptimizer(config: BuildConfig) {
3334
bundle: true,
3435
sourcemap: false,
3536
target,
36-
banner,
3737
external: [
3838
/* no nodejs built-in externals allowed! */
3939
],
@@ -45,6 +45,7 @@ export async function submoduleOptimizer(config: BuildConfig) {
4545
const esmBuild = build({
4646
...opts,
4747
format: 'esm',
48+
banner: { js: getBanner('@builder.io/qwik/optimizer') },
4849
outExtension: { '.js': '.mjs' },
4950
define: {
5051
'globalThis.IS_CJS': 'false',
@@ -55,9 +56,18 @@ export async function submoduleOptimizer(config: BuildConfig) {
5556
watch: watcher(config, submodule),
5657
});
5758

59+
const cjsBanner = [
60+
readFileSync(injectGlobalThisPoly(config), 'utf-8'),
61+
`globalThis.qwikOptimizer = (function (module) {`,
62+
].join('\n');
63+
5864
const cjsBuild = build({
5965
...opts,
6066
format: 'cjs',
67+
banner: { js: cjsBanner },
68+
footer: {
69+
js: `return module.exports; })(typeof module === 'object' && module.exports ? module : { exports: {} });`,
70+
},
6171
outExtension: { '.js': '.cjs' },
6272
define: {
6373
'globalThis.IS_CJS': 'true',
@@ -102,6 +112,7 @@ export async function submoduleOptimizer(config: BuildConfig) {
102112
braces: true,
103113
beautify: true,
104114
indent_level: 2,
115+
preamble: getBanner('@builder.io/qwik/optimizer'),
105116
},
106117
mangle: false,
107118
});

scripts/submodule-server.ts

Lines changed: 55 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,17 @@ import { build, BuildOptions, Plugin } from 'esbuild';
22
import { join } from 'path';
33
import {
44
BuildConfig,
5-
banner,
5+
getBanner,
66
importPath,
77
injectGlobalThisPoly,
8-
nodeBuiltIns,
8+
injectGlobalPoly,
99
nodeTarget,
10-
PackageJSON,
1110
target,
1211
watcher,
13-
injectGlobalPoly,
1412
} from './util';
1513
import { inlineQwikScriptsEsBuild } from './submodule-qwikloader';
16-
import { readPackageJson, writePackageJson } from './package-json';
14+
import { readPackageJson } from './package-json';
15+
import { readFileSync } from 'fs';
1716

1817
/**
1918
* Builds @builder.io/server
@@ -25,69 +24,71 @@ export async function submoduleServer(config: BuildConfig) {
2524
const submodule = 'server';
2625

2726
const qwikDomPlugin = await bundleQwikDom(config);
27+
const qwikDomVersion = await getQwikDomVersion();
2828

2929
const opts: BuildOptions = {
3030
entryPoints: [join(config.srcDir, submodule, 'index.ts')],
31-
outdir: join(config.distPkgDir, submodule),
31+
entryNames: 'server',
32+
outdir: config.distPkgDir,
3233
sourcemap: config.dev,
3334
bundle: true,
3435
target,
35-
banner,
36-
external: [...nodeBuiltIns, '@builder.io/qwik-dom'],
37-
define: {
38-
...(await inlineQwikScriptsEsBuild(config)),
39-
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
40-
'globalThis.DOMINO_VERSION': JSON.stringify(await getDominoVersion()),
41-
},
36+
external: [/* no nodejs built-in externals allowed! */ '@builder.io/qwik-dom'],
4237
};
4338

4439
const esm = build({
4540
...opts,
4641
format: 'esm',
42+
banner: { js: getBanner('@builder.io/qwik/server') },
4743
outExtension: { '.js': '.mjs' },
48-
plugins: [
49-
importPath(/^@builder\.io\/qwik$/, '../core.mjs'),
50-
importPath(/^@builder\.io\/qwik\/optimizer$/, '../optimizer.mjs'),
51-
qwikDomPlugin,
52-
],
44+
plugins: [importPath(/^@builder\.io\/qwik$/, './core.mjs'), qwikDomPlugin],
5345
watch: watcher(config, submodule),
5446
inject: [injectGlobalPoly(config)],
47+
define: {
48+
...(await inlineQwikScriptsEsBuild(config)),
49+
'globalThis.IS_CJS': 'false',
50+
'globalThis.IS_ESM': 'true',
51+
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
52+
'globalThis.QWIK_DOM_VERSION': JSON.stringify(qwikDomVersion),
53+
},
5554
});
5655

56+
const cjsBanner = [
57+
getBanner('@builder.io/qwik/server'),
58+
readFileSync(injectGlobalThisPoly(config), 'utf-8'),
59+
readFileSync(injectGlobalPoly(config), 'utf-8'),
60+
`globalThis.qwikServer = (function (module) {`,
61+
browserCjsRequireShim,
62+
].join('\n');
63+
5764
const cjs = build({
5865
...opts,
5966
format: 'cjs',
67+
banner: {
68+
js: cjsBanner,
69+
},
70+
footer: {
71+
js: `return module.exports; })(typeof module === 'object' && module.exports ? module : { exports: {} });`,
72+
},
6073
outExtension: { '.js': '.cjs' },
61-
plugins: [
62-
importPath(/^@builder\.io\/qwik$/, '../core.cjs'),
63-
importPath(/^@builder\.io\/qwik\/optimizer$/, '../optimizer.cjs'),
64-
qwikDomPlugin,
65-
],
74+
plugins: [importPath(/^@builder\.io\/qwik$/, './core.cjs'), qwikDomPlugin],
6675
watch: watcher(config),
6776
platform: 'node',
6877
target: nodeTarget,
69-
inject: [injectGlobalThisPoly(config), injectGlobalPoly(config)],
78+
define: {
79+
...(await inlineQwikScriptsEsBuild(config)),
80+
'globalThis.IS_CJS': 'true',
81+
'globalThis.IS_ESM': 'false',
82+
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
83+
'globalThis.QWIK_DOM_VERSION': JSON.stringify(qwikDomVersion),
84+
},
7085
});
7186

7287
await Promise.all([esm, cjs]);
73-
await generateServerPackageJson(config);
7488

7589
console.log('🐰', submodule);
7690
}
7791

78-
async function generateServerPackageJson(config: BuildConfig) {
79-
const pkg: PackageJSON = {
80-
name: '@builder.io/qwik/server',
81-
version: config.distVersion,
82-
main: 'index.cjs',
83-
module: 'index.mjs',
84-
types: 'index.d.ts',
85-
private: true,
86-
};
87-
const serverDistDir = join(config.distPkgDir, 'server');
88-
await writePackageJson(serverDistDir, pkg);
89-
}
90-
9192
async function bundleQwikDom(config: BuildConfig) {
9293
const outfile = join(config.distDir, 'qwikdom.mjs');
9394

@@ -104,7 +105,7 @@ async function bundleQwikDom(config: BuildConfig) {
104105
await build(opts);
105106

106107
const qwikDomPlugin: Plugin = {
107-
name: 'domiqwikDomPluginnoPlugin',
108+
name: 'qwikDomPlugin',
108109
setup(build) {
109110
build.onResolve({ filter: /@builder.io\/qwik-dom/ }, () => {
110111
return {
@@ -117,9 +118,23 @@ async function bundleQwikDom(config: BuildConfig) {
117118
return qwikDomPlugin;
118119
}
119120

120-
async function getDominoVersion() {
121+
async function getQwikDomVersion() {
121122
const indexPath = require.resolve('@builder.io/qwik-dom');
122123
const pkgJsonPath = join(indexPath, '..', '..');
123124
const pkgJson = await readPackageJson(pkgJsonPath);
124125
return pkgJson.version;
125126
}
127+
128+
const browserCjsRequireShim = `
129+
if (typeof require !== 'function' && typeof location !== 'undefined' && typeof navigator !== 'undefined') {
130+
// shim cjs require() for core.cjs within a browser
131+
globalThis.require = function(path) {
132+
if (path === './core.cjs') {
133+
if (!self.qwikCore) {
134+
throw new Error('Qwik Core global, "globalThis.qwikCore", must already be loaded for the Qwik Server to be used within a browser.');
135+
}
136+
return self.qwikCore;
137+
}
138+
throw new Error('Unable to require() path "' + path + '" from a browser environment.');
139+
};
140+
}`;

0 commit comments

Comments
 (0)