@mosetta/build 0.0.38 → 0.0.40

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/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @mosetta/build
2
2
 
3
+ ## 0.0.40
4
+
5
+ ### Patch Changes
6
+
7
+ - Shift SourceMap v3 VLQ columns after dynamic `import()` AST rewrites for exact minified column accuracy, parallelize native esbuild compilation phases deterministically (tiles, BFS dependency waves, shared CSS, server monoliths, SSR), and stabilize default SSR sourcemap virtual paths.
8
+ - @mosetta/router@0.0.40
9
+ - @mosetta/runtime@0.0.40
10
+ - @mosetta/server@0.0.40
11
+ - @mosetta/server-action@0.0.40
12
+ - @mosetta/tar@0.0.40
13
+
14
+ ## 0.0.39
15
+
16
+ ### Patch Changes
17
+
18
+ - Replace Rollup and SystemJS with a unified esbuild build pipeline, passive factory artifacts (`globalThis.__mosetta__`), unified `@mosetta/runtime/loader` with native browser SRI, and AST-rewritten lazy dynamic `import()` (`__meta.import()` and `lazyDependencies`).
19
+ - Updated dependencies
20
+ - @mosetta/runtime@0.0.39
21
+ - @mosetta/server@0.0.39
22
+ - @mosetta/server-action@0.0.39
23
+ - @mosetta/router@0.0.39
24
+ - @mosetta/tar@0.0.39
25
+
3
26
  ## 0.0.38
4
27
 
5
28
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosetta/build",
3
- "version": "0.0.38",
3
+ "version": "0.0.40",
4
4
  "license": "MIT",
5
5
  "description": "The core of the tile forge: builds a tile palette — its tile side artifacts, their dependency closure, the tile host descriptor. Environment-agnostic — the file system and the bundling engine are supplied from outside.",
6
6
  "type": "module",
@@ -17,22 +17,19 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@pnpm/dependency-path": "^1000.0.9",
20
- "@rollup/plugin-commonjs": "^28.0.9",
21
- "@rollup/plugin-replace": "^6.0.3",
22
- "cjs-module-lexer": "^2.2.0",
20
+ "acorn": "^8.17.0",
23
21
  "postcss": "^8.5.15",
24
22
  "postcss-value-parser": "^4.2.0",
25
23
  "react": "*",
26
24
  "react-dom": "*",
27
25
  "resolve.exports": "^2.0.3",
28
26
  "scheduler": "*",
29
- "systemjs": "^6.15.1",
30
27
  "yaml": "^2.9.0",
31
- "@mosetta/router": "0.0.38",
32
- "@mosetta/server-action": "0.0.38",
33
- "@mosetta/server": "0.0.38",
34
- "@mosetta/runtime": "0.0.38",
35
- "@mosetta/tar": "0.0.38"
28
+ "@mosetta/router": "0.0.40",
29
+ "@mosetta/runtime": "0.0.40",
30
+ "@mosetta/tar": "0.0.40",
31
+ "@mosetta/server-action": "0.0.40",
32
+ "@mosetta/server": "0.0.40"
36
33
  },
37
34
  "publishConfig": {
38
35
  "access": "public"
@@ -88,3 +88,21 @@ export function applyBrowserEntry(fileSystem, specifier, file, conditions) {
88
88
  if (pkg.name && specifier !== pkg.name) return file; // subpath — the root entry does not apply
89
89
  return path.resolve(dir, pkg.browser);
90
90
  }
91
+
92
+ /**
93
+ * Bare-specifier substitution inside a package's own `browser` map (e.g. `"crypto": false`).
94
+ * Returns `BROWSER_EMPTY`, a substituted absolute path, or `null` when untouched.
95
+ */
96
+ export function applyBrowserBareMap(fileSystem, specifier, fromDir, conditions) {
97
+ if (!conditions?.includes('browser')) return null;
98
+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) return null;
99
+ const dir = packageDirOf(fileSystem, path.join(fromDir, '_'));
100
+ if (!dir) return null;
101
+ const pkg = readPackage(fileSystem, dir);
102
+ const map = pkg?.browser;
103
+ if (!map || typeof map !== 'object' || !Object.hasOwn(map, specifier)) return null;
104
+ const hit = map[specifier];
105
+ if (hit === false) return BROWSER_EMPTY;
106
+ if (typeof hit === 'string' && hit.startsWith('.')) return path.resolve(dir, hit);
107
+ return null;
108
+ }
package/src/build.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  import { crypto, path } from './nodeApi.mjs';
2
2
  import { packageDirOf } from './packageMeta.mjs';
3
3
  import { discoverRoots, discoverModulesIn, discoverServerModulesIn, discoverRouterModulesIn, discoverPrefabsIn, discoverPagesIn, readConfig } from './discovery.mjs';
4
- import { buildModule, buildLoaderProlog } from './buildModules.mjs';
4
+ import { buildModule, buildLoader } from './buildModules.mjs';
5
5
  import { fullTileName } from './moduleName.mjs';
6
6
  import { buildServerModule, buildSsrModule } from './buildServer.mjs';
7
7
  import { buildDependency } from './buildDependencies.mjs';
8
8
  import { resolveSpecifier, dependencyFullId } from './specifiers.mjs';
9
- import { cjsNamedExports } from './cjsExports.mjs';
10
9
  import { processCss } from './css.mjs';
11
10
  import { INERT_BUILD_CONFIG } from './buildConfig.mjs';
12
11
  import { formatBytes } from './format.mjs';
@@ -18,18 +17,6 @@ import { DocIndex, renderPaletteDocs, renderTileDocs, tileDocHref, tileDocModule
18
17
  export { formatBytes };
19
18
  export { INERT_BUILD_CONFIG } from './buildConfig.mjs';
20
19
 
21
- // core + the named-register extra: artifacts are NAMED System.register('<full-id>', …) bundles
22
- // (SSR epic stage 1) — the extra links a URL load to its name (one instance both ways).
23
- // Read THROUGH THE PORT and lazily: importing the build module must not touch the disk by itself.
24
- let systemjsCache = null;
25
- function readSystemjs(fileSystem, resolver) {
26
- if (!systemjsCache) {
27
- systemjsCache = `${fileSystem.readFile(resolver.resolveFramework('systemjs/dist/system.js'), 'utf8')}\n${
28
- fileSystem.readFile(resolver.resolveFramework('systemjs/dist/extras/named-register.js'), 'utf8')}`;
29
- }
30
- return systemjsCache;
31
- }
32
-
33
20
  // Distributive layout: the in-memory FS (and any disk mirror) is split into two top-level
34
21
  // namespaces so nothing leaks across the trust boundary on deploy:
35
22
  // public/ — client-facing static (modules + co-located loaders, deps, prefabs, pages, manifests).
@@ -94,7 +81,27 @@ async function offersOf(jsCode, evaluate) {
94
81
  }
95
82
  }
96
83
 
84
+ /** Run `fn` over `items` with at most `limit` concurrent promises, preserving input order. */
85
+ async function mapLimit(items, limit, fn) {
86
+ if (items.length <= 1 || limit <= 1) {
87
+ const results = [];
88
+ for (let i = 0; i < items.length; i++) results.push(await fn(items[i], i));
89
+ return results;
90
+ }
91
+ const results = new Array(items.length);
92
+ let next = 0;
93
+ const worker = async () => {
94
+ while (next < items.length) {
95
+ const i = next++;
96
+ results[i] = await fn(items[i], i);
97
+ }
98
+ };
99
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
100
+ return results;
101
+ }
102
+
97
103
  export async function build(root, { mode = 'development', log, fileSystem, resolver, engine, frameworkDir, buildConfig = INERT_BUILD_CONFIG, cache = null, evaluate = null, released = null }) {
104
+ const concurrency = Math.max(1, Number(engine?.concurrency) || 1);
98
105
  const out = new OutputFS();
99
106
  const watchFiles = new Set();
100
107
  const addWatch = (arr) => arr.forEach((f) => watchFiles.add(f));
@@ -165,14 +172,15 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
165
172
  // within an epoch artifacts live by the mtime of their graphs.
166
173
  cache?.epoch([mode, buildConfig?.stamp ?? 'none', resolver.stamp, mtimeStamp(fileSystem, [...watchFiles])].join('|'));
167
174
 
168
- // the loader for script facets: systemjs + named-register + resolver prolog,
169
- // co-located into EVERY script facet's folder — a System.register entry is not executable
170
- // without the loader, and the module folder gives it a version-qualified (immutable) URL.
175
+ // the self-contained loader for script facets (`loader.js`), co-located into EVERY script
176
+ // facet's folder — installs the factory module loader (`@mosetta/runtime/loader`) from
177
+ // `#pageContent`, boots `<script type="mosetta-module">` entries with native SRI, and in dev
178
+ // attaches SSE livereload + error overlay.
171
179
  let loaderJs = null;
172
180
  if (mods.some((m) => m.type === 'script')) {
173
- const prolog = await buildLoaderProlog(fileSystem, { resolver, mode, buildConfig, engine, sourceBase: root });
174
- addWatch(prolog.watchFiles);
175
- loaderJs = `${readSystemjs(fileSystem, resolver)}\n${prolog.jsCode}`;
181
+ const builtLoader = await buildLoader(fileSystem, { resolver, mode, buildConfig, engine, sourceBase: root });
182
+ addWatch(builtLoader.watchFiles);
183
+ loaderJs = builtLoader.jsCode;
176
184
  }
177
185
 
178
186
  // catalog of LOGICAL artifacts for the report (renderBuildReport): distributive → module → facets
@@ -207,11 +215,33 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
207
215
  const docFileOf = (full) => `${full}.doc.md`;
208
216
  const docHref = tileDocHref(docIndex, (module) => `${fullOfDoc.get(module.address)}/${docFileOf(fullOfDoc.get(module.address))}`);
209
217
 
218
+ // Bundle client tile sides (and their settings schemas, when present) in parallel up to
219
+ // `concurrency`, then emit artifacts in deterministic `mods` order so `modules.json` is
220
+ // byte-for-byte identical between native Node and single-threaded WASM builds.
221
+ const builtModules = await mapLimit(mods, concurrency, async (m) => {
222
+ const full = fullTileName(m);
223
+ const cached = await memo(`module:${full}`,
224
+ () => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
225
+ let settingsFile = null;
226
+ let described = null;
227
+ let settingsSkipped = false;
228
+ if (m.type === 'component') {
229
+ settingsFile = path.join(path.dirname(m.file), `${m.name}${SETTINGS_SUFFIX}`);
230
+ if (fileSystem.exists(settingsFile)) {
231
+ if (evaluate) {
232
+ described = await memo(`settings:${full}`,
233
+ () => describeSettings(fileSystem, settingsFile, { resolver, engine, evaluate, frameworkDir, sourceBase: root }));
234
+ } else {
235
+ settingsSkipped = true;
236
+ }
237
+ }
238
+ }
239
+ return { m, cached, settingsFile, described, settingsSkipped };
240
+ });
241
+
210
242
  const moduleResults = [];
211
243
  let skippedSettings = 0;
212
- for (const m of mods) {
213
- const cached = await memo(`module:${fullTileName(m)}`,
214
- () => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
244
+ for (const { m, cached, settingsFile, described, settingsSkipped } of builtModules) {
215
245
  // the descriptor below gets AUGMENTED (edges to css entities, integrity) — the cached object
216
246
  // must stay untouched, otherwise edits would accumulate from iteration to iteration
217
247
  const r = { ...cached, descriptor: { ...cached.descriptor, dependencies: [...cached.descriptor.dependencies] } };
@@ -238,17 +268,12 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
238
268
  }
239
269
  // its SETTINGS: `<name>.settings.ts` beside it — what the block's node keeps, as JSON Schema
240
270
  // in the descriptor (settings.mjs); run by the host, skipped where the host runs nothing
241
- const settingsFile = path.join(path.dirname(m.file), `${m.name}${SETTINGS_SUFFIX}`);
242
271
  watchFiles.add(settingsFile);
243
- if (fileSystem.exists(settingsFile)) {
244
- if (evaluate) {
245
- const described = await memo(`settings:${r.full}`,
246
- () => describeSettings(fileSystem, settingsFile, { resolver, engine, evaluate, frameworkDir, sourceBase: root }));
247
- addWatch(described.watchFiles);
248
- r.descriptor.settings = described.schema;
249
- } else {
250
- skippedSettings++;
251
- }
272
+ if (described) {
273
+ addWatch(described.watchFiles);
274
+ r.descriptor.settings = described.schema;
275
+ } else if (settingsSkipped) {
276
+ skippedSettings++;
252
277
  }
253
278
  // its PAGE: what its sides say of it in doc comments, as Markdown beside it — `<id>.doc.md`,
254
279
  // named by the descriptor's `doc`; the settings schema, when read, closes it as a table
@@ -260,7 +285,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
260
285
  }
261
286
  out.set(`${PUB}/modules/${r.full}/${r.full}.json`, JSON.stringify(r.descriptor, null, 2));
262
287
  if (r.css) out.set(`${PUB}/modules/${r.full}/${r.full}.css`, r.css);
263
- if (m.type === 'script') out.set(`${PUB}/modules/${r.full}/system.js`, loaderJs);
288
+ if (m.type === 'script') out.set(`${PUB}/modules/${r.full}/loader.js`, loaderJs);
264
289
  let assetBytes = 0;
265
290
  for (const [outName, srcAbs] of r.assets) {
266
291
  const content = fileSystem.readFile(srcAbs);
@@ -298,61 +323,70 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
298
323
  let depCount = 0;
299
324
  let releasedDeps = 0;
300
325
  const depRows = []; // {specifier, version, bytes} — for the dependency-artifact report
326
+ // Process BFS dependency closure wave-by-wave: each wave resolves/dedups deterministically,
327
+ // bundles in parallel up to `concurrency`, and emits descriptors in exact BFS order.
301
328
  while (queue.length) {
302
- const [specifier, importerDir] = queue.shift();
303
- const resolved = resolveSpecifier(fileSystem, resolver, specifier, importerDir, log);
304
- if (!resolved) continue;
305
- const { full, resolvedFile, kind, version } = resolved;
306
- if (seen.has(full)) continue;
307
- seen.add(full);
308
- // a PUBLISHED package already released where this build goes is there with everything it
309
- // imports (released together with it): neither it nor its closure is built again. A package of
310
- // the distribution's own sources always is — new bytes under its version must be seen
311
- if (released?.has(full) && fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules')) {
312
- releasedDeps++;
313
- continue;
329
+ const rawWave = queue.splice(0);
330
+ const wave = [];
331
+ for (const [specifier, importerDir] of rawWave) {
332
+ const resolved = resolveSpecifier(fileSystem, resolver, specifier, importerDir, log);
333
+ if (!resolved) continue;
334
+ const { full, resolvedFile, version } = resolved;
335
+ if (seen.has(full)) continue;
336
+ seen.add(full);
337
+ // a PUBLISHED package already released where this build goes is there with everything it
338
+ // imports (released together with it): neither it nor its closure is built again. A package of
339
+ // the distribution's own sources always is — new bytes under its version must be seen
340
+ const inNodeModules = fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules');
341
+ if (released?.has(full) && inNodeModules) {
342
+ releasedDeps++;
343
+ continue;
344
+ }
345
+ wave.push({ specifier, full, resolvedFile, version, inNodeModules });
346
+ }
347
+ if (!wave.length) continue;
348
+
349
+ const builtWave = await mapLimit(wave, concurrency, ({ full, resolvedFile }) => memo(`dep:${full}`, () => buildDependency(fileSystem, {
350
+ resolver, resolvedFile, full, mode, buildConfig, engine, sourceBase: root,
351
+ })));
352
+
353
+ for (let i = 0; i < wave.length; i++) {
354
+ const { specifier, full, resolvedFile, version: depVersion, inNodeModules } = wave[i];
355
+ const res = builtWave[i];
356
+ addWatch(res.watchFiles);
357
+ writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
358
+ const depDescriptor = {
359
+ id: full,
360
+ reference: { type: 'package', specifier, version: depVersion },
361
+ assets: [],
362
+ dependencies: res.imports,
363
+ ...(res.lazyImports?.length ? { lazyDependencies: res.lazyImports } : {}),
364
+ integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
365
+ // built from the distribution's OWN sources (a workspace package), not a published one: new
366
+ // bytes under its version are a change that needs a new version — a published package's
367
+ // bytes may differ by build tooling alone, and its first deployed copy stands (deploy.mjs)
368
+ ...(inNodeModules ? {} : { local: true }),
369
+ };
370
+ out.set(`${PUB}/modules/${full}/${full}.json`, JSON.stringify(depDescriptor, null, 2));
371
+ entityDescriptors.push(depDescriptor);
372
+ depRows.push({ specifier, version: depVersion, bytes: res.jsCode.length });
373
+ // this artifact's own imports resolve from ITS package next
374
+ enqueue(res.rawImports, packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile));
375
+ depCount++;
314
376
  }
315
-
316
- // a dependency artifact is cached together with its cjs-export scan: both read the same
317
- // package files and only change together with them
318
- const res = await memo(`dep:${full}`, async () => {
319
- const namedExports = kind === 'builtin' ? null : await cjsNamedExports(fileSystem, resolver, resolvedFile, importerDir);
320
- return buildDependency(fileSystem, { resolver, specifier, resolvedFile, full, namedExports, mode, buildConfig, engine, sourceBase: root });
321
- });
322
- addWatch(res.watchFiles);
323
- writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
324
- const depVersion = version;
325
- const depDescriptor = {
326
- id: full,
327
- reference: { type: 'package', specifier, version: depVersion },
328
- assets: [],
329
- dependencies: res.imports,
330
- integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
331
- // built from the distribution's OWN sources (a workspace package), not a published one: new
332
- // bytes under its version are a change that needs a new version — a published package's
333
- // bytes may differ by build tooling alone, and its first deployed copy stands (deploy.mjs)
334
- ...(fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules') ? {} : { local: true }),
335
- };
336
- out.set(`${PUB}/modules/${full}/${full}.json`, JSON.stringify(depDescriptor, null, 2));
337
- entityDescriptors.push(depDescriptor);
338
- depRows.push({ specifier, version: depVersion, bytes: res.jsCode.length });
339
- // this artifact's own imports resolve from ITS package next
340
- enqueue(res.rawImports, packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile));
341
- depCount++;
342
377
  }
343
378
 
344
379
  // 3b) css entities: a shared UNscoped css artifact is a full catalog entity
345
380
  // (folder: css + url() assets + descriptor, no JS facet)
346
- for (const [cssFull, s] of sharedCssArtifacts) {
347
- if (released?.has(cssFull)) continue; // released with the package it comes from
348
- // a dependency's css entity is the file itself plus its url() assets; there is no graph here,
349
- // so we assemble the watched set ourselves (otherwise editing an image would not change its
350
- // hash-based name)
351
- const { css, assets: cssAssets } = await memo(`css:${cssFull}`,
352
- async () => {
353
- const r = await processCss({ fileSystem, cssFiles: [s.file], scopeClass: null, engine, mode });
354
- return { ...r, watchFiles: [s.file, ...r.assets.values()] };
355
- });
381
+ const sharedCssEntries = [...sharedCssArtifacts.entries()].filter(([cssFull]) => !released?.has(cssFull));
382
+ const builtSharedCss = await mapLimit(sharedCssEntries, concurrency, ([cssFull, s]) => memo(`css:${cssFull}`,
383
+ async () => {
384
+ const r = await processCss({ fileSystem, cssFiles: [s.file], scopeClass: null, engine, mode });
385
+ return { ...r, watchFiles: [s.file, ...r.assets.values()] };
386
+ }));
387
+ for (let i = 0; i < sharedCssEntries.length; i++) {
388
+ const [cssFull, s] = sharedCssEntries[i];
389
+ const { css, assets: cssAssets } = builtSharedCss[i];
356
390
  out.set(`${PUB}/modules/${cssFull}/${cssFull}.css`, css);
357
391
  for (const [outName, srcAbs] of cssAssets) {
358
392
  out.set(`${PUB}/modules/${cssFull}/${outName}`, fileSystem.readFile(srcAbs));
@@ -471,8 +505,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
471
505
  };
472
506
  const serverMods = builtRoots.flatMap((r) => discoverServerModulesIn(fileSystem, r));
473
507
  const actionPermissionsByNamespace = new Map();
474
- let serverCount = 0;
475
- for (const sm of serverMods) {
508
+ const builtServerMods = await mapLimit(serverMods, concurrency, async (sm) => {
476
509
  try {
477
510
  // what the module OFFERS — its actions that offer themselves as tools, its handlers, their
478
511
  // input and settings as JSON Schema — asked of the built module itself, kept with the build
@@ -481,27 +514,37 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
481
514
  const built = await buildServerModule(fileSystem, sm, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir });
482
515
  return { ...built, offers: evaluate ? await offersOf(built.jsCode, evaluate) : null };
483
516
  });
484
- addWatch(s.watchFiles);
485
- writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
486
- // the facet's wasm imports travel as assets next to the monolith: the runner will declare
487
- // them as bundle modules under the same relative names
488
- for (const [assetName, srcFile] of s.wasmAssets) {
489
- out.set(`private/modules/${s.full}/${assetName}`, fileSystem.readFile(srcFile));
490
- }
491
- if (s.offers?.permissions?.length) {
492
- const list = actionPermissionsByNamespace.get(sm.namespace) ?? [];
493
- list.push(...s.offers.permissions);
494
- actionPermissionsByNamespace.set(sm.namespace, list);
495
- }
496
- recordPrivate(s.full, { namespace: sm.namespace, name: sm.name, type: 'server', version: sm.version },
497
- s.offers ? { offers: s.offers } : {}, [...s.wasmAssets.keys()]);
498
- record(sm, 'server', s.jsCode.length, 'private'
499
- + (s.wasmAssets.size ? `, ${s.wasmAssets.size} wasm asset(s)` : ''));
500
- serverCount++;
517
+ return { sm, ok: true, s };
501
518
  } catch (e) {
502
- log(` ! server side ${sm.name}@${sm.namespace} not bundled (${String(e.message || e)})`
519
+ return { sm, ok: false, e };
520
+ }
521
+ });
522
+ let serverCount = 0;
523
+ for (const item of builtServerMods) {
524
+ const { sm } = item;
525
+ if (!item.ok) {
526
+ log(` ! server side ${sm.name}@${sm.namespace} not bundled (${String(item.e.message || item.e)})`
503
527
  + ` — skipped; needs @mosetta/server-action Web-API port`);
528
+ continue;
529
+ }
530
+ const { s } = item;
531
+ addWatch(s.watchFiles);
532
+ writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
533
+ // the facet's wasm imports travel as assets next to the monolith: the runner will declare
534
+ // them as bundle modules under the same relative names
535
+ for (const [assetName, srcFile] of s.wasmAssets) {
536
+ out.set(`private/modules/${s.full}/${assetName}`, fileSystem.readFile(srcFile));
537
+ }
538
+ if (s.offers?.permissions?.length) {
539
+ const list = actionPermissionsByNamespace.get(sm.namespace) ?? [];
540
+ list.push(...s.offers.permissions);
541
+ actionPermissionsByNamespace.set(sm.namespace, list);
504
542
  }
543
+ recordPrivate(s.full, { namespace: sm.namespace, name: sm.name, type: 'server', version: sm.version },
544
+ s.offers ? { offers: s.offers } : {}, [...s.wasmAssets.keys()]);
545
+ record(sm, 'server', s.jsCode.length, 'private'
546
+ + (s.wasmAssets.size ? `, ${s.wasmAssets.size} wasm asset(s)` : ''));
547
+ serverCount++;
505
548
  }
506
549
  for (const [namespace, declared] of actionPermissionsByNamespace) {
507
550
  let entry = distributionByNamespace.get(namespace);
@@ -537,9 +580,11 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
537
580
  let ssrCount = 0;
538
581
  const scriptDirs = new Set(mods.filter((m) => m.type === 'script').map((m) => path.dirname(m.file)));
539
582
  const ssrRoots = mods.filter((m) => m.type === 'component' && scriptDirs.has(path.dirname(m.file)));
540
- for (const am of ssrRoots) {
541
- const s = await memo(`ssr:${fullTileName(am)}`,
542
- () => buildSsrModule(fileSystem, am, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir }));
583
+ const builtSsrRoots = await mapLimit(ssrRoots, concurrency, (am) => memo(`ssr:${fullTileName(am)}`,
584
+ () => buildSsrModule(fileSystem, am, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir })));
585
+ for (let i = 0; i < ssrRoots.length; i++) {
586
+ const am = ssrRoots[i];
587
+ const s = builtSsrRoots[i];
543
588
  if (s.watchFile) watchFiles.add(s.watchFile);
544
589
  addWatch(s.watchFiles);
545
590
  writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
@@ -5,18 +5,27 @@
5
5
 
6
6
  /** Inert form: `mosetta.build.mjs` is absent or the caller did not load it. */
7
7
  export const INERT_BUILD_CONFIG = Object.freeze({
8
- file: null, stamp: 'none', clientPlugins: null, serverEsbuild: null, rollupOptions: null,
8
+ file: null, stamp: 'none', plugins: null, esbuildOptions: null,
9
9
  });
10
10
 
11
+ /** User esbuild plugins from `mosetta.build.mjs`, placed BEFORE framework plugins. */
12
+ export function userPluginsFor(buildConfig, target, mode) {
13
+ return buildConfig?.plugins?.({ target, mode }) ?? [];
14
+ }
15
+
16
+ /** User esbuild options escape hatch from `mosetta.build.mjs` (sync or async). */
17
+ export async function applyEsbuildOptions(buildConfig, options, target, mode) {
18
+ return (await buildConfig?.esbuildOptions?.(options, { target, mode })) ?? options;
19
+ }
11
20
 
12
- // The protocol invariant a user plugin must not break: a client artifact is a
13
- // NAMED System.register — the runtime links artifacts by these string names. Checked after every
14
- // generate; quote-agnostic (production minify normalizes quotes).
15
- export function assertNamedRegister(code, full, buildConfig) {
16
- const re = new RegExp(`System\\.register\\(\\s*["']${full.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`);
21
+ // The protocol invariant a user plugin must not break: a client artifact is a passive
22
+ // factory registration on `globalThis.__mosetta__["<full-id>"] = [function(...), [...]]`.
23
+ export function assertFactoryArtifact(code, full, buildConfig) {
24
+ const escaped = full.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
25
+ const re = new RegExp(`__mosetta__\\s*\\|\\|\\s*\\{\\}\\s*\\)\\s*\\[\\s*["']${escaped}["']\\s*\\]\\s*=\\s*\\[\\s*function`);
17
26
  if (re.test(code)) return;
18
27
  const hint = buildConfig?.file && buildConfig.stamp !== 'none'
19
28
  ? ` — check your plugins in ${buildConfig.file} (reproduce without them first)`
20
29
  : '';
21
- throw new Error(`artifact ${full} lost its named System.register form${hint}`);
30
+ throw new Error(`artifact ${full} lost its passive factory registration form${hint}`);
22
31
  }
@@ -1,97 +1,46 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
1
  import { path } from './nodeApi.mjs';
3
2
  import { packageDirOf } from './packageMeta.mjs';
4
- import { defineEnv } from './plugins/defineEnv.mjs';
5
- import { portResolve } from './plugins/portResolve.mjs';
6
3
  import { resolveSpecifier } from './specifiers.mjs';
7
- import { assertNamedRegister } from './buildConfig.mjs';
8
- import { userPluginsFor } from './buildModules.mjs';
9
- import { sourcemapPathTransformFor } from './sourcemap.mjs';
10
- import { transformTs, minifyChunk } from './plugins/transform.mjs';
11
-
12
- const isBareExternal = (id) =>
13
- !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0');
14
-
15
- const FACADE_ID = '\0mosetta-facade';
4
+ import { generateFactory } from './buildModules.mjs';
16
5
 
17
6
  /**
18
- * Build one external dependency (npm or framework package) into a System artifact.
19
- * Internal/relative imports are bundled; cross-package bare imports stay external
20
- * (→ their own artifacts, resolved by the import map).
21
- * For CJS deps, `namedExports` (enumerated via Node) generates a facade so the artifact
22
- * exposes real named exports (needed for cross-artifact `import { x } from 'pkg'`).
23
- * Returns { full, code, imports } where imports = bare deps of this artifact.
7
+ * Build one external dependency (npm or framework package) into a passive factory artifact.
8
+ * Internal/relative imports are bundled; cross-package bare imports stay external (rewritten to
9
+ * version-qualified full-ids). CJS dependencies (react, react-dom, scheduler) are handled
10
+ * natively by esbuild with no `cjs-module-lexer` facade needed.
24
11
  */
25
- export async function buildDependency(fileSystem, { resolver, specifier, resolvedFile, full, namedExports, mode = 'development', buildConfig = null, engine, sourceBase }) {
12
+ export async function buildDependency(fileSystem, { resolver, resolvedFile, full, mode = 'development', buildConfig = null, engine, sourceBase }) {
26
13
  // this dependency's OWN transitives resolve from ITS package — dockview finds
27
14
  // dockview-core in its .pnpm neighbourhood, no app-level declarations
28
15
  const baseDir = packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile);
29
16
  // maps are always EXTERNAL (placed into the private counterpart by writeJs); in dev,
30
17
  // heavy vendor deps (react) skip map generation entirely — nobody debugs their internals
31
18
  const isTS = /\.tsx?$/.test(resolvedFile);
32
- const sourcemap = mode === 'production' || isTS;
33
- const useFacade = Array.isArray(namedExports) && namedExports.length > 0;
34
- const facadeCode = useFacade
35
- ? `import __cjs from ${JSON.stringify(resolvedFile)};\n`
36
- + `export default __cjs;\n`
37
- + `export const { ${namedExports.join(', ')} } = __cjs;\n`
38
- : null;
19
+ const wantSourcemap = mode === 'production' || isTS;
39
20
 
40
- // the rollupOptions escape hatch transforms the composed INPUT options; user
41
- // plugins land after the facade virtual entry (it must keep resolving first) and before the
42
- // framework chain
43
- const optionsHook = (o) => buildConfig?.rollupOptions?.(o, { target: 'dependency', mode }) ?? o;
44
- const bundle = await engine.rollup(optionsHook({
45
- input: useFacade ? FACADE_ID : resolvedFile,
46
- external: isBareExternal,
47
- plugins: [
48
- {
49
- name: 'mosetta-facade',
50
- resolveId(id) {
51
- return id === FACADE_ID ? id : null;
52
- },
53
- load(id) {
54
- return id === FACADE_ID ? facadeCode : null;
55
- },
56
- },
57
- ...userPluginsFor(buildConfig, 'dependency', mode),
58
- defineEnv(mode),
59
- portResolve(fileSystem, resolver, baseDir),
60
- commonjs(),
61
- transformTs(engine), // .js (CJS deps like react) is handled by @rollup/plugin-commonjs
62
- ],
63
- onwarn(w, warn) {
64
- if (w.code === 'UNRESOLVED_IMPORT' || w.code === 'CIRCULAR_DEPENDENCY') return;
65
- warn(w);
66
- },
67
- }));
68
-
69
- // rewrite cross-package externals `bare` → version-qualified full-id
70
- const externalMap = new Map();
71
- const paths = (id) => {
72
- const f = resolveSpecifier(fileSystem, resolver, id, baseDir)?.full || id;
73
- externalMap.set(id, f);
74
- return f;
75
- };
76
- // named register (SSR epic stage 1) — same rationale as buildModules.generateSystem; production
77
- // minify mangles only artifact-internal scope (linkage names are string literals)
78
- const { output } = await bundle.generate({
79
- format: 'system', name: full, exports: 'named', sourcemap, paths,
80
- sourcemapPathTransform: sourcemapPathTransformFor(sourceBase),
81
- plugins: mode === 'production' ? [minifyChunk(engine)] : [],
21
+ const { code, map, imports, lazyImports, rawImports, watchFiles } = await generateFactory({
22
+ engine,
23
+ fileSystem,
24
+ resolver,
25
+ sourceBase,
26
+ baseDir,
27
+ input: resolvedFile,
28
+ name: full,
29
+ wantSourcemap,
30
+ resolveExternal: (id) => resolveSpecifier(fileSystem, resolver, id, baseDir)?.full,
31
+ minified: mode === 'production',
32
+ buildConfig,
33
+ target: 'dependency',
34
+ mode,
82
35
  });
83
- const watchFiles = bundle.watchFiles.slice();
84
- await bundle.close();
85
36
 
86
- const chunk = output.find((o) => o.type === 'chunk');
87
- assertNamedRegister(chunk.code, full, buildConfig); // protocol invariant
88
- const map = sourcemap === true && chunk.map ? chunk.map.toString() : null;
89
37
  return {
90
38
  full,
91
- jsCode: chunk.code,
39
+ jsCode: code,
92
40
  map,
93
- imports: [...externalMap.values()], // full-ids
94
- rawImports: [...externalMap.keys()], // bare specifiers (for closure traversal)
41
+ imports,
42
+ lazyImports,
43
+ rawImports,
95
44
  watchFiles,
96
45
  };
97
46
  }