Skip to content

Commit 4ded5bd

Browse files
committed
refactor: simplify build helpers
1 parent d6fbb61 commit 4ded5bd

7 files changed

Lines changed: 59 additions & 129 deletions

build.mjs

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,6 @@ const fail = (msg) => {
127127
process.exit(1);
128128
};
129129

130-
const bin = name => path.join(BIN_DIR, process.platform === 'win32' ? `${name}.cmd` : name);
131-
132130
const getTreeBuild = () => {
133131
const buildType = type ?? 'rel';
134132

@@ -151,14 +149,8 @@ const getTreeBuild = () => {
151149
return `build:${format}:${buildType}`;
152150
};
153151

154-
const runTreeBuild = (items) => {
155-
const env = items ? [...items] : [];
156-
if (!items) {
157-
const build = getTreeBuild();
158-
if (build) {
159-
env.push(build);
160-
}
161-
}
152+
const runTreeBuild = () => {
153+
const env = [getTreeBuild()];
162154
env.push(...trees);
163155

164156
const args = ['-c'];
@@ -172,7 +164,7 @@ const runTreeBuild = (items) => {
172164
args.push('-w', '--no-watch.clearScreen');
173165
}
174166

175-
return run(bin('rollup'), args);
167+
return run(path.join(BIN_DIR, process.platform === 'win32' ? 'rollup.cmd' : 'rollup'), args);
176168
};
177169

178170
const ms = (value) => {
@@ -183,12 +175,9 @@ const bold = (value) => {
183175
return COLORS ? `${BOLD}${value}${REGULAR}` : value;
184176
};
185177

186-
const color = (code, value) => {
187-
return COLORS ? `${code}${value}${RESET}` : value;
188-
};
189-
190178
const writeLog = (stream, code, value) => {
191-
stream.write(`${color(code, value)}\n`);
179+
const text = COLORS ? `${code}${value}${RESET}` : value;
180+
stream.write(`${text}\n`);
192181
};
193182

194183
const startLog = (input, output) => writeLog(process.stderr, CYAN, `${bold(input)}${bold(output)}...`);
@@ -207,14 +196,6 @@ const targetOutput = (buildType, moduleFormat) => {
207196
return moduleFormat === 'esm' && buildType !== 'min' ? `${file}, build/${prefix}/` : file;
208197
};
209198

210-
const includeJSTarget = (buildType, moduleFormat) => {
211-
if (type === 'types' || trees.length) {
212-
return false;
213-
}
214-
215-
return buildType === type && moduleFormat === format;
216-
};
217-
218199
const getJSTargets = () => {
219200
if (!hasType) {
220201
fail('--type is required');
@@ -240,7 +221,7 @@ const getJSTargets = () => {
240221
const targets = [];
241222
JS_TYPES.forEach((buildType) => {
242223
MODULE_FORMATS.forEach((moduleFormat) => {
243-
if (includeJSTarget(buildType, moduleFormat)) {
224+
if (type !== 'types' && !trees.length && buildType === type && moduleFormat === format) {
244225
targets.push({ buildType, moduleFormat });
245226
}
246227
});

utils/esbuild-build-target.mjs

Lines changed: 22 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import { parse } from 'acorn';
55
import { fileURLToPath } from 'node:url';
66

77
import { importValidationPlugin } from './plugins/esbuild-import-validation.mjs';
8-
import { applyTransforms, createStripTransform, transformPipelinePlugin } from './plugins/esbuild-transform-pipeline.mjs';
8+
import {
9+
applyTransforms,
10+
createStripTransform,
11+
transformPipelinePlugin
12+
} from './plugins/esbuild-transform-pipeline.mjs';
913
import { getBanner } from './rollup-get-banner.mjs';
1014
import { revision, version } from './rollup-version-revision.mjs';
1115

@@ -69,8 +73,6 @@ const PRUNABLE_IMPORTS = new Set([
6973
'validateUserChunks'
7074
]);
7175

72-
const toPosix = value => value.split(path.sep).join('/');
73-
7476
const compactIndent = code => code.replace(/^ +/gm, spaces => spaces.replace(/ {2}/g, '\t'));
7577

7678
const shouldCompactIndent = ({ buildType, sourcemaps }) => {
@@ -116,22 +118,18 @@ const getImportMetaUrl = (file) => {
116118
};
117119

118120
const getUmdBanner = (banner) => {
119-
return [
120-
banner,
121-
'(function (global, factory) {',
122-
'\ttypeof exports === \'object\' && typeof module !== \'undefined\' ? factory(exports) :',
123-
'\ttypeof define === \'function\' && define.amd ? define([\'exports\'], factory) :',
124-
'\t(global = typeof globalThis !== \'undefined\' ? globalThis : global || self, factory(global.pc = {}));',
125-
'})(this, (function (exports) { \'use strict\';',
126-
'\tvar _documentCurrentScript = typeof document !== \'undefined\' ? document.currentScript : null;'
127-
].join('\n');
121+
return `${banner}
122+
(function (global, factory) {
123+
\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
124+
\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :
125+
\t(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pc = {}));
126+
})(this, (function (exports) { 'use strict';
127+
\tvar _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;`;
128128
};
129129

130130
const getUmdFooter = () => {
131-
return [
132-
'Object.assign(exports, pc);',
133-
'}));'
134-
].join('\n');
131+
return `Object.assign(exports, pc);
132+
}));`;
135133
};
136134

137135
const getPlugins = ({
@@ -257,15 +255,6 @@ const watchBundled = async (options, startLog, log) => {
257255
return ctx;
258256
};
259257

260-
const resolveSource = (source, importer) => {
261-
if (!source.startsWith('.')) {
262-
return null;
263-
}
264-
265-
const resolved = path.resolve(path.dirname(importer), source);
266-
return path.extname(resolved) ? resolved : `${resolved}.js`;
267-
};
268-
269258
const collectIdentifiers = (node, used) => {
270259
if (!node || typeof node !== 'object' || node.type === 'ImportDeclaration') {
271260
return;
@@ -328,26 +317,22 @@ const collectImports = (source, file) => {
328317
continue;
329318
}
330319

331-
const resolved = resolveSource(name, file);
332-
if (resolved) {
333-
imports.push(resolved);
320+
if (name.startsWith('.')) {
321+
const resolved = path.resolve(path.dirname(file), name);
322+
imports.push(path.extname(resolved) ? resolved : `${resolved}.js`);
334323
}
335324
}
336325

337326
return imports.sort();
338327
};
339328

340-
const sameImports = (a, b) => {
341-
return a.length === b.length && a.every((value, i) => value === b[i]);
342-
};
343-
344329
const rewriteFflate = (source, file, input) => {
345330
if (!source.includes(`from '${FFLATE}'`) && !source.includes(`from "${FFLATE}"`)) {
346331
return source;
347332
}
348333

349334
const root = path.dirname(path.resolve(input));
350-
const rel = toPosix(path.relative(path.dirname(file), root));
335+
const rel = path.relative(path.dirname(file), root).split(path.sep).join('/');
351336
const modulePath = path.posix.join(rel, '..', 'modules', FFLATE, 'esm', 'browser.js');
352337

353338
return source.replace(/from ['"]fflate['"]/g, `from '${modulePath}'`);
@@ -551,7 +536,10 @@ const watchUnbundled = async (options, startLog, log) => {
551536

552537
const next = await transformFile(file, ctx);
553538
const prev = graph.get(file);
554-
if (!sameImports(prev.imports, next.imports)) {
539+
if (
540+
prev.imports.length !== next.imports.length ||
541+
!prev.imports.every((value, i) => value === next.imports[i])
542+
) {
555543
await fullBuild();
556544
return;
557545
}

utils/plugins/esbuild-dynamic.mjs

Lines changed: 0 additions & 17 deletions
This file was deleted.

utils/plugins/esbuild-jscc.mjs

Lines changed: 0 additions & 20 deletions
This file was deleted.

utils/plugins/esbuild-shader-chunks.mjs

Lines changed: 0 additions & 18 deletions
This file was deleted.

utils/plugins/esbuild-transform-pipeline.mjs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import fs from 'node:fs';
2+
import jscc from 'jscc';
23

3-
import { applyDynamicImportLegacy, applyDynamicImportSuppress } from './esbuild-dynamic.mjs';
4-
import { processJSCC } from './esbuild-jscc.mjs';
5-
import { processShaderChunks } from './esbuild-shader-chunks.mjs';
64
import { createStripTransform } from './esbuild-strip.mjs';
75

6+
const processJSCC = (source, values, keepLines) => {
7+
const result = jscc(source, null, {
8+
values,
9+
keepLines,
10+
sourceMap: false,
11+
prefixes: ['// ']
12+
});
13+
14+
return result.code;
15+
};
16+
17+
const processShaderChunks = (source) => {
18+
return source.replace(/\/\* *(glsl|wgsl) *\*\/\s*(`.*?`)/gs, (match, type, code) => {
19+
return code
20+
.trim()
21+
.replace(/\r/g, '')
22+
.replace(/ {4}/g, '\t')
23+
.replace(/[ \t]*\/\/.*/g, '')
24+
.replace(/[ \t]*\/\*[\s\S]*?\*\//g, '')
25+
.concat('\n')
26+
.replace(/\n{2,}/g, '\n');
27+
});
28+
};
29+
830
/**
931
* @param {string} source - The source code.
1032
* @param {object} options - The transform options.
@@ -43,10 +65,10 @@ const applyTransforms = (source, {
4365
source = source.replace(/import\.meta\.url/g, importMetaUrl);
4466
}
4567
if (dynamicImportLegacy) {
46-
source = applyDynamicImportLegacy(source);
68+
source = source.replace(/(\W)import\(/g, '$1new Function("modulePath", "return import(modulePath)")(');
4769
}
4870
if (dynamicImportSuppress) {
49-
source = applyDynamicImportSuppress(source);
71+
source = source.replace(/import\(([^'])/g, 'import(/* @vite-ignore */ /* webpackIgnore: true */ $1');
5072
}
5173

5274
return source;

utils/types-build-target.mjs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ const REQUIRED_TYPES = [
2020
'build/playcanvas/src/framework/script/script-type.d.ts'
2121
];
2222

23-
const bin = name => path.join(BIN_DIR, process.platform === 'win32' ? `${name}.cmd` : name);
24-
2523
const exists = (file) => {
2624
return fs.promises.stat(file).then(() => true, () => false);
2725
};
@@ -45,7 +43,8 @@ const latestTypesMtime = async (dir) => {
4543

4644
const runTsc = (root) => {
4745
return new Promise((resolve, reject) => {
48-
const child = spawn(bin('tsc'), ['--project', path.join(root, TSC_CONFIG)], {
46+
const cmd = path.join(BIN_DIR, process.platform === 'win32' ? 'tsc.cmd' : 'tsc');
47+
const child = spawn(cmd, ['--project', path.join(root, TSC_CONFIG)], {
4948
shell: process.platform === 'win32',
5049
stdio: 'inherit'
5150
});
@@ -60,16 +59,11 @@ const runTsc = (root) => {
6059
});
6160
};
6261

63-
const missingTypes = async (root) => {
62+
const emitTypes = async (root) => {
6463
const found = await Promise.all(REQUIRED_TYPES.map((file) => {
6564
return exists(path.join(root, file));
6665
}));
67-
68-
return found.some(value => !value);
69-
};
70-
71-
const emitTypes = async (root) => {
72-
if (await missingTypes(root)) {
66+
if (found.some(value => !value)) {
7367
await fs.promises.rm(path.join(root, TSC_INFO), { force: true });
7468
}
7569
await runTsc(root);

0 commit comments

Comments
 (0)