Repository navigation
Expand file tree
/
Copy pathlib_compiler_ComponentParser.js.html
More file actions
2597 lines (2338 loc) · 128 KB
/
Copy pathlib_compiler_ComponentParser.js.html
File metadata and controls
2597 lines (2338 loc) · 128 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: lib/compiler/ComponentParser.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: lib/compiler/ComponentParser.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import fs from 'fs';
import path from 'path';
import ExpressionParser, { readDeclarations } from './expressionParser.js';
import { analyzeBridgeFile, findBridgeImports } from './BridgeParser.js';
import ContractValidator from './ContractValidator.js';
import { logger } from '../core/runtime/AvenxLogger.js';
import { AvenxErrorCodes } from '../core/runtime/AvenxError.js';
import { RESERVED_INSTANCE_KEYS } from '../core/runtime/AvenxComponent.js';
import { TemplateValidationError, BuildError } from './errors/index.js';
import { reportWarning } from './utils/warningReporter.js';
import { replaceEnvVariables } from '../env.js';
import { processBindDirectives, escapeTemplateMarkers } from '../core/utils/templateUtils.js';
import loadConfig, { resolvePathAlias, getClosestKey } from '../config.js';
import { collectLocations } from './sourceMapTrace.js';
import { addCachedComponentUnit } from './atlas/cache.js';
import { collectTemplateEvents } from './templateEvents.js';
import { getLineAndColumn, parseAttributes, parseHTML, scanTagEnd, serializeHTML } from './parser/htmlTree.js';
import { buildTemplateIR, parseForHeader } from './ir/build.js';
import { lowerToProgram } from './ir/lower.js';
import { validateComponentExpressions } from './validateExpressions.js';
import { collectImportStatements } from './modules.js';
/**
* The executable source of each declared resource, keyed by name.
*
* A resource is emitted either as a bare handler string or as
* `{ handler, pollInterval }`, and the runtime prefixes a bare expression with
* `return`. Both shapes are normalised here so the generator sees exactly the
* text the runtime will execute -- otherwise a polling resource would compile
* against a string that is not what runs, and quietly miss.
* @param {object} resources - The parsed resource declarations.
* @returns {Object<string, string>} Handler sources by resource name.
*/
function resourceBodies(resources) {
const bodies = {};
for (const [name, definition] of Object.entries(resources || {})) {
const handler = definition && typeof definition === 'object' ? definition.handler : definition;
if (typeof handler !== 'string' || handler.trim() === '') continue;
bodies[name] = handler.trim().startsWith('return') ? handler : `return ${handler}`;
}
return bodies;
}
import { collectExpressions } from './codegen/collect.js';
import { buildExpressionTable, buildProgramTables } from './codegen/table.js';
/**
* Framework tags the compiler understands directly. These are never real
* components, so a reference to one must not be reported as an unresolved
* component (see {@link ComponentParser#validateComponentTags} / AVX_W46).
*
* The `@`-prefixed directives (`@for`, `@if`, `@suspense`, …) are handled
* separately: any tag beginning with `@` is skipped unconditionally, so it is
* enough to list the non-prefixed framework tags here.
* @type {Set<string>}
*/
const BUILTIN_TAGS = new Set([
'slot',
'resource',
'state',
'action',
'transition',
'template',
'component',
'script',
'style',
]);
/**
* The parameter names bound by arrow functions in an expression.
*
* Covers `x => …` and `(x, y) => …`, which is the whole of what the template
* expression language admits -- a destructuring parameter is not an expression
* and is refused before it reaches here.
* @param {string} code - The expression source.
* @returns {Set<string>} The bound names.
*/
function arrowParameters(code) {
const names = new Set();
const arrow = /(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s*=>/g;
let match;
while ((match = arrow.exec(code)) !== null) {
const list = match[1] !== undefined ? match[1] : match[2];
for (const part of list.split(',')) {
const name = part.trim();
if (/^[A-Za-z_$][\w$]*$/.test(name)) names.add(name);
}
}
return names;
}
/**
* Adds every name a `<@for>` header binds to the declared set.
*
* `index` is included for every loop, named or not, because that is how the
* loop index has always been reached -- and reporting it as undeclared was a
* warning on correct code, which is worse than no warning at all.
* @param {object} node - A parsed template node.
* @param {Set<string>} declared - The set to add to.
*/
function collectLoopBindings(node, declared) {
if (!node || node.type !== 'element') return;
if ((node.tagName || '').toLowerCase() === '@for') {
declared.add('index');
try {
const parts = parseForHeader(node.rawAttrs);
if (parts.item) declared.add(parts.item);
for (const name of parts.destructure || []) declared.add(name);
} catch {
// A malformed header is reported by the IR builder, with a location and
// a reason. Adding a second, vaguer complaint here would not help.
}
}
for (const child of node.children || []) {
collectLoopBindings(child, declared);
}
}
/**
* A conservative set of known HTML and SVG element names. Element names are
* lowercase, so a PascalCase tag can practically never collide with one; this
* set exists only as a defensive net for an element written with an unusual
* case. It is deliberately not exhaustive — anything lowercase is treated as an
* ordinary element regardless of membership (see {@link ComponentParser#validateComponentTags}).
* @type {Set<string>}
*/
const KNOWN_ELEMENTS = new Set([
// Common HTML
'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog',
'div', 'dl', 'dt', 'em', 'fieldset', 'figcaption', 'figure', 'footer',
'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup',
'html', 'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map',
'mark', 'menu', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt',
'ruby', 's', 'samp', 'section', 'select', 'small', 'span', 'strong', 'sub',
'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead',
'time', 'tr', 'u', 'ul', 'var', 'video',
// SVG
'svg', 'circle', 'clippath', 'defs', 'ellipse', 'foreignobject', 'g',
'image', 'line', 'lineargradient', 'marker', 'mask', 'path', 'pattern',
'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'symbol', 'text',
'tspan', 'use',
]);
/**
* The local names a component's own imports bind, excluding bridges and the
* runtime entry.
*
* A bridge already reaches the template through the bridges argument, and the
* runtime import binds the base class the generated module extends. Everything
* else -- an npm package, a local helper -- is a value the developer expects to
* be able to name, so it becomes part of the component's evaluation scope.
* @param {string} source - The component source.
* @param {string[]} bridgeLocals - Local names already bound as bridges.
* @returns {string[]} Local binding names, in source order.
*/
function collectImportBindings(source, bridgeLocals) {
const bridges = new Set(bridgeLocals);
const names = [];
for (const statement of collectImportStatements(source)) {
const match = statement.match(/^import\s+([\s\S]*?)\s+from\s*['"]([^'"]*)['"]/);
if (!match) continue;
if (/^(avenx-core(\/(runtime|core))?)$/.test(match[2])) continue;
const clause = match[1].trim();
const braceStart = clause.indexOf('{');
const head = (braceStart === -1 ? clause : clause.slice(0, braceStart)).replace(/,\s*$/, '').trim();
const star = head.match(/^(?:([A-Za-z_$][\w$]*)\s*,\s*)?\*\s+as\s+([A-Za-z_$][\w$]*)$/);
if (star) {
if (star[1]) names.push(star[1]);
names.push(star[2]);
} else if (/^[A-Za-z_$][\w$]*$/.test(head)) {
names.push(head);
}
if (braceStart !== -1) {
const close = clause.indexOf('}', braceStart);
const inner = close === -1 ? clause.slice(braceStart + 1) : clause.slice(braceStart + 1, close);
for (const part of inner.split(',')) {
const trimmed = part.trim();
if (!trimmed) continue;
const aliased = trimmed.split(/\s+as\s+/);
const local = (aliased[1] || aliased[0]).trim();
if (/^[A-Za-z_$][\w$]*$/.test(local)) names.push(local);
}
}
}
return names.filter((name) => !bridges.has(name) && !names.includes(name, names.indexOf(name) + 1));
}
/**
* Cache of resolved `avenx.config.json` contents, keyed by the directory
* the search started from, so each component file doesn't re-read and
* re-parse the config from disk.
* @type {Map<string, object|null>}
*/
const configCache = new Map();
/**
* Walks up the directory tree from `startDir` looking for an
* `avenx.config.json` file, and returns its parsed contents (or `null` if
* none is found, or if it fails to parse).
* @param {string} startDir - Absolute directory to start searching from.
* @returns {object|null}
*/
function loadAvenxConfig(startDir) {
if (configCache.has(startDir)) {
return configCache.get(startDir);
}
let config = null;
let currentDir = startDir;
while (currentDir) {
const configPath = path.join(currentDir, 'avenx.config.json');
if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch (err) {
reportWarning(AvenxErrorCodes.COMPILER_INVALID_CONFIG, new BuildError(AvenxErrorCodes.COMPILER_INVALID_CONFIG, configPath, err.message));
config = null;
}
break;
}
const parent = path.dirname(currentDir);
if (parent === currentDir) {
break;
}
currentDir = parent;
}
configCache.set(startDir, config);
return config;
}
/**
* Resolves the list of project-specific void tags declared in
* `avenx.config.json` (via a `voidTags` array) for the given component
* file, e.g.:
* ```json
* { "voidTags": ["my-video", "my-icon"] }
* ```
* @param {string} [filePath] - Absolute path of the component file being compiled.
* @returns {string[]} Lowercased, trimmed custom void tag names. Empty if none configured.
*/
function getCustomVoidTags(filePath) {
if (!filePath) {
return [];
}
const startDir = path.resolve(path.dirname(filePath));
const config = loadAvenxConfig(startDir);
if (!config || !Array.isArray(config.voidTags)) {
return [];
}
return config.voidTags
.filter((tag) => typeof tag === 'string' && tag.trim() !== '')
.map((tag) => tag.trim().toLowerCase());
}
/**
* Builds the atomic descriptor the generated constructor carries.
*
* Only the runtime-relevant half of a modifier reaches the bundle. The write
* set, the boundedness flag and the irreversible-effect list are compile-time
* findings: they exist to be reported before the application ships, and the
* journal does not need them because it observes the reactive proxies rather
* than a prediction of what they will do.
*
* A modifier naming an action the component does not declare is dropped. The
* generated code would otherwise reference a method that is not there, and a
* typo in `name=` is already reported by the action itself being missing.
* @param {Object<string, {atomic: boolean, onConflict: string=}>} modifiers - Parsed modifiers.
* @param {Object<string, string>} methods - The component's action bodies.
* @returns {Object<string, object>|null} The descriptor, or null when there is nothing to emit.
*/
function buildAtomicSpec(modifiers, methods) {
if (!modifiers) return null;
/** @type {Object<string, object>} */
const spec = {};
let found = false;
for (const name of Object.keys(modifiers).sort()) {
if (!Object.prototype.hasOwnProperty.call(methods || {}, name)) continue;
const modifier = modifiers[name];
if (!modifier || !modifier.atomic) continue;
spec[name] = modifier.onConflict ? { onConflict: modifier.onConflict } : {};
found = true;
}
return found ? spec : null;
}
/**
* ComponentParser handles the parsing of Avenx component files (.js and .css).
* It extracts component state, computed properties, methods, and templates,
* and coordinates with the StyleProcessor to handle styles.
*/
class ComponentParser {
/**
* Fails the build when a refused template uses a compiled-only construct.
*
* Falling back is safe for a construct both renderers implement: the template
* renders, more slowly, and the build says so. `<@if>` is not such a
* construct. It only ever existed on the compiled path, so the string
* renderer has no rewrite for it -- a refused template containing one would
* render `<@if cond>` into the document as a literal element, wrapping the
* branch it was supposed to choose between.
*
* That is exactly the silent miscompile the compile-or-refuse rule exists to
* prevent, so it is an error with a location rather than a warning. The fix
* is always the same: get the template compiling, by moving the construct
* that refused into a child component.
* @param {string} name - The component class name.
* @param {string} filePath - The component's path.
* @param {string} template - The semantic template.
* @param {{reason: string, detail: string}} refusal - Why it refused.
* @throws {TemplateValidationError} When the template cannot fall back safely.
*/
assertNoCompiledOnlyConstruct(name, filePath, template, refusal) {
const match = template.match(/<@(if|elseif|elif|else)\b/i);
if (!match) return;
const error = new TemplateValidationError(
AvenxErrorCodes.COMPILER_COMPILED_ONLY_CONSTRUCT,
name,
match[1],
`${refusal.reason} (${refusal.detail})`,
);
error.setLocation({ source: template, index: match.index, filePath });
throw error;
}
/**
* Compiles this component's template to a render program.
*
* Runs on {@link ComponentParser#lastSemanticTemplate} -- the template after
* styles and two-way bindings and before any directive rewrite -- so the IR
* reads `<@for>` and `<@if>` as the constructs they are rather than as the
* markup they used to be turned into.
*
* Either half may refuse. The IR refuses a construct it does not model yet;
* the lowering refuses an IR node it cannot emit. Either way the component
* keeps the string renderer and the reason is recorded for the build to
* report, which is the same compile-or-refuse rule that has always applied.
* @param {string} name - The component class name.
* @param {string} filePath - The component's path, for diagnostics.
* @param {string[]} voidTags - The effective void tag set.
* @returns {{program: object|null, expressions: string[], statements: string[]}}
* The program and the sources its indices address.
*/
compileRenderProgram(name, filePath, voidTags) {
const source = this.lastSemanticTemplate;
if (typeof source !== 'string' || source.trim() === '') {
return { program: null, expressions: [], statements: [] };
}
// Static marking runs on the semantic template rather than on the rewritten
// one, because the IR is built from the semantic template and a mark
// applied after it would never be seen.
const marked = this.optimizeStaticSubtrees(source, filePath);
const built = buildTemplateIR(marked, { voidTags });
if (built.refusal) {
this.assertNoCompiledOnlyConstruct(name, filePath, source, built.refusal);
this.renderFallbacks.push({ name, reason: built.refusal.reason, detail: built.refusal.detail });
return { program: null, expressions: [], statements: [] };
}
const lowered = lowerToProgram(built.ir, { voidTags });
if (lowered.refusal) {
this.assertNoCompiledOnlyConstruct(name, filePath, source, lowered.refusal);
this.renderFallbacks.push({ name, reason: lowered.refusal.reason, detail: lowered.refusal.detail });
return { program: null, expressions: [], statements: [] };
}
return { program: lowered.program, expressions: lowered.expressions, statements: lowered.statements };
}
/**
* @param {StyleProcessor} styleProcessor - An instance of StyleProcessor to handle styles.
* @param {string[]} [customVoidTags] - Additional void tag names (lowercase).
* @param {object} [config] - Project configuration object.
*/
constructor(styleProcessor, customVoidTags = [], config = null) {
/** @type {StyleProcessor} */
this.styleProcessor = styleProcessor;
/** @type {object|null} */
this.config = config;
/** @type {ExpressionParser} */
this.expressionParser = new ExpressionParser(config);
/** @type {string[]} */
this.customVoidTags = customVoidTags || [];
/**
* Bridges discovered by the compiler, keyed by absolute path. Set by
* AvenxCompiler before components are parsed; when a component is parsed
* standalone (tests, the Vite plugin) bridges are analysed on demand.
* @type {Map<string, object>}
*/
this.bridges = new Map();
/**
* Source locations of every declaration parsed so far, keyed by class name.
*
* Collected as a by-product of parsing and written beside the bundle rather
* than into it, so `avenx trace view` can turn a recorded action name into
* a file and a line without an application paying for the mapping.
* @type {Map<string, object>}
*/
this.locations = new Map();
/**
* The Atlas model being populated, or null when Atlas is not being built.
*
* Set by AvenxCompiler. When it is null, `parse` does no Atlas work at
* all, so a caller that only wants a compiled class — the Vite plugin, a
* unit test, `loadComponent` — pays nothing for it.
* @type {AppModel|null}
*/
this.model = null;
/**
* The units handed to Atlas so far, so render edges can be resolved once
* every component name is known.
* @type {Array<{name: string, filePath: string, content: string, kind: string}>}
*/
this.__atlasUnits = [];
/**
* Every registered component and page name in the project, supplied by the
* compiler through {@link ComponentParser#setComponentNames} before any
* file is parsed. Used by the unresolved-component check (AVX_W46). Empty
* when a component is parsed standalone, which disables that check.
* @type {Set<string>}
*/
this.__componentNames = new Set();
/**
* Components whose template could not be compiled to a render program, and
* why.
*
* A component without a program renders through the string path: correct,
* and proportional to the whole template on every update. That is a real
* cost, so it is reported rather than absorbed silently -- the same house
* rule Atlas follows when its analysis is incomplete.
* @type {Array<{name: string, reason: string, detail: string}>}
*/
/**
* Per-unit information the module generator needs, keyed by absolute
* source path. Filled by {@link ComponentParser#parse}.
* @type {Map<string, object>}
*/
this.moduleMeta = new Map();
this.renderFallbacks = [];
/**
* Component tag names referenced by any template in this build.
*
* Populated as templates compile, so by the time the entry module is built
* the answer is exact rather than a guess from the source text.
* @type {Set<string>}
*/
this.referencedComponents = new Set();
/**
* What the expression generator could not compile, per unit.
*
* A security refusal fails the build; a language gap is reported as a
* warning and leaves that one expression on the runtime path. Recorded
* here rather than thrown at the point of generation so a build reports
* every unit's problems at once instead of the first one's.
* @type {Array<{name: string, refusals: object[], gaps: object[]}>}
*/
this.expressionGaps = [];
/**
* The project root, when the compiler has told the parser what it is.
*
* `findProjectRoot` walks up from a component looking for a project
* marker, which lands somewhere arbitrary in a directory that has none —
* a scratch project in a temp directory, for instance — and every reported
* path is then relative to the wrong place. The compiler resolved the root
* once and authoritatively, so it is preferred when available.
* @type {string|null}
*/
this.rootDir = null;
}
/**
* Tells the parser which directory reported paths are relative to.
* @param {string} rootDir - The project root.
* @returns {void}
*/
setRootDir(rootDir) {
this.rootDir = rootDir || null;
}
/**
* Attaches an Atlas model for `parse` to populate.
* @param {AppModel|null} model - The model.
* @returns {void}
*/
setModel(model) {
this.model = model || null;
this.__atlasUnits = [];
}
/**
* Supplies the project's bridge descriptors, so imports can be resolved
* without re-reading each bridge module for every component.
* @param {Map<string, object>} bridges - Descriptors keyed by absolute path.
*/
setBridges(bridges) {
this.bridges = bridges instanceof Map ? bridges : new Map();
}
/**
* Supplies the full set of registered component and page names, so a template
* tag can be validated against every name in the project rather than only the
* ones parsed so far.
*
* The compiler discovers all names by filename before it parses any file, and
* hands them over here. When it is never called — a component parsed
* standalone in a test or the Vite plugin — the set stays empty and the
* unresolved-component check does nothing, so a lone component is never
* flagged for referencing a sibling the parser could not see.
* @param {Iterable<string>} names - Registered component and page names.
* @returns {void}
*/
setComponentNames(names) {
this.__componentNames = names ? new Set(names) : new Set();
}
/**
* Resolves the bridges a component imports into template scope bindings.
*
* The import is the declaration: a component sees exactly the bridges it
* imported, under the local name it chose. Nothing is ambient, so the
* compiler knows every consumer of every bridge.
* @param {string} filePath - Absolute path to the component file.
* @param {string} content - The component source.
* @param {string} name - The component class name, for diagnostics.
* @param {Set<string>} contracts - The component's declared contracts.
* @returns {Array<{local: string, binding: string, bridge: string}>} The bindings.
* @private
*/
resolveBridgeBindings(filePath, content, name, contracts) {
const bindings = [];
for (const entry of findBridgeImports(filePath, content)) {
const key = path.resolve(entry.resolved);
let descriptor = this.bridges.get(key);
if (!descriptor) {
descriptor = analyzeBridgeFile(key, replaceEnvVariables);
if (!descriptor) {
continue;
}
this.bridges.set(key, descriptor);
}
if (contracts && contracts.has('isolated')) {
throw new BuildError(AvenxErrorCodes.COMPILER_BRIDGE_ISOLATED_IMPORT, name, descriptor.name);
}
bindings.push({ local: entry.local, binding: descriptor.binding, bridge: descriptor.name });
}
return bindings;
}
/**
* Parses a .component.js or .page.js file and its corresponding CSS file.
* @param {string} filePath - The absolute path to the file.
* @param {'component'|'page'} [type] - The type of file being parsed.
* @returns {string} The generated JavaScript class.
*/
parse(filePath, type = 'component') {
const config = this.config || (filePath ? loadAvenxConfig(path.dirname(filePath)) : null);
const rootDir = this.rootDir || (filePath ? loadConfig.findProjectRoot(path.dirname(filePath)) : process.cwd());
filePath = resolvePathAlias(filePath, config, rootDir);
const isPage = type === 'page';
const content = replaceEnvVariables(fs.readFileSync(filePath, 'utf-8'));
const fileName = path.basename(filePath).replace(/\.(component|page)?\.(js|html|avx)$/i, '');
// Convert user-profile or user_profile to UserProfile
const name = fileName
.split(/[-_]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
const desPath = filePath.replace(/\.(component|page)?\.(js|html|avx)$/i, isPage ? '.page.css' : '.component.css');
const desBlocks = {};
const styles = {};
if (fs.existsSync(desPath)) {
const desContent = fs.readFileSync(desPath, 'utf-8');
const globalMatch = desContent.match(/<@global>([\s\S]*?)<\/ ?@global>/i);
if (globalMatch) {
const inner = globalMatch[1];
const defRegex = /@def\s+([\w-]+)\s+([^;]+);/g;
let defMatch;
while ((defMatch = defRegex.exec(inner)) !== null) {
styles[defMatch[1]] = defMatch[2].trim();
}
}
this.styleProcessor.registerSourceFile(desPath, desContent);
this.extractStylesAndVars(desContent, desBlocks, desPath);
}
const contracts = this.extractContracts(content);
const bridgeBindings = this.resolveBridgeBindings(filePath, content, name, contracts);
// Everything else the file imports. Bridges are excluded because they reach
// the template through the bridges argument already, and the runtime entry
// is excluded because those names are the base class the module extends.
const importedLocals = collectImportBindings(content, bridgeBindings.map((entry) => entry.local));
const state = this.extractState(content, filePath, config);
const computed = this.extractComputed(content);
const methods = this.extractMethods(content, name, filePath, config);
const actionModifiers = this.extractActionModifiers(content);
const resources = this.expressionParser.parseResources(content);
let template = this.extractTemplate(
content,
desBlocks,
name,
filePath,
state,
computed,
methods,
resources,
[...bridgeBindings.map((entry) => entry.local), ...importedLocals],
);
// Handle declarative tags: <MyComponent /> or <MyComponent>...</MyComponent> -> <div data-avenx-comp="MyComponent">...</div>
// Only if it looks like a component (starts with uppercase)
template = this.processComponentTags(template);
// Which components this build actually references. The compiler uses it to
// decide whether a built-in's registering module joins the graph, so an
// application that never writes `<VirtualList>` does not carry it.
for (const match of template.matchAll(/data-avenx-comp="([A-Za-z0-9_]+)"/g)) {
this.referencedComponents.add(match[1]);
}
// Validate compiler contracts (static, pure, deterministic, isolated)
const customVoidTags = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const astNodes = parseHTML(template, customVoidTags);
const validation = ContractValidator.validate(astNodes, {
name,
filePath,
contracts,
state,
computed,
methods,
resources,
config,
});
if (!validation.valid && validation.errors.length > 0) {
throw validation.errors[0];
}
this.locations.set(name, collectLocations({
name,
filePath,
rootDir,
content,
computed,
methods,
resources,
contracts,
}));
// Atlas is retention, not a second pass: everything it needs was produced
// above on the way to generating this class, and is handed over rather
// than recomputed. The original `content` goes with it because the
// template below has already been rewritten past the point where its
// offsets point at anything a developer can open.
if (this.model) {
const atlasUnit = addCachedComponentUnit(this.model, {
name,
kind: isPage ? 'page' : 'component',
filePath,
rootDir,
content,
state,
computed,
methods,
resources,
contracts,
actionModifiers,
bridgeBindings,
bridges: this.bridges,
});
this.__atlasUnits.push({
name,
filePath,
content,
kind: isPage ? 'page' : 'component',
// The mask is the expensive half of reading a template; the render
// pass reuses the one the relationship pass already built.
masked: atlasUnit.masked,
starts: atlasUnit.starts,
});
}
// Template expressions are evaluated by Avenx's expression evaluator, which
// refuses anything outside the expression language. Checking here means an
// unsupported expression fails the build with a file and a line, rather
// than becoming an AVX_R32 the first time that component renders.
const expressionErrors = validateComponentExpressions({
name,
filePath,
content,
template,
computed,
});
if (expressionErrors.length > 0) {
throw expressionErrors[0];
}
// Identify and mark static subtrees for patcher performance optimization
template = this.optimizeStaticSubtrees(template, filePath);
// The render program is compiled from the *semantic* template -- the one
// the author wrote, before any directive was rewritten into markup. That
// ordering is the point of the IR: `<@for item in items>` still says what
// it means at that stage, and after the rewrites above it does not.
const customVoidTagsForProgram = [...(this.customVoidTags || []), ...getCustomVoidTags(filePath)];
const rendered = this.compileRenderProgram(name, filePath, customVoidTagsForProgram);
// Templates and method bodies are emitted as JSON string literals rather
// than backtick-wrapped template literals: a `${...}` sequence in component
// HTML (or a legitimate template literal inside an <action> body) would
// otherwise be interpolated by the generated bundle instead of being
// preserved verbatim.
let optionImports = '';
// A compiled component does not render from the template, so a production
// build does not carry it. That is the larger half of what the previous
// design shipped twice: the whole template travelled beside the program,
// with its `{{ }}` and its JSON-encoded handlers still in it, for a runtime
// that never looked at it.
//
// Development keeps it. `__getTemplate()` is the seam renderer benchmarks
// and the render-path parity test use to drive the same class through both
// renderers, and a suspense or error-boundary fallback is still read out of
// the template by regex -- neither of which a compiled component can have,
// because both refuse to compile, but both of which a *fallback* component
// in the same build still needs.
const shipTemplate = !rendered.program || !this.production;
const templateLiteral = JSON.stringify(shipTemplate ? template : '');
// The options argument stays absent unless something needs it, so a
// component that declares neither contracts nor atomic actions compiles to
// exactly the same constructor call it did before either feature existed.
if (importedLocals.length > 0) {
// Emitted as shorthand properties, so the object references the module's
// own bindings and the bundler sees them used.
optionImports = `imports: { ${importedLocals.join(', ')} }`;
}
const contractsList = Array.from(contracts || []);
const atomicSpec = buildAtomicSpec(actionModifiers, methods);
const optionParts = [];
if (optionImports) {
optionParts.push(optionImports);
}
if (contractsList.length > 0) {
optionParts.push(`contracts: ${JSON.stringify(contractsList)}`);
}
if (atomicSpec) {
optionParts.push(`atomic: ${JSON.stringify(atomicSpec)}`);
}
// The program travels in the options object rather than as another
// positional argument. The constructor already takes nine, and the options
// argument is the extension point that exists precisely so it does not have
// to take ten. A component compiled before render programs existed simply
// has no `program` key and takes the string path.
//
// It is referenced as a static rather than written inline, because the
// runtime caches one parsed skeleton per program *object*. An object
// literal inside the constructor is a fresh object on every `new`, so the
// cache would never hit and every instance would reparse the template --
// which is most of the cost this whole mechanism exists to remove.
let programStatic = '';
if (rendered.program) {
// The expression and statement closures the program's indices address.
// Built here rather than in the source-keyed table below because an
// indexed entry that will not compile leaves nothing behind for the
// runtime to fall back to, so the whole program has to be withdrawn.
const programTables = buildProgramTables(name, rendered.expressions, rendered.statements);
if (programTables.failure) {
this.renderFallbacks.push({
name,
reason: 'an expression the code generator could not compile',
detail: `${programTables.failure.source} (${programTables.failure.reason})`,
});
rendered.program = null;
} else {
optionParts.push(`program: ${name}.__axProgram`);
// The handler sources, for Trace only, and only in a development
// build. A causal tree reads better with "@click=\"inc()\"" on the
// event node than with "handler #2", and Trace is a development
// feature -- the recorder is not reachable from a production bundle at
// all. Gating it here is what keeps the source out of shipped output
// while leaving the tool that wants it fully served.
// Development-only debug tables. Trace names a woken binding by the
// expression it evaluates and an event node by the handler that fired,
// and both of those are source. A production bundle cannot start a
// recording at all, so carrying the source there would be weight
// nothing can read.
let debugStatic = '';
if (!this.production) {
if (rendered.expressions.length > 0) {
debugStatic += `${name}.__axProgramExprSrc = ${JSON.stringify(rendered.expressions)};\n`;
}
if (rendered.statements.length > 0) {
debugStatic += `${name}.__axProgramStmtSrc = ${JSON.stringify(rendered.statements)};\n`;
}
}
programStatic = `\n${name}.__axProgram = ${JSON.stringify(rendered.program)};\n${programTables.source}${debugStatic}`;
}
}
// Every expression this unit will evaluate, compiled to a closure the
// engine itself will parse. The table is attached as a static beside the
// program so the runtime can find it from the class, and so it is created
// once per class rather than once per instance.
const collected = collectExpressions({
template,
computed,
program: rendered.program,
voidTags: customVoidTagsForProgram,
});
// Actions and resources are addressed by name at run time, so they are
// compiled into their own tables rather than into the source-keyed one.
collected.actions = methods;
collected.resources = resourceBodies(resources);
const table = buildExpressionTable(name, collected);
if (table.refusals.length > 0 || table.gaps.length > 0) {
this.expressionGaps.push({ name, refusals: table.refusals, gaps: table.gaps });
}
const expressionStatic = table.source;
// An action whose body compiled is reached through `__axActions`, keyed by
// name, so the body text is no longer needed to *run* it. It is still
// emitted in a development build because Trace records it and
// `avenx trace view` prints it; a production bundle cannot start a
// recording, so carrying the text there is weight nothing can read. The
// name still has to be emitted -- it is what tells the runtime the action
// exists.
const keepBodies = !this.production;
const methodStrings = Object.entries(methods)
.map(([key, body]) => {
const drop = !keepBodies && table.compiledActions && table.compiledActions.has(key);
return `${JSON.stringify(key)}: ${JSON.stringify(drop ? '' : body)}`;
})
.join(',\n ');
const contractsParam = optionParts.length > 0 ? `, { ${optionParts.join(', ')} }` : '';
// What the compiler needs in order to frame this class as an ES module: the
// class name, the import statements the developer wrote, and the bridge
// bindings the class body refers to. Recorded on the parser rather than
// returned, so `parse()` keeps the bare-class output shape that
// avenx-core/testing, the Vite plugin and the render-path tests consume.
this.moduleMeta.set(path.resolve(filePath), {
importedLocals,
className: name,
isPage,
imports: collectImportStatements(content),
bridgeBindings,
});
// Imported bridges join the component's template scope under their local
// name, on top of the bridges the app registered.
const bridgesExpr =
bridgeBindings.length > 0
? `{ ...bridges, ${bridgeBindings.map((entry) => `${JSON.stringify(entry.local)}: ${entry.binding}`).join(', ')} }`
: 'bridges';
if (isPage) {
return `
/**
* Page component representing ${name}.
*/
class ${name} extends AvenxPage {
/**
* @param {Object} bridges - Mapped bridges.
* @param {Object} componentRegistry - Registry of components.
* @param {Object} props - Page properties.
*/
constructor(bridges, componentRegistry, props) {
super(${JSON.stringify(state)}, ${JSON.stringify(computed)}, ${bridgesExpr}, ${templateLiteral}, { ${methodStrings} }, componentRegistry, props, ${JSON.stringify(styles)}, ${JSON.stringify(resources)}${contractsParam});
}
}
${programStatic}${expressionStatic}`;
}
return `
/**
* Component representing ${name}.
*/
class ${name} extends AvenxComponent {
/**
* @param {Object} bridges - Mapped bridges.
* @param {Object} props - Component properties.
*/
constructor(bridges, props) {
super(${JSON.stringify(state)}, ${JSON.stringify(computed)}, ${bridgesExpr}, ${templateLiteral}, { ${methodStrings} }, props, ${JSON.stringify(styles)}, ${JSON.stringify(resources)}${contractsParam});
}
}
${programStatic}${expressionStatic}`;
}
/**
* Extracts global CSS variables and component-specific style blocks from CSS content.
* @param {string} desContent - The content of the .component.css file.
* @param {object} desBlocks - An object to store the extracted style blocks.
* @param {string} [desPath] - The original CSS file path.
* @private
*/
extractStylesAndVars(desContent, desBlocks, desPath = '') {
const globalMatch = desContent.match(/<@global>([\s\S]*?)<\/ ?@global>/i);
let rawGlobalCss = '';
if (globalMatch) {
const idx = desContent.indexOf(globalMatch[0]);
const globalStartLine = desContent.substring(0, idx).split('\n').length;
const inner = globalMatch[1];
const defRegex = /@def\s+([\w-]+)\s+([^;]+);/g;
let defMatch;
while ((defMatch = defRegex.exec(inner)) !== null) {
this.styleProcessor.addVariable(defMatch[1], defMatch[2].trim());
}
// Remove @def lines and add the rest as global CSS
rawGlobalCss = inner.replace(/@def\s+[\w-]+\s+[^;]+;/g, '').trim();
let compiledGlobalCss = rawGlobalCss;
if (this.styleProcessor.options && this.styleProcessor.options.preprocessor) {
compiledGlobalCss = this.styleProcessor.preprocessCss(rawGlobalCss, this.styleProcessor.options.preprocessor);
}
if (compiledGlobalCss) {
this.styleProcessor.addGlobalCSS(compiledGlobalCss, desPath, globalStartLine);
}
}
const cssBlockMatch = desContent.match(/<@css>([\s\S]*?)<\/ ?@css>/i);
if (cssBlockMatch) {
const cssContentOffset = desContent.indexOf(cssBlockMatch[0]);
const cssStartLine = desContent.substring(0, cssContentOffset).split('\n').length;
const inner = cssBlockMatch[1];
let depth = 0,
currentName = '',
currentBody = '',
inBlock = false;
let inString = null;
let inComment = false;
let blockStartLineOffset = 0;
let currentLineOffset = 0;
for (let i = 0; i < inner.length; i++) {
const char = inner[i];
if (char === '\n') {