slicejs-cli 4.3.0 → 4.4.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/LICENSE +21 -21
- package/README.md +260 -257
- package/client.js +927 -823
- package/commands/Print.js +163 -163
- package/commands/Validations.js +92 -92
- package/commands/build/build.js +97 -107
- package/commands/buildProduction/buildProduction.js +613 -613
- package/commands/bundle/bundle.js +251 -239
- package/commands/createComponent/VisualComponentTemplate.js +55 -55
- package/commands/createComponent/createComponent.js +128 -128
- package/commands/deleteComponent/deleteComponent.js +81 -81
- package/commands/docs/docs.js +365 -365
- package/commands/doctor/doctor.js +677 -563
- package/commands/getComponent/getComponent.js +842 -842
- package/commands/init/init.js +526 -475
- package/commands/lint/lint.js +75 -0
- package/commands/lint/types.js +85 -0
- package/commands/listComponents/listComponents.js +172 -172
- package/commands/seo/check.js +91 -0
- package/commands/seo/images.js +586 -0
- package/commands/seo/sitemap.js +106 -0
- package/commands/seo/support.js +130 -0
- package/commands/setup/lint.js +151 -0
- package/commands/skill/skill.js +236 -236
- package/commands/startServer/startServer.js +240 -240
- package/commands/startServer/watchServer.js +66 -66
- package/commands/typecheck/typecheck.js +83 -0
- package/commands/types/types.js +1378 -1097
- package/commands/utils/JsMinifier.js +230 -230
- package/commands/utils/LocalCliDelegation.js +78 -53
- package/commands/utils/PackageManager.js +148 -148
- package/commands/utils/PathHelper.js +87 -75
- package/commands/utils/ProjectValidation.js +274 -0
- package/commands/utils/SourceDiagnostics.js +201 -201
- package/commands/utils/VersionChecker.js +169 -169
- package/commands/utils/analyzeSource.js +77 -77
- package/commands/utils/bundling/BundleGenerator.js +3748 -3776
- package/commands/utils/bundling/DependencyAnalyzer.js +976 -976
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
- package/commands/utils/componentAudit.js +74 -0
- package/commands/utils/compressAssets.js +103 -103
- package/commands/utils/cssScope.js +83 -0
- package/commands/utils/loadConfig.js +31 -31
- package/commands/utils/semver.js +66 -0
- package/commands/utils/sliceConfigSchema.js +72 -0
- package/commands/utils/sliceScripts.js +48 -48
- package/commands/utils/updateManager.js +471 -471
- package/eslint-config.js +128 -0
- package/package.json +19 -13
|
@@ -1,298 +1,298 @@
|
|
|
1
|
-
// commands/utils/bundling/ExternalModuleBundler.js
|
|
2
|
-
//
|
|
3
|
-
// Internal wrapper around esbuild used to resolve and bundle bare package
|
|
4
|
-
// imports (e.g. `import dayjs from 'dayjs'`) from the project's node_modules
|
|
5
|
-
// into a single, self-contained module string that the Slice bundle runtime
|
|
6
|
-
// can evaluate.
|
|
7
|
-
//
|
|
8
|
-
// Design notes:
|
|
9
|
-
// - esbuild does the hard parts we deliberately do NOT reimplement by hand:
|
|
10
|
-
// Node resolution (package.json exports/main/module, index fallback,
|
|
11
|
-
// nested node_modules), CommonJS <-> ESM interop, transitive third-party
|
|
12
|
-
// graph, and tree-shaking.
|
|
13
|
-
// - Output format is CJS. esbuild wraps the virtual entry's exports onto a
|
|
14
|
-
// `module.exports` object; we evaluate that inside an IIFE that provides
|
|
15
|
-
// `module`/`exports`, and return the resulting namespace-like object. This
|
|
16
|
-
// avoids running esbuild's already-bundled output back through the Babel
|
|
17
|
-
// export-rewriting used for hand-written relative helper modules.
|
|
18
|
-
// - The returned object mirrors an ES module namespace: named exports as own
|
|
19
|
-
// keys plus a `default` key (when requested), which is exactly what the
|
|
20
|
-
// existing `buildDependencyBindings` runtime contract expects.
|
|
21
|
-
//
|
|
22
|
-
// This module is the ONLY place allowed to import esbuild. All other code must
|
|
23
|
-
// go through this wrapper (team rule: external libraries stay behind an
|
|
24
|
-
// internal abstraction).
|
|
25
|
-
|
|
26
|
-
import { build } from 'esbuild';
|
|
27
|
-
|
|
28
|
-
const URL_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
|
|
29
|
-
|
|
30
|
-
// Non-JS assets a package may import. They are inlined as base64 data URLs so
|
|
31
|
-
// the emitted dependency module stays self-contained (no sidecar files). WASM
|
|
32
|
-
// as a data URL works with the common `fetch(url) -> WebAssembly.instantiate`
|
|
33
|
-
// pattern; url() references inside bundled CSS are inlined the same way.
|
|
34
|
-
export const ASSET_LOADERS = {
|
|
35
|
-
'.wasm': 'dataurl',
|
|
36
|
-
'.png': 'dataurl',
|
|
37
|
-
'.jpg': 'dataurl',
|
|
38
|
-
'.jpeg': 'dataurl',
|
|
39
|
-
'.gif': 'dataurl',
|
|
40
|
-
'.svg': 'dataurl',
|
|
41
|
-
'.webp': 'dataurl',
|
|
42
|
-
'.avif': 'dataurl',
|
|
43
|
-
'.woff': 'dataurl',
|
|
44
|
-
'.woff2': 'dataurl',
|
|
45
|
-
'.ttf': 'dataurl',
|
|
46
|
-
'.eot': 'dataurl',
|
|
47
|
-
// Text assets some packages import as strings (GLSL shaders, templates).
|
|
48
|
-
// Loaded verbatim so `import src from './x.glsl'` yields the file contents.
|
|
49
|
-
'.txt': 'text',
|
|
50
|
-
'.glsl': 'text',
|
|
51
|
-
'.vert': 'text',
|
|
52
|
-
'.frag': 'text',
|
|
53
|
-
'.vs': 'text',
|
|
54
|
-
'.fs': 'text'
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Minimal browser shims for the Node globals that browser-targeted packages
|
|
59
|
-
* still touch at runtime: `process` (env/platform/nextTick) and `global`. This
|
|
60
|
-
* is NOT a Node polyfill — there is no Buffer, stream, or fs. It only prevents
|
|
61
|
-
* a ReferenceError when a package reads e.g. `process.platform` or `global`
|
|
62
|
-
* dynamically; static `process.env.NODE_ENV` is still folded at bundle time by
|
|
63
|
-
* the esbuild `define`. The snippet is idempotent and guarded (it never
|
|
64
|
-
* clobbers a real `process`), so prepending it to every bundled package as an
|
|
65
|
-
* esbuild banner is safe.
|
|
66
|
-
* @param {string} nodeEnv value exposed as process.env.NODE_ENV at runtime.
|
|
67
|
-
* @returns {string}
|
|
68
|
-
*/
|
|
69
|
-
export function nodeGlobalsBanner(nodeEnv) {
|
|
70
|
-
return [
|
|
71
|
-
'(function(){',
|
|
72
|
-
' if (typeof globalThis === "undefined") return;',
|
|
73
|
-
' if (typeof globalThis.global === "undefined") globalThis.global = globalThis;',
|
|
74
|
-
' if (typeof globalThis.process === "undefined") {',
|
|
75
|
-
` globalThis.process = { env: { NODE_ENV: ${JSON.stringify(nodeEnv)} }, argv: [], platform: "browser", browser: true, version: "", versions: {}, cwd: function(){ return "/"; }, nextTick: function(cb){ Promise.resolve().then(cb); } };`,
|
|
76
|
-
' } else if (typeof globalThis.process.env === "undefined") {',
|
|
77
|
-
` globalThis.process.env = { NODE_ENV: ${JSON.stringify(nodeEnv)} };`,
|
|
78
|
-
' }',
|
|
79
|
-
'})();'
|
|
80
|
-
].join('\n');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Stable short key for a CSS payload (djb2), used to de-duplicate injection. */
|
|
84
|
-
export function cssInjectionKey(css) {
|
|
85
|
-
let h = 5381;
|
|
86
|
-
for (let i = 0; i < css.length; i += 1) {
|
|
87
|
-
h = ((h << 5) + h + css.charCodeAt(i)) >>> 0;
|
|
88
|
-
}
|
|
89
|
-
return `ext-${h.toString(36)}`;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Runtime snippet that injects a package's bundled CSS as a <style> element.
|
|
94
|
-
* esbuild resolves @import and url() while bundling, so the passed CSS is
|
|
95
|
-
* already flattened and self-contained. Injection is idempotent: the same CSS
|
|
96
|
-
* (e.g. a package present in two route bundles) is only injected once.
|
|
97
|
-
* @param {string} css
|
|
98
|
-
* @returns {string}
|
|
99
|
-
*/
|
|
100
|
-
export function buildCssInjectionSnippet(css) {
|
|
101
|
-
const key = cssInjectionKey(css);
|
|
102
|
-
return [
|
|
103
|
-
'(function(){',
|
|
104
|
-
' if (typeof document === "undefined") return;',
|
|
105
|
-
` var __k = ${JSON.stringify(key)};`,
|
|
106
|
-
" if (document.querySelector('style[data-slice-external=\"' + __k + '\"]')) return;",
|
|
107
|
-
' var __sliceStyle = document.createElement("style");',
|
|
108
|
-
' __sliceStyle.setAttribute("data-slice-external", __k);',
|
|
109
|
-
` __sliceStyle.textContent = ${JSON.stringify(css)};`,
|
|
110
|
-
' document.head.appendChild(__sliceStyle);',
|
|
111
|
-
'})();'
|
|
112
|
-
].join('\n');
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Splits esbuild's outputFiles into the JS entry text plus an optional injected
|
|
117
|
-
* CSS side-effect snippet. Shared by the build and dev bundlers.
|
|
118
|
-
* @param {Array<{ path: string, text: string }>} outputFiles
|
|
119
|
-
* @returns {string}
|
|
120
|
-
*/
|
|
121
|
-
export function combineEsbuildOutputs(outputFiles = []) {
|
|
122
|
-
const jsOut = outputFiles.find((f) => /\.(js|mjs|cjs)$/.test(f.path)) || outputFiles[0];
|
|
123
|
-
const cssOut = outputFiles.find((f) => f.path.endsWith('.css'));
|
|
124
|
-
let code = jsOut?.text || '';
|
|
125
|
-
if (cssOut?.text && cssOut.text.trim()) {
|
|
126
|
-
code += `\n${buildCssInjectionSnippet(cssOut.text)}`;
|
|
127
|
-
}
|
|
128
|
-
return code;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export default class ExternalModuleBundler {
|
|
132
|
-
/**
|
|
133
|
-
* @param {object} options
|
|
134
|
-
* @param {string} options.resolveDir Directory esbuild resolves node_modules from (project root).
|
|
135
|
-
* @param {string} [options.target] esbuild target (default 'es2020').
|
|
136
|
-
* @param {boolean} [options.minify] Minify the bundled dependency output.
|
|
137
|
-
*/
|
|
138
|
-
constructor({ resolveDir, target = 'es2020', minify = false } = {}) {
|
|
139
|
-
if (!resolveDir) {
|
|
140
|
-
throw new Error('ExternalModuleBundler requires a resolveDir');
|
|
141
|
-
}
|
|
142
|
-
this.resolveDir = resolveDir;
|
|
143
|
-
this.target = target;
|
|
144
|
-
this.minify = minify;
|
|
145
|
-
// Cache keyed by `${specifier}::${needsDefault}` so a package used by many
|
|
146
|
-
// components is only bundled once per build.
|
|
147
|
-
this.cache = new Map();
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Returns true for bare package specifiers: not relative ('./', '../'), not
|
|
152
|
-
* absolute ('/…' — those are served from src/public/), not a URL/data/blob
|
|
153
|
-
* scheme, not a Node subpath import ('#…'). Scoped packages ('@scope/pkg')
|
|
154
|
-
* and deep subpaths ('lodash/fp') are bare.
|
|
155
|
-
* @param {string} spec
|
|
156
|
-
* @returns {boolean}
|
|
157
|
-
*/
|
|
158
|
-
static isBareSpecifier(spec) {
|
|
159
|
-
if (typeof spec !== 'string' || spec.length === 0) return false;
|
|
160
|
-
if (spec.startsWith('.')) return false;
|
|
161
|
-
if (spec.startsWith('/')) return false;
|
|
162
|
-
if (spec.startsWith('#')) return false;
|
|
163
|
-
if (URL_SCHEME_RE.test(spec)) return false;
|
|
164
|
-
return true;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Bundles a bare package into a self-contained module expression.
|
|
169
|
-
*
|
|
170
|
-
* @param {string} specifier e.g. 'dayjs', '@scope/pkg', 'lodash/fp'
|
|
171
|
-
* @param {object} [usage]
|
|
172
|
-
* @param {boolean} [usage.needsDefault] Whether any consumer default-imports it.
|
|
173
|
-
* @returns {Promise<{ name: string, expression: string, warnings: string[] }>}
|
|
174
|
-
* @throws when esbuild cannot resolve or bundle the package.
|
|
175
|
-
*/
|
|
176
|
-
async bundle(specifier, usage = {}) {
|
|
177
|
-
const needsDefault = usage.needsDefault !== false; // default true unless explicitly false
|
|
178
|
-
const cacheKey = `${specifier}::${needsDefault}`;
|
|
179
|
-
if (this.cache.has(cacheKey)) {
|
|
180
|
-
return this.cache.get(cacheKey);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
let result;
|
|
184
|
-
try {
|
|
185
|
-
result = await this.runEsbuild(this.buildVirtualEntry(specifier, needsDefault));
|
|
186
|
-
} catch (error) {
|
|
187
|
-
// A package with no default export makes the explicit default re-export
|
|
188
|
-
// fail; retry with a namespace-only entry so named-only ESM packages still
|
|
189
|
-
// resolve (esp. for dynamic imports, which request the default blindly).
|
|
190
|
-
if (needsDefault && /default/i.test(this.formatEsbuildError(error))) {
|
|
191
|
-
try {
|
|
192
|
-
result = await this.runEsbuild(this.buildVirtualEntry(specifier, false));
|
|
193
|
-
} catch (retryError) {
|
|
194
|
-
throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(retryError)}
|
|
195
|
-
}
|
|
196
|
-
} else {
|
|
197
|
-
throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(error)}
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// JS entry plus an optional injected-CSS side effect (kept self-contained).
|
|
202
|
-
const code = combineEsbuildOutputs(result.outputFiles);
|
|
203
|
-
const warnings = (result.warnings || []).map((w) => w.text);
|
|
204
|
-
const out = {
|
|
205
|
-
name: specifier,
|
|
206
|
-
expression: this.wrapAsModuleExpression(code),
|
|
207
|
-
warnings
|
|
208
|
-
};
|
|
209
|
-
this.cache.set(cacheKey, out);
|
|
210
|
-
return out;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
runEsbuild(entry) {
|
|
214
|
-
return build({
|
|
215
|
-
stdin: {
|
|
216
|
-
contents: entry,
|
|
217
|
-
resolveDir: this.resolveDir,
|
|
218
|
-
sourcefile: 'slice-external-entry.js',
|
|
219
|
-
loader: 'js'
|
|
220
|
-
},
|
|
221
|
-
bundle: true,
|
|
222
|
-
format: 'cjs',
|
|
223
|
-
platform: 'browser',
|
|
224
|
-
target: this.target,
|
|
225
|
-
minify: this.minify,
|
|
226
|
-
write: false,
|
|
227
|
-
metafile: false,
|
|
228
|
-
legalComments: 'none',
|
|
229
|
-
logLevel: 'silent',
|
|
230
|
-
// Standard browser-build substitutions (as Vite/webpack do): let packages
|
|
231
|
-
// that gate on NODE_ENV or reference `global` work without a polyfill.
|
|
232
|
-
// esbuild respects local shadowing, so this only rewrites free references.
|
|
233
|
-
define: {
|
|
234
|
-
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
235
|
-
global: 'globalThis'
|
|
236
|
-
},
|
|
237
|
-
// Runtime shim for the Node globals `define` cannot fold statically (a
|
|
238
|
-
// dynamic `process.platform` / `process.env[key]` / free `global`). Runs
|
|
239
|
-
// once, guarded, before the package body — see nodeGlobalsBanner.
|
|
240
|
-
banner: { js: nodeGlobalsBanner('production') },
|
|
241
|
-
// A virtual outdir is required for esbuild to emit a CSS output file
|
|
242
|
-
// (in outputFiles) when a package imports CSS; nothing is written to
|
|
243
|
-
// disk because write:false.
|
|
244
|
-
outdir: 'slice-external-out',
|
|
245
|
-
// Inline non-JS assets (WASM, images, fonts) as data URLs, and let
|
|
246
|
-
// esbuild bundle any CSS the package imports (resolving @import/url()).
|
|
247
|
-
loader: ASSET_LOADERS,
|
|
248
|
-
// Keep import.meta from crashing browser CJS output for packages that
|
|
249
|
-
// reference it; esbuild replaces it with an empty object shim.
|
|
250
|
-
supported: { 'import-meta': false }
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/**
|
|
255
|
-
* Virtual entry re-exporting the target package. `export *` covers named +
|
|
256
|
-
* namespace usage; the explicit default re-export is added only when a
|
|
257
|
-
* consumer actually default-imports the package, so ESM packages without a
|
|
258
|
-
* default export don't fail to build when nobody asked for their default.
|
|
259
|
-
*/
|
|
260
|
-
buildVirtualEntry(specifier, needsDefault) {
|
|
261
|
-
const spec = JSON.stringify(specifier);
|
|
262
|
-
const lines = [`export * from ${spec};`];
|
|
263
|
-
if (needsDefault) {
|
|
264
|
-
lines.push(`export { default } from ${spec};`);
|
|
265
|
-
}
|
|
266
|
-
return lines.join('\n');
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* Wraps esbuild's CJS output in an IIFE that provides the CommonJS scaffolding
|
|
271
|
-
* and returns the populated `module.exports`. The result is an expression that
|
|
272
|
-
* can be assigned directly: `SLICE_BUNDLE_DEPENDENCIES["pkg"] = <expression>;`
|
|
273
|
-
*/
|
|
274
|
-
wrapAsModuleExpression(cjsCode) {
|
|
275
|
-
const indented = String(cjsCode)
|
|
276
|
-
.split('\n')
|
|
277
|
-
.map((line) => (line ? ` ${line}` : line))
|
|
278
|
-
.join('\n');
|
|
279
|
-
return [
|
|
280
|
-
'(() => {',
|
|
281
|
-
' const module = { exports: {} };',
|
|
282
|
-
' let exports = module.exports;',
|
|
283
|
-
' const require = (id) => {',
|
|
284
|
-
' throw new Error(`[Slice.js] Unexpected runtime require("${id}") in a bundled dependency`);',
|
|
285
|
-
' };',
|
|
286
|
-
indented,
|
|
287
|
-
' return module.exports;',
|
|
288
|
-
'})()'
|
|
289
|
-
].join('\n');
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
formatEsbuildError(error) {
|
|
293
|
-
if (error && Array.isArray(error.errors) && error.errors.length > 0) {
|
|
294
|
-
return error.errors.map((e) => e.text).join('; ');
|
|
295
|
-
}
|
|
296
|
-
return error?.message || String(error);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
1
|
+
// commands/utils/bundling/ExternalModuleBundler.js
|
|
2
|
+
//
|
|
3
|
+
// Internal wrapper around esbuild used to resolve and bundle bare package
|
|
4
|
+
// imports (e.g. `import dayjs from 'dayjs'`) from the project's node_modules
|
|
5
|
+
// into a single, self-contained module string that the Slice bundle runtime
|
|
6
|
+
// can evaluate.
|
|
7
|
+
//
|
|
8
|
+
// Design notes:
|
|
9
|
+
// - esbuild does the hard parts we deliberately do NOT reimplement by hand:
|
|
10
|
+
// Node resolution (package.json exports/main/module, index fallback,
|
|
11
|
+
// nested node_modules), CommonJS <-> ESM interop, transitive third-party
|
|
12
|
+
// graph, and tree-shaking.
|
|
13
|
+
// - Output format is CJS. esbuild wraps the virtual entry's exports onto a
|
|
14
|
+
// `module.exports` object; we evaluate that inside an IIFE that provides
|
|
15
|
+
// `module`/`exports`, and return the resulting namespace-like object. This
|
|
16
|
+
// avoids running esbuild's already-bundled output back through the Babel
|
|
17
|
+
// export-rewriting used for hand-written relative helper modules.
|
|
18
|
+
// - The returned object mirrors an ES module namespace: named exports as own
|
|
19
|
+
// keys plus a `default` key (when requested), which is exactly what the
|
|
20
|
+
// existing `buildDependencyBindings` runtime contract expects.
|
|
21
|
+
//
|
|
22
|
+
// This module is the ONLY place allowed to import esbuild. All other code must
|
|
23
|
+
// go through this wrapper (team rule: external libraries stay behind an
|
|
24
|
+
// internal abstraction).
|
|
25
|
+
|
|
26
|
+
import { build } from 'esbuild';
|
|
27
|
+
|
|
28
|
+
const URL_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
|
|
29
|
+
|
|
30
|
+
// Non-JS assets a package may import. They are inlined as base64 data URLs so
|
|
31
|
+
// the emitted dependency module stays self-contained (no sidecar files). WASM
|
|
32
|
+
// as a data URL works with the common `fetch(url) -> WebAssembly.instantiate`
|
|
33
|
+
// pattern; url() references inside bundled CSS are inlined the same way.
|
|
34
|
+
export const ASSET_LOADERS = {
|
|
35
|
+
'.wasm': 'dataurl',
|
|
36
|
+
'.png': 'dataurl',
|
|
37
|
+
'.jpg': 'dataurl',
|
|
38
|
+
'.jpeg': 'dataurl',
|
|
39
|
+
'.gif': 'dataurl',
|
|
40
|
+
'.svg': 'dataurl',
|
|
41
|
+
'.webp': 'dataurl',
|
|
42
|
+
'.avif': 'dataurl',
|
|
43
|
+
'.woff': 'dataurl',
|
|
44
|
+
'.woff2': 'dataurl',
|
|
45
|
+
'.ttf': 'dataurl',
|
|
46
|
+
'.eot': 'dataurl',
|
|
47
|
+
// Text assets some packages import as strings (GLSL shaders, templates).
|
|
48
|
+
// Loaded verbatim so `import src from './x.glsl'` yields the file contents.
|
|
49
|
+
'.txt': 'text',
|
|
50
|
+
'.glsl': 'text',
|
|
51
|
+
'.vert': 'text',
|
|
52
|
+
'.frag': 'text',
|
|
53
|
+
'.vs': 'text',
|
|
54
|
+
'.fs': 'text'
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Minimal browser shims for the Node globals that browser-targeted packages
|
|
59
|
+
* still touch at runtime: `process` (env/platform/nextTick) and `global`. This
|
|
60
|
+
* is NOT a Node polyfill — there is no Buffer, stream, or fs. It only prevents
|
|
61
|
+
* a ReferenceError when a package reads e.g. `process.platform` or `global`
|
|
62
|
+
* dynamically; static `process.env.NODE_ENV` is still folded at bundle time by
|
|
63
|
+
* the esbuild `define`. The snippet is idempotent and guarded (it never
|
|
64
|
+
* clobbers a real `process`), so prepending it to every bundled package as an
|
|
65
|
+
* esbuild banner is safe.
|
|
66
|
+
* @param {string} nodeEnv value exposed as process.env.NODE_ENV at runtime.
|
|
67
|
+
* @returns {string}
|
|
68
|
+
*/
|
|
69
|
+
export function nodeGlobalsBanner(nodeEnv) {
|
|
70
|
+
return [
|
|
71
|
+
'(function(){',
|
|
72
|
+
' if (typeof globalThis === "undefined") return;',
|
|
73
|
+
' if (typeof globalThis.global === "undefined") globalThis.global = globalThis;',
|
|
74
|
+
' if (typeof globalThis.process === "undefined") {',
|
|
75
|
+
` globalThis.process = { env: { NODE_ENV: ${JSON.stringify(nodeEnv)} }, argv: [], platform: "browser", browser: true, version: "", versions: {}, cwd: function(){ return "/"; }, nextTick: function(cb){ Promise.resolve().then(cb); } };`,
|
|
76
|
+
' } else if (typeof globalThis.process.env === "undefined") {',
|
|
77
|
+
` globalThis.process.env = { NODE_ENV: ${JSON.stringify(nodeEnv)} };`,
|
|
78
|
+
' }',
|
|
79
|
+
'})();'
|
|
80
|
+
].join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Stable short key for a CSS payload (djb2), used to de-duplicate injection. */
|
|
84
|
+
export function cssInjectionKey(css) {
|
|
85
|
+
let h = 5381;
|
|
86
|
+
for (let i = 0; i < css.length; i += 1) {
|
|
87
|
+
h = ((h << 5) + h + css.charCodeAt(i)) >>> 0;
|
|
88
|
+
}
|
|
89
|
+
return `ext-${h.toString(36)}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Runtime snippet that injects a package's bundled CSS as a <style> element.
|
|
94
|
+
* esbuild resolves @import and url() while bundling, so the passed CSS is
|
|
95
|
+
* already flattened and self-contained. Injection is idempotent: the same CSS
|
|
96
|
+
* (e.g. a package present in two route bundles) is only injected once.
|
|
97
|
+
* @param {string} css
|
|
98
|
+
* @returns {string}
|
|
99
|
+
*/
|
|
100
|
+
export function buildCssInjectionSnippet(css) {
|
|
101
|
+
const key = cssInjectionKey(css);
|
|
102
|
+
return [
|
|
103
|
+
'(function(){',
|
|
104
|
+
' if (typeof document === "undefined") return;',
|
|
105
|
+
` var __k = ${JSON.stringify(key)};`,
|
|
106
|
+
" if (document.querySelector('style[data-slice-external=\"' + __k + '\"]')) return;",
|
|
107
|
+
' var __sliceStyle = document.createElement("style");',
|
|
108
|
+
' __sliceStyle.setAttribute("data-slice-external", __k);',
|
|
109
|
+
` __sliceStyle.textContent = ${JSON.stringify(css)};`,
|
|
110
|
+
' document.head.appendChild(__sliceStyle);',
|
|
111
|
+
'})();'
|
|
112
|
+
].join('\n');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Splits esbuild's outputFiles into the JS entry text plus an optional injected
|
|
117
|
+
* CSS side-effect snippet. Shared by the build and dev bundlers.
|
|
118
|
+
* @param {Array<{ path: string, text: string }>} outputFiles
|
|
119
|
+
* @returns {string}
|
|
120
|
+
*/
|
|
121
|
+
export function combineEsbuildOutputs(outputFiles = []) {
|
|
122
|
+
const jsOut = outputFiles.find((f) => /\.(js|mjs|cjs)$/.test(f.path)) || outputFiles[0];
|
|
123
|
+
const cssOut = outputFiles.find((f) => f.path.endsWith('.css'));
|
|
124
|
+
let code = jsOut?.text || '';
|
|
125
|
+
if (cssOut?.text && cssOut.text.trim()) {
|
|
126
|
+
code += `\n${buildCssInjectionSnippet(cssOut.text)}`;
|
|
127
|
+
}
|
|
128
|
+
return code;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export default class ExternalModuleBundler {
|
|
132
|
+
/**
|
|
133
|
+
* @param {object} options
|
|
134
|
+
* @param {string} options.resolveDir Directory esbuild resolves node_modules from (project root).
|
|
135
|
+
* @param {string} [options.target] esbuild target (default 'es2020').
|
|
136
|
+
* @param {boolean} [options.minify] Minify the bundled dependency output.
|
|
137
|
+
*/
|
|
138
|
+
constructor({ resolveDir, target = 'es2020', minify = false } = {}) {
|
|
139
|
+
if (!resolveDir) {
|
|
140
|
+
throw new Error('ExternalModuleBundler requires a resolveDir');
|
|
141
|
+
}
|
|
142
|
+
this.resolveDir = resolveDir;
|
|
143
|
+
this.target = target;
|
|
144
|
+
this.minify = minify;
|
|
145
|
+
// Cache keyed by `${specifier}::${needsDefault}` so a package used by many
|
|
146
|
+
// components is only bundled once per build.
|
|
147
|
+
this.cache = new Map();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Returns true for bare package specifiers: not relative ('./', '../'), not
|
|
152
|
+
* absolute ('/…' — those are served from src/public/), not a URL/data/blob
|
|
153
|
+
* scheme, not a Node subpath import ('#…'). Scoped packages ('@scope/pkg')
|
|
154
|
+
* and deep subpaths ('lodash/fp') are bare.
|
|
155
|
+
* @param {string} spec
|
|
156
|
+
* @returns {boolean}
|
|
157
|
+
*/
|
|
158
|
+
static isBareSpecifier(spec) {
|
|
159
|
+
if (typeof spec !== 'string' || spec.length === 0) return false;
|
|
160
|
+
if (spec.startsWith('.')) return false;
|
|
161
|
+
if (spec.startsWith('/')) return false;
|
|
162
|
+
if (spec.startsWith('#')) return false;
|
|
163
|
+
if (URL_SCHEME_RE.test(spec)) return false;
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Bundles a bare package into a self-contained module expression.
|
|
169
|
+
*
|
|
170
|
+
* @param {string} specifier e.g. 'dayjs', '@scope/pkg', 'lodash/fp'
|
|
171
|
+
* @param {object} [usage]
|
|
172
|
+
* @param {boolean} [usage.needsDefault] Whether any consumer default-imports it.
|
|
173
|
+
* @returns {Promise<{ name: string, expression: string, warnings: string[] }>}
|
|
174
|
+
* @throws when esbuild cannot resolve or bundle the package.
|
|
175
|
+
*/
|
|
176
|
+
async bundle(specifier, usage = {}) {
|
|
177
|
+
const needsDefault = usage.needsDefault !== false; // default true unless explicitly false
|
|
178
|
+
const cacheKey = `${specifier}::${needsDefault}`;
|
|
179
|
+
if (this.cache.has(cacheKey)) {
|
|
180
|
+
return this.cache.get(cacheKey);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let result;
|
|
184
|
+
try {
|
|
185
|
+
result = await this.runEsbuild(this.buildVirtualEntry(specifier, needsDefault));
|
|
186
|
+
} catch (error) {
|
|
187
|
+
// A package with no default export makes the explicit default re-export
|
|
188
|
+
// fail; retry with a namespace-only entry so named-only ESM packages still
|
|
189
|
+
// resolve (esp. for dynamic imports, which request the default blindly).
|
|
190
|
+
if (needsDefault && /default/i.test(this.formatEsbuildError(error))) {
|
|
191
|
+
try {
|
|
192
|
+
result = await this.runEsbuild(this.buildVirtualEntry(specifier, false));
|
|
193
|
+
} catch (retryError) {
|
|
194
|
+
throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(retryError)}`, { cause: retryError });
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(error)}`, { cause: error });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// JS entry plus an optional injected-CSS side effect (kept self-contained).
|
|
202
|
+
const code = combineEsbuildOutputs(result.outputFiles);
|
|
203
|
+
const warnings = (result.warnings || []).map((w) => w.text);
|
|
204
|
+
const out = {
|
|
205
|
+
name: specifier,
|
|
206
|
+
expression: this.wrapAsModuleExpression(code),
|
|
207
|
+
warnings
|
|
208
|
+
};
|
|
209
|
+
this.cache.set(cacheKey, out);
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
runEsbuild(entry) {
|
|
214
|
+
return build({
|
|
215
|
+
stdin: {
|
|
216
|
+
contents: entry,
|
|
217
|
+
resolveDir: this.resolveDir,
|
|
218
|
+
sourcefile: 'slice-external-entry.js',
|
|
219
|
+
loader: 'js'
|
|
220
|
+
},
|
|
221
|
+
bundle: true,
|
|
222
|
+
format: 'cjs',
|
|
223
|
+
platform: 'browser',
|
|
224
|
+
target: this.target,
|
|
225
|
+
minify: this.minify,
|
|
226
|
+
write: false,
|
|
227
|
+
metafile: false,
|
|
228
|
+
legalComments: 'none',
|
|
229
|
+
logLevel: 'silent',
|
|
230
|
+
// Standard browser-build substitutions (as Vite/webpack do): let packages
|
|
231
|
+
// that gate on NODE_ENV or reference `global` work without a polyfill.
|
|
232
|
+
// esbuild respects local shadowing, so this only rewrites free references.
|
|
233
|
+
define: {
|
|
234
|
+
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
235
|
+
global: 'globalThis'
|
|
236
|
+
},
|
|
237
|
+
// Runtime shim for the Node globals `define` cannot fold statically (a
|
|
238
|
+
// dynamic `process.platform` / `process.env[key]` / free `global`). Runs
|
|
239
|
+
// once, guarded, before the package body — see nodeGlobalsBanner.
|
|
240
|
+
banner: { js: nodeGlobalsBanner('production') },
|
|
241
|
+
// A virtual outdir is required for esbuild to emit a CSS output file
|
|
242
|
+
// (in outputFiles) when a package imports CSS; nothing is written to
|
|
243
|
+
// disk because write:false.
|
|
244
|
+
outdir: 'slice-external-out',
|
|
245
|
+
// Inline non-JS assets (WASM, images, fonts) as data URLs, and let
|
|
246
|
+
// esbuild bundle any CSS the package imports (resolving @import/url()).
|
|
247
|
+
loader: ASSET_LOADERS,
|
|
248
|
+
// Keep import.meta from crashing browser CJS output for packages that
|
|
249
|
+
// reference it; esbuild replaces it with an empty object shim.
|
|
250
|
+
supported: { 'import-meta': false }
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Virtual entry re-exporting the target package. `export *` covers named +
|
|
256
|
+
* namespace usage; the explicit default re-export is added only when a
|
|
257
|
+
* consumer actually default-imports the package, so ESM packages without a
|
|
258
|
+
* default export don't fail to build when nobody asked for their default.
|
|
259
|
+
*/
|
|
260
|
+
buildVirtualEntry(specifier, needsDefault) {
|
|
261
|
+
const spec = JSON.stringify(specifier);
|
|
262
|
+
const lines = [`export * from ${spec};`];
|
|
263
|
+
if (needsDefault) {
|
|
264
|
+
lines.push(`export { default } from ${spec};`);
|
|
265
|
+
}
|
|
266
|
+
return lines.join('\n');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Wraps esbuild's CJS output in an IIFE that provides the CommonJS scaffolding
|
|
271
|
+
* and returns the populated `module.exports`. The result is an expression that
|
|
272
|
+
* can be assigned directly: `SLICE_BUNDLE_DEPENDENCIES["pkg"] = <expression>;`
|
|
273
|
+
*/
|
|
274
|
+
wrapAsModuleExpression(cjsCode) {
|
|
275
|
+
const indented = String(cjsCode)
|
|
276
|
+
.split('\n')
|
|
277
|
+
.map((line) => (line ? ` ${line}` : line))
|
|
278
|
+
.join('\n');
|
|
279
|
+
return [
|
|
280
|
+
'(() => {',
|
|
281
|
+
' const module = { exports: {} };',
|
|
282
|
+
' let exports = module.exports;',
|
|
283
|
+
' const require = (id) => {',
|
|
284
|
+
' throw new Error(`[Slice.js] Unexpected runtime require("${id}") in a bundled dependency`);',
|
|
285
|
+
' };',
|
|
286
|
+
indented,
|
|
287
|
+
' return module.exports;',
|
|
288
|
+
'})()'
|
|
289
|
+
].join('\n');
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
formatEsbuildError(error) {
|
|
293
|
+
if (error && Array.isArray(error.errors) && error.errors.length > 0) {
|
|
294
|
+
return error.errors.map((e) => e.text).join('; ');
|
|
295
|
+
}
|
|
296
|
+
return error?.message || String(error);
|
|
297
|
+
}
|
|
298
|
+
}
|