@rangular-framework/cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/cli/src/cli.js +1217 -0
  2. package/dist/compiler/src/catalog.js +198 -0
  3. package/dist/compiler/src/class/formInit.js +370 -0
  4. package/dist/compiler/src/class/parseComponent.js +430 -0
  5. package/dist/compiler/src/class/parseDirective.js +227 -0
  6. package/dist/compiler/src/class/parseRoutes.js +163 -0
  7. package/dist/compiler/src/codegen/generate.js +3466 -0
  8. package/dist/compiler/src/codegen/methods.js +975 -0
  9. package/dist/compiler/src/codegen/sourceMap.js +77 -0
  10. package/dist/compiler/src/compile.js +775 -0
  11. package/dist/compiler/src/diagnostics.js +113 -0
  12. package/dist/compiler/src/doctor.js +144 -0
  13. package/dist/compiler/src/fix.js +44 -0
  14. package/dist/compiler/src/index.js +38 -0
  15. package/dist/compiler/src/preview/renderPreview.js +7158 -0
  16. package/dist/compiler/src/preview/styleSnapshot.js +268 -0
  17. package/dist/compiler/src/propTable.js +107 -0
  18. package/dist/compiler/src/style/css.js +161 -0
  19. package/dist/compiler/src/template/ast.js +19 -0
  20. package/dist/compiler/src/template/evaluate.js +151 -0
  21. package/dist/compiler/src/template/expr.js +360 -0
  22. package/dist/compiler/src/template/forms.js +80 -0
  23. package/dist/compiler/src/template/literal.js +248 -0
  24. package/dist/compiler/src/template/parser.js +230 -0
  25. package/dist/compiler/src/template/pipes.js +225 -0
  26. package/dist/compiler/src/template/printAst.js +38 -0
  27. package/dist/compiler/src/template/structural.js +51 -0
  28. package/dist/runtime/src/index.js +1197 -0
  29. package/dist/ui/src/chart.js +196 -0
  30. package/dist/ui/src/datetime.js +240 -0
  31. package/dist/ui/src/icons.js +310 -0
  32. package/dist/ui/src/mask.js +103 -0
  33. package/dist/ui/src/palette.js +141 -0
  34. package/dist/ui/src/tokens.js +173 -0
  35. package/package.json +28 -4
  36. package/README.md +0 -3
@@ -0,0 +1,775 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.resolveSiblingPath = resolveSiblingPath;
37
+ exports.isWithinRoot = isWithinRoot;
38
+ exports.compileComponent = compileComponent;
39
+ exports.hasErrors = hasErrors;
40
+ const parseComponent_1 = require("./class/parseComponent");
41
+ const parseRoutes_1 = require("./class/parseRoutes");
42
+ const formInit_1 = require("./class/formInit");
43
+ const generate_1 = require("./codegen/generate");
44
+ const diagnostics_1 = require("./diagnostics");
45
+ const css_1 = require("./style/css");
46
+ const parser_1 = require("./template/parser");
47
+ const ts = __importStar(require("typescript"));
48
+ /**
49
+ * Join a templateUrl or styleUrl onto the directory of the file that
50
+ * declares it, with '.' and '..' segments normalised. File keys here are
51
+ * plain strings (absolute paths from the CLI, bare names in tests), so
52
+ * this stays string based and platform neutral.
53
+ */
54
+ function resolveSiblingPath(fromFile, rel) {
55
+ if (rel.startsWith('/'))
56
+ return rel;
57
+ const dir = fromFile.includes('/') ? fromFile.slice(0, fromFile.lastIndexOf('/')) : '';
58
+ const parts = (dir ? dir.split('/') : []).filter((p) => p !== '');
59
+ for (const seg of rel.split('/')) {
60
+ if (seg === '' || seg === '.')
61
+ continue;
62
+ if (seg === '..')
63
+ parts.pop();
64
+ else
65
+ parts.push(seg);
66
+ }
67
+ return (fromFile.startsWith('/') ? '/' : '') + parts.join('/');
68
+ }
69
+ /** Normalise a string file key ('.' and '..' segments resolved). */
70
+ function normalizeKey(p) {
71
+ const isAbs = p.startsWith('/');
72
+ const parts = [];
73
+ for (const seg of p.split('/')) {
74
+ if (seg === '' || seg === '.')
75
+ continue;
76
+ if (seg === '..') {
77
+ if (parts.length && parts[parts.length - 1] !== '..')
78
+ parts.pop();
79
+ else if (!isAbs)
80
+ parts.push('..');
81
+ continue;
82
+ }
83
+ parts.push(seg);
84
+ }
85
+ return (isAbs ? '/' : '') + parts.join('/');
86
+ }
87
+ /**
88
+ * True when `candidate` is `root` or lives under it. Only absolute keys
89
+ * are judged: a relative or bare key is an in-memory name from a test
90
+ * resolver, not a filesystem path, and is always allowed through (the
91
+ * CLI passes absolute keys, so the boundary is enforced there).
92
+ */
93
+ function isWithinRoot(candidate, root) {
94
+ if (!candidate.startsWith('/') || !root.startsWith('/'))
95
+ return true;
96
+ const c = normalizeKey(candidate);
97
+ const r = normalizeKey(root);
98
+ if (c === r)
99
+ return true;
100
+ const prefix = r.endsWith('/') ? r : `${r}/`;
101
+ return c.startsWith(prefix);
102
+ }
103
+ /** Tag diagnostics with their source file where the origin is known (Stage 5). */
104
+ function tagFile(diags, file) {
105
+ if (!file)
106
+ return diags;
107
+ return diags.map((d) => (d.file ? d : { ...d, file }));
108
+ }
109
+ /**
110
+ * Diagnostic codes whose origin is the template file rather than the
111
+ * class file: template parse problems plus the codegen diagnostics that
112
+ * carry template positions (unknown tags, structural TODO notes). The
113
+ * TPL_NGFOR codes come out of codegen via parseNgFor, so they are listed
114
+ * here as well as under the TPL prefix.
115
+ */
116
+ function isTemplateDriven(code) {
117
+ return code.startsWith('TPL_')
118
+ || code === 'GEN_UNKNOWN_TAG'
119
+ || code === 'GEN_NGIF_ELSE_TODO'
120
+ || code === 'GEN_STRUCTURAL_TODO'
121
+ || code === 'GEN_CONTROL_NESTING'
122
+ || code === 'GEN_ICON_UNKNOWN'
123
+ || code === 'GEN_ICON_NAME'
124
+ || code === 'GEN_ICON_SIZE'
125
+ || code === 'GEN_NGMODEL_TARGET'
126
+ || code === 'GEN_NGMODEL_EXPR'
127
+ || code === 'GEN_FORM_CONTROL'
128
+ || code === 'GEN_FORM_ARRAY'
129
+ || code === 'GEN_FORMGROUP_TYPE'
130
+ || code === 'GEN_ROUTE_UNSUPPORTED'
131
+ || code === 'GEN_ROUTER_NO_OUTLET'
132
+ || code === 'GEN_PICKER_MODE'
133
+ || code === 'GEN_PICKER_PRESENTATION'
134
+ || code === 'GEN_BUTTON_COLOR'
135
+ || code === 'GEN_SWITCH_COLOR'
136
+ || code === 'GEN_PICKER_INTERVAL'
137
+ || code === 'GEN_OVERLAY_OPEN'
138
+ || code === 'GEN_EVENT_ASSIGNMENT'
139
+ || code === 'PIPE_UNKNOWN'
140
+ || code === 'GEN_VALIDATOR_ARG'
141
+ || code === 'DIR_UNSUPPORTED'
142
+ || code === 'PROJECTION_SELECT_UNSUPPORTED'
143
+ || code === 'GEN_CLASS_BINDING'
144
+ || code === 'GEN_STYLE_BINDING'
145
+ || code === 'GEN_ATTR_BINDING';
146
+ }
147
+ function isStyleDriven(code) {
148
+ return code.startsWith('CSS_') || code === 'STYLE_OFF_SCALE';
149
+ }
150
+ /**
151
+ * The full pipeline: class parse -> import registry (Stage 3: child
152
+ * components and services are followed through relative imports) ->
153
+ * template parse -> CSS parse -> code generation. Never throws for bad
154
+ * user input; it reports diagnostics.
155
+ */
156
+ function compileComponent(options) {
157
+ const diagnostics = [];
158
+ const entryKey = options.fileName ?? 'component.ts';
159
+ // Project root boundary (security audit, 2026-11-12): see rootDir.
160
+ const rootDir = options.rootDir;
161
+ const escapesRoot = (p) => rootDir !== undefined && !isWithinRoot(p, rootDir);
162
+ const pathEscape = (what, p) => (0, diagnostics_1.error)('CMP_PATH_ESCAPE', `${what} '${p}' resolves outside the project root '${rootDir}'; the file was not read`, undefined, undefined, 'Keep every templateUrl, styleUrl and relative import inside the project tree (the folder holding your package.json), or move the file into the project');
163
+ /** The styleUrls of one class that stay inside the root; escapes are reported and dropped. */
164
+ const allowedStyleUrls = (info, fileKey) => {
165
+ const allowed = [];
166
+ for (const url of info.styleUrls) {
167
+ const key = resolveSiblingPath(fileKey, url);
168
+ if (escapesRoot(key)) {
169
+ diagnostics.push(pathEscape(`styleUrl '${url}' of ${info.className}`, key));
170
+ continue;
171
+ }
172
+ allowed.push(url);
173
+ }
174
+ return allowed;
175
+ };
176
+ /**
177
+ * The binding names of one import that the importing file actually
178
+ * uses as values, judged from its classes' own texts: field
179
+ * initializers, method bodies and constructor bodies. A name used
180
+ * only as a type never appears there, so type-only imports of a
181
+ * classless file (a models file, say) stay quiet.
182
+ */
183
+ const classlessUsedNames = (importerParsed, imp) => {
184
+ const haystacks = [];
185
+ const collect = (fields, methods, ctor) => {
186
+ for (const f of fields)
187
+ if (f.initializer)
188
+ haystacks.push(f.initializer);
189
+ for (const m of methods)
190
+ if (m.body)
191
+ haystacks.push(m.body);
192
+ if (ctor)
193
+ haystacks.push(ctor);
194
+ };
195
+ for (const c of importerParsed.components)
196
+ collect(c.fields, c.methodDetails, c.constructorBody);
197
+ for (const s of importerParsed.services)
198
+ collect(s.fields, s.methodDetails, s.constructorBody);
199
+ for (const p of importerParsed.pipes)
200
+ collect(p.fields, p.methodDetails, p.constructorBody);
201
+ for (const d of importerParsed.directives) {
202
+ for (const i of d.inputs)
203
+ if (i.initializer)
204
+ haystacks.push(i.initializer);
205
+ if (d.initBody)
206
+ haystacks.push(d.initBody);
207
+ if (d.setter)
208
+ haystacks.push(d.setter.body);
209
+ }
210
+ const used = [];
211
+ for (const b of imp.bindings) {
212
+ if (b.typeOnly)
213
+ continue;
214
+ const pattern = b.imported === '*'
215
+ ? new RegExp(`\\b${b.local}\\s*\\.`)
216
+ : new RegExp(`\\b${b.local}\\b`);
217
+ if (haystacks.some((h) => pattern.test(h)))
218
+ used.push(b.local);
219
+ }
220
+ return used;
221
+ };
222
+ const readRelative = (importer, rel) => {
223
+ if (options.resolveImport)
224
+ return options.resolveImport(rel, importer);
225
+ if (options.resolveFile) {
226
+ const direct = options.resolveFile(rel);
227
+ if (direct !== undefined)
228
+ return { source: direct, fileName: rel };
229
+ const withExt = options.resolveFile(rel + '.ts');
230
+ if (withExt !== undefined)
231
+ return { source: withExt, fileName: rel + '.ts' };
232
+ }
233
+ return undefined;
234
+ };
235
+ // --- Import registry (Stage 3) -------------------------------------------
236
+ // Classes are registered BEFORE recursing into a file's imports, so an
237
+ // import cycle still resolves every class on the cycle; the cycle itself
238
+ // is reported once as CMP_IMPORT_CYCLE.
239
+ const componentsBySelector = new Map();
240
+ const servicesByName = new Map();
241
+ const pipesByName = new Map();
242
+ const directivesByAttr = new Map();
243
+ const visited = new Set();
244
+ const stack = [];
245
+ /** Source text per visited file, kept for source map sourcesContent. */
246
+ const fileSources = new Map();
247
+ /** The parsed view of every visited file, kept for the import pass below. */
248
+ const parsedByFile = new Map();
249
+ /** Literal module constants carried into the generated module (0.6.5), by local binding name. */
250
+ const carriedConsts = new Map();
251
+ let entryParsed;
252
+ const visitFile = (fileName, source) => {
253
+ fileSources.set(fileName, source);
254
+ if (stack.includes(fileName)) {
255
+ diagnostics.push((0, diagnostics_1.warning)('CMP_IMPORT_CYCLE', `Import cycle detected: ${[...stack, fileName].join(' -> ')}, classes on the cycle were registered from their first visit`, undefined, undefined, 'Break the cycle by moving the shared class (component or service) into its own file that both sides import'));
256
+ return;
257
+ }
258
+ if (visited.has(fileName))
259
+ return;
260
+ visited.add(fileName);
261
+ stack.push(fileName);
262
+ const parsed = (0, parseComponent_1.parseClassFile)(source, fileName);
263
+ parsedByFile.set(fileName, parsed);
264
+ for (const pe of parsed.parseErrors) {
265
+ diagnostics.push({
266
+ ...(0, diagnostics_1.error)('CLS_PARSE', `TypeScript could not parse this file: ${pe.message}`, pe.line, pe.column, 'Fix the syntax error; classes and fields after it may be missing from the generated code'),
267
+ file: fileName,
268
+ });
269
+ }
270
+ if (fileName === entryKey)
271
+ entryParsed = parsed;
272
+ for (const info of parsed.components) {
273
+ if (!info.selector)
274
+ continue;
275
+ const prev = componentsBySelector.get(info.selector);
276
+ if (prev && prev.info.className !== info.className) {
277
+ diagnostics.push((0, diagnostics_1.error)('CMP_DUP_SELECTOR', `Selector '${info.selector}' is declared by both ${prev.info.className} and ${info.className}`, undefined, undefined, 'Give each component a unique selector, selectors are how templates find child components'));
278
+ }
279
+ else if (!prev) {
280
+ componentsBySelector.set(info.selector, { info, fileName });
281
+ }
282
+ }
283
+ for (const svc of parsed.services) {
284
+ if (!servicesByName.has(svc.className))
285
+ servicesByName.set(svc.className, svc);
286
+ }
287
+ for (const pipe of parsed.pipes) {
288
+ if (!pipesByName.has(pipe.pipeName))
289
+ pipesByName.set(pipe.pipeName, pipe);
290
+ }
291
+ for (const directive of parsed.directives) {
292
+ if (directive.attrName && !directivesByAttr.has(directive.attrName)) {
293
+ directivesByAttr.set(directive.attrName, directive);
294
+ }
295
+ }
296
+ for (const imp of parsed.imports) {
297
+ if (!imp.from.startsWith('.'))
298
+ continue;
299
+ const resolved = readRelative(fileName, imp.from);
300
+ if (!resolved) {
301
+ diagnostics.push((0, diagnostics_1.error)('CMP_IMPORT_UNRESOLVED', `Could not resolve import '${imp.from}' from '${fileName}'`, undefined, undefined, `Check the path is relative to the importing file and the file exists, e.g. import { MailService } from './mail.service';`));
302
+ continue;
303
+ }
304
+ if (escapesRoot(resolved.fileName)) {
305
+ diagnostics.push(pathEscape(`Import '${imp.from}' from '${fileName}'`, resolved.fileName));
306
+ continue;
307
+ }
308
+ visitFile(resolved.fileName, resolved.source);
309
+ // A name imported from another file and used as a value must
310
+ // reach the generated module. Classes reach it as generated
311
+ // code; an exported literal constant reaches it by being
312
+ // carried verbatim (0.6.5), which is what makes the Angular
313
+ // environment.ts shape work. A resolved file with no
314
+ // compilable class and no carriable constant for a used name
315
+ // contributes nothing for that name, so the name would be
316
+ // undefined at run time. That drop used to be silent; report
317
+ // it (GEN_IMPORT_CLASSLESS).
318
+ const target = parsedByFile.get(resolved.fileName);
319
+ if (target) {
320
+ const used = new Set(classlessUsedNames(parsed, imp));
321
+ const missing = [];
322
+ for (const b of imp.bindings) {
323
+ if (b.typeOnly || !used.has(b.local))
324
+ continue;
325
+ const konst = b.imported === '*'
326
+ ? undefined
327
+ : target.consts.find((c) => c.name === b.imported && c.exported && c.literal);
328
+ if (konst) {
329
+ if (!carriedConsts.has(b.local)) {
330
+ carriedConsts.set(b.local, {
331
+ name: b.local,
332
+ text: b.local === konst.name ? konst.text : `const ${b.local} = ${konst.initText};`,
333
+ });
334
+ }
335
+ }
336
+ else if (target.components.length === 0 && target.services.length === 0
337
+ && target.pipes.length === 0 && target.directives.length === 0) {
338
+ missing.push(b.local);
339
+ }
340
+ }
341
+ if (missing.length) {
342
+ diagnostics.push({
343
+ ...(0, diagnostics_1.error)('GEN_IMPORT_CLASSLESS', `Import from '${imp.from}' binds ${missing.map((n) => `'${n}'`).join(', ')}, but that file declares no component, service, pipe or directive and the name is not one of its exported literal constants, so nothing for it reaches the generated code and the name would be undefined at run time`, imp.line, undefined, 'Move shared values into an @Injectable service and inject it, declare the values in the class that uses them, or export them from that file as literal constants (strings, numbers, booleans, and arrays or objects of literals), which the compiler carries into the generated code'),
344
+ file: fileName,
345
+ });
346
+ }
347
+ }
348
+ }
349
+ stack.pop();
350
+ };
351
+ visitFile(entryKey, options.tsSource);
352
+ const files = [...visited];
353
+ const component = entryParsed?.components[0];
354
+ if (!component) {
355
+ diagnostics.push({ ...(0, diagnostics_1.error)('CLS_NO_COMPONENT', 'No @Component-decorated class found in the source', undefined, undefined, "Decorate the class: @Component({ selector: 'app-x', templateUrl: './x.component.html' }) export class XComponent { ... }, only @Component classes are compiled; @NgModule/@Injectable classes are not entry points"), file: entryKey });
356
+ return { code: '', diagnostics, children: [], services: [...servicesByName.values()], pipes: [...pipesByName.values()], directives: [...directivesByAttr.values()], routes: [], files };
357
+ }
358
+ // --- Entry template --------------------------------------------------------
359
+ // The resolved template path (for per-file diagnostics and the watch set).
360
+ // An inline template lives in the .ts file itself, so its diagnostics
361
+ // belong to the class file.
362
+ const entryTemplateFile = component.templateUrl
363
+ ? resolveSiblingPath(entryKey, component.templateUrl)
364
+ : entryKey;
365
+ if (component.templateUrl && escapesRoot(entryTemplateFile)) {
366
+ diagnostics.push(pathEscape(`templateUrl '${component.templateUrl}'`, entryTemplateFile));
367
+ return { code: '', diagnostics, component, children: [], services: [...servicesByName.values()], pipes: [...pipesByName.values()], directives: [...directivesByAttr.values()], routes: [], files };
368
+ }
369
+ if (component.templateUrl)
370
+ files.push(entryTemplateFile);
371
+ const entryStyleUrls = allowedStyleUrls(component, entryKey);
372
+ for (const url of entryStyleUrls)
373
+ files.push(resolveSiblingPath(entryKey, url));
374
+ let templateSource = options.templateSource ?? component.template;
375
+ if (!templateSource && component.templateUrl) {
376
+ templateSource = options.resolveFile?.(component.templateUrl)
377
+ ?? readRelative(entryKey, component.templateUrl)?.source;
378
+ if (!templateSource) {
379
+ diagnostics.push({ ...(0, diagnostics_1.error)('CMP_TEMPLATE', `Could not resolve templateUrl '${component.templateUrl}', pass templateSource or a resolveFile callback`, undefined, undefined, 'Check the path is relative to the component file and the template file exists, e.g. templateUrl: \'./x.component.html\''), file: entryKey });
380
+ return { code: '', diagnostics, component, children: [], services: [...servicesByName.values()], pipes: [...pipesByName.values()], directives: [...directivesByAttr.values()], routes: [], files };
381
+ }
382
+ }
383
+ if (!templateSource) {
384
+ diagnostics.push({ ...(0, diagnostics_1.error)('CMP_TEMPLATE', 'Component has neither an inline template nor a templateUrl', undefined, undefined, "Add templateUrl: './x.component.html' (or an inline template: `...`) to the @Component decorator"), file: entryKey });
385
+ return { code: '', diagnostics, component, children: [], services: [...servicesByName.values()], pipes: [...pipesByName.values()], directives: [...directivesByAttr.values()], routes: [], files };
386
+ }
387
+ const { root, diagnostics: tplDiags } = (0, parser_1.parseTemplate)(templateSource);
388
+ diagnostics.push(...tagFile(tplDiags, entryTemplateFile));
389
+ // --- Routes (Stage 9) ------------------------------------------------------
390
+ // Discovery rule (the one rule, also stated in AGENTS.md and the
391
+ // Routing section of docs/AI_GUIDE.md): the routes file is the one
392
+ // named by routesSpecifier (the CLI --routes flag), or a sibling
393
+ // 'app.routes.ts' next to the entry component. It is read whenever it
394
+ // exists; it is REQUIRED whenever routing is used: a <router-outlet>
395
+ // or routerLink in a template, or a Router / ActivatedRoute injection
396
+ // in any registered component. The routes file is visited like any
397
+ // imported file, so the components it imports register as children
398
+ // before the child pass below runs.
399
+ const routingUsageIn = (nodes) => {
400
+ const usage = { outlet: false, links: false };
401
+ const walk = (list) => {
402
+ for (const n of list) {
403
+ if (n.type !== 'element')
404
+ continue;
405
+ if (n.tag.toLowerCase() === 'router-outlet')
406
+ usage.outlet = true;
407
+ if (n.attrs['routerLink'] !== undefined
408
+ || n.propBindings.some((b) => b.name === 'routerLink'))
409
+ usage.links = true;
410
+ walk(n.children);
411
+ }
412
+ };
413
+ walk(nodes);
414
+ return usage;
415
+ };
416
+ const entryUsage = routingUsageIn(root.children);
417
+ const injectsRouter = [component, ...[...componentsBySelector.values()].map((c) => c.info)]
418
+ .some((info) => (info.constructorDeps ?? []).some((d) => d.typeName === 'Router' || d.typeName === 'ActivatedRoute'));
419
+ const routingUsed = entryUsage.outlet || entryUsage.links || injectsRouter;
420
+ const routesSpecifier = options.routesSpecifier ?? './app.routes.ts';
421
+ // A resolver may signal a missing file by throwing instead of
422
+ // returning undefined; for the optional routes file both mean absent.
423
+ let routesResolved;
424
+ try {
425
+ routesResolved = readRelative(entryKey, routesSpecifier);
426
+ }
427
+ catch {
428
+ routesResolved = undefined;
429
+ }
430
+ let routes;
431
+ if (routesResolved) {
432
+ if (escapesRoot(routesResolved.fileName)) {
433
+ diagnostics.push(pathEscape(`Routes file '${routesSpecifier}'`, routesResolved.fileName));
434
+ }
435
+ else {
436
+ const visitedBefore = new Set(files);
437
+ visitFile(routesResolved.fileName, routesResolved.source);
438
+ for (const f of visited)
439
+ if (!visitedBefore.has(f))
440
+ files.push(f);
441
+ const parsedRoutes = (0, parseRoutes_1.parseRoutesFile)(routesResolved.source, routesResolved.fileName);
442
+ diagnostics.push(...tagFile(parsedRoutes.diagnostics, routesResolved.fileName));
443
+ if (!parsedRoutes.found && (routingUsed || options.routesSpecifier)) {
444
+ diagnostics.push({
445
+ ...(0, diagnostics_1.error)('GEN_ROUTES_MISSING', `Routes file '${routesResolved.fileName}' holds no Routes array; nothing was registered`, undefined, undefined, "Export the route table from the routes file: export const routes: Routes = [{ path: 'home', component: HomeComponent }];"),
446
+ file: entryKey,
447
+ });
448
+ }
449
+ else {
450
+ const byClassName = new Map();
451
+ byClassName.set(component.className, component);
452
+ for (const { info } of componentsBySelector.values())
453
+ byClassName.set(info.className, info);
454
+ const seenPaths = new Set();
455
+ routes = [];
456
+ for (const def of parsedRoutes.routes) {
457
+ if (seenPaths.has(def.path)) {
458
+ diagnostics.push({
459
+ ...(0, diagnostics_1.warning)('GEN_ROUTE_DUPLICATE', `Path '${def.path}' is declared more than once in the routes file; the first entry wins and this one never matches`, undefined, undefined, 'Give each route a unique path; matching tries entries in declaration order'),
460
+ file: routesResolved.fileName,
461
+ });
462
+ }
463
+ seenPaths.add(def.path);
464
+ if (def.componentName !== undefined) {
465
+ const info = byClassName.get(def.componentName);
466
+ if (!info) {
467
+ diagnostics.push({
468
+ ...(0, diagnostics_1.error)('GEN_ROUTE_COMPONENT', `Route '${def.path}' names component '${def.componentName}', which is not an @Component class resolved in this compilation`, undefined, undefined, `Import ${def.componentName} in the routes file (its file is followed like any import) and make sure it is decorated with @Component`),
469
+ file: routesResolved.fileName,
470
+ });
471
+ continue;
472
+ }
473
+ if (info === component) {
474
+ diagnostics.push({
475
+ ...(0, diagnostics_1.error)('GEN_ROUTE_COMPONENT', `Route '${def.path}' names the root component '${def.componentName}' itself; the root component hosts the outlet and cannot also be a route target`, undefined, undefined, 'Point the route at a separate screen component and keep the root component as the shell'),
476
+ file: routesResolved.fileName,
477
+ });
478
+ continue;
479
+ }
480
+ routes.push({ ...def, selector: info.selector });
481
+ }
482
+ else {
483
+ routes.push({ ...def });
484
+ }
485
+ }
486
+ const declaredPaths = new Set(parsedRoutes.routes.map((r) => r.path));
487
+ for (const def of parsedRoutes.routes) {
488
+ if (def.redirectTo !== undefined && !declaredPaths.has(def.redirectTo)) {
489
+ diagnostics.push({
490
+ ...(0, diagnostics_1.error)('GEN_ROUTE_UNSUPPORTED', `Route '${def.path}' redirects to '${def.redirectTo}', which is not the path of any route in the table`, undefined, undefined, `Point redirectTo at a declared path (declared: ${[...declaredPaths].join(', ')}), or add a route with that path`),
491
+ file: routesResolved.fileName,
492
+ });
493
+ }
494
+ }
495
+ }
496
+ }
497
+ }
498
+ else if (routingUsed || options.routesSpecifier) {
499
+ diagnostics.push({
500
+ ...(0, diagnostics_1.error)('GEN_ROUTES_MISSING', `Routing is used (${[
501
+ entryUsage.outlet ? 'a <router-outlet>' : '',
502
+ entryUsage.links ? 'routerLink' : '',
503
+ injectsRouter ? 'a Router/ActivatedRoute injection' : '',
504
+ ].filter(Boolean).join(', ')}) but no routes file was found at '${routesSpecifier}'`, undefined, undefined, "Create app.routes.ts next to the root component: export const routes: Routes = [{ path: 'home', component: HomeComponent }]; or pass the routes file explicitly (rg build --routes <file>)"),
505
+ file: entryKey,
506
+ });
507
+ }
508
+ const loadCss = (info, fileKey, styleUrls) => {
509
+ let stylesText = info.styles ?? '';
510
+ for (const url of styleUrls) {
511
+ const cssText = fileKey === entryKey
512
+ ? options.resolveFile?.(url) ?? readRelative(fileKey, url)?.source
513
+ : readRelative(fileKey, url)?.source;
514
+ if (cssText)
515
+ stylesText += '\n' + cssText;
516
+ }
517
+ return (0, css_1.parseCss)(stylesText);
518
+ };
519
+ const css = loadCss(component, entryKey, entryStyleUrls);
520
+ // --- Child components: parse each registered child's template -------------
521
+ const children = [];
522
+ for (const { info, fileName } of componentsBySelector.values()) {
523
+ if (info === component)
524
+ continue;
525
+ const childTemplateFile = info.templateUrl ? resolveSiblingPath(fileName, info.templateUrl) : fileName;
526
+ if (info.templateUrl && escapesRoot(childTemplateFile)) {
527
+ diagnostics.push(pathEscape(`templateUrl '${info.templateUrl}' of child component ${info.className}`, childTemplateFile));
528
+ continue;
529
+ }
530
+ if (info.templateUrl)
531
+ files.push(childTemplateFile);
532
+ const childStyleUrls = allowedStyleUrls(info, fileName);
533
+ for (const url of childStyleUrls)
534
+ files.push(resolveSiblingPath(fileName, url));
535
+ let childTemplate = info.template;
536
+ if (!childTemplate && info.templateUrl) {
537
+ childTemplate = readRelative(fileName, info.templateUrl)?.source;
538
+ if (!childTemplate) {
539
+ diagnostics.push({ ...(0, diagnostics_1.error)('CMP_TEMPLATE', `Could not resolve templateUrl '${info.templateUrl}' for child component ${info.className}`, undefined, undefined, 'Check the path is relative to the child component file and the template file exists'), file: fileName });
540
+ continue;
541
+ }
542
+ }
543
+ if (!childTemplate) {
544
+ diagnostics.push({ ...(0, diagnostics_1.error)('CMP_TEMPLATE', `Child component ${info.className} has neither an inline template nor a templateUrl`, undefined, undefined, "Add templateUrl: './x.component.html' (or an inline template) to the child's @Component decorator"), file: fileName });
545
+ continue;
546
+ }
547
+ const parsedTpl = (0, parser_1.parseTemplate)(childTemplate);
548
+ diagnostics.push(...tagFile(parsedTpl.diagnostics, childTemplateFile));
549
+ if (options.sourceMap)
550
+ fileSources.set(childTemplateFile, childTemplate);
551
+ children.push({ info, ast: parsedTpl.root, css: loadCss(info, fileName, childStyleUrls), fileName, templateFile: childTemplateFile });
552
+ }
553
+ const services = [...servicesByName.values()];
554
+ // Reactive form initializers the preview cannot evaluate (Stage 8):
555
+ // the generated app runs them verbatim, so this is a warning, and it
556
+ // belongs to the class file that declares the field.
557
+ for (const [info, file] of [
558
+ [component, entryKey],
559
+ ...children.map((c) => [c.info, c.fileName ?? entryKey]),
560
+ ]) {
561
+ const builderDeps = (0, formInit_1.builderDepsOf)(info);
562
+ for (const field of info.fields) {
563
+ if (!(0, formInit_1.isFormInitializer)(field.initializer, builderDeps))
564
+ continue;
565
+ const analysis = (0, formInit_1.analyzeFormInitializer)(field.initializer, builderDeps);
566
+ if (!analysis.supported) {
567
+ diagnostics.push({
568
+ ...(0, diagnostics_1.warning)('GEN_FORM_INITIALIZER', `Field '${field.name}' of ${info.className} has a form initializer the preview cannot evaluate (${analysis.reason ?? 'unsupported shape'}); the generated app runs it as written, but the preview renders the form without live values`, undefined, undefined, 'Keep form initializers to literals, Validators references and validator calls, nested groups and FormArrays, or the same shapes built by an injected FormBuilder: new FormGroup({ email: new FormControl(\'\', [Validators.required, Validators.email]) })'),
569
+ file,
570
+ });
571
+ }
572
+ }
573
+ }
574
+ if (options.sourceMap)
575
+ fileSources.set(entryTemplateFile, templateSource);
576
+ const pipes = [...pipesByName.values()];
577
+ const directives = [...directivesByAttr.values()];
578
+ // --- Third-party imports ---------------------------------------------------
579
+ // The generated module inlines the classes of the contributing files
580
+ // (the entry component, the child components, the providedIn: 'root'
581
+ // services, the custom pipes), so an import of a bare third-party
582
+ // module in one of those files must be carried into the generated
583
+ // module, merged across files, or the generated code references a
584
+ // name nothing binds (a runtime ReferenceError, found in the wild
585
+ // with AsyncStorage in a service). The @angular/* and @rangular-framework/*
586
+ // specifiers are consumed semantically and never carried. react
587
+ // and react-native are NOT consumed: an import of them in a
588
+ // contributing file carries like any other bare specifier (fix,
589
+ // 2026-11-17: `import { Platform } from 'react-native'` in a
590
+ // service was silently dropped while its uses were emitted, which
591
+ // left Platform unbound at runtime). A carried name the generated
592
+ // module already defines (its own react and react-native imports
593
+ // included) drops in codegen with a GEN_IMPORT_COLLISION warning,
594
+ // so carrying can never duplicate a binding. Relative imports
595
+ // keep their behaviour (followed above, classes inlined).
596
+ // Directive files contribute no module code (their expressions admit
597
+ // only inputs and locals, anything else is DIR_UNSUPPORTED), so they
598
+ // are not contributing files here.
599
+ const isFrameworkSpecifier = (spec) => spec.startsWith('@angular/')
600
+ || spec.startsWith('@rangular-framework/');
601
+ const contributingFiles = [];
602
+ const addContributing = (f) => {
603
+ if (f && !contributingFiles.includes(f))
604
+ contributingFiles.push(f);
605
+ };
606
+ addContributing(entryKey);
607
+ for (const c of children)
608
+ addContributing(c.fileName);
609
+ for (const s of services)
610
+ if (s.providedInRoot)
611
+ addContributing(s.fileName);
612
+ for (const p of pipes)
613
+ addContributing(p.fileName);
614
+ const carriedBindings = [];
615
+ const carriedSideEffects = [];
616
+ const boundLocals = new Map();
617
+ const sideEffectSeen = new Set();
618
+ for (const file of contributingFiles) {
619
+ const parsed = parsedByFile.get(file);
620
+ if (!parsed)
621
+ continue;
622
+ for (const eq of parsed.importEquals) {
623
+ diagnostics.push({
624
+ ...(0, diagnostics_1.warning)('CMP_IMPORT_FORM', `'${file}' declares 'import ${eq.local} = ...', a form the generated module cannot carry; the declaration was dropped, so code using '${eq.local}' has no binding`, eq.line, undefined, `Write it as an ES module import: import ${eq.local} from '<module>'; (or import { ... } from '<module>';) and the import is carried into the generated module`),
625
+ file,
626
+ });
627
+ }
628
+ for (const imp of parsed.imports) {
629
+ if (imp.from.startsWith('.') || isFrameworkSpecifier(imp.from))
630
+ continue;
631
+ if (!imp.bindings.length) {
632
+ if (!sideEffectSeen.has(imp.from)) {
633
+ sideEffectSeen.add(imp.from);
634
+ carriedSideEffects.push({ from: imp.from, file });
635
+ }
636
+ continue;
637
+ }
638
+ for (const b of imp.bindings) {
639
+ const prev = boundLocals.get(b.local);
640
+ if (prev) {
641
+ if (prev.from === imp.from && prev.imported === b.imported) {
642
+ // The same binding declared again in another contributing
643
+ // file: its effect already exists, carry it once. A value
644
+ // binding subsumes a type-only one of the same origin.
645
+ if (prev.typeOnly && !b.typeOnly)
646
+ prev.typeOnly = false;
647
+ continue;
648
+ }
649
+ diagnostics.push({
650
+ ...(0, diagnostics_1.warning)('GEN_IMPORT_COLLISION', `Import of '${b.local}' from '${imp.from}' in '${file}' was dropped: the name '${b.local}' is already bound by the import from '${prev.from}' in '${prev.file}', and the generated module can hold only one binding of that name (the first wins)`, imp.line, undefined, `Give one of the two imports of the name '${b.local}' a different local name (an 'as' alias on a named import, or a different name on a default import) so both survive in the generated module`),
651
+ file,
652
+ });
653
+ continue;
654
+ }
655
+ const carried = { ...b, from: imp.from, file };
656
+ boundLocals.set(b.local, carried);
657
+ carriedBindings.push(carried);
658
+ }
659
+ }
660
+ }
661
+ const { code, diagnostics: genDiags, sourceMap } = (0, generate_1.generateComponent)(component, root, css, {
662
+ children,
663
+ services,
664
+ pipes,
665
+ directives,
666
+ routes,
667
+ externalImports: { bindings: carriedBindings, sideEffects: carriedSideEffects },
668
+ consts: [...carriedConsts.values()],
669
+ ...(options.sourceMap
670
+ ? { sourceMap: { entryTsFile: entryKey, entryTemplateFile, contents: fileSources } }
671
+ : {}),
672
+ });
673
+ // --- Navigate targets (runtime prevention round, 2026-11-29,
674
+ // point 7a): a literal navigate or navigateByUrl target that no
675
+ // route declares lands on a blank page when the app has no
676
+ // wildcard route. Dynamic targets cannot be judged and stay
677
+ // silent; a '**' route handles every path by design and also
678
+ // stays silent. The same-path half of the point is runtime
679
+ // knowledge and is not claimed here.
680
+ if (routes && routes.length > 0 && !routes.some((r) => r.path === '**')) {
681
+ diagnostics.push(...navigateTargetDiagnostics([component, ...children.map((c) => c.info), ...services], routes.map((r) => r.path), entryKey));
682
+ }
683
+ // Per-file origins for codegen diagnostics (Stage 5): template-driven
684
+ // codes belong to the entry template (child units share the entry
685
+ // tagging in v1), style codes to the file holding the entry styles
686
+ // (the first styleUrl when external, else the .ts file), and everything
687
+ // else to the entry class file.
688
+ const entryStylesFile = component.styleUrls.length
689
+ ? resolveSiblingPath(entryKey, component.styleUrls[0])
690
+ : entryKey;
691
+ for (const d of genDiags) {
692
+ if (d.file) {
693
+ diagnostics.push(d);
694
+ continue;
695
+ }
696
+ if (isTemplateDriven(d.code))
697
+ diagnostics.push({ ...d, file: entryTemplateFile });
698
+ else if (isStyleDriven(d.code))
699
+ diagnostics.push({ ...d, file: entryStylesFile });
700
+ else
701
+ diagnostics.push({ ...d, file: entryKey });
702
+ }
703
+ return { code, diagnostics, ast: root, component, css, children, services, pipes, directives, routes: routes ?? [], files, sourceMap };
704
+ }
705
+ function hasErrors(diagnostics) {
706
+ return diagnostics.some((d) => d.severity === 'error');
707
+ }
708
+ /**
709
+ * Literal navigate targets vs the route table (point 7a above).
710
+ * A target segment is a string, or null for a segment the source
711
+ * computes (a number literal is concrete text; any other
712
+ * expression is unknowable and matches any route segment, so a
713
+ * partly dynamic target is judged only on its literal segments).
714
+ */
715
+ function navigateTargetDiagnostics(hosts, routePaths, file) {
716
+ const routeSegs = routePaths.map((p) => (p === '' ? [] : p.split('/')));
717
+ const matches = (target) => routeSegs.some((segs) => segs.length === target.length
718
+ && segs.every((seg, i) => seg.startsWith(':') || target[i] === null || seg === target[i]));
719
+ const splitLiteral = (text) => text.replace(/^\//, '').split('/').filter((s) => s.length > 0);
720
+ const out = [];
721
+ for (const host of hosts) {
722
+ const routerProps = new Set((host.constructorDeps ?? [])
723
+ .filter((d) => d.typeName === 'Router')
724
+ .map((d) => d.propertyName));
725
+ if (!routerProps.size)
726
+ continue;
727
+ for (const method of host.methodDetails) {
728
+ if (!method.body)
729
+ continue;
730
+ const params = method.params.map((p) => p.name).join(', ');
731
+ const sf = ts.createSourceFile('method.ts', `function __m(${params}) ${method.body}`, ts.ScriptTarget.Latest, true);
732
+ const visit = (node) => {
733
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
734
+ && ts.isPropertyAccessExpression(node.expression.expression)
735
+ && node.expression.expression.expression.kind === ts.SyntaxKind.ThisKeyword
736
+ && routerProps.has(node.expression.expression.name.text)
737
+ && (node.expression.name.text === 'navigate' || node.expression.name.text === 'navigateByUrl')) {
738
+ const kind = node.expression.name.text;
739
+ const arg = node.arguments[0];
740
+ let target;
741
+ if (kind === 'navigate' && arg && ts.isArrayLiteralExpression(arg)) {
742
+ target = [];
743
+ for (const el of arg.elements) {
744
+ if (ts.isStringLiteral(el))
745
+ target.push(...splitLiteral(el.text));
746
+ else if (ts.isNumericLiteral(el))
747
+ target.push(el.text);
748
+ else
749
+ target.push(null);
750
+ }
751
+ }
752
+ else if (kind === 'navigateByUrl' && arg && ts.isStringLiteral(arg)) {
753
+ target = splitLiteral(arg.text);
754
+ }
755
+ else if (kind === 'navigateByUrl' && arg && ts.isTemplateExpression(arg)) {
756
+ target = [...splitLiteral(arg.head.text)];
757
+ for (const span of arg.templateSpans) {
758
+ target.push(null, ...splitLiteral(span.literal.text));
759
+ }
760
+ }
761
+ if (target && !matches(target)) {
762
+ const shown = '/' + target.map((s) => s ?? ':param').join('/');
763
+ out.push({
764
+ ...(0, diagnostics_1.warning)('GEN_NAV_UNDECLARED', `Method '${method.name}' in ${host.className} navigates to '${shown}', which no route declares; with no wildcard route the tap lands on a blank page`, undefined, undefined, `Check the path against the route table in app.routes.ts, fix the spelling, or add the route`),
765
+ file,
766
+ });
767
+ }
768
+ }
769
+ ts.forEachChild(node, visit);
770
+ };
771
+ visit(sf);
772
+ }
773
+ }
774
+ return out;
775
+ }