Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 60354x 60354x 60354x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 1x 1x 1x 1x 1x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 6x 6x 6x 6x 6x 6x 6x 6x 6x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 206x 15275x 15275x 6x 6x 6x 6x 6x 6x 6x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 15275x 206x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 3x 3x 3x 3x 3x 3x 3x 3x 3x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 18968x 4x 4x 18968x 1x 1x 18963x 18968x 18968x 18968x 18968x 18968x 18959x 18959x 18968x 18968x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 6x 6x 460x 460x 460x 460x 460x 460x 460x 3x 3x 3x 3x 3x 3x 3x 3x 3x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 246x 460x 460x 460x 460x 460x 460x 460x 57815x 57815x 1289x 57815x 57815x 460x 460x 460x 460x 460x 460x 460x 460x 18966x 1048x 1048x 17918x 18966x 3x 3x 3x 1x 1x 1x 1x 1x 3x 17915x 18966x 460x 460x 460x 460x 460x 460x 460x 460x 460x 58040x 58040x 39074x 39074x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 18966x 58040x 11x 1x 1x 1x 1x 1x 1x 1x 11x 18964x 58040x 58040x 57815x 9x 9x 57806x 57806x 57806x 57806x 18942x 18942x 58040x 460x 460x 460x 460x 460x 460x 460x 246x 246x 232x 232x 232x 246x 460x 460x 460x 460x 460x 460x 460x 460x 460x 232x 232x 232x 18326x 18326x 211x 211x 18115x 18115x 18326x 6x 6x 6x 6x 6x 18326x 18109x 61208x 61208x 18109x 24354x 24354x 18109x 211x 211x 211x 837x 837x 837x 211x 18109x 18115x 18115x 18115x 232x 232x 232x 18115x 18115x 232x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 232x 18112x 18106x 18106x 99102x 99102x 99102x 99102x 3x 3x 3x 3x 3x 3x 3x 99102x 99102x 99102x 99102x 99102x 18106x 18106x 18112x 45683x 45683x 45683x 74207x 74207x 45680x 18112x 24354x 24354x 18103x 232x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 229x 229x 229x 229x 229x 55174x 55174x 55174x 211x 211x 211x 211x 211x 211x 18026x 18026x 18026x 18026x 18026x 18026x 18026x 54945x 54945x 18026x 18026x 18026x 18026x 18026x 229x 229x 229x 229x 229x 229x 229x 229x 460x 460x 460x 460x 460x 460x 460x 460x 60143x 60143x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 460x 246x 246x 246x 246x 246x 232x 232x 232x 232x 232x 229x 229x 229x 246x 460x 460x | /**
* @file graph.js
* @description Builds the module graph an Avenx application actually has.
*
* ## The invariant this file exists to establish
*
* ```text
* avenx build reports success => every import in the application resolved,
* and every name it imported is exported
* ```
*
* The concatenator could not state anything of the kind. It had no graph: it
* read a directory, appended text, and deleted the imports it did not
* recognise. An import that named nothing and an import that named a real
* package produced the same output — none — so "the build succeeded" carried
* no information about whether the application could start.
*
* Here, loading a module means resolving each of its specifiers. A specifier
* that resolves to nothing throws, with the importer and the reason. Nothing is
* skipped, and there is no path through this file that drops an edge.
*
* ## Binding validation
*
* Real ES modules are checked further: `import { formt } from './format.js'`
* fails at link time in a browser, so it fails here, with the near-miss
* suggested. CommonJS modules are exempt because their exports are a runtime
* object rather than a declaration — claiming to know them statically would
* produce confident false positives, which is worse than not checking.
*
* ## Cycles
*
* Cycles are legal ES modules and the runtime contains one
* (`reactive/watcher.js` ↔ `trace/reactive.js`), so refusing them is not an
* option. They are detected, recorded per edge, and handed to the emitter,
* which reproduces the only guarantee the language itself makes across a cycle:
* function declarations hoist, so a cyclic import of a function works and a
* cyclic import of a class or a `const` is a temporal dead zone. The emitter
* mirrors that exactly rather than inventing a weaker rule.
* @module lib/bundler/graph
*/
import fs from 'fs';
import { parseModule } from './parseModule.js';
import { CodeMask } from './scanner.js';
import { ResolveError } from './resolve.js';
/**
* Keys an edge for the cyclic-edge set.
*
* A NUL separator rather than a space, because module ids are file paths and a
* path may legitimately contain spaces.
* @param {string} from - Importing module id.
* @param {string} to - Imported module id.
* @returns {string} The edge key.
*/
function edgeKey(from, to) {
return `${from}\u0000${to}`;
}
/**
* Signals a dynamic import the build cannot resolve.
*/
export class DynamicImportError extends Error {
/**
* @param {string} message - The diagnostic.
* @param {string} importer - The module containing it.
*/
constructor(message, importer) {
super(message);
this.name = 'DynamicImportError';
/** @type {string} */
this.importer = importer;
}
}
/**
* Signals an `import.meta` in a module the bundle would contain.
*/
export class ImportMetaError extends Error {
/**
* @param {string} message - What the reader can do about it.
* @param {string} file - The module containing it.
* @param {string} excerpt - The source around it.
* @param {number} [line] - Its line, when the module is the file on disk.
*/
constructor(message, file, excerpt, line) {
super(message);
this.name = 'ImportMetaError';
/** @type {string} */
this.file = file;
/** @type {string} */
this.excerpt = excerpt;
/** @type {number|undefined} */
this.line = line;
}
}
/**
* Rejects `import.meta` in the modules that reached the bundle.
*
* Checked after shaking rather than while reading: a dual-environment package
* can keep a Node-only file behind a barrel, and a module the bundle drops
* cannot break it.
* @param {object} graph - The linked module graph.
* @param {Set<string>} included - Module ids being emitted.
* @returns {void}
* @throws {ImportMetaError} When an included module uses `import.meta`.
*/
export function assertNoImportMeta(graph, included) {
for (const id of included) {
const { record, source, virtual } = graph.modules.get(id);
if (record.importMeta.length === 0) continue;
const start = record.importMeta[0];
const lineStart = source.lastIndexOf('\n', start) + 1;
// From `meta`, because the expression itself may span lines.
const lineEnd = source.indexOf('\n', source.indexOf('meta', start));
// A window, because a dependency's line may be a whole minified file.
const excerpt = source
.slice(Math.max(lineStart, start - 40), Math.min(lineEnd === -1 ? source.length : lineEnd, start + 80))
.replace(/\s+/g, ' ')
.trim();
const owner = id.match(/.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/);
throw new ImportMetaError(
owner
? `This comes from the package "${owner[1].replace('\\', '/')}", not your code. Use a browser build of it, or a package that does not need import.meta.`
: 'For environment variables use process.env.AVX_PUBLIC_*, which the build inlines in the entry, components, pages, bridges and guards, but not in other imported modules. For the page\'s own address use document.baseURI.',
id,
excerpt,
// A virtual module's offsets may not match the file a developer sees.
virtual ? undefined : source.slice(0, start).split('\n').length,
);
}
}
/**
* Signals that a module imports a name its source does not export.
*/
export class BindingError extends Error {
/**
* @param {string} message - The diagnostic.
* @param {string} importer - The module doing the importing.
* @param {string} specifier - The specifier it imported from.
* @param {string} name - The missing export.
*/
constructor(message, importer, specifier, name) {
super(message);
this.name = 'BindingError';
/** @type {string} */
this.importer = importer;
/** @type {string} */
this.specifier = specifier;
/** @type {string} */
this.missing = name;
}
}
/**
* Detects whether a source is CommonJS rather than an ES module.
*
* ES syntax wins outright: a file with `import` or `export` declarations is a
* module regardless of what else it contains. Only when there are none does a
* `module.exports`, `exports.x` or `require(` marker make it CommonJS.
* @param {object} record - The parsed module record.
* @param {string} source - The module source.
* @param {string} file - The module path, for extension hints.
* @returns {'esm'|'cjs'} The module format.
*/
export function detectFormat(record, source, file) {
if (file.endsWith('.cjs')) {
return 'cjs';
}
if (file.endsWith('.mjs')) {
return 'esm';
}
const hasEsm =
record.imports.length > 0 ||
record.exports.length > 0 ||
record.reExports.length > 0 ||
record.starReExports.length > 0;
if (hasEsm) {
return 'esm';
}
return /\bmodule\.exports\b|\bexports\.[A-Za-z_$]|\brequire\s*\(/.test(source) ? 'cjs' : 'esm';
}
/**
* Finds the static `require()` specifiers in a CommonJS module.
*
* A CommonJS dependency is as real as an ES one, so it belongs in the graph.
* Only literal specifiers are collected: `require(name)` with a computed
* argument cannot be resolved at build time by anyone, and pretending otherwise
* would produce a confident wrong answer.
* @param {string} source - The module source.
* @returns {string[]} Distinct specifiers, in source order.
*/
function collectRequires(source) {
const mask = new CodeMask(source);
const text = mask.withoutComments();
const pattern = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
const found = [];
let match;
while ((match = pattern.exec(text)) !== null) {
// The specifier itself sits inside a string, so test the `require` keyword.
if (!mask.isCode(match.index)) continue;
if (!found.includes(match[2])) found.push(match[2]);
}
return found;
}
/**
* Suggests the closest name to a missing one, for a diagnostic.
* @param {string} name - The name that was not found.
* @param {string[]} candidates - Names that do exist.
* @returns {string} A suggestion clause, or an empty string.
*/
function suggest(name, candidates) {
const lower = name.toLowerCase();
const near = candidates.find(
(candidate) =>
candidate.toLowerCase() === lower ||
(Math.abs(candidate.length - name.length) <= 2 && candidate.toLowerCase().startsWith(lower.slice(0, 3))),
);
return near ? ` Did you mean "${near}"?` : '';
}
/**
* One module in the graph.
* @typedef {object} GraphModule
* @property {string} id - Resolved module id.
* @property {string} source - Module source.
* @property {'esm'|'cjs'} format - How the module declares its exports.
* @property {object} record - The parsed module structure.
* @property {Map<string, string>} resolved - Specifier to resolved module id.
* @property {boolean} virtual - Whether the compiler generated this module.
* @property {Set<string>} exportNames - Every name the module exports.
* @property {boolean} external - Whether the module came from node_modules.
*/
/**
* The module graph for one bundle.
*/
export class ModuleGraph {
/**
* @param {object} options - Graph options.
* @param {Resolver} options.resolver - Specifier resolution.
* @param {string[]} [options.externalDynamicImports] - Specifiers to preserve as native dynamic imports.
*/
constructor({ resolver, externalDynamicImports = [] }) {
/** @type {Resolver} */
this.resolver = resolver;
/** @type {string[]} */
this.externalDynamicImports = externalDynamicImports;
/** @type {Map<string, GraphModule>} */
this.modules = new Map();
/** @type {string[]} */
this.entries = [];
/** @type {Array<string[]>} */
this.cycles = [];
/** @type {Set<string>} */
this.cyclicEdges = new Set();
}
/**
* Checks whether a specifier is marked as an external dynamic import.
* @param {string} specifier - The specifier.
* @returns {boolean}
*/
isExternalDynamic(specifier) {
if (!specifier) return false;
return this.externalDynamicImports.some((pattern) =>
pattern.endsWith('/') ? specifier.startsWith(pattern) : specifier === pattern
);
}
/**
* Reads a module's source, from the virtual table or from disk.
* @param {string} id - The module id.
* @returns {string} The source text.
* @private
*/
readSource(id) {
if (this.resolver.isVirtual(id)) {
return this.resolver.virtualModules.get(id);
}
const source = fs.readFileSync(id, 'utf-8');
if (id.endsWith('.json')) {
try {
return `export default ${JSON.stringify(JSON.parse(source))};`;
} catch (error) {
if (error instanceof SyntaxError) {
error.message = `Invalid JSON in ${id}: ${error.message}`;
}
throw error;
}
}
return source;
}
/**
* Loads a module and, transitively, everything it imports.
* @param {string} id - The resolved module id.
* @returns {GraphModule} The loaded module.
* @throws {ResolveError} When one of its specifiers resolves to nothing.
* @private
*/
load(id) {
const existing = this.modules.get(id);
if (existing) {
return existing;
}
const source = this.readSource(id);
const record = parseModule(source, id);
const format = detectFormat(record, source, id);
/** @type {GraphModule} */
const module = {
id,
source,
format,
record,
resolved: new Map(),
virtual: this.resolver.isVirtual(id),
exportNames: new Set(),
external: id.includes('node_modules'),
};
this.modules.set(id, module);
for (const entry of record.dynamicImports) {
if (entry.specifier === null) {
throw new DynamicImportError(
'A dynamic import with a computed specifier cannot be resolved at build time, and an Avenx ' +
'bundle is a classic script with no module loader to resolve it at run time.\n' +
"Use a literal specifier -- import('./thing.js') -- so the module can be bundled.",
id,
);
}
}
const specifiers = format === 'esm' ? record.dependencies : collectRequires(source);
for (const specifier of specifiers) {
if (this.isExternalDynamic(specifier)) {
continue;
}
const target = this.resolver.resolve(specifier, id);
module.resolved.set(specifier, target);
this.load(target);
}
return module;
}
/**
* Adds an entry module and everything reachable from it.
* @param {string} id - The resolved entry id.
* @returns {GraphModule} The entry module.
*/
addEntry(id) {
const module = this.load(id);
if (!this.entries.includes(id)) {
this.entries.push(id);
}
return module;
}
/**
* Computes each module's export names, following re-exports and `export *`.
*
* Runs after every module is loaded, because `export * from './x.js'` cannot
* be answered until `x.js` itself has been read.
* @returns {void}
*/
resolveExportNames() {
const inProgress = new Set();
const compute = (id) => {
const module = this.modules.get(id);
if (!module || module.exportNames.size > 0 || inProgress.has(id)) {
return module ? module.exportNames : new Set();
}
inProgress.add(id);
if (module.format === 'cjs') {
// A CommonJS module's shape is a runtime value. `default` is the whole
// exports object and named access is checked by nothing here, which is
// honest: the alternative is a static claim that cannot be true.
module.exportNames.add('default');
module.exportNames.add('*');
} else {
for (const entry of module.record.exports) {
module.exportNames.add(entry.exported);
}
for (const entry of module.record.reExports) {
module.exportNames.add(entry.exported);
}
for (const entry of module.record.starReExports) {
const target = module.resolved.get(entry.specifier);
if (!target) continue;
for (const name of compute(target)) {
// `export *` never re-exports `default`.
if (name !== 'default') module.exportNames.add(name);
}
}
}
inProgress.delete(id);
return module.exportNames;
};
for (const id of this.modules.keys()) {
compute(id);
}
}
/**
* Checks that every imported name is actually exported.
*
* Only ES modules are checked, and only when the *target* is an ES module: a
* CommonJS target has no static export list, and a wildcard entry (`*`)
* stands for "cannot be known".
* @returns {void}
* @throws {BindingError} When a module imports a name that does not exist.
*/
validateBindings() {
for (const module of this.modules.values()) {
if (module.format !== 'esm') continue;
const check = (specifier, imported, label) => {
const targetId = module.resolved.get(specifier);
const target = targetId && this.modules.get(targetId);
if (!target || target.format !== 'esm' || target.exportNames.has('*')) return;
if (imported === '*' || target.exportNames.has(imported)) return;
const available = [...target.exportNames].sort();
throw new BindingError(
`${label} "${imported}" from "${specifier}", but that module does not export it.` +
suggest(imported, available) +
(available.length > 0
? `\nIt exports: ${available.join(', ')}`
: '\nIt exports nothing.'),
module.id,
specifier,
imported,
);
};
for (const entry of module.record.imports) {
if (entry.namespace) continue;
if (entry.defaultLocal) check(entry.specifier, 'default', 'imports');
for (const binding of entry.bindings) {
check(entry.specifier, binding.imported, 'imports');
}
}
for (const entry of module.record.reExports) {
check(entry.specifier, entry.imported, 're-exports');
}
}
}
/**
* Orders modules so a dependency is emitted before its dependants.
*
* Depth-first post-order. When the walk meets a module already on the stack
* it has found a cycle: the cycle is recorded for diagnostics and the edge
* that closes it is marked, so the emitter knows which bindings cannot be
* read at module-initialisation time.
* @returns {string[]} Module ids in emission order.
*/
topologicalOrder() {
const order = [];
const state = new Map();
const stack = [];
const visit = (id) => {
const current = state.get(id);
if (current === 'done') return;
if (current === 'active') {
const start = stack.indexOf(id);
const cycle = stack.slice(start).concat(id);
this.cycles.push(cycle);
this.cyclicEdges.add(edgeKey(stack[stack.length - 1], id));
return;
}
state.set(id, 'active');
stack.push(id);
const module = this.modules.get(id);
if (module) {
for (const target of module.resolved.values()) {
visit(target);
}
}
stack.pop();
state.set(id, 'done');
order.push(id);
};
for (const entry of this.entries) {
visit(entry);
}
return order;
}
/**
* Whether an edge closes a cycle.
* @param {string} from - Importing module id.
* @param {string} to - Imported module id.
* @returns {boolean} True when the import is a back edge.
*/
isCyclicEdge(from, to) {
return this.cyclicEdges.has(edgeKey(from, to));
}
}
/**
* Builds a graph from one or more entry modules.
* @param {object} options - Build options.
* @param {string[]} options.entries - Resolved entry module ids.
* @param {Resolver} options.resolver - Specifier resolution.
* @param {boolean} [options.validate] - Whether to check imported names exist.
* @param {string[]} [options.externalDynamicImports] - Specifiers to preserve as native dynamic imports.
* @returns {{graph: ModuleGraph, order: string[]}} The graph and its emission order.
* @throws {ResolveError|BindingError} When the application does not link.
*/
export function buildGraph({ entries, resolver, validate = true, externalDynamicImports = [] }) {
const graph = new ModuleGraph({ resolver, externalDynamicImports });
for (const entry of entries) {
graph.addEntry(entry);
}
graph.resolveExportNames();
if (validate) {
graph.validateBindings();
}
const order = graph.topologicalOrder();
return { graph, order };
}
export { ResolveError };
|