@nativescript/compiler-angular 0.0.0-stage → 9.2.0-alpha.9

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.
@@ -0,0 +1,746 @@
1
+ import { ts } from "./core-api.js";
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, relative } from 'node:path';
4
+ /**
5
+ * A component extending a class, as Angular's InheritDefinitionFeature merges them: one class with the base's members
6
+ * (fields, inputs and outputs, methods, hooks) copied in, overridden ones left out, `super.m()` calling the base's `m`
7
+ * copied under a name of its own, and the base's constructor run where `super(…)` would run it. The base itself stays
8
+ * a class of its own, so what needs the subclass to be one (`instanceof Base`, injecting or querying by `Base`, `Base`
9
+ * as a type) stops the build (`refuseBaseUses`).
10
+ */
11
+ const parse = (file, text) => ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
12
+ const classIn = (sf, name) => sf.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === name);
13
+ const unsupported = (where, what) => new Error(`${where}: ${what} is not supported in a release build yet`);
14
+ const isStatic = (m) => !!(ts.canHaveModifiers(m) && ts.getModifiers(m)?.some((x) => x.kind === ts.SyntaxKind.StaticKeyword));
15
+ const isAbstract = (m) => !!(ts.canHaveModifiers(m) && ts.getModifiers(m)?.some((x) => x.kind === ts.SyntaxKind.AbstractKeyword));
16
+ const decoratorsOf = (m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []);
17
+ const memberName = (m) => (m.name && (ts.isIdentifier(m.name) || ts.isPrivateIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined);
18
+ const lineOf = (n) => n.getSourceFile().getLineAndCharacterOfPosition(n.getStart()).line + 1;
19
+ const withoutExt = (f) => f.replace(/\.tsx?$/, '').replace(/\/index$/, '');
20
+ /** An import's file: relative, or under the app's `~/` or `@/` alias (its `src` or `app` folder). */
21
+ export function resolveClassImport(fromFile, spec) {
22
+ const candidates = [];
23
+ if (spec.startsWith('.')) {
24
+ const base = join(dirname(fromFile), spec);
25
+ candidates.push(base + '.ts', join(base, 'index.ts'));
26
+ }
27
+ else if (spec.startsWith('~/') || spec.startsWith('@/')) {
28
+ const sub = spec.slice(2);
29
+ for (let dir = dirname(fromFile); dirname(dir) !== dir; dir = dirname(dir)) {
30
+ if (!existsSync(join(dir, 'package.json')))
31
+ continue;
32
+ for (const appDir of ['src', 'app'])
33
+ candidates.push(join(dir, appDir, sub + '.ts'), join(dir, appDir, sub, 'index.ts'));
34
+ break;
35
+ }
36
+ }
37
+ return candidates.find((c) => existsSync(c));
38
+ }
39
+ const readFile = (f) => readFileSync(f, 'utf8');
40
+ /** The class a module exports as `name`, followed through re-exports (`export * from`, `export { X as name } from`). */
41
+ function exportedClass(file, name, read, seen = new Set()) {
42
+ if (seen.has(`${file}#${name}`))
43
+ return undefined;
44
+ seen.add(`${file}#${name}`);
45
+ const sf = parse(file, read(file));
46
+ if (classIn(sf, name))
47
+ return { file, name };
48
+ for (const st of sf.statements) {
49
+ if (ts.isExportDeclaration(st) && st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier)) {
50
+ const target = resolveClassImport(file, st.moduleSpecifier.text);
51
+ if (!target)
52
+ continue;
53
+ if (!st.exportClause) {
54
+ const found = exportedClass(target, name, read, seen);
55
+ if (found)
56
+ return found;
57
+ }
58
+ else if (ts.isNamedExports(st.exportClause)) {
59
+ const el = st.exportClause.elements.find((e) => e.name.text === name);
60
+ if (el)
61
+ return exportedClass(target, (el.propertyName ?? el.name).text, read, seen);
62
+ }
63
+ }
64
+ else if (ts.isExportDeclaration(st) && st.exportClause && ts.isNamedExports(st.exportClause)) {
65
+ // `import { X } from './x'; export { X as name };`
66
+ const el = st.exportClause.elements.find((e) => e.name.text === name);
67
+ const local = el ? (el.propertyName ?? el.name).text : undefined;
68
+ if (local)
69
+ return classOfName(file, sf, local, read, seen);
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+ /** The class a file's own name refers to: declared there, or imported. */
75
+ function classOfName(file, sf, name, read, seen = new Set()) {
76
+ if (classIn(sf, name))
77
+ return { file, name };
78
+ for (const st of sf.statements) {
79
+ if (!ts.isImportDeclaration(st) || !st.importClause || !ts.isStringLiteral(st.moduleSpecifier))
80
+ continue;
81
+ const bindings = st.importClause.namedBindings;
82
+ const el = bindings && ts.isNamedImports(bindings) ? bindings.elements.find((e) => e.name.text === name) : undefined;
83
+ if (!el)
84
+ continue;
85
+ const target = resolveClassImport(file, st.moduleSpecifier.text);
86
+ return target ? exportedClass(target, (el.propertyName ?? el.name).text, read, seen) : undefined;
87
+ }
88
+ return undefined;
89
+ }
90
+ function extendsOf(cls) {
91
+ return cls.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
92
+ }
93
+ function baseOf(file, sf, cls, read) {
94
+ const ext = extendsOf(cls);
95
+ const where = `${file}:${lineOf(ext)}`;
96
+ if (!ts.isIdentifier(ext.expression))
97
+ throw unsupported(where, `the component ${cls.name.text} extending ${ext.expression.getText()}`);
98
+ const found = classOfName(file, sf, ext.expression.text, read);
99
+ if (!found)
100
+ throw unsupported(where, `the component ${cls.name.text} extending ${ext.expression.text}, a class the build finds no source of in the app`);
101
+ return found;
102
+ }
103
+ function bindingsOf(file, sf) {
104
+ const out = new Map();
105
+ const exportsAs = new Map();
106
+ for (const st of sf.statements) {
107
+ if (ts.isExportDeclaration(st) && !st.moduleSpecifier && st.exportClause && ts.isNamedExports(st.exportClause)) {
108
+ for (const e of st.exportClause.elements)
109
+ exportsAs.set((e.propertyName ?? e.name).text, e.name.text);
110
+ }
111
+ }
112
+ const own = (name, node) => {
113
+ const exported = !!(ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword));
114
+ const typeOnly = ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node);
115
+ out.set(name, { module: withoutExt(file), spec: '', name: exported ? name : exportsAs.get(name) ?? name, typeOnly, exported: exported || exportsAs.has(name) });
116
+ };
117
+ for (const st of sf.statements) {
118
+ if (ts.isImportDeclaration(st) && st.importClause && ts.isStringLiteral(st.moduleSpecifier)) {
119
+ const spec = st.moduleSpecifier.text;
120
+ const target = resolveClassImport(file, spec);
121
+ const module = target ? withoutExt(target) : spec;
122
+ const clause = st.importClause;
123
+ if (clause.name)
124
+ out.set(clause.name.text, { module, spec, name: 'default', typeOnly: clause.isTypeOnly, exported: true });
125
+ const b = clause.namedBindings;
126
+ if (b && ts.isNamespaceImport(b))
127
+ out.set(b.name.text, { module, spec, name: '*', typeOnly: clause.isTypeOnly, exported: true });
128
+ if (b && ts.isNamedImports(b))
129
+ for (const e of b.elements)
130
+ out.set(e.name.text, { module, spec, name: (e.propertyName ?? e.name).text, typeOnly: clause.isTypeOnly || e.isTypeOnly, exported: true });
131
+ }
132
+ else if ((ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEnumDeclaration(st) || ts.isModuleDeclaration(st)) && st.name && ts.isIdentifier(st.name)) {
133
+ own(st.name.text, st);
134
+ }
135
+ else if (ts.isVariableStatement(st)) {
136
+ for (const d of st.declarationList.declarations)
137
+ if (ts.isIdentifier(d.name))
138
+ own(d.name.text, st);
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+ /** The names a node declares inside itself (parameters, locals), which a top-level name of the same spelling does not reach. */
144
+ function localNames(node) {
145
+ const out = new Set();
146
+ const visit = (n) => {
147
+ if ((ts.isParameter(n) || ts.isVariableDeclaration(n) || ts.isBindingElement(n)) && ts.isIdentifier(n.name))
148
+ out.add(n.name.text);
149
+ if ((ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n) || ts.isClassExpression(n)) && n.name)
150
+ out.add(n.name.text);
151
+ if (ts.isTypeParameterDeclaration(n))
152
+ out.add(n.name.text);
153
+ ts.forEachChild(n, visit);
154
+ };
155
+ ts.forEachChild(node, visit);
156
+ return out;
157
+ }
158
+ /** An identifier read as a name in scope, not as a member or property name. */
159
+ function isReference(id) {
160
+ const p = id.parent;
161
+ if (ts.isPropertyAccessExpression(p) && p.name === id)
162
+ return false;
163
+ if (ts.isQualifiedName(p) && p.right === id)
164
+ return false;
165
+ if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isMethodDeclaration(p) || ts.isAccessor(p) || ts.isPropertySignature(p) || ts.isMethodSignature(p) || ts.isEnumMember(p)) && p.name === id)
166
+ return false;
167
+ if (ts.isBindingElement(p) && p.propertyName === id)
168
+ return false;
169
+ if ((ts.isParameter(p) || ts.isVariableDeclaration(p) || ts.isBindingElement(p) || ts.isFunctionDeclaration(p) || ts.isFunctionExpression(p) || ts.isClassExpression(p) || ts.isTypeParameterDeclaration(p)) && p.name === id)
170
+ return false;
171
+ if (ts.isLabeledStatement(p) || ts.isBreakOrContinueStatement(p))
172
+ return false;
173
+ return true;
174
+ }
175
+ const applyEdits = (text, offset, edits) => {
176
+ let t = text;
177
+ for (const e of [...edits].sort((a, b) => b.start - a.start))
178
+ t = t.slice(0, e.start - offset) + e.text + t.slice(e.end - offset);
179
+ return t;
180
+ };
181
+ /** A node's text, leading comments included, with the edits inside it applied. */
182
+ const render = (n, edits, full = true) => {
183
+ const start = full ? n.getFullStart() : n.getStart();
184
+ return applyEdits(n.getSourceFile().text.slice(start, n.getEnd()), start, edits.filter((e) => e.start >= start && e.end <= n.getEnd()));
185
+ };
186
+ const modifiersText = (m, drop = []) => (ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : []).filter((x) => !drop.includes(x.kind) && x.kind !== ts.SyntaxKind.OverrideKeyword).map((x) => x.getText() + ' ').join('');
187
+ /** `this.x` read directly by an expression, outside the functions it creates (which run later). */
188
+ function readsThis(n, names) {
189
+ let found = false;
190
+ const visit = (x) => {
191
+ if (found || ts.isArrowFunction(x) || ts.isFunctionExpression(x) || ts.isClassExpression(x))
192
+ return;
193
+ if (x.kind === ts.SyntaxKind.ThisKeyword) {
194
+ const p = x.parent;
195
+ found = !names || (ts.isPropertyAccessExpression(p) && p.expression === x && names.has(p.name.text));
196
+ return;
197
+ }
198
+ ts.forEachChild(x, visit);
199
+ };
200
+ visit(n);
201
+ return found;
202
+ }
203
+ /** `this` anywhere a function's own `this` reaches: its body and the arrows in it. */
204
+ function usesThis(n) {
205
+ let found = false;
206
+ const visit = (x) => {
207
+ if (found || ts.isFunctionExpression(x) || ts.isFunctionDeclaration(x) || ts.isClassLike(x))
208
+ return;
209
+ if (x.kind === ts.SyntaxKind.ThisKeyword)
210
+ found = true;
211
+ else
212
+ ts.forEachChild(x, visit);
213
+ };
214
+ ts.forEachChild(n, visit);
215
+ return found;
216
+ }
217
+ const REACTIVE = /^(input|input\.required|model|model\.required|output|signal|computed|linkedSignal|toSignal|viewChild|viewChildren|contentChild|contentChildren|inject)$/;
218
+ const reactive = (e) => !!e && ((ts.isCallExpression(e) && REACTIVE.test(e.expression.getText())) || (ts.isNewExpression(e) && e.expression.getText() === 'EventEmitter'));
219
+ const BASE_META = new Set(['providers', 'viewProviders', 'host', 'inputs', 'outputs', 'queries', 'hostDirectives']);
220
+ /**
221
+ * The file's text with the class `name` flattened: no `extends`, its bases' members its own. `null` when the class
222
+ * extends nothing.
223
+ */
224
+ export function flattenComponent(path, text, name, read = readFile, seen = new Set()) {
225
+ let sf = parse(path, text);
226
+ let cls = classIn(sf, name);
227
+ if (!extendsOf(cls))
228
+ return null;
229
+ if (seen.has(`${path}#${name}`))
230
+ throw unsupported(path, `the class ${name} extending itself through its bases`);
231
+ seen.add(`${path}#${name}`);
232
+ const base = baseOf(path, sf, cls, read);
233
+ let baseSf;
234
+ if (base.file === path) {
235
+ // A base in the same file is flattened there first, and the component read again from that text.
236
+ const flat = flattenComponent(path, text, base.name, read, seen);
237
+ if (flat !== null) {
238
+ text = flat;
239
+ sf = parse(path, text);
240
+ cls = classIn(sf, name);
241
+ }
242
+ baseSf = sf;
243
+ }
244
+ else {
245
+ const original = read(base.file);
246
+ baseSf = parse(base.file, flattenComponent(base.file, original, base.name, read, seen) ?? original);
247
+ }
248
+ const B = classIn(baseSf, base.name);
249
+ const C = name;
250
+ const where = (n) => `${path}:${lineOf(n)}`;
251
+ const bwhere = (n) => `${base.file}:${lineOf(n)}`;
252
+ for (const d of decoratorsOf(B)) {
253
+ const meta = ts.isCallExpression(d.expression) ? d.expression.arguments[0] : undefined;
254
+ for (const p of meta && ts.isObjectLiteralExpression(meta) ? meta.properties : []) {
255
+ const key = p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : '';
256
+ if (BASE_META.has(key))
257
+ throw unsupported(bwhere(p), `the ${key} of ${base.name}, a class the component ${C} extends,`);
258
+ }
259
+ }
260
+ const instance = (members) => members.filter((m) => !isStatic(m) && !ts.isClassStaticBlockDeclaration(m) && !ts.isSemicolonClassElement(m) && !ts.isIndexSignatureDeclaration(m));
261
+ for (const m of [...instance(B.members), ...instance(cls.members)]) {
262
+ if (m.name && ts.isPrivateIdentifier(m.name))
263
+ throw unsupported(m.getSourceFile() === sf ? where(m) : bwhere(m), `the #private member ${m.name.text} in a component that extends a class, or in its base,`);
264
+ if (m.name && ts.isComputedPropertyName(m.name))
265
+ throw unsupported(m.getSourceFile() === sf ? where(m) : bwhere(m), `the computed member name ${m.name.getText()} in a component that extends a class, or in its base,`);
266
+ }
267
+ const baseMembers = instance(B.members).filter((m) => !ts.isConstructorDeclaration(m) && !isAbstract(m));
268
+ const own = instance(cls.members);
269
+ const ownByName = new Map();
270
+ for (const m of own) {
271
+ const n = memberName(m);
272
+ if (n !== undefined)
273
+ ownByName.set(n, [...(ownByName.get(n) ?? []), m]);
274
+ }
275
+ const kind = (m) => (ts.isPropertyDeclaration(m) ? 'field' : ts.isMethodDeclaration(m) ? 'method' : ts.isAccessor(m) ? 'accessor' : 'other');
276
+ // ---- Names: the base's text reads its own file's imports and declarations; the component's file binds them too.
277
+ const sameFile = base.file === path;
278
+ const mine = bindingsOf(path, sf);
279
+ const theirs = bindingsOf(base.file, baseSf);
280
+ const imports = [];
281
+ const mapped = new Map();
282
+ const nameFor = (n, at) => {
283
+ if (sameFile)
284
+ return n;
285
+ if (mapped.has(n))
286
+ return mapped.get(n);
287
+ const b = theirs.get(n);
288
+ if (!b.exported)
289
+ throw unsupported(bwhere(at), `${base.name}'s members naming ${n}, which ${base.file} does not export, in the component ${C} that extends it,`);
290
+ const same = (x) => x.module === b.module && x.name === b.name;
291
+ let local = mine.get(n) && same(mine.get(n)) ? n : [...mine].find(([, x]) => same(x))?.[0];
292
+ if (!local) {
293
+ local = mine.has(n) || mapped.has(n) ? `${n}__${base.name}` : n;
294
+ const spec = b.spec && !b.spec.startsWith('.') ? b.spec : (() => { const r = relative(dirname(path), b.module); return r.startsWith('.') ? r : './' + r; })();
295
+ const type = b.typeOnly ? 'type ' : '';
296
+ imports.push(b.name === 'default' ? `import ${type}${local} from '${spec}';` : b.name === '*' ? `import ${type}* as ${local} from '${spec}';` : `import ${type}{ ${b.name === local ? local : `${b.name} as ${local}`} } from '${spec}';`);
297
+ mine.set(local, b);
298
+ }
299
+ mapped.set(n, local);
300
+ return local;
301
+ };
302
+ // The base's type parameters, as the component's `extends Base<…>` gives them.
303
+ const typeArgs = new Map();
304
+ (B.typeParameters ?? []).forEach((p, i) => typeArgs.set(p.name.text, `(${extendsOf(cls).typeArguments?.[i]?.getText() ?? p.default?.getText() ?? 'any'})`));
305
+ /** A base node's text in the component's file, with `extra` edits of its own; `scope` declares its locals. */
306
+ const fromBase = (m, extra = [], full = true, scope = m) => {
307
+ const edits = [...extra];
308
+ const locals = localNames(scope);
309
+ const visit = (n) => {
310
+ if (ts.isIdentifier(n) && isReference(n) && !locals.has(n.text)) {
311
+ const t = typeArgs.get(n.text);
312
+ if (t !== undefined && ts.isTypeReferenceNode(n.parent))
313
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: t });
314
+ else if (theirs.has(n.text)) {
315
+ const local = nameFor(n.text, n);
316
+ if (local !== n.text)
317
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: ts.isShorthandPropertyAssignment(n.parent) ? `${n.text}: ${local}` : local });
318
+ }
319
+ }
320
+ ts.forEachChild(n, visit);
321
+ };
322
+ visit(m);
323
+ for (const x of ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : [])
324
+ if (x.kind === ts.SyntaxKind.OverrideKeyword)
325
+ edits.push({ start: x.getStart(), end: x.getEnd() + 1, text: '' });
326
+ return render(m, edits, full);
327
+ };
328
+ // ---- `super.x` in the component: the base's `x`, copied under a name of its own.
329
+ const superName = (n) => `$super_${base.name}_${n}`;
330
+ const supers = new Set();
331
+ const ownEdits = [];
332
+ let superCall;
333
+ const visitSuper = (n, member) => {
334
+ if (n.kind === ts.SyntaxKind.SuperKeyword) {
335
+ const p = n.parent;
336
+ if (ts.isCallExpression(p) && p.expression === n) {
337
+ const ctor = member;
338
+ const first = ts.isConstructorDeclaration(ctor) ? ctor.body?.statements[0] : undefined;
339
+ if (!first || !ts.isExpressionStatement(first) || first.expression !== p)
340
+ throw unsupported(where(p), `super(…) other than as the first statement of ${C}'s constructor, in a component that extends a class,`);
341
+ superCall = p;
342
+ return;
343
+ }
344
+ if (!ts.isPropertyAccessExpression(p) || p.expression !== n)
345
+ throw unsupported(where(p), `${p.getText()} in the component ${C}`);
346
+ if (isStatic(member))
347
+ throw unsupported(where(p), `super.${p.name.text} in a static member of the component ${C}`);
348
+ const target = baseMembers.filter((x) => memberName(x) === p.name.text);
349
+ if (!target.length || target.some((x) => !ts.isMethodDeclaration(x) && !ts.isAccessor(x)))
350
+ throw unsupported(where(p), `super.${p.name.text}, where ${base.name} has no method or accessor ${p.name.text},`);
351
+ supers.add(p.name.text);
352
+ ownEdits.push({ start: n.getStart(), end: n.getEnd(), text: 'this' }, { start: p.name.getStart(), end: p.name.getEnd(), text: superName(p.name.text) });
353
+ return;
354
+ }
355
+ ts.forEachChild(n, (c) => visitSuper(c, member));
356
+ };
357
+ for (const m of cls.members) {
358
+ visitSuper(m, m);
359
+ for (const x of ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : [])
360
+ if (x.kind === ts.SyntaxKind.OverrideKeyword)
361
+ ownEdits.push({ start: x.getStart(), end: x.getEnd() + 1, text: '' });
362
+ }
363
+ const fromOwn = (m, extra = [], full = true) => render(m, [...ownEdits, ...extra], full);
364
+ // ---- The base's constructor: its parameter properties and body, run where `super(…)` runs them.
365
+ const K = B.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
366
+ const ownCtor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
367
+ const paramProps = (K?.parameters ?? []).filter((p) => (ts.getModifiers(p) ?? []).length);
368
+ const work = !!K && (K.parameters.length > 0 || K.body.statements.length > 0);
369
+ // Fields the component declares again: one field, where the base declares it.
370
+ const merged = new Map();
371
+ const dropped = new Set();
372
+ const assigned = [];
373
+ const overridden = new Set();
374
+ for (const bm of baseMembers) {
375
+ const n = memberName(bm);
376
+ const mine2 = n === undefined ? undefined : ownByName.get(n);
377
+ if (!mine2)
378
+ continue;
379
+ overridden.add(n);
380
+ const kinds = new Set(mine2.map(kind));
381
+ if (kinds.size > 1 || kind(bm) !== [...kinds][0])
382
+ throw unsupported(where(mine2[0]), `${C}.${n}, a ${[...kinds][0]} over ${base.name}'s ${kind(bm)},`);
383
+ if (!ts.isPropertyDeclaration(bm))
384
+ continue;
385
+ const of = mine2[0];
386
+ dropped.add(of);
387
+ const plain = !decoratorsOf(of).length && !decoratorsOf(bm).length && !reactive(of.initializer) && !reactive(bm.initializer);
388
+ // The base's declaration with the type the component declares it with (a narrower one).
389
+ const retyped = () => fromBase(bm, !of.type ? [] : bm.type ? [{ start: bm.type.getStart(), end: bm.type.getEnd(), text: of.type.getText() }] : [{ start: (bm.questionToken ?? bm.exclamationToken ?? bm.name).getEnd(), end: (bm.questionToken ?? bm.exclamationToken ?? bm.name).getEnd(), text: `: ${of.type.getText()}` }]);
390
+ if (!of.initializer && !decoratorsOf(of).length) {
391
+ merged.set(bm, retyped());
392
+ }
393
+ else if (of.initializer && plain) {
394
+ // The base's value first, as its constructor sees it; the component's once the base's constructor has run.
395
+ merged.set(bm, retyped());
396
+ assigned.push(`this.${n} = ${fromOwn(of.initializer, [], false)};`);
397
+ }
398
+ else if (!of.initializer && bm.initializer) {
399
+ // Decorated again without a value: the base's value stays.
400
+ const at = (of.type ?? of.questionToken ?? of.name).getEnd();
401
+ merged.set(bm, fromOwn(of, [{ start: at, end: at, text: ` = ${fromBase(bm.initializer, [], false)}` }, ...(of.exclamationToken ? [{ start: of.exclamationToken.getStart(), end: of.exclamationToken.getEnd(), text: '' }] : [])]));
402
+ }
403
+ else {
404
+ merged.set(bm, fromOwn(of));
405
+ }
406
+ }
407
+ const ownFields = own.filter((m) => ts.isPropertyDeclaration(m) && !!m.initializer && !dropped.has(m));
408
+ if (assigned.length) {
409
+ const reader = ownFields.find((f) => readsThis(f.initializer, overridden));
410
+ if (reader)
411
+ throw unsupported(where(reader), `${C}.${memberName(reader)}'s initializer reading a field ${C} declares again over ${base.name}'s`);
412
+ }
413
+ const sensitive = ownFields.some((f) => readsThis(f.initializer));
414
+ const pieces = [];
415
+ const params = K ? K.parameters : [];
416
+ const baseBody = K ? K.body : undefined;
417
+ /** The base constructor's body as a method's, returning true, and its readonly fields assigned there writable. */
418
+ const writes = new Set();
419
+ const bodyText = (prelude) => {
420
+ const edits = [];
421
+ const visit = (n) => {
422
+ if (ts.isFunctionLike(n) && n !== K)
423
+ return;
424
+ if (ts.isReturnStatement(n)) {
425
+ if (n.expression)
426
+ throw unsupported(bwhere(n), `a value returned from ${base.name}'s constructor`);
427
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: 'return true;' });
428
+ }
429
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(n.left) && n.left.expression.kind === ts.SyntaxKind.ThisKeyword)
430
+ writes.add(n.left.name.text);
431
+ ts.forEachChild(n, visit);
432
+ };
433
+ visit(baseBody);
434
+ const inner = fromBase(baseBody, edits, true, K).trim().slice(1, -1);
435
+ return `{\n ${prelude.join('\n ')}${inner}\n return true;\n }`;
436
+ };
437
+ const plainParams = params.filter((p) => !(ts.getModifiers(p) ?? []).length);
438
+ const namesRead = (n, names) => {
439
+ const found = new Set();
440
+ const visit = (x) => { if (ts.isIdentifier(x) && isReference(x) && names.includes(x.text))
441
+ found.add(x.text); ts.forEachChild(x, visit); };
442
+ if (n)
443
+ visit(n);
444
+ return found;
445
+ };
446
+ const returns = (() => {
447
+ let found = false;
448
+ const visit = (n) => { if (ts.isReturnStatement(n))
449
+ found = true;
450
+ else if (!ts.isFunctionLike(n))
451
+ ts.forEachChild(n, visit); };
452
+ if (baseBody)
453
+ ts.forEachChild(baseBody, visit);
454
+ return found;
455
+ })();
456
+ /** `name` read as `this.name`, for the component's parameter properties read where only fields are. */
457
+ const asFields = (n, names) => {
458
+ const e = [];
459
+ const visit = (x) => { if (ts.isIdentifier(x) && isReference(x) && names.has(x.text))
460
+ e.push({ start: x.getStart(), end: x.getEnd(), text: `this.${x.text}` }); ts.forEachChild(x, visit); };
461
+ visit(n);
462
+ return e;
463
+ };
464
+ const initName = `$init_${base.name}`;
465
+ let initCall;
466
+ let ownCtorText;
467
+ let ctorPiece;
468
+ if (work && ownCtor) {
469
+ const ps = params.map((p) => `${p.name.getText()}${p.questionToken ? '?' : ''}${p.type ? `: ${fromBase(p.type, [], false)}` : ''}${p.initializer ? ` = ${fromBase(p.initializer, [], false)}` : ''}`);
470
+ const prelude = paramProps.map((p) => `this.${p.name.getText()} = ${p.name.getText()};`);
471
+ const args = superCall?.arguments ?? [];
472
+ if (sensitive) {
473
+ // Run as a field, between the base's fields and the component's, as TypeScript runs `super(…)`.
474
+ const ownParams = ownCtor.parameters.map((p) => p.name.getText());
475
+ const props = new Set(ownCtor.parameters.filter((p) => (ts.getModifiers(p) ?? []).length).map((p) => p.name.getText()));
476
+ const bad = args.flatMap((a) => [...namesRead(a, ownParams)]).find((x) => !props.has(x));
477
+ if (bad)
478
+ throw unsupported(where(superCall), `${C}'s field initializers reading this, with super(…) given its constructor's parameter ${bad},`);
479
+ const argText = args.map((a) => fromOwn(a, asFields(a, props), false));
480
+ initCall = ` private readonly $${base.name}_ready = this.${initName}(${argText.join(', ')});`;
481
+ }
482
+ pieces.push(` ${initName}(${ps.join(', ')}): boolean ${bodyText(prelude)}`);
483
+ const first = ownCtor.body.statements[0];
484
+ const replaced = (sensitive ? '' : `this.${initName}(${(superCall?.arguments ?? []).map((a) => fromOwn(a, [], false)).join(', ')});`) + (assigned.length ? ' ' + assigned.join(' ') : '');
485
+ ownCtorText = fromOwn(ownCtor, superCall ? [{ start: first.getStart(), end: first.getEnd(), text: replaced }] : []);
486
+ }
487
+ else if (work) {
488
+ // Angular injects the base constructor's parameters into a component that declares no constructor.
489
+ const sig = `constructor(${params.map((p) => fromBase(p, [], false)).join(', ')})`;
490
+ // The component's own field values follow the base constructor's body, even one that returns early.
491
+ if ((!sensitive && !(returns && assigned.length)) || !K.body.statements.length) {
492
+ const inner = fromBase(K.body, [], true, K).trim().slice(1, -1);
493
+ ctorPiece = ` ${sig} {${inner}${assigned.length ? '\n ' + assigned.join('\n ') : ''}\n }`;
494
+ }
495
+ else {
496
+ const plain = namesRead(baseBody, plainParams.map((p) => p.name.getText()));
497
+ if (plain.size)
498
+ throw unsupported(where(cls), `${C}'s field initializers reading this, with ${base.name}'s constructor body reading its parameter ${[...plain][0]},`);
499
+ const props = namesRead(baseBody, paramProps.map((p) => p.name.getText()));
500
+ pieces.push(` ${initName}(): boolean ${bodyText([...props].map((p) => `const ${p} = this.${p};`))}`);
501
+ initCall = ` private readonly $${base.name}_ready = this.${initName}();`;
502
+ ctorPiece = ` ${sig} {${assigned.length ? '\n ' + assigned.join('\n ') + '\n ' : ''}}`;
503
+ }
504
+ }
505
+ else if (ownCtor) {
506
+ const first = ownCtor.body.statements[0];
507
+ ownCtorText = fromOwn(ownCtor, superCall ? [{ start: first.getStart(), end: first.getEnd(), text: assigned.join(' ') }] : []);
508
+ }
509
+ else if (assigned.length) {
510
+ ctorPiece = ` constructor() {\n ${assigned.join('\n ')}\n }`;
511
+ }
512
+ // ---- The base's statics, which JavaScript reads through the component (`C.x` finds `Base.x`): members reading the
513
+ // base's own. Where that differs (`this` in them is C in JavaScript, a write through C makes C's own), `refuseBaseUses`
514
+ // stops the build. A private one can't be read through C; a plain base's protected one can't be read from C once C
515
+ // no longer extends it (a component base's are opened, `openStatics`).
516
+ const ref = extendsOf(cls).expression.text;
517
+ const component = decoratorsOf(B).some((d) => /^Component\b/.test(d.expression.getText()));
518
+ const ownStatics = new Set(cls.members.filter(isStatic).map(memberName));
519
+ const forwards = [];
520
+ const forwarded = new Set();
521
+ for (const bm of B.members) {
522
+ const n = memberName(bm);
523
+ if (!isStatic(bm) || n === undefined || !bm.name || !ts.isIdentifier(bm.name) || ownStatics.has(n) || forwarded.has(n))
524
+ continue;
525
+ const mods = ts.canHaveModifiers(bm) ? ts.getModifiers(bm) ?? [] : [];
526
+ if (mods.some((x) => x.kind === ts.SyntaxKind.PrivateKeyword) || (!component && mods.some((x) => x.kind === ts.SyntaxKind.ProtectedKeyword)))
527
+ continue;
528
+ forwarded.add(n);
529
+ const same = B.members.filter((x) => isStatic(x) && memberName(x) === n);
530
+ if (same.some((x) => ts.isMethodDeclaration(x))) {
531
+ const impl = same.find((x) => ts.isMethodDeclaration(x) && !!x.body);
532
+ if (!impl)
533
+ continue;
534
+ const overloads = same.filter((x) => ts.isMethodDeclaration(x) && !x.body).map((x) => fromBase(x, [], false));
535
+ const typeParams = impl.typeParameters ? `<${impl.typeParameters.map((t) => fromBase(t, [], false)).join(', ')}>` : '';
536
+ const ps = impl.parameters.map((q) => fromBase(q, [], false));
537
+ const args = impl.parameters.map((q) => `${q.dotDotDotToken ? '...' : ''}${q.name.getText()}`);
538
+ forwards.push(...overloads.map((o) => `\n ${o}`), `\n static ${n}${typeParams}(${ps.join(', ')})${impl.type ? `: ${fromBase(impl.type, [], false)}` : ''} {\n return ${ref}.${n}(${args.join(', ')});\n }`);
539
+ continue;
540
+ }
541
+ const set = same.find(ts.isSetAccessorDeclaration);
542
+ forwards.push(`\n static get ${n}() {\n return ${ref}.${n};\n }`);
543
+ if (set)
544
+ forwards.push(`\n static set ${n}(value: typeof ${ref}.${n}) {\n ${ref}.${n} = value;\n }`);
545
+ }
546
+ // ---- The class: the base's members, then the component's.
547
+ const out = [];
548
+ const movedToMethod = work && (!!ownCtor || !!initCall);
549
+ for (const p of work && ownCtor ? paramProps : []) {
550
+ out.push(`\n ${modifiersText(p, [ts.SyntaxKind.ReadonlyKeyword])}${p.name.getText()}!: ${p.type ? fromBase(p.type, [], false) : 'any'};`);
551
+ }
552
+ for (const bm of baseMembers) {
553
+ if (merged.has(bm)) {
554
+ out.push(merged.get(bm));
555
+ continue;
556
+ }
557
+ const n = memberName(bm);
558
+ if (n !== undefined && ownByName.has(n))
559
+ continue;
560
+ const extra = [];
561
+ if (movedToMethod && ts.isPropertyDeclaration(bm)) {
562
+ const ro = (ts.getModifiers(bm) ?? []).find((x) => x.kind === ts.SyntaxKind.ReadonlyKeyword);
563
+ if (ro && n && writes.has(n))
564
+ extra.push({ start: ro.getStart(), end: ro.getEnd() + 1, text: '' });
565
+ if (!bm.initializer && !bm.questionToken && !bm.exclamationToken && !decoratorsOf(bm).length && bm.type)
566
+ extra.push({ start: bm.name.getEnd(), end: bm.name.getEnd(), text: '!' });
567
+ }
568
+ out.push(fromBase(bm, extra));
569
+ }
570
+ for (const n of supers) {
571
+ for (const bm of baseMembers.filter((x) => memberName(x) === n))
572
+ out.push(fromBase(bm, [{ start: bm.name.getStart(), end: bm.name.getEnd(), text: superName(n) }]));
573
+ }
574
+ out.push(...pieces.map((p) => '\n' + p));
575
+ if (initCall)
576
+ out.push('\n' + initCall);
577
+ if (ctorPiece)
578
+ out.push('\n' + ctorPiece);
579
+ for (const m of cls.members) {
580
+ if (dropped.has(m))
581
+ continue;
582
+ out.push(m === ownCtor && ownCtorText !== undefined ? ownCtorText : fromOwn(m));
583
+ }
584
+ out.push(...forwards);
585
+ const ext = cls.heritageClauses.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
586
+ const others = cls.heritageClauses.filter((h) => h !== ext);
587
+ const head = text.slice(cls.getStart(), ext.getFullStart()) + (others.length ? ' ' + others.map((h) => h.getText()).join(' ') : '') + ' {';
588
+ const flat = head + out.join('') + '\n}';
589
+ return (imports.length ? imports.join('\n') + '\n' : '') + text.slice(0, cls.getStart()) + flat + text.slice(cls.getEnd());
590
+ }
591
+ const QUERIES = /^(ViewChild|ViewChildren|ContentChild|ContentChildren|viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/;
592
+ const PROVIDER_KEYS = new Set(['provide', 'useClass', 'useExisting', 'providers', 'viewProviders']);
593
+ /** What a reference to a flattened base needs of it that the copy cannot give, or nothing. */
594
+ function needsBase(id, name) {
595
+ const p = id.parent;
596
+ if (ts.isBinaryExpression(p) && p.right === id && p.operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword)
597
+ return `instanceof ${name}`;
598
+ if (ts.isTypeReferenceNode(p) && p.typeName === id)
599
+ return `${name} as a type`;
600
+ for (let n = p; n && !ts.isSourceFile(n); n = n.parent) {
601
+ if (ts.isCallExpression(n) && n.arguments.some((a) => a.pos <= id.pos && id.end <= a.end)) {
602
+ const callee = n.expression.getText();
603
+ if (callee === 'inject')
604
+ return `inject(${name})`;
605
+ if (callee === 'Inject' && ts.isDecorator(n.parent))
606
+ return `@Inject(${name})`;
607
+ if (QUERIES.test(callee))
608
+ return `a query by ${name} (${callee})`;
609
+ }
610
+ if (ts.isPropertyAssignment(n) && n.initializer.pos <= id.pos && id.end <= n.initializer.end && PROVIDER_KEYS.has(n.name.getText()))
611
+ return `${name} as a provider (${n.name.getText()})`;
612
+ if (ts.isStatement(n) || ts.isClassElement(n))
613
+ break;
614
+ }
615
+ return undefined;
616
+ }
617
+ /**
618
+ * A class that a component extends is copied into it (`flattenComponent`), so the component is no instance of it: an
619
+ * app file reading one as such (`instanceof`, injection or a query by it, a provider of it, a type) stops the build.
620
+ */
621
+ export function refuseBaseUses(files, read = readFile) {
622
+ const bases = new Map();
623
+ const derived = new Map();
624
+ for (const f of files) {
625
+ const text = read(f);
626
+ if (!/@Component\b/.test(text) || !/\bextends\b/.test(text))
627
+ continue;
628
+ const sf = parse(f, text);
629
+ for (const st of sf.statements) {
630
+ if (!ts.isClassDeclaration(st) || !st.name || !decoratorsOf(st).some((d) => /^Component\b/.test(d.expression.getText())))
631
+ continue;
632
+ let file = f, at = sf, cls = st;
633
+ const seen = new Set();
634
+ const statics = new Map();
635
+ const declared = new Set(st.members.filter(isStatic).map(memberName));
636
+ while (cls && extendsOf(cls) && ts.isIdentifier(extendsOf(cls).expression)) {
637
+ const b = classOfName(file, at, extendsOf(cls).expression.text, read);
638
+ if (!b || seen.has(`${b.file}#${b.name}`))
639
+ break;
640
+ seen.add(`${b.file}#${b.name}`);
641
+ if (!bases.has(`${b.file}#${b.name}`))
642
+ bases.set(`${b.file}#${b.name}`, { name: b.name, by: st.name.text });
643
+ file = b.file;
644
+ at = parse(file, read(file));
645
+ cls = classIn(at, b.name);
646
+ for (const m of cls?.members ?? []) {
647
+ const n = memberName(m);
648
+ if (!isStatic(m) || n === undefined || declared.has(n))
649
+ continue;
650
+ const kind = ts.isPropertyDeclaration(m) ? 'field' : ts.isMethodDeclaration(m) && m.body && usesThis(m.body) ? 'method' : ts.isSetAccessorDeclaration(m) && m.body && usesThis(m.body) ? 'setter' : null;
651
+ if (kind && !statics.has(n))
652
+ statics.set(n, { base: b.name, kind });
653
+ }
654
+ for (const m of cls?.members ?? [])
655
+ if (isStatic(m))
656
+ declared.add(memberName(m));
657
+ }
658
+ if (statics.size)
659
+ derived.set(`${f}#${st.name.text}`, { name: st.name.text, statics });
660
+ }
661
+ }
662
+ if (!bases.size)
663
+ return;
664
+ const names = [...new Set([...bases.values(), ...derived.values()].map((b) => b.name))];
665
+ /** The class declared or imported under `n` in this file, among `among`. */
666
+ const resolve = (f, sf, among) => {
667
+ const local = new Map();
668
+ for (const n of names) {
669
+ const found = sf.text.includes(n) ? classOfName(f, sf, n, read) : undefined;
670
+ const b = found && among.get(`${found.file}#${found.name}`);
671
+ if (b)
672
+ local.set(n, b);
673
+ }
674
+ for (const st of sf.statements) {
675
+ if (!ts.isImportDeclaration(st) || !st.importClause?.namedBindings || !ts.isNamedImports(st.importClause.namedBindings))
676
+ continue;
677
+ for (const e of st.importClause.namedBindings.elements) {
678
+ if (local.has(e.name.text) || !e.propertyName)
679
+ continue;
680
+ const found = classOfName(f, sf, e.name.text, read);
681
+ const b = found && among.get(`${found.file}#${found.name}`);
682
+ if (b)
683
+ local.set(e.name.text, b);
684
+ }
685
+ }
686
+ return local;
687
+ };
688
+ for (const f of files) {
689
+ const text = read(f);
690
+ if (!names.some((n) => text.includes(n)))
691
+ continue;
692
+ const sf = parse(f, text);
693
+ const local = resolve(f, sf, bases);
694
+ const sub = resolve(f, sf, derived);
695
+ if (!local.size && !sub.size)
696
+ continue;
697
+ // `C.x` (or `this.x` in C's statics) of a static C inherits, where the copy differs from JavaScript's lookup.
698
+ const inherited = (pa, d) => {
699
+ const s = d.statics.get(pa.name.text);
700
+ const p = pa.parent;
701
+ const write = (ts.isBinaryExpression(p) && p.left === pa && p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && p.operatorToken.kind <= ts.SyntaxKind.LastAssignment)
702
+ || ((ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) && (p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken));
703
+ const at = `${f}:${lineOf(pa)}`;
704
+ if (s?.kind === 'method')
705
+ throw unsupported(at, `${d.name}.${pa.name.text}, a static method of ${s.base} reading this, through the component ${d.name} that extends it,`);
706
+ if (write && s?.kind === 'field')
707
+ throw unsupported(at, `writing ${d.name}.${pa.name.text}, a static field the component ${d.name} inherits from ${s.base} (write ${s.base}.${pa.name.text}),`);
708
+ if (write && s?.kind === 'setter')
709
+ throw unsupported(at, `writing ${d.name}.${pa.name.text}, a static setter of ${s.base} reading this, through the component ${d.name} that extends it,`);
710
+ };
711
+ const visit = (n, self) => {
712
+ if (ts.isIdentifier(n) && local.has(n.text) && isReference(n) && !ts.isImportSpecifier(n.parent) && !ts.isExportSpecifier(n.parent) && !(ts.isClassDeclaration(n.parent) && n.parent.name === n)) {
713
+ const b = local.get(n.text);
714
+ const what = needsBase(n, n.text);
715
+ if (what)
716
+ throw unsupported(`${f}:${lineOf(n)}`, `${what}, where ${b.name} is a class the component ${b.by} extends (and the release build copies into it),`);
717
+ }
718
+ if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression) && sub.has(n.expression.text))
719
+ inherited(n, sub.get(n.expression.text));
720
+ if (self && ts.isPropertyAccessExpression(n) && n.expression.kind === ts.SyntaxKind.ThisKeyword)
721
+ inherited(n, self);
722
+ if (ts.isClassDeclaration(n) && n.name && sub.has(n.name.text) && derived.get(`${f}#${n.name.text}`)) {
723
+ for (const m of n.members)
724
+ visit(m, isStatic(m) ? derived.get(`${f}#${n.name.text}`) : undefined);
725
+ return;
726
+ }
727
+ ts.forEachChild(n, (c) => visit(c, self && (ts.isFunctionExpression(c) || ts.isFunctionDeclaration(c) || ts.isClassLike(c)) ? undefined : self));
728
+ };
729
+ visit(sf);
730
+ }
731
+ }
732
+ /**
733
+ * A component's static members without `private`/`protected`: a subclass's copy of its methods names them through
734
+ * the class. The native classes have no such access levels either.
735
+ */
736
+ export function openStatics(text, cls) {
737
+ const edits = [];
738
+ for (const m of cls.members) {
739
+ if (!isStatic(m))
740
+ continue;
741
+ for (const x of ts.getModifiers(m) ?? [])
742
+ if (x.kind === ts.SyntaxKind.PrivateKeyword || x.kind === ts.SyntaxKind.ProtectedKeyword)
743
+ edits.push({ start: x.getStart(), end: x.getEnd() + 1, text: '' });
744
+ }
745
+ return edits.length ? applyEdits(text, 0, edits) : text;
746
+ }