slicejs-cli 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +16 -2
- package/commands/build/build.js +18 -1
- package/commands/buildProduction/buildProduction.js +82 -81
- package/commands/types/types.js +116 -7
- package/commands/utils/JsMinifier.js +230 -0
- package/commands/utils/SourceDiagnostics.js +201 -0
- package/commands/utils/bundling/BundleGenerator.js +634 -63
- package/package.json +1 -1
|
@@ -4,7 +4,8 @@ import path from 'path';
|
|
|
4
4
|
import crypto from 'crypto';
|
|
5
5
|
import { parse } from '@babel/parser';
|
|
6
6
|
import traverse from '@babel/traverse';
|
|
7
|
-
import {
|
|
7
|
+
import { minifyJs, bundleOptions } from '../JsMinifier.js';
|
|
8
|
+
import { describeSyntaxError } from '../SourceDiagnostics.js';
|
|
8
9
|
import { getSrcPath, getComponentsJsPath, getDistPath, getConfigPath, getProjectRoot } from '../PathHelper.js';
|
|
9
10
|
import ExternalModuleBundler from './ExternalModuleBundler.js';
|
|
10
11
|
|
|
@@ -54,7 +55,12 @@ export default class BundleGenerator {
|
|
|
54
55
|
|
|
55
56
|
// When true, an unresolved node_modules dependency fails the build instead
|
|
56
57
|
// of warning + emitting an empty module. Driven by `slice build --strict-external`.
|
|
57
|
-
|
|
58
|
+
// Unresolved bare imports fail the build unless explicitly allowed. They
|
|
59
|
+
// used to only warn, and the warning said the components "will fail at
|
|
60
|
+
// runtime" — which is a build error described in prose. `--no-strict-external`
|
|
61
|
+
// keeps the old behaviour for the one legitimate case: a package provided
|
|
62
|
+
// some other way (a shim under src/public/).
|
|
63
|
+
this.strictExternal = options.strictExternal !== false;
|
|
58
64
|
|
|
59
65
|
// Bare-package (node_modules) import support is always on. Bare imports are
|
|
60
66
|
// resolved+bundled with esbuild (see ExternalModuleBundler) and registered
|
|
@@ -927,13 +933,19 @@ export default class BundleGenerator {
|
|
|
927
933
|
if (isExternal && !content) continue;
|
|
928
934
|
|
|
929
935
|
if (!routeDependencyIndex[bundleKey][depName]) {
|
|
930
|
-
routeDependencyIndex[bundleKey][depName] = {
|
|
936
|
+
routeDependencyIndex[bundleKey][depName] = {
|
|
937
|
+
content,
|
|
938
|
+
external: isExternal,
|
|
939
|
+
moduleImports: isExternal ? [] : (depEntry?.moduleImports || [])
|
|
940
|
+
};
|
|
931
941
|
}
|
|
932
942
|
if (!this.vendorShared.dependencyModules.has(depName)) {
|
|
943
|
+
const moduleImports = isExternal ? [] : (depEntry?.moduleImports || []);
|
|
933
944
|
this.vendorShared.dependencyModules.set(depName, {
|
|
934
945
|
name: depName,
|
|
935
946
|
content,
|
|
936
|
-
external: isExternal
|
|
947
|
+
external: isExternal,
|
|
948
|
+
moduleImports
|
|
937
949
|
});
|
|
938
950
|
}
|
|
939
951
|
}
|
|
@@ -954,7 +966,8 @@ export default class BundleGenerator {
|
|
|
954
966
|
bundleKeys: new Set(),
|
|
955
967
|
bundleCount: 0,
|
|
956
968
|
content: dependencyEntry?.content || '',
|
|
957
|
-
external: !!dependencyEntry?.external
|
|
969
|
+
external: !!dependencyEntry?.external,
|
|
970
|
+
moduleImports: dependencyEntry?.moduleImports || []
|
|
958
971
|
});
|
|
959
972
|
}
|
|
960
973
|
const entry = usage.get(dependencyName);
|
|
@@ -986,6 +999,61 @@ export default class BundleGenerator {
|
|
|
986
999
|
shared.add(dependencyName);
|
|
987
1000
|
}
|
|
988
1001
|
|
|
1002
|
+
this.expandSharedSetWithDependencyClosure(shared);
|
|
1003
|
+
|
|
1004
|
+
return shared;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* Grows the shared set to the full dependency closure of everything in it.
|
|
1009
|
+
*
|
|
1010
|
+
* The usage/size thresholds decide which modules are worth extracting, but
|
|
1011
|
+
* they must not decide the closure. A helper that clears
|
|
1012
|
+
* minVendorSharedTransformedSize is emitted into vendor-shared and omitted
|
|
1013
|
+
* from the route bundles; if a module it imports fell under the threshold, it
|
|
1014
|
+
* stayed inlined in the route bundles instead, and the helper's IIFE inside
|
|
1015
|
+
* vendor-shared bound a key vendor-shared never registered. Since
|
|
1016
|
+
* vendor-shared evaluates before anything renders, that surfaced as the whole
|
|
1017
|
+
* app failing to boot with `Cannot read properties of undefined`.
|
|
1018
|
+
*
|
|
1019
|
+
* Pulling a small module in is also the cheaper outcome: it stops being
|
|
1020
|
+
* duplicated across every route bundle that used it.
|
|
1021
|
+
*
|
|
1022
|
+
* Mutates `shared` in place, following moduleImports transitively and
|
|
1023
|
+
* tolerating cycles.
|
|
1024
|
+
*
|
|
1025
|
+
* @param {Set<string>} shared
|
|
1026
|
+
* @returns {Set<string>} the same set
|
|
1027
|
+
*/
|
|
1028
|
+
expandSharedSetWithDependencyClosure(shared) {
|
|
1029
|
+
const pending = Array.from(shared);
|
|
1030
|
+
const visited = new Set(pending);
|
|
1031
|
+
|
|
1032
|
+
while (pending.length > 0) {
|
|
1033
|
+
const dependencyName = pending.pop();
|
|
1034
|
+
const entry = this.vendorShared.dependencyModules.get(dependencyName)
|
|
1035
|
+
|| this.vendorShared.dependencyUsage.get(dependencyName);
|
|
1036
|
+
|
|
1037
|
+
for (const moduleImport of entry?.moduleImports || []) {
|
|
1038
|
+
const importedName = moduleImport?.depName;
|
|
1039
|
+
if (!importedName || visited.has(importedName)) continue;
|
|
1040
|
+
visited.add(importedName);
|
|
1041
|
+
|
|
1042
|
+
// Only modules the vendor-shared bundle can actually emit. Anything
|
|
1043
|
+
// unresolvable has no content to register, so adding it would omit it
|
|
1044
|
+
// from the route bundles and register nothing in its place — the very
|
|
1045
|
+
// failure this closure exists to prevent.
|
|
1046
|
+
const collected = this.vendorShared.dependencyModules.get(importedName);
|
|
1047
|
+
const emittable = collected?.external
|
|
1048
|
+
? !!this.externalModulesByName.get(importedName)
|
|
1049
|
+
: !!collected?.content;
|
|
1050
|
+
if (!emittable) continue;
|
|
1051
|
+
|
|
1052
|
+
shared.add(importedName);
|
|
1053
|
+
pending.push(importedName);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
|
|
989
1057
|
return shared;
|
|
990
1058
|
}
|
|
991
1059
|
|
|
@@ -1000,7 +1068,8 @@ export default class BundleGenerator {
|
|
|
1000
1068
|
// up by name in buildV2DependencyModuleBlockFromModules), so the flag
|
|
1001
1069
|
// must survive here.
|
|
1002
1070
|
const external = !!(usageEntry?.external || collectedEntry?.external);
|
|
1003
|
-
|
|
1071
|
+
const moduleImports = usageEntry?.moduleImports || collectedEntry?.moduleImports || [];
|
|
1072
|
+
return { name: dependencyName, content, external, moduleImports };
|
|
1004
1073
|
})
|
|
1005
1074
|
.filter((entry) => !!entry.content);
|
|
1006
1075
|
|
|
@@ -1079,34 +1148,18 @@ export default class BundleGenerator {
|
|
|
1079
1148
|
}
|
|
1080
1149
|
|
|
1081
1150
|
const wantMap = !!this.options.sourcemap;
|
|
1082
|
-
const
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
drop_console: false,
|
|
1089
|
-
drop_debugger: true,
|
|
1090
|
-
passes: 1
|
|
1091
|
-
} : false,
|
|
1092
|
-
mangle: this.options.obfuscate ? {
|
|
1093
|
-
properties: false
|
|
1094
|
-
} : false,
|
|
1095
|
-
keep_fnames: true,
|
|
1096
|
-
keep_classnames: true,
|
|
1097
|
-
format: {
|
|
1098
|
-
comments: false,
|
|
1099
|
-
ecma: 2022
|
|
1100
|
-
},
|
|
1101
|
-
// Map the minified output back to the readable pre-minified bundle
|
|
1102
|
-
// (embedded via includeSources so DevTools shows it without a sidecar
|
|
1103
|
-
// source). The URL comment is appended by the caller.
|
|
1104
|
-
...(wantMap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
|
|
1105
|
-
};
|
|
1151
|
+
const createOptions = () => bundleOptions({
|
|
1152
|
+
minify: this.options.minify,
|
|
1153
|
+
obfuscate: this.options.obfuscate,
|
|
1154
|
+
sourcemap: wantMap,
|
|
1155
|
+
fileName
|
|
1156
|
+
});
|
|
1106
1157
|
|
|
1107
1158
|
let result;
|
|
1108
1159
|
try {
|
|
1109
|
-
result
|
|
1160
|
+
// minifyJs normalizes a reported `result.error` into a throw, so both
|
|
1161
|
+
// failure shapes land here and the bundle is dumped once.
|
|
1162
|
+
result = await minifyJs(bundleContent, createOptions);
|
|
1110
1163
|
} catch (error) {
|
|
1111
1164
|
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1112
1165
|
const safeName = fileName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
@@ -1121,19 +1174,6 @@ export default class BundleGenerator {
|
|
|
1121
1174
|
throw new Error(`Terser failed for ${fileName}: ${message} Saved bundle to ${tmpPath}`);
|
|
1122
1175
|
}
|
|
1123
1176
|
|
|
1124
|
-
if (result.error) {
|
|
1125
|
-
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1126
|
-
const safeName = fileName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
1127
|
-
const tmpPath = path.join(tmpDir, `terser-fail-${safeName}`);
|
|
1128
|
-
try {
|
|
1129
|
-
await fs.ensureDir(tmpDir);
|
|
1130
|
-
await fs.writeFile(tmpPath, bundleContent, 'utf-8');
|
|
1131
|
-
} catch (writeError) {
|
|
1132
|
-
console.warn(`Warning: Failed to write ${tmpPath}:`, writeError.message);
|
|
1133
|
-
}
|
|
1134
|
-
throw new Error(`Terser failed for ${fileName}: ${result.error.message}. Saved bundle to ${tmpPath}`);
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
1177
|
return { code: result.code || bundleContent, map: wantMap ? (result.map || null) : null };
|
|
1138
1178
|
}
|
|
1139
1179
|
|
|
@@ -1157,6 +1197,7 @@ export default class BundleGenerator {
|
|
|
1157
1197
|
* @returns {Promise<{ file: string, path: string, hash: string, rawSize: number }>}
|
|
1158
1198
|
*/
|
|
1159
1199
|
async emitBundleArtifact(baseFileName, rawContent) {
|
|
1200
|
+
await this.validateGeneratedBundle(rawContent, baseFileName);
|
|
1160
1201
|
const { code, map } = await this.applyBundleTransforms(rawContent, baseFileName);
|
|
1161
1202
|
const fileName = this.hashBundleFileName(baseFileName, code);
|
|
1162
1203
|
let finalCode = code;
|
|
@@ -1174,6 +1215,134 @@ export default class BundleGenerator {
|
|
|
1174
1215
|
}
|
|
1175
1216
|
|
|
1176
1217
|
|
|
1218
|
+
/**
|
|
1219
|
+
* Asserts a generated bundle parses as an ES module, before it is transformed
|
|
1220
|
+
* or written.
|
|
1221
|
+
*
|
|
1222
|
+
* This is a guard on the generator's own output, not on user code. Every
|
|
1223
|
+
* bundler bug found so far had the same shape: valid source in, invalid
|
|
1224
|
+
* JavaScript out, and nothing checking. Terser used to be the accidental
|
|
1225
|
+
* gatekeeper, which made for two bad failure modes — its error named the
|
|
1226
|
+
* generated file instead of the source, and with `--minify` off
|
|
1227
|
+
* applyBundleTransforms returns early, so the broken bundle was written
|
|
1228
|
+
* silently and only failed once a browser tried to parse it.
|
|
1229
|
+
*
|
|
1230
|
+
* Runs unconditionally for that reason: the check is worth more precisely when
|
|
1231
|
+
* minification is off.
|
|
1232
|
+
*
|
|
1233
|
+
* @param {string} bundleContent
|
|
1234
|
+
* @param {string} fileName
|
|
1235
|
+
* @returns {Promise<void>}
|
|
1236
|
+
* @throws {Error} naming the bundle, the source it came from, and a saved copy
|
|
1237
|
+
*/
|
|
1238
|
+
async validateGeneratedBundle(bundleContent, fileName) {
|
|
1239
|
+
try {
|
|
1240
|
+
parse(bundleContent, { sourceType: 'module', plugins: ['jsx'] });
|
|
1241
|
+
return;
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
const position = typeof error.pos === 'number' ? error.pos : 0;
|
|
1244
|
+
const owner = this.describeBundleOwner(bundleContent, position);
|
|
1245
|
+
const savedPath = await this.saveFailedBundle(bundleContent, fileName, 'invalid-bundle');
|
|
1246
|
+
|
|
1247
|
+
const where = owner ? ` The invalid code comes from ${owner}.` : '';
|
|
1248
|
+
const detail = error.message || 'unknown parse error';
|
|
1249
|
+
throw new Error(
|
|
1250
|
+
`Generated bundle "${fileName}" is not valid JavaScript: ${detail}.${where}`
|
|
1251
|
+
+ ` This is a bundler bug, not a problem with your source. Saved bundle to ${savedPath}`
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* Writes a bundle that could not be processed to `.tmp/` so it can be read.
|
|
1258
|
+
* @param {string} bundleContent
|
|
1259
|
+
* @param {string} fileName
|
|
1260
|
+
* @param {string} prefix
|
|
1261
|
+
* @returns {Promise<string>} the path written (or attempted)
|
|
1262
|
+
*/
|
|
1263
|
+
async saveFailedBundle(bundleContent, fileName, prefix) {
|
|
1264
|
+
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1265
|
+
const safeName = String(fileName).replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
1266
|
+
const tmpPath = path.join(tmpDir, `${prefix}-${safeName}`);
|
|
1267
|
+
try {
|
|
1268
|
+
await fs.ensureDir(tmpDir);
|
|
1269
|
+
await fs.writeFile(tmpPath, bundleContent, 'utf-8');
|
|
1270
|
+
} catch (writeError) {
|
|
1271
|
+
console.warn(`Warning: Failed to write ${tmpPath}:`, writeError.message);
|
|
1272
|
+
}
|
|
1273
|
+
return tmpPath;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* Maps an offset in a generated bundle back to whatever produced that region:
|
|
1278
|
+
* a component's class factory, or a dependency module's IIFE. Turns "bundle X
|
|
1279
|
+
* is broken" into "component Y emitted invalid code", which is the difference
|
|
1280
|
+
* between a usable error and a scavenger hunt.
|
|
1281
|
+
*
|
|
1282
|
+
* @param {string} bundleContent
|
|
1283
|
+
* @param {number} position
|
|
1284
|
+
* @returns {string|null}
|
|
1285
|
+
*/
|
|
1286
|
+
describeBundleOwner(bundleContent, position) {
|
|
1287
|
+
const regions = [];
|
|
1288
|
+
|
|
1289
|
+
// Dependency modules: `const __sliceDepExportsN = (() => {` ... then
|
|
1290
|
+
// `SLICE_BUNDLE_DEPENDENCIES["key"] = __sliceDepExportsN;` closes it, which
|
|
1291
|
+
// is also where the key becomes known.
|
|
1292
|
+
const depAssignment = /SLICE_BUNDLE_DEPENDENCIES\[("(?:[^"\\]|\\.)*")\]\s*=\s*(__sliceDepExports\d+)\s*;/g;
|
|
1293
|
+
for (let match = depAssignment.exec(bundleContent); match; match = depAssignment.exec(bundleContent)) {
|
|
1294
|
+
const [, quotedKey, exportVar] = match;
|
|
1295
|
+
const openIndex = bundleContent.indexOf(`const ${exportVar} = (() => {`);
|
|
1296
|
+
if (openIndex === -1) continue;
|
|
1297
|
+
let key = quotedKey;
|
|
1298
|
+
try { key = JSON.parse(quotedKey); } catch { /* keep the raw form */ }
|
|
1299
|
+
regions.push({ start: openIndex, end: match.index + match[0].length, label: `dependency "${key}"` });
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
// Component factories: from `const SLICE_CLASS_FACTORY_x = ` up to the next
|
|
1303
|
+
// factory or the template declarations that follow the whole block.
|
|
1304
|
+
const factoryStarts = [];
|
|
1305
|
+
const factory = /const (SLICE_CLASS_FACTORY_\S+) = \(\) => \{/g;
|
|
1306
|
+
for (let match = factory.exec(bundleContent); match; match = factory.exec(bundleContent)) {
|
|
1307
|
+
factoryStarts.push({ start: match.index, identifier: match[1] });
|
|
1308
|
+
}
|
|
1309
|
+
for (const [index, entry] of factoryStarts.entries()) {
|
|
1310
|
+
const next = factoryStarts[index + 1]?.start;
|
|
1311
|
+
const templates = bundleContent.indexOf('const __templateElement_', entry.start);
|
|
1312
|
+
const candidates = [next, templates === -1 ? undefined : templates, bundleContent.length]
|
|
1313
|
+
.filter((value) => typeof value === 'number');
|
|
1314
|
+
regions.push({
|
|
1315
|
+
start: entry.start,
|
|
1316
|
+
end: Math.min(...candidates),
|
|
1317
|
+
label: `component "${this.componentNameFromFactory(entry.identifier)}"`
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// Innermost match wins, so a dependency IIFE nested in a factory is named
|
|
1322
|
+
// rather than the factory around it.
|
|
1323
|
+
const containing = regions
|
|
1324
|
+
.filter((region) => position >= region.start && position <= region.end)
|
|
1325
|
+
.sort((a, b) => (a.end - a.start) - (b.end - b.start));
|
|
1326
|
+
|
|
1327
|
+
return containing[0]?.label || null;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* Reverses toSafeIdentifier() so an error can name the component as the
|
|
1332
|
+
* developer wrote it. The encoding is injective, so this is exact.
|
|
1333
|
+
* @param {string} factoryIdentifier
|
|
1334
|
+
* @returns {string}
|
|
1335
|
+
*/
|
|
1336
|
+
componentNameFromFactory(factoryIdentifier) {
|
|
1337
|
+
const encoded = String(factoryIdentifier)
|
|
1338
|
+
.replace(/^SLICE_CLASS_FACTORY_/, '')
|
|
1339
|
+
.replace(/^SliceComponent_/, '');
|
|
1340
|
+
return encoded.replace(/_([0-9a-f]+)_/g, (match, hex) => {
|
|
1341
|
+
const codePoint = Number.parseInt(hex, 16);
|
|
1342
|
+
return Number.isFinite(codePoint) ? String.fromCharCode(codePoint) : match;
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1177
1346
|
/**
|
|
1178
1347
|
* Bare-package (node_modules) imports are always resolved and bundled — no
|
|
1179
1348
|
* configuration needed, mirroring how a React/Vite project imports npm
|
|
@@ -1382,7 +1551,7 @@ export default class BundleGenerator {
|
|
|
1382
1551
|
}
|
|
1383
1552
|
// Follow relative helper modules so packages imported only by a helper
|
|
1384
1553
|
// are discovered too.
|
|
1385
|
-
for (const dep of this.analyzeDependencies(code, path.dirname(filePath))) {
|
|
1554
|
+
for (const dep of this.analyzeDependencies(code, path.dirname(filePath), filePath)) {
|
|
1386
1555
|
await walk(dep.path);
|
|
1387
1556
|
}
|
|
1388
1557
|
};
|
|
@@ -1429,13 +1598,15 @@ export default class BundleGenerator {
|
|
|
1429
1598
|
}
|
|
1430
1599
|
}
|
|
1431
1600
|
|
|
1432
|
-
//
|
|
1433
|
-
//
|
|
1601
|
+
// A package that cannot be resolved is emitted as an empty namespace, so
|
|
1602
|
+
// every binding from it is undefined — a guaranteed runtime failure. Fail
|
|
1603
|
+
// here instead, unless the caller opted out.
|
|
1434
1604
|
if (this.strictExternal && this.externalResolutionErrors.size > 0) {
|
|
1435
1605
|
const names = Array.from(this.externalResolutionErrors.keys()).sort().join(', ');
|
|
1436
1606
|
throw new Error(
|
|
1437
|
-
|
|
1438
|
-
|
|
1607
|
+
`${this.externalResolutionErrors.size} package(s) could not be resolved from node_modules: ${names}. `
|
|
1608
|
+
+ 'Install them, remove the imports, or pass --no-strict-external if they are provided '
|
|
1609
|
+
+ 'another way (a shim under src/public/).'
|
|
1439
1610
|
);
|
|
1440
1611
|
}
|
|
1441
1612
|
}
|
|
@@ -1443,8 +1614,17 @@ export default class BundleGenerator {
|
|
|
1443
1614
|
/**
|
|
1444
1615
|
* Analyzes dependencies of a JavaScript file using simple regex
|
|
1445
1616
|
*/
|
|
1446
|
-
|
|
1617
|
+
/**
|
|
1618
|
+
* Extensions resolveImportPath() will try. A relative import of one of these
|
|
1619
|
+
* (or of nothing, meaning extensionless) points at a JavaScript module that is
|
|
1620
|
+
* expected to exist in the repo — so failing to resolve it is a typo, not a
|
|
1621
|
+
* supported pattern. Anything else (an asset, say) is left alone.
|
|
1622
|
+
*/
|
|
1623
|
+
static RESOLVABLE_MODULE_EXTENSIONS = ['.js', '.json', '.mjs'];
|
|
1624
|
+
|
|
1625
|
+
analyzeDependencies(jsContent, componentPath, sourceFile = null) {
|
|
1447
1626
|
const dependencies = [];
|
|
1627
|
+
const unresolved = [];
|
|
1448
1628
|
|
|
1449
1629
|
const resolveImportPath = (importPath) => {
|
|
1450
1630
|
const resolvedPath = path.resolve(componentPath, importPath);
|
|
@@ -1478,6 +1658,7 @@ export default class BundleGenerator {
|
|
|
1478
1658
|
|
|
1479
1659
|
const resolvedPath = resolveImportPath(importPath);
|
|
1480
1660
|
if (!resolvedPath) {
|
|
1661
|
+
unresolved.push(importPath);
|
|
1481
1662
|
return;
|
|
1482
1663
|
}
|
|
1483
1664
|
|
|
@@ -1525,6 +1706,7 @@ export default class BundleGenerator {
|
|
|
1525
1706
|
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1526
1707
|
const resolvedPath = resolveImportPath(src);
|
|
1527
1708
|
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1709
|
+
else unresolved.push(src);
|
|
1528
1710
|
},
|
|
1529
1711
|
|
|
1530
1712
|
ExportAllDeclaration(pathNode) {
|
|
@@ -1532,15 +1714,55 @@ export default class BundleGenerator {
|
|
|
1532
1714
|
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1533
1715
|
const resolvedPath = resolveImportPath(src);
|
|
1534
1716
|
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1717
|
+
else unresolved.push(src);
|
|
1535
1718
|
}
|
|
1536
1719
|
});
|
|
1537
1720
|
} catch (error) {
|
|
1538
1721
|
console.warn(`Warning: Could not analyze dependencies for ${componentPath}:`, error.message);
|
|
1539
1722
|
}
|
|
1540
1723
|
|
|
1724
|
+
this.assertRelativeImportsResolve(unresolved, componentPath, sourceFile);
|
|
1725
|
+
|
|
1541
1726
|
return dependencies;
|
|
1542
1727
|
}
|
|
1543
1728
|
|
|
1729
|
+
/**
|
|
1730
|
+
* Fails the build on a relative import that points at nothing.
|
|
1731
|
+
*
|
|
1732
|
+
* These used to be dropped silently: `import { x } from './typo.js'` produced
|
|
1733
|
+
* a bundle where `x` was simply undefined, with no warning at build time and
|
|
1734
|
+
* no clue at runtime. A relative specifier names a file in the repo, so an
|
|
1735
|
+
* unresolved one is a typo or a deleted file — there is no legitimate "it will
|
|
1736
|
+
* be provided some other way" story, unlike a bare package (which
|
|
1737
|
+
* --strict-external governs, and which can be shimmed from src/public/).
|
|
1738
|
+
*
|
|
1739
|
+
* Only specifiers that name a JavaScript module are enforced: an extensionless
|
|
1740
|
+
* one, or .js/.json/.mjs. A relative asset import is left alone.
|
|
1741
|
+
*
|
|
1742
|
+
* @param {string[]} specifiers
|
|
1743
|
+
* @param {string} componentPath directory the import was resolved against
|
|
1744
|
+
* @param {string|null} sourceFile importing file, when the caller knows it
|
|
1745
|
+
* @throws {Error} listing every unresolved specifier
|
|
1746
|
+
*/
|
|
1747
|
+
assertRelativeImportsResolve(specifiers, componentPath, sourceFile = null) {
|
|
1748
|
+
const moduleLike = specifiers.filter((specifier) => {
|
|
1749
|
+
const ext = path.extname(specifier);
|
|
1750
|
+
return ext === '' || BundleGenerator.RESOLVABLE_MODULE_EXTENSIONS.includes(ext);
|
|
1751
|
+
});
|
|
1752
|
+
if (moduleLike.length === 0) return;
|
|
1753
|
+
|
|
1754
|
+
const where = sourceFile || componentPath;
|
|
1755
|
+
const details = moduleLike
|
|
1756
|
+
.map((specifier) => ` "${specifier}" -> ${path.resolve(componentPath, specifier)}`)
|
|
1757
|
+
.join('\n');
|
|
1758
|
+
|
|
1759
|
+
throw new Error(
|
|
1760
|
+
`Cannot resolve ${moduleLike.length} import(s) in ${where}:\n${details}\n`
|
|
1761
|
+
+ `Checked those paths plus ${BundleGenerator.RESOLVABLE_MODULE_EXTENSIONS.join(', ')} for extensionless specifiers. `
|
|
1762
|
+
+ 'Fix the path or create the file — an unresolved relative import silently becomes `undefined` at runtime.'
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1544
1766
|
/**
|
|
1545
1767
|
* Generates the content of a bundle
|
|
1546
1768
|
*/
|
|
@@ -1580,6 +1802,7 @@ export default class BundleGenerator {
|
|
|
1580
1802
|
categoryType: comp.categoryType,
|
|
1581
1803
|
js: cleanedJavaScript.code,
|
|
1582
1804
|
hoistedImports: cleanedJavaScript.hoistedImports,
|
|
1805
|
+
hasTopLevelAwait: cleanedJavaScript.hasTopLevelAwait,
|
|
1583
1806
|
html: htmlContent,
|
|
1584
1807
|
css: cssContent,
|
|
1585
1808
|
externalDependencies,
|
|
@@ -1649,11 +1872,17 @@ export default class BundleGenerator {
|
|
|
1649
1872
|
});
|
|
1650
1873
|
const body = component.js && component.js.trim()
|
|
1651
1874
|
? component.js
|
|
1652
|
-
: `
|
|
1875
|
+
// Bracket-keyed: a registered name like `my-btn` is a valid key but
|
|
1876
|
+
// not a valid identifier.
|
|
1877
|
+
: `return window[${JSON.stringify(component.name)}];`;
|
|
1653
1878
|
const bodyWithBindings = dependencyBindings
|
|
1654
1879
|
? `${dependencyBindings}\n${body}`
|
|
1655
1880
|
: body;
|
|
1656
|
-
|
|
1881
|
+
// A component module may legitimately use top-level await. Its code ends
|
|
1882
|
+
// up inside this factory, so the factory has to be async for that to be
|
|
1883
|
+
// valid — and only then, to keep every other bundle byte-identical.
|
|
1884
|
+
const arrow = component.hasTopLevelAwait ? 'async () =>' : '() =>';
|
|
1885
|
+
return `const ${factoryName} = ${arrow} {\n${this.indentCodeBlock(bodyWithBindings, 2)}\n};`;
|
|
1657
1886
|
})
|
|
1658
1887
|
.join('\n\n');
|
|
1659
1888
|
|
|
@@ -1667,7 +1896,13 @@ export default class BundleGenerator {
|
|
|
1667
1896
|
const classRegistrations = uniqueComponents
|
|
1668
1897
|
.map((component) => {
|
|
1669
1898
|
const componentName = JSON.stringify(component.name);
|
|
1670
|
-
|
|
1899
|
+
// An async factory returns a promise; registerAll is already async and
|
|
1900
|
+
// the framework awaits it (Controller.loadBundleWithDependencies), so
|
|
1901
|
+
// awaiting here keeps `classes` holding the class itself, never a promise.
|
|
1902
|
+
const call = component.hasTopLevelAwait
|
|
1903
|
+
? `await ${this.classFactoryName(component.name)}()`
|
|
1904
|
+
: `${this.classFactoryName(component.name)}()`;
|
|
1905
|
+
return ` if (!controller.classes.has(${componentName})) {\n controller.classes.set(${componentName}, ${call});\n }`;
|
|
1671
1906
|
})
|
|
1672
1907
|
.join('\n');
|
|
1673
1908
|
|
|
@@ -1717,11 +1952,15 @@ export default class BundleGenerator {
|
|
|
1717
1952
|
const omittedDependencies = options.omittedDependencies instanceof Set
|
|
1718
1953
|
? options.omittedDependencies
|
|
1719
1954
|
: new Set(options.omittedDependencies || []);
|
|
1955
|
+
const emittedModules = modules.filter((module) => !omittedDependencies.has(module.name));
|
|
1956
|
+
|
|
1957
|
+
// A cycle has no topological order, and this emission strategy cannot
|
|
1958
|
+
// reproduce ESM's live bindings, so it must be reported rather than emitted.
|
|
1959
|
+
this.assertNoDependencyCycles(emittedModules);
|
|
1960
|
+
|
|
1720
1961
|
// Emit in topological order so a module is registered before any module
|
|
1721
1962
|
// that depends on it (its transitive imports resolve at IIFE-eval time).
|
|
1722
|
-
const filteredModules = this.sortDependencyModulesTopologically(
|
|
1723
|
-
modules.filter((module) => !omittedDependencies.has(module.name))
|
|
1724
|
-
);
|
|
1963
|
+
const filteredModules = this.sortDependencyModulesTopologically(emittedModules);
|
|
1725
1964
|
|
|
1726
1965
|
const lines = [
|
|
1727
1966
|
'const SLICE_BUNDLE_DEPENDENCIES = {};',
|
|
@@ -1799,6 +2038,83 @@ export default class BundleGenerator {
|
|
|
1799
2038
|
return lines.join('\n');
|
|
1800
2039
|
}
|
|
1801
2040
|
|
|
2041
|
+
/**
|
|
2042
|
+
* Fails the build when the helper modules about to be emitted import each
|
|
2043
|
+
* other in a cycle.
|
|
2044
|
+
*
|
|
2045
|
+
* Each dependency is emitted as an eagerly-evaluated IIFE, and its imports are
|
|
2046
|
+
* bound by *copying* values out of the modules registered before it
|
|
2047
|
+
* (`const B = SLICE_BUNDLE_DEPENDENCIES["b.js"].B`). That is sound for a DAG,
|
|
2048
|
+
* emitted in topological order. A cycle has no such order: whichever module
|
|
2049
|
+
* runs first copies from an object that is not populated yet.
|
|
2050
|
+
*
|
|
2051
|
+
* There is no safe way to paper over this. Registering the exports objects up
|
|
2052
|
+
* front would stop the crash, but the copied binding would stay `undefined`
|
|
2053
|
+
* forever — trading a loud failure for a silent wrong value, which is worse.
|
|
2054
|
+
* Reproducing ESM's live bindings would mean rewriting every reference into a
|
|
2055
|
+
* member access, with full scope analysis.
|
|
2056
|
+
*
|
|
2057
|
+
* Cycles work in `slice dev`, where each file is a real ES module, so this has
|
|
2058
|
+
* to be reported at build time or it becomes a dev/production divergence.
|
|
2059
|
+
*
|
|
2060
|
+
* @param {Array<{name: string, moduleImports?: Array<{depName: string}>}>} modules
|
|
2061
|
+
* @throws {Error} naming the modules in the cycle
|
|
2062
|
+
*/
|
|
2063
|
+
assertNoDependencyCycles(modules = []) {
|
|
2064
|
+
const cycle = this.findDependencyCycle(modules);
|
|
2065
|
+
if (!cycle) return;
|
|
2066
|
+
|
|
2067
|
+
throw new Error(
|
|
2068
|
+
`Circular import between bundled modules: ${cycle.join(' -> ')}. `
|
|
2069
|
+
+ 'Bundled helper modules are evaluated in dependency order and cannot reproduce '
|
|
2070
|
+
+ "ES module live bindings, so whichever module runs first would read the other's "
|
|
2071
|
+
+ 'exports before they exist. This works in `slice dev` (real ES modules) but not in a build. '
|
|
2072
|
+
+ 'Break the cycle — usually by moving what both files share into a third module they each import.'
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
/**
|
|
2077
|
+
* Finds one import cycle, if any, and returns it as a readable path.
|
|
2078
|
+
* @param {Array<object>} modules
|
|
2079
|
+
* @returns {string[]|null} e.g. ['a.js', 'b.js', 'a.js']
|
|
2080
|
+
*/
|
|
2081
|
+
findDependencyCycle(modules = []) {
|
|
2082
|
+
const byName = new Map(modules.map((module) => [module.name, module]));
|
|
2083
|
+
const visited = new Set();
|
|
2084
|
+
const stack = [];
|
|
2085
|
+
const onStack = new Set();
|
|
2086
|
+
|
|
2087
|
+
const walk = (module) => {
|
|
2088
|
+
if (visited.has(module.name)) return null;
|
|
2089
|
+
|
|
2090
|
+
stack.push(module.name);
|
|
2091
|
+
onStack.add(module.name);
|
|
2092
|
+
|
|
2093
|
+
for (const imported of module.moduleImports || []) {
|
|
2094
|
+
const next = byName.get(imported?.depName);
|
|
2095
|
+
if (!next) continue;
|
|
2096
|
+
|
|
2097
|
+
if (onStack.has(next.name)) {
|
|
2098
|
+
// Report from the first occurrence so the path reads as a loop.
|
|
2099
|
+
return [...stack.slice(stack.indexOf(next.name)), next.name];
|
|
2100
|
+
}
|
|
2101
|
+
const found = walk(next);
|
|
2102
|
+
if (found) return found;
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
onStack.delete(module.name);
|
|
2106
|
+
stack.pop();
|
|
2107
|
+
visited.add(module.name);
|
|
2108
|
+
return null;
|
|
2109
|
+
};
|
|
2110
|
+
|
|
2111
|
+
for (const module of modules) {
|
|
2112
|
+
const found = walk(module);
|
|
2113
|
+
if (found) return found;
|
|
2114
|
+
}
|
|
2115
|
+
return null;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
1802
2118
|
sortDependencyModulesTopologically(modules = []) {
|
|
1803
2119
|
const byName = new Map(modules.map((module) => [module.name, module]));
|
|
1804
2120
|
const visited = new Set();
|
|
@@ -1885,9 +2201,57 @@ export default class BundleGenerator {
|
|
|
1885
2201
|
/**
|
|
1886
2202
|
* Cleans JavaScript code by removing imports/exports and ensuring class is available globally
|
|
1887
2203
|
*/
|
|
2204
|
+
/**
|
|
2205
|
+
* Fails the build on a component whose source is not valid JavaScript, before
|
|
2206
|
+
* anything tries to transform it.
|
|
2207
|
+
*
|
|
2208
|
+
* Without this the broken source flowed through every transform (each of which
|
|
2209
|
+
* silently falls back to a regex when it cannot parse) and into the bundle,
|
|
2210
|
+
* where the generated-bundle validation reported a position in the *generated*
|
|
2211
|
+
* file and said "this is a bundler bug" — actively misleading when the mistake
|
|
2212
|
+
* is a missing brace in the developer's own component. The real position was
|
|
2213
|
+
* only ever visible in warnings nobody reads.
|
|
2214
|
+
*
|
|
2215
|
+
* @param {string} code
|
|
2216
|
+
* @param {string} componentName
|
|
2217
|
+
* @param {string} sourceContext file path shown in the error
|
|
2218
|
+
* @throws {Error} with the file, line, column and a source frame
|
|
2219
|
+
*/
|
|
2220
|
+
assertComponentSourceParses(code, componentName, sourceContext) {
|
|
2221
|
+
const diagnosis = describeSyntaxError(code, sourceContext);
|
|
2222
|
+
if (diagnosis.ok) return;
|
|
2223
|
+
|
|
2224
|
+
throw new Error(
|
|
2225
|
+
`Syntax error in component "${componentName}" at ${diagnosis.message}`
|
|
2226
|
+
+ '\nFix the source above — the build cannot bundle a file it cannot parse.'
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
|
|
1888
2230
|
cleanJavaScript(code, componentName, sourceContext = componentName) {
|
|
1889
|
-
//
|
|
1890
|
-
|
|
2231
|
+
// Before any transform: a file that does not parse cannot be bundled, and
|
|
2232
|
+
// every downstream step degrades to regex fallbacks that hide the real cause.
|
|
2233
|
+
this.assertComponentSourceParses(code, componentName, sourceContext);
|
|
2234
|
+
|
|
2235
|
+
// Detect this on the pristine source: the transforms below append a
|
|
2236
|
+
// top-level `return`, after which the code no longer parses as a module.
|
|
2237
|
+
const hasTopLevelAwait = this.hasModuleTopLevelAwait(code);
|
|
2238
|
+
|
|
2239
|
+
// Resolve what the module actually default-exports, while the source is
|
|
2240
|
+
// still pristine. The factory has to return *that* binding: a component's
|
|
2241
|
+
// registered name and its class name need not match, and the registered name
|
|
2242
|
+
// may not even be a legal identifier (`my-btn`).
|
|
2243
|
+
const defaultExport = this.resolveDefaultExportBinding(code, componentName, sourceContext);
|
|
2244
|
+
|
|
2245
|
+
// Drop module-level `export` keywords before anything else, while the
|
|
2246
|
+
// source is still pristine enough to parse as a module.
|
|
2247
|
+
code = this.stripModuleExports(code, sourceContext);
|
|
2248
|
+
|
|
2249
|
+
// Remove export default. An anonymous one (`export default class {}`) has no
|
|
2250
|
+
// binding to return, so give it one instead of leaving a bare class
|
|
2251
|
+
// expression, which is not a valid statement.
|
|
2252
|
+
code = defaultExport.anonymous
|
|
2253
|
+
? code.replace(/export\s+default\s+/, `const ${defaultExport.name} = `)
|
|
2254
|
+
: code.replace(/export\s+default\s+/g, '');
|
|
1891
2255
|
|
|
1892
2256
|
// Remove only unsupported imports (relative always removed, allowed absolute kept)
|
|
1893
2257
|
const stripped = this.stripImports(code, {
|
|
@@ -1914,11 +2278,16 @@ export default class BundleGenerator {
|
|
|
1914
2278
|
}
|
|
1915
2279
|
);
|
|
1916
2280
|
|
|
1917
|
-
// Make sure the class is available globally for bundle evaluation
|
|
2281
|
+
// Make sure the class is available globally for bundle evaluation.
|
|
2282
|
+
// Keyed by component name as a *string*: a registered name like `my-btn` is
|
|
2283
|
+
// a perfectly good key but not a valid identifier, so `window.my-btn = ...`
|
|
2284
|
+
// would be a syntax error.
|
|
2285
|
+
const globalKey = `window[${JSON.stringify(componentName)}]`;
|
|
2286
|
+
|
|
1918
2287
|
// Preserve original customElements.define if it exists
|
|
1919
2288
|
if (code.includes('customElements.define')) {
|
|
1920
2289
|
// Add global assignment before guarded or direct customElements.define
|
|
1921
|
-
const globalAssignment =
|
|
2290
|
+
const globalAssignment = `${globalKey} = ${defaultExport.name};\n`;
|
|
1922
2291
|
const guardedDefineRegex = /if\s*\(\s*!\s*customElements\.get\([^)]*\)\s*\)\s*\{\s*customElements\.define\([^;]+\);?\s*\}\s*$/;
|
|
1923
2292
|
const directDefineRegex = /customElements\.define\([^;]+\);?\s*$/;
|
|
1924
2293
|
if (guardedDefineRegex.test(code)) {
|
|
@@ -1928,18 +2297,109 @@ export default class BundleGenerator {
|
|
|
1928
2297
|
}
|
|
1929
2298
|
} else {
|
|
1930
2299
|
// If no customElements.define found, just assign to global
|
|
1931
|
-
code += `\
|
|
2300
|
+
code += `\n${globalKey} = ${defaultExport.name};`;
|
|
1932
2301
|
}
|
|
1933
2302
|
|
|
1934
2303
|
// Add return statement for bundle evaluation compatibility
|
|
1935
|
-
code += `\nreturn ${
|
|
2304
|
+
code += `\nreturn ${defaultExport.name};`;
|
|
1936
2305
|
|
|
1937
2306
|
return {
|
|
1938
2307
|
code,
|
|
1939
|
-
hoistedImports
|
|
2308
|
+
hoistedImports,
|
|
2309
|
+
hasTopLevelAwait
|
|
1940
2310
|
};
|
|
1941
2311
|
}
|
|
1942
2312
|
|
|
2313
|
+
/**
|
|
2314
|
+
* Works out which binding a component module default-exports.
|
|
2315
|
+
*
|
|
2316
|
+
* The bundle wraps the component's code in a factory that has to end with
|
|
2317
|
+
* `return <the class>`, and register it on `window` for bundle evaluation.
|
|
2318
|
+
* Both used to be written as the *component name*, which assumed two things
|
|
2319
|
+
* that are not true: that the registered name matches the class name, and that
|
|
2320
|
+
* it is a valid JavaScript identifier. A component registered as `my-btn`
|
|
2321
|
+
* produced `window.my-btn = my-btn; return my-btn;` — a syntax error.
|
|
2322
|
+
*
|
|
2323
|
+
* A component with no default export is a source error, not a bundler one:
|
|
2324
|
+
* the runtime loads components with `const { default: myClass } = await
|
|
2325
|
+
* import(...)` (Slice.getClass), so such a component could never be built at
|
|
2326
|
+
* all. It fails the build here, with the file named and the fix spelled out,
|
|
2327
|
+
* rather than emitting a bundle that dies later.
|
|
2328
|
+
*
|
|
2329
|
+
* @param {string} code component source, before any transform
|
|
2330
|
+
* @param {string} componentName registered name
|
|
2331
|
+
* @param {string} sourceContext path, used in the error
|
|
2332
|
+
* @returns {{name: string, anonymous: boolean}}
|
|
2333
|
+
* @throws {Error} when the module has no default export
|
|
2334
|
+
*/
|
|
2335
|
+
resolveDefaultExportBinding(code, componentName, sourceContext) {
|
|
2336
|
+
const anonymousBinding = `__sliceComponent_${this.toSafeIdentifier(componentName)}`;
|
|
2337
|
+
|
|
2338
|
+
let ast;
|
|
2339
|
+
try {
|
|
2340
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
2341
|
+
} catch (error) {
|
|
2342
|
+
// Unparseable source. Don't guess a binding — the generated bundle is
|
|
2343
|
+
// validated before it is written, and that reports the real problem.
|
|
2344
|
+
return { name: anonymousBinding, anonymous: false };
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
for (const node of ast.program.body) {
|
|
2348
|
+
if (node.type !== 'ExportDefaultDeclaration') continue;
|
|
2349
|
+
const declaration = node.declaration;
|
|
2350
|
+
|
|
2351
|
+
if ((declaration.type === 'ClassDeclaration' || declaration.type === 'FunctionDeclaration')
|
|
2352
|
+
&& declaration.id?.name) {
|
|
2353
|
+
return { name: declaration.id.name, anonymous: false };
|
|
2354
|
+
}
|
|
2355
|
+
if (declaration.type === 'Identifier') {
|
|
2356
|
+
return { name: declaration.name, anonymous: false };
|
|
2357
|
+
}
|
|
2358
|
+
// `export default class {}`, `export default function () {}`, or any
|
|
2359
|
+
// expression: nothing to reference, so bind it on the way out.
|
|
2360
|
+
return { name: anonymousBinding, anonymous: true };
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
throw new Error(
|
|
2364
|
+
`Component "${componentName}" has no default export (${sourceContext}). `
|
|
2365
|
+
+ 'Slice loads a component with `const { default: myClass } = await import(...)`, '
|
|
2366
|
+
+ `so ${componentName}.js must end with \`export default class ${componentName.replace(/[^A-Za-z0-9]/g, '')} { ... }\`.`
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
/**
|
|
2371
|
+
* True when a component module awaits at its own top level (rather than inside
|
|
2372
|
+
* a function). Such a module is valid ESM, but its code is emitted inside the
|
|
2373
|
+
* class factory — so the factory must be declared async.
|
|
2374
|
+
*
|
|
2375
|
+
* @param {string} code component source, before any transform
|
|
2376
|
+
* @returns {boolean}
|
|
2377
|
+
*/
|
|
2378
|
+
hasModuleTopLevelAwait(code) {
|
|
2379
|
+
let ast;
|
|
2380
|
+
try {
|
|
2381
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
2382
|
+
} catch (error) {
|
|
2383
|
+
// Unparseable source: assume no top-level await. The bundle validation in
|
|
2384
|
+
// emitBundleArtifact is what catches whatever is actually wrong.
|
|
2385
|
+
return false;
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
let found = false;
|
|
2389
|
+
traverse.default(ast, {
|
|
2390
|
+
// `for await (...)` counts too — it is only legal in an async context.
|
|
2391
|
+
'AwaitExpression|ForOfStatement': (pathNode) => {
|
|
2392
|
+
if (found) return;
|
|
2393
|
+
if (pathNode.node.type === 'ForOfStatement' && !pathNode.node.await) return;
|
|
2394
|
+
if (pathNode.getFunctionParent()) return; // awaits inside a function are fine
|
|
2395
|
+
found = true;
|
|
2396
|
+
pathNode.stop();
|
|
2397
|
+
}
|
|
2398
|
+
});
|
|
2399
|
+
|
|
2400
|
+
return found;
|
|
2401
|
+
}
|
|
2402
|
+
|
|
1943
2403
|
/**
|
|
1944
2404
|
* Formats the bundle file
|
|
1945
2405
|
*/
|
|
@@ -2707,6 +3167,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2707
3167
|
isFramework: true,
|
|
2708
3168
|
js: cleanedJavaScript.code,
|
|
2709
3169
|
hoistedImports: cleanedJavaScript.hoistedImports,
|
|
3170
|
+
hasTopLevelAwait: cleanedJavaScript.hasTopLevelAwait,
|
|
2710
3171
|
externalDependencies: dependencyContents,
|
|
2711
3172
|
componentDependencies: Array.from(comp.dependencies),
|
|
2712
3173
|
html: fs.existsSync(path.join(comp.path, `${fileBaseName}.html`))
|
|
@@ -3028,6 +3489,116 @@ if (window.slice && window.slice.controller) {
|
|
|
3028
3489
|
}
|
|
3029
3490
|
}
|
|
3030
3491
|
|
|
3492
|
+
/**
|
|
3493
|
+
* Removes module-level `export` keywords from a component's own source.
|
|
3494
|
+
*
|
|
3495
|
+
* A component file is a real ES module, so `export const` / `export function`
|
|
3496
|
+
* / `export class` are valid there and work in dev (each file is loaded as a
|
|
3497
|
+
* module). The bundle, however, embeds this code inside
|
|
3498
|
+
* `SLICE_CLASS_FACTORY_* = () => { ... }`, and `export` is only legal at the
|
|
3499
|
+
* top level of a module — so the emitted bundle is a syntax error. With
|
|
3500
|
+
* minification on that surfaces as `Terser failed for slice-bundle.*.js:
|
|
3501
|
+
* "Export" statement may only appear at the top level`, which names the
|
|
3502
|
+
* generated file rather than the source; with minification off
|
|
3503
|
+
* applyBundleTransforms returns early, so the broken bundle ships and the
|
|
3504
|
+
* browser rejects it at parse time instead.
|
|
3505
|
+
*
|
|
3506
|
+
* Only the keyword is removed — the declaration stays, so references to the
|
|
3507
|
+
* name from elsewhere in the same file keep working. Nothing can consume
|
|
3508
|
+
* these names through the bundle anyway: the Bundling V2 contract reads
|
|
3509
|
+
* exactly SLICE_BUNDLE_META and registerAll (Controller.validateBundleModule),
|
|
3510
|
+
* and another component that imports `{ NAME }` from this file resolves it
|
|
3511
|
+
* from the separate copy emitted on the dependency path
|
|
3512
|
+
* (buildDependencyContents), where transformDependencyContent rewrites named
|
|
3513
|
+
* exports onto an exports object properly.
|
|
3514
|
+
*
|
|
3515
|
+
* `export default` is handled by the caller's own strip, which also appends
|
|
3516
|
+
* the `return <ComponentName>;` the factory needs.
|
|
3517
|
+
*
|
|
3518
|
+
* @param {string} code component source
|
|
3519
|
+
* @param {string|null} sourceContext path used in warnings
|
|
3520
|
+
* @returns {string}
|
|
3521
|
+
*/
|
|
3522
|
+
stripModuleExports(code, sourceContext = null) {
|
|
3523
|
+
let exportNodes;
|
|
3524
|
+
try {
|
|
3525
|
+
exportNodes = this.parseModuleExportsFromCode(code);
|
|
3526
|
+
} catch (error) {
|
|
3527
|
+
// Unparseable (e.g. TS syntax): fall back to a conservative keyword strip
|
|
3528
|
+
// rather than emitting a bundle that cannot be parsed at all.
|
|
3529
|
+
return this.stripModuleExportsWithFallbackRegex(code);
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
if (exportNodes.length === 0) return code;
|
|
3533
|
+
|
|
3534
|
+
let cleaned = '';
|
|
3535
|
+
let cursor = 0;
|
|
3536
|
+
for (const node of exportNodes) {
|
|
3537
|
+
cleaned += code.slice(cursor, node.start);
|
|
3538
|
+
cleaned += this.rewriteModuleExportStatement(node, code, sourceContext);
|
|
3539
|
+
cursor = node.end;
|
|
3540
|
+
}
|
|
3541
|
+
cleaned += code.slice(cursor);
|
|
3542
|
+
|
|
3543
|
+
return cleaned;
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
/**
|
|
3547
|
+
* Top-level named/star export statements, in source order. Exports are only
|
|
3548
|
+
* valid at the top level, so program.body is the whole search space.
|
|
3549
|
+
* @param {string} code
|
|
3550
|
+
* @returns {Array<object>}
|
|
3551
|
+
*/
|
|
3552
|
+
parseModuleExportsFromCode(code) {
|
|
3553
|
+
const ast = parse(code, {
|
|
3554
|
+
sourceType: 'module',
|
|
3555
|
+
plugins: ['jsx']
|
|
3556
|
+
});
|
|
3557
|
+
|
|
3558
|
+
return ast.program.body
|
|
3559
|
+
.filter((node) => node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration')
|
|
3560
|
+
.filter((node) => typeof node.start === 'number' && typeof node.end === 'number')
|
|
3561
|
+
.sort((a, b) => a.start - b.start);
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
rewriteModuleExportStatement(node, code, sourceContext) {
|
|
3565
|
+
// `export const X = 1` / `export function f() {}` / `export class C {}`
|
|
3566
|
+
// become the bare declaration.
|
|
3567
|
+
if (node.type === 'ExportNamedDeclaration' && node.declaration) {
|
|
3568
|
+
return code.slice(node.declaration.start, node.declaration.end);
|
|
3569
|
+
}
|
|
3570
|
+
|
|
3571
|
+
// A re-export (`export { x } from './y'`, `export * from './y'`) has no
|
|
3572
|
+
// local declaration to keep, and the factory has no exports object to
|
|
3573
|
+
// attach one to. Dropping it costs nothing inside the bundle, but it means
|
|
3574
|
+
// this file is acting as a barrel — worth saying so out loud.
|
|
3575
|
+
if (node.source) {
|
|
3576
|
+
console.warn(this.buildImportWarningMessage(
|
|
3577
|
+
`Warning: Dropping re-export '${code.slice(node.start, node.end).split('\n')[0].trim()}' from a component file (not supported in bundles)`,
|
|
3578
|
+
sourceContext
|
|
3579
|
+
));
|
|
3580
|
+
return '';
|
|
3581
|
+
}
|
|
3582
|
+
|
|
3583
|
+
// Plain `export { a, b }` — the declarations of a and b stay in the file,
|
|
3584
|
+
// so removing the statement loses nothing.
|
|
3585
|
+
return '';
|
|
3586
|
+
}
|
|
3587
|
+
|
|
3588
|
+
/**
|
|
3589
|
+
* Last-resort strip for sources Babel cannot parse. Anchored to the start of
|
|
3590
|
+
* a line and required to be followed by a declaration keyword, so `export`
|
|
3591
|
+
* inside a string, a comment or a longer identifier is left alone.
|
|
3592
|
+
* @param {string} code
|
|
3593
|
+
* @returns {string}
|
|
3594
|
+
*/
|
|
3595
|
+
stripModuleExportsWithFallbackRegex(code) {
|
|
3596
|
+
return code.replace(
|
|
3597
|
+
/^([ \t]*)export[ \t]+(?=(?:const|let|var|class|function|async[ \t]+function)\b)/gm,
|
|
3598
|
+
'$1'
|
|
3599
|
+
);
|
|
3600
|
+
}
|
|
3601
|
+
|
|
3031
3602
|
async loadComponentsMap() {
|
|
3032
3603
|
const componentsConfigPath = path.join(this.componentsPath, 'components.js');
|
|
3033
3604
|
if (!await fs.pathExists(componentsConfigPath)) {
|