@nstudio/nativescript-compiler-angular 9.2.0-alpha.10 → 9.2.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/angular-libraries.js +225 -12
- package/dist/angular.js +1453 -202
- package/dist/component-bases.js +144 -37
- package/dist/entry.js +32 -2
- package/dist/index.js +93 -25
- package/dist/kotlin.js +9 -7
- package/dist/modules.js +100 -20
- package/dist/refusals.js +0 -1
- package/dist/semantics.js +16 -4
- package/dist/swift.js +9 -9
- package/kit-android/fromcore/AngularAPI.kt +3 -1
- package/kit-android/fromcore/AngularRouter.kt +105 -2
- package/kit-android/main/AngularCore.kt +121 -8
- package/kit-android/main/AngularRx.kt +4 -0
- package/kit-apple/AngularAPI.swift +6 -2
- package/kit-apple/AngularCore.swift +119 -5
- package/kit-apple/AngularRouter.swift +105 -0
- package/kit-apple/AngularRx.swift +4 -0
- package/kit-apple/kit-index.json +103 -5
- package/package.json +2 -2
- package/runtime/angular-cdk.ts +673 -0
- package/runtime/angular-rx.ts +38 -2
package/dist/angular.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import * as ng from '@angular/compiler';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { dirname, extname, isAbsolute, join, relative } from 'node:path';
|
|
6
6
|
import { core, ts } from "./core-api.js";
|
|
7
|
-
import { flattenComponent, openStatics } from "./component-bases.js";
|
|
7
|
+
import { flattenComponent, inheritedDirectiveClasses, isRealDirectiveBaseChain, openStatics } from "./component-bases.js";
|
|
8
8
|
import { decorator } from "./ng-modules.js";
|
|
9
9
|
/** The elements of the binary-only plugins `release.stubPlugins` can stub, by lowercase tag, and their packages. */
|
|
10
10
|
const STUB_ELEMENTS = {
|
|
@@ -46,6 +46,42 @@ const COMMON_PIPES = {
|
|
|
46
46
|
keyvalue: { className: 'KeyValuePipe', file: RUNTIME, pure: false },
|
|
47
47
|
};
|
|
48
48
|
const UNSUPPORTED_COMMON_PIPES = new Set(['currency', 'i18nPlural', 'i18nSelect']);
|
|
49
|
+
/**
|
|
50
|
+
* Every NativeScript Angular `@Component` class in `path` as a virtual class: the file's own source with one method
|
|
51
|
+
* appended per template expression on each component class. Multiple `@Component` classes in one file share one virtual
|
|
52
|
+
* `.release.ts` file so imports and file-local helpers resolve without duplication.
|
|
53
|
+
*/
|
|
54
|
+
export function angularComponents(path, text, selectors, options = {}) {
|
|
55
|
+
if (!text.includes('@Component'))
|
|
56
|
+
return [];
|
|
57
|
+
const initialSf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
58
|
+
const targets = initialSf.statements
|
|
59
|
+
.filter((s) => ts.isClassDeclaration(s) && !!s.name && !!decorator(s, 'Component'))
|
|
60
|
+
.map((s) => s.name.text);
|
|
61
|
+
if (!targets.length)
|
|
62
|
+
return [];
|
|
63
|
+
let currentText = text;
|
|
64
|
+
const results = [];
|
|
65
|
+
for (const targetName of targets) {
|
|
66
|
+
const beforeLines = currentText.split('\n').length;
|
|
67
|
+
const { component, nextText, prependedLines } = compileOneComponent(path, text, currentText, targetName, selectors, options);
|
|
68
|
+
if (prependedLines > 0) {
|
|
69
|
+
for (const prev of results) {
|
|
70
|
+
if (prev.templateLines)
|
|
71
|
+
prev.templateLines.lines = prev.templateLines.lines.map(([v, src]) => [v + prependedLines, src]);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
void beforeLines;
|
|
75
|
+
currentText = nextText;
|
|
76
|
+
results.push(component);
|
|
77
|
+
}
|
|
78
|
+
const stripped = declarableSource(path, currentText);
|
|
79
|
+
if (stripped)
|
|
80
|
+
currentText = stripped;
|
|
81
|
+
for (const c of results)
|
|
82
|
+
c.source = currentText;
|
|
83
|
+
return results;
|
|
84
|
+
}
|
|
49
85
|
/**
|
|
50
86
|
* A NativeScript Angular standalone component (`@Component` with a template
|
|
51
87
|
* of @nativescript/core elements, signals, `input()`/`output()`, `inject()`)
|
|
@@ -54,28 +90,28 @@ const UNSUPPORTED_COMMON_PIPES = new Set(['currency', 'i18nPlural', 'i18nSelect'
|
|
|
54
90
|
* knows what `signal()`, `computed()`, `input()`, `output()` and `inject()` mean.
|
|
55
91
|
*/
|
|
56
92
|
export function angularComponent(path, text, selectors, options = {}) {
|
|
57
|
-
|
|
93
|
+
return angularComponents(path, text, selectors, options)[0] ?? null;
|
|
94
|
+
}
|
|
95
|
+
function compileOneComponent(path, written, text, targetName, selectors, options) {
|
|
96
|
+
const findTarget = (source) => source.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === targetName && !!decorator(s, 'Component'));
|
|
58
97
|
let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
59
|
-
let cls = sf
|
|
60
|
-
if (!cls || !cls.name)
|
|
61
|
-
return null;
|
|
62
|
-
const others = sf.statements.filter((s) => s !== cls && ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
63
|
-
if (others.length)
|
|
64
|
-
throw new Error(`${path}: ${others.length + 1} components in one file; a compiled release takes one @Component per file`);
|
|
98
|
+
let cls = findTarget(sf);
|
|
65
99
|
const asWritten = cls;
|
|
66
|
-
|
|
67
|
-
const
|
|
100
|
+
let prependedLines = 0;
|
|
101
|
+
const flat = flattenComponent(path, text, cls.name.text, undefined, undefined, options.aliased);
|
|
102
|
+
const opened = openStatics(flat ?? text, flat === null ? cls : findTarget(ts.createSourceFile(path, flat, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
|
|
68
103
|
if (opened !== text) {
|
|
69
104
|
text = opened;
|
|
70
105
|
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
71
|
-
cls = sf
|
|
106
|
+
cls = findTarget(sf);
|
|
72
107
|
}
|
|
73
108
|
// A class with decorated inputs and outputs, or constructor injection, as the signal-style class the translator reads.
|
|
74
109
|
const classic = classicClass(path, text, cls);
|
|
75
110
|
if (classic) {
|
|
111
|
+
prependedLines += classic.prependedLines;
|
|
76
112
|
text = classic.text;
|
|
77
113
|
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
78
|
-
cls = sf
|
|
114
|
+
cls = findTarget(sf);
|
|
79
115
|
}
|
|
80
116
|
const meta = decorator(cls, 'Component').arguments[0];
|
|
81
117
|
const prop = (name) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === name)?.initializer;
|
|
@@ -89,14 +125,16 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
89
125
|
throw new Error(`${path}: @Component's ${key} is not supported in a release build yet`);
|
|
90
126
|
}
|
|
91
127
|
const providers = prop('providers');
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
128
|
+
const viewProviders = prop('viewProviders');
|
|
129
|
+
const hasProviders = !!(providers || viewProviders);
|
|
130
|
+
if (hasProviders) {
|
|
95
131
|
refuseScopedInjection(path, asWritten);
|
|
96
|
-
text = withInjector(path, text, cls, providers);
|
|
132
|
+
text = withInjector(path, text, cls, providers, viewProviders);
|
|
97
133
|
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
98
|
-
cls = sf
|
|
134
|
+
cls = findTarget(sf);
|
|
99
135
|
}
|
|
136
|
+
const hostMeta = prop('host');
|
|
137
|
+
const hostDirectivesMeta = prop('hostDirectives');
|
|
100
138
|
const selector = prop('selector')?.text ?? cls.name.text;
|
|
101
139
|
const inline = prop('template');
|
|
102
140
|
const templateUrl = prop('templateUrl')?.text;
|
|
@@ -115,8 +153,8 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
115
153
|
for (const k of [tag, tag.toLowerCase(), tag.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()])
|
|
116
154
|
metas.set(k, keys);
|
|
117
155
|
/**
|
|
118
|
-
* A plugin tag registered with a `ViewClassMeta` (`registerElement('Drawer', () => Drawer, meta)`):
|
|
119
|
-
*
|
|
156
|
+
* A plugin tag registered with a `ViewClassMeta` (`registerElement('Drawer', () => Drawer, meta)`): `insertChild` and
|
|
157
|
+
* `removeChild` run at runtime through the kit's `ViewMetaRegistry`; `skipAddToDom` and invisible-node hooks remain refused.
|
|
120
158
|
*/
|
|
121
159
|
const checkMeta = (n) => {
|
|
122
160
|
if (core.canonical(n.name) || core.canonical(n.name.replace(/-/g, '')))
|
|
@@ -128,17 +166,44 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
128
166
|
throw new Error(`${path}: <${n.name}> is registered with a ViewClassMeta the build cannot read (not an object literal in the registering file)`);
|
|
129
167
|
if (keys.includes('skipAddToDom'))
|
|
130
168
|
throw new Error(`${path}: <${n.name}> is registered with skipAddToDom, which a release build does not support yet`);
|
|
131
|
-
const hooks = keys.filter((k) => ['
|
|
169
|
+
const hooks = keys.filter((k) => ['insertInvisibleNode', 'removeInvisibleNode'].includes(k));
|
|
132
170
|
if (hooks.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim())) {
|
|
133
171
|
throw new Error(`${path}: the children of <${n.name}> join it through its registerElement meta (${hooks.join(', ')}), which a release build does not run yet`);
|
|
134
172
|
}
|
|
135
173
|
};
|
|
136
|
-
const { members, props, optional, outputs, inputAliases } = publicMembers(path, cls, classic);
|
|
174
|
+
const { members, props, optional, outputs, inputAliases, inputTransforms } = publicMembers(path, cls, classic);
|
|
175
|
+
const inheritedSetters = new Set();
|
|
176
|
+
const inheritedBases = flat === null && isRealDirectiveBaseChain(path, sf, cls, options.readFile, options.aliased)
|
|
177
|
+
? inheritedDirectiveClasses(path, sf, cls, options.readFile, options.aliased)
|
|
178
|
+
: [];
|
|
179
|
+
for (const base of inheritedBases) {
|
|
180
|
+
const bm = publicMembers(base.file, base.cls, null);
|
|
181
|
+
for (const m of bm.members)
|
|
182
|
+
members.add(m);
|
|
183
|
+
for (const p of bm.props)
|
|
184
|
+
if (!props.includes(p))
|
|
185
|
+
props.push(p);
|
|
186
|
+
for (const o of bm.optional)
|
|
187
|
+
if (!optional.includes(o))
|
|
188
|
+
optional.push(o);
|
|
189
|
+
for (const o of bm.outputs)
|
|
190
|
+
if (!outputs.includes(o))
|
|
191
|
+
outputs.push(o);
|
|
192
|
+
for (const [k, v] of Object.entries(bm.inputAliases))
|
|
193
|
+
if (!(k in inputAliases))
|
|
194
|
+
inputAliases[k] = v;
|
|
195
|
+
for (const k of bm.inputTransforms.keys())
|
|
196
|
+
if (!inputTransforms.has(k))
|
|
197
|
+
inheritedSetters.add(k);
|
|
198
|
+
}
|
|
137
199
|
const scope = { names: new Map([...members].map((m) => [m, classic?.inputs.has(m) ? `this.${m}()` : `this.${m}`])) };
|
|
138
|
-
const
|
|
200
|
+
const findLifecycleMethod = (name) => [cls, ...inheritedBases.map((b) => b.cls)]
|
|
201
|
+
.map((c) => c.members.find((x) => ts.isMethodDeclaration(x) && x.name.getText() === name))
|
|
202
|
+
.find(Boolean);
|
|
203
|
+
const init = findLifecycleMethod('ngOnInit');
|
|
139
204
|
/** A lifecycle hook the class implements: a method of that name, taking nothing. */
|
|
140
205
|
const hook = (name) => {
|
|
141
|
-
const m =
|
|
206
|
+
const m = findLifecycleMethod(name);
|
|
142
207
|
if (m?.parameters.length)
|
|
143
208
|
throw new Error(`${path}: ${name} takes no parameters`);
|
|
144
209
|
return !!m;
|
|
@@ -172,6 +237,7 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
172
237
|
const sites = new Map();
|
|
173
238
|
const imported = new Map();
|
|
174
239
|
let usesRuntime = false;
|
|
240
|
+
let usesInject = false;
|
|
175
241
|
/** The class a pipe's name resolves to, imported into the component's file under a name of its own. */
|
|
176
242
|
const pipeClass = (name) => {
|
|
177
243
|
const decl = options.pipes?.get(name) ?? COMMON_PIPES[name];
|
|
@@ -199,7 +265,22 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
199
265
|
const { alias, decl } = pipeClass(p.name);
|
|
200
266
|
const k = sites.size;
|
|
201
267
|
const pipe = `$p${k}`;
|
|
202
|
-
|
|
268
|
+
let construct;
|
|
269
|
+
if (decl.deps?.length) {
|
|
270
|
+
usesInject = true;
|
|
271
|
+
const depArgs = decl.deps.map((dep) => {
|
|
272
|
+
const names = imported.get(dep.from) ?? new Map();
|
|
273
|
+
imported.set(dep.from, names);
|
|
274
|
+
if (!names.has(dep.name))
|
|
275
|
+
names.set(dep.name, `$PipeDep_${dep.name}`);
|
|
276
|
+
return `inject(${names.get(dep.name)})`;
|
|
277
|
+
});
|
|
278
|
+
construct = `new ${alias}(${depArgs.join(', ')})`;
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
construct = decl.create ? `${alias}.$create()` : `new ${alias}()`;
|
|
282
|
+
}
|
|
283
|
+
const make = expr(construct, inner);
|
|
203
284
|
inner = [...inner, { item: pipe, param: `${pipe}: ${alias}` }];
|
|
204
285
|
const destroy = decl.destroy ? handlerOf(`${pipe}.ngOnDestroy()`, inner) : undefined;
|
|
205
286
|
made.push({ name: pipe, make, ...(destroy ? { destroy } : {}) });
|
|
@@ -235,6 +316,7 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
235
316
|
};
|
|
236
317
|
const code = (value, _loops) => {
|
|
237
318
|
const root = value instanceof ng.ASTWithSource ? value.ast : value;
|
|
319
|
+
const rawSrc = value instanceof ng.ASTWithSource && typeof value.source === 'string' ? value.source : null;
|
|
238
320
|
// `text="How {{ x }}"`: Angular renders the literal text with each expression's value, undefined and null as ''.
|
|
239
321
|
const interpolation = root instanceof ng.Interpolation ? root : null;
|
|
240
322
|
if (!specialsIn(root).length && !interpolation)
|
|
@@ -246,7 +328,7 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
246
328
|
if (node instanceof ng.BindingPipe) {
|
|
247
329
|
const site = sites.get(node);
|
|
248
330
|
if (!site)
|
|
249
|
-
throw new Error(`${path}: the ${node.name} pipe where the release build gives it no view (in ${template.slice(node.sourceSpan.start, node.sourceSpan.end)})`);
|
|
331
|
+
throw new Error(`${path}: the ${node.name} pipe where the release build gives it no view (in ${rawSrc ? rawSrc.slice(node.span.start, node.span.end) : template.slice(node.sourceSpan.start, node.sourceSpan.end)})`);
|
|
250
332
|
const given = [node.exp, ...node.args].map(textOf);
|
|
251
333
|
if (!site.cache)
|
|
252
334
|
return `${site.pipe}.transform(${given.join(', ')})`;
|
|
@@ -255,15 +337,29 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
255
337
|
const xs = given.map((_, i) => `$x${i}`);
|
|
256
338
|
return `${site.cache}.pure${given.length}(${given.map((g) => `(${g})`).join(', ')}, (${xs.join(', ')}) => ${site.pipe}.transform(${xs.join(', ')}))`;
|
|
257
339
|
}
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
340
|
+
const spanOf = (n) => (rawSrc !== null ? n.span : n.sourceSpan);
|
|
341
|
+
const sp = spanOf(node);
|
|
342
|
+
const at = sp.start;
|
|
343
|
+
let out = (rawSrc ?? template).slice(at, sp.end);
|
|
344
|
+
for (const p of specialsIn(node).sort((a, b) => spanOf(b).start - spanOf(a).start)) {
|
|
345
|
+
const ps = spanOf(p);
|
|
346
|
+
out = out.slice(0, ps.start - at) + textOf(p) + out.slice(ps.end - at);
|
|
262
347
|
}
|
|
263
348
|
return out;
|
|
264
349
|
};
|
|
350
|
+
const neverNullish = (n) => {
|
|
351
|
+
if (n instanceof ng.LiteralPrimitive)
|
|
352
|
+
return n.value != null;
|
|
353
|
+
if (n instanceof ng.PrefixNot || n instanceof ng.Unary)
|
|
354
|
+
return true;
|
|
355
|
+
if (n instanceof ng.Binary)
|
|
356
|
+
return !['&&', '||', '??'].includes(n.operation);
|
|
357
|
+
if (n instanceof ng.Conditional)
|
|
358
|
+
return neverNullish(n.trueExp) && neverNullish(n.falseExp);
|
|
359
|
+
return false;
|
|
360
|
+
};
|
|
265
361
|
if (interpolation)
|
|
266
|
-
return '`' + interpolation.strings.map((s, i) => s.replace(/[`\\$]/g, (x) => '\\' + x) + (i < interpolation.expressions.length ? `\${(${textOf(interpolation.expressions[i])}) ?? ''}` : '')).join('') + '`';
|
|
362
|
+
return '`' + interpolation.strings.map((s, i) => s.replace(/[`\\$]/g, (x) => '\\' + x) + (i < interpolation.expressions.length ? (neverNullish(interpolation.expressions[i]) ? `\${(${textOf(interpolation.expressions[i])})}` : `\${(${textOf(interpolation.expressions[i])}) ?? ''}`) : '')).join('') + '`';
|
|
267
363
|
return textOf(root);
|
|
268
364
|
};
|
|
269
365
|
// `$any(x)` is Angular's escape from template type checking; the release build is typed by the component's code,
|
|
@@ -283,9 +379,12 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
283
379
|
if (here !== null)
|
|
284
380
|
located.set(methods.length - 1, here);
|
|
285
381
|
};
|
|
382
|
+
/** Pure narrowing guards from enclosing `@if` / `@else` branches so TypeScript narrows discriminated unions inside branch methods. */
|
|
383
|
+
let narrowing = [];
|
|
384
|
+
const guardPrefix = () => (narrowing.length ? `if (!(${narrowing.join(' && ')})) throw new Error(); ` : '');
|
|
286
385
|
const expr = (code, loops, untyped = false) => {
|
|
287
386
|
const m = `$b${next++}`;
|
|
288
|
-
add(` ${m}(${params(loops)})${untyped ? ': any' : ''} { return ${core.rewrite(clean(code), local(loops))}; }`);
|
|
387
|
+
add(` ${m}(${params(loops)})${untyped ? ': any' : ''} { ${guardPrefix()}return ${core.rewrite(clean(code), local(loops))}; }`);
|
|
289
388
|
return m;
|
|
290
389
|
};
|
|
291
390
|
/** A method of statements over the names in scope (a pipe's `ngOnDestroy`). */
|
|
@@ -299,9 +398,57 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
299
398
|
// A component's output gives its handler the emitted value as `$event`; a view's event gives the event data.
|
|
300
399
|
const handler = (code, loops, payload = false) => {
|
|
301
400
|
const m = `$e${next++}`;
|
|
302
|
-
add(` ${m}(${[params(loops), `$event: ${payload ? 'any' : '$EventData'}`].filter(Boolean).join(', ')}) { ${core.rewrite(clean(code), local(loops), 'statements')}; }`);
|
|
401
|
+
add(` ${m}(${[params(loops), `$event: ${payload ? 'any' : '$EventData'}`].filter(Boolean).join(', ')}) { ${guardPrefix()}${core.rewrite(clean(code), local(loops), 'statements')}; }`);
|
|
303
402
|
return m;
|
|
304
403
|
};
|
|
404
|
+
/** Enclosing projected component whose `contentChild`/`contentChildren` queries match nodes inside its slots. */
|
|
405
|
+
const activeContentHost = [];
|
|
406
|
+
const contentQueryHooks = (refs, component, tag, loops) => {
|
|
407
|
+
const host = activeContentHost.at(-1);
|
|
408
|
+
if (!host)
|
|
409
|
+
return [];
|
|
410
|
+
const hooks = [];
|
|
411
|
+
for (const q of host.queries) {
|
|
412
|
+
if (q.descendants === false && host.depth > 0)
|
|
413
|
+
continue;
|
|
414
|
+
if (q.ref ? !refs.includes(q.ref) : q.type !== component && q.type !== tag)
|
|
415
|
+
continue;
|
|
416
|
+
const instance = !!component && (q.read === null || q.read === component);
|
|
417
|
+
const wrapped = q.read === 'ElementRef' || (q.read === null && !component);
|
|
418
|
+
if (wrapped)
|
|
419
|
+
usesElementRef = true;
|
|
420
|
+
const own = instance ? component : !wrapped && q.read === tag ? tag : null;
|
|
421
|
+
const value = wrapped ? 'new $ElementRef($q)' : own || !q.read ? '$q' : `($q as ${q.read})`;
|
|
422
|
+
const inner = [...loops, { item: '$host', param: `$host: ${host.alias}` }, { item: '$q', param: `$q: ${own ?? 'any'}` }];
|
|
423
|
+
const set = q.many && !q.signal
|
|
424
|
+
? handlerOf(`$host.$cqSet_${q.field}($q, ${value})`, inner)
|
|
425
|
+
: handlerOf(`$host.$cqSet_${q.field}(${value})`, inner);
|
|
426
|
+
const unset = q.signal
|
|
427
|
+
? handlerOf(`$host.$cqUnset_${q.field}(${value})`, inner)
|
|
428
|
+
: q.many ? handlerOf(`$host.$cqUnset_${q.field}($q)`, inner) : undefined;
|
|
429
|
+
hooks.push({ set, ...(unset ? { unset } : {}), on: instance ? 'instance' : 'view', contentHost: true });
|
|
430
|
+
}
|
|
431
|
+
return hooks;
|
|
432
|
+
};
|
|
433
|
+
const directiveContentHooks = (d, loops) => {
|
|
434
|
+
const host = activeContentHost.at(-1);
|
|
435
|
+
if (!host)
|
|
436
|
+
return [];
|
|
437
|
+
const hooks = [];
|
|
438
|
+
for (const q of host.queries) {
|
|
439
|
+
if (q.descendants === false && host.depth > 0)
|
|
440
|
+
continue;
|
|
441
|
+
if (q.ref || q.type !== d.className)
|
|
442
|
+
continue;
|
|
443
|
+
const inner = [...loops, { item: '$host', param: `$host: ${host.alias}` }, { item: '$q', param: `$q: any` }];
|
|
444
|
+
const set = q.many && !q.signal
|
|
445
|
+
? handlerOf(`$host.$cqSet_${q.field}($q, $q)`, inner)
|
|
446
|
+
: handlerOf(`$host.$cqSet_${q.field}($q)`, inner);
|
|
447
|
+
const unset = q.signal || q.many ? handlerOf(`$host.$cqUnset_${q.field}($q)`, inner) : undefined;
|
|
448
|
+
hooks.push({ set, ...(unset ? { unset } : {}), on: 'instance', contentHost: true });
|
|
449
|
+
}
|
|
450
|
+
return hooks;
|
|
451
|
+
};
|
|
305
452
|
/**
|
|
306
453
|
* The view queries an element or a component's host matches (`#ref`, or the component's class), as the methods that
|
|
307
454
|
* set and clear each one's field: an ElementRef of the view, the component itself, or the view read as its class.
|
|
@@ -321,15 +468,23 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
321
468
|
const value = wrapped ? 'new $ElementRef($q)' : own || !q.read ? '$q' : `($q as ${q.read})`;
|
|
322
469
|
const inner = [...loops, { item: '$q', param: `$q: ${own ?? 'any'}` }];
|
|
323
470
|
// A single query keeps its match once the match's view goes, which Angular's next refresh would clear.
|
|
324
|
-
const set =
|
|
325
|
-
|
|
471
|
+
const set = q.signal
|
|
472
|
+
? handlerOf(q.many ? `this.${q.field}.update((xs) => [...xs, ${value}])` : `this.${q.field}.set(${value})`, inner)
|
|
473
|
+
: handlerOf(q.many ? `this.${q.field}.$add($q, ${value})` : `this.${q.field} = ${value}`, inner);
|
|
474
|
+
const unset = q.signal
|
|
475
|
+
? handlerOf(q.many ? `this.${q.field}.update((xs) => xs.filter((x) => x !== ${value}))` : `this.${q.field}.set(undefined as any)`, inner)
|
|
476
|
+
: q.many ? handlerOf(`this.${q.field}.$remove($q)`, inner) : undefined;
|
|
326
477
|
hooks.push({ set, ...(unset ? { unset } : {}), on: instance ? 'instance' : 'view' });
|
|
327
478
|
}
|
|
479
|
+
hooks.push(...contentQueryHooks(refs, component, tag, loops));
|
|
328
480
|
return hooks;
|
|
329
481
|
};
|
|
330
482
|
let usesElementRef = false;
|
|
483
|
+
let usesTemplateRef = false;
|
|
331
484
|
let usesUnset = false;
|
|
332
485
|
const queries = classic?.queries ?? [];
|
|
486
|
+
const contentQueries = classic?.contentQueries ?? [];
|
|
487
|
+
const slotNames = new Set();
|
|
333
488
|
/** The `#refs` of the template's own elements, outside any embedded view: what a static query can resolve. */
|
|
334
489
|
const staticRefs = new Set();
|
|
335
490
|
/** The static queries not yet resolved where the template walk is; ngOnInit waits for them. */
|
|
@@ -349,13 +504,15 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
349
504
|
}
|
|
350
505
|
};
|
|
351
506
|
const importsMeta = prop('imports');
|
|
352
|
-
expand(importsMeta && ts.isArrayLiteralExpression(importsMeta)
|
|
507
|
+
expand(importsMeta && ts.isArrayLiteralExpression(importsMeta)
|
|
508
|
+
? importsMeta.elements.flatMap((e) => ts.isIdentifier(e) ? [e.text] : ts.isSpreadElement(e) && ts.isIdentifier(e.expression) ? [e.expression.text] : [])
|
|
509
|
+
: []);
|
|
353
510
|
for (const [, names] of options.ngModules ?? [])
|
|
354
511
|
if (names.includes(cls.name.text))
|
|
355
512
|
expand(names);
|
|
356
513
|
const matcher = new ng.SelectorMatcher();
|
|
357
514
|
for (const d of options.directives ?? [])
|
|
358
|
-
if (inScope.has(d.className))
|
|
515
|
+
if (d.selector && inScope.has(d.className))
|
|
359
516
|
matcher.addSelectables(ng.CssSelector.parse(d.selector), d);
|
|
360
517
|
/** The directives an element matches: its name, attributes, bound inputs and outputs, as Angular matches them. */
|
|
361
518
|
const matched = (name, attributes, bound) => {
|
|
@@ -403,21 +560,28 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
403
560
|
* element's bindings and attributes of their names (the bindings then are the directive's, not the view's), its
|
|
404
561
|
* host listeners and bindings on the element, and its hooks.
|
|
405
562
|
*/
|
|
406
|
-
const directiveUse = (d, n, loops, consumed) => {
|
|
563
|
+
const directiveUse = (d, n, loops, consumed, consumedOutputs, dirRefs, dirScopes) => {
|
|
407
564
|
const names = imported.get(d.file) ?? new Map();
|
|
408
565
|
imported.set(d.file, names);
|
|
409
566
|
if (!names.has(d.className))
|
|
410
567
|
names.set(d.className, `$Dir_${d.className}`);
|
|
411
568
|
const alias = names.get(d.className);
|
|
569
|
+
const typeArgs = d.typeParams ? `<${Array(d.typeParams).fill('any').join(', ')}>` : '';
|
|
412
570
|
const name = `$d${directiveCount++}`;
|
|
571
|
+
const namedRefs = n.references.filter((r) => !!r.value && !!d.exportAs?.includes(r.value));
|
|
572
|
+
for (const r of namedRefs)
|
|
573
|
+
dirRefs?.add(r.name);
|
|
413
574
|
const make = expr(d.create ? `${alias}.$create()` : `new ${alias}()`, loops);
|
|
414
|
-
const
|
|
575
|
+
const loopEntry = { item: name, param: `${name}: ${alias}${typeArgs}`, ...(namedRefs.length ? { names: Object.fromEntries(namedRefs.map((r) => [r.name, name])) } : {}) };
|
|
576
|
+
if (namedRefs.length)
|
|
577
|
+
dirScopes?.push(loopEntry);
|
|
578
|
+
const inner = [...loops, loopEntry];
|
|
415
579
|
const valued = [...inner, { item: '$v', param: '$v: any' }];
|
|
416
580
|
const own = { names: new Map(d.members.map((m) => [m, `${name}.${m}`])) };
|
|
417
|
-
const setter = (input, member) => handlerOf(`${name}.${member}${d.signals.has(member) ? '.$assign($v)' : ' = $v'}${d.hooks.has('ngOnChanges') ? `; ${name}.$change(${JSON.stringify(member)}, $v)` : ''}`, valued);
|
|
581
|
+
const setter = (input, member) => handlerOf(`${d.transforms?.has(member) ? `${name}.$set_${member}($v)` : `${name}.${member}${d.signals.has(member) ? '.$assign($v)' : ' = $v'}`}${d.hooks.has('ngOnChanges') ? `; ${name}.$change(${JSON.stringify(member)}, $v)` : ''}`, valued);
|
|
418
582
|
const inputs = [];
|
|
419
583
|
for (const [input, member] of d.inputs) {
|
|
420
|
-
const b = n.inputs.find((i) => i.name === input && i.type === ng.BindingType.Property);
|
|
584
|
+
const b = n.inputs.find((i) => i.name === input && (i.type === ng.BindingType.Property || i.type === ng.BindingType.TwoWay));
|
|
421
585
|
const a = n.attributes.find((x) => x.name === input);
|
|
422
586
|
if (b) {
|
|
423
587
|
at(b.sourceSpan);
|
|
@@ -427,6 +591,16 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
427
591
|
else if (a)
|
|
428
592
|
inputs.push({ set: setter(input, member), value: a.value });
|
|
429
593
|
}
|
|
594
|
+
const dirOutputs = [];
|
|
595
|
+
for (const [outName, member] of d.outputs ?? []) {
|
|
596
|
+
for (const o of n.outputs.filter((x) => x.name === outName)) {
|
|
597
|
+
at(o.sourceSpan);
|
|
598
|
+
consumedOutputs?.add(o);
|
|
599
|
+
const target = code(o.handler, loops);
|
|
600
|
+
const stmt = o.type !== ng.ParsedEventType.TwoWay ? target : /^[A-Za-z_$][\w$]*$/.test(target) && signalMember(target) ? `${target}.set($event)` : `${target} = $event`;
|
|
601
|
+
dirOutputs.push({ name: member, method: handler(stmt, inner, true) });
|
|
602
|
+
}
|
|
603
|
+
}
|
|
430
604
|
const listeners = d.listeners.map((l) => ({ event: l.event, method: handlerOf(core.rewrite(l.code, { names: new Map([...own.names, ['$event', '$event']]) }, 'statements'), [...inner, { item: '$event', param: '$event: any' }]) }));
|
|
431
605
|
const bindings = d.bindings.map((b) => ({ prop: b.prop, method: expr(core.rewrite(b.code, own), inner, true) }));
|
|
432
606
|
const hook = (h) => (d.hooks.has(h) ? handlerOf(`${name}.${h}()`, inner) : undefined);
|
|
@@ -435,7 +609,25 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
435
609
|
const m = hook(h);
|
|
436
610
|
return m ? [[field, m]] : [];
|
|
437
611
|
}));
|
|
438
|
-
|
|
612
|
+
const dirQueries = directiveContentHooks(d, loops);
|
|
613
|
+
const hasCompanions = !!(d.styleBindings?.length || d.classBindings?.length);
|
|
614
|
+
const uses = [{ name, make, inputs, listeners, bindings, ...hooks, ...(d.hooks.has('ngOnChanges') ? { changes: true } : {}), ...(dirOutputs.length ? { outputs: dirOutputs } : {}), ...(namedRefs.length || hasCompanions ? { exposed: true } : {}), ...(dirQueries.length ? { queries: dirQueries } : {}), attributes: d.attributes }];
|
|
615
|
+
if (d.styleBindings?.length) {
|
|
616
|
+
const sAlias = fromRuntime('NgStyle');
|
|
617
|
+
usesUnset = true;
|
|
618
|
+
const sName = `$d${directiveCount++}`;
|
|
619
|
+
const sInner = [...inner, { item: sName, param: `${sName}: ${sAlias}` }];
|
|
620
|
+
const pairs = d.styleBindings.map((b) => `${JSON.stringify(b.prop)}: (${core.rewrite(b.code, own)})`).join(', ');
|
|
621
|
+
uses.push({ name: sName, make: expr(`new ${sAlias}($unsetValue)`, inner), inputs: [{ set: handlerOf(`${sName}.apply($v)`, [...sInner, { item: '$v', param: '$v: any' }]), method: expr(`[{ ${pairs} }] as any[]`, inner, true) }], listeners: [], bindings: [], attributes: [] });
|
|
622
|
+
}
|
|
623
|
+
if (d.classBindings?.length) {
|
|
624
|
+
const cAlias = fromRuntime('NgClass');
|
|
625
|
+
const cName = `$d${directiveCount++}`;
|
|
626
|
+
const cInner = [...inner, { item: cName, param: `${cName}: ${cAlias}` }];
|
|
627
|
+
const pairs = d.classBindings.flatMap((b) => [JSON.stringify(b.name), `(${core.rewrite(b.code, own)})`]).join(', ');
|
|
628
|
+
uses.push({ name: cName, make: expr(`new ${cAlias}()`, inner), inputs: [{ set: handlerOf(`${cName}.apply($v)`, [...cInner, { item: '$v', param: '$v: any' }]), method: expr(`["", null, [${pairs}]] as any[]`, inner, true) }], listeners: [], bindings: [], attributes: [] });
|
|
629
|
+
}
|
|
630
|
+
return uses;
|
|
439
631
|
};
|
|
440
632
|
/** A function or class of the build's Angular runtime module, imported into the component's file under a name of its own. */
|
|
441
633
|
const fromRuntime = (name) => {
|
|
@@ -454,10 +646,19 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
454
646
|
*/
|
|
455
647
|
const classAttr = (n, attrs, loops, ngClass, shared = false) => {
|
|
456
648
|
const toggles = n.inputs.filter((i) => i.type === ng.BindingType.Class);
|
|
457
|
-
|
|
649
|
+
const boundClass = n.inputs.find((i) => i.name === 'class' && i.type === ng.BindingType.Property);
|
|
650
|
+
const fixedIdx = attrs.findIndex((a) => a.name === 'class');
|
|
651
|
+
// Static `class="a b"` beside `[class]="expr"` (without `[ngClass]`): merge both as Angular does, rather than letting `[class]` wipe static classes.
|
|
652
|
+
if (!toggles.length && !ngClass) {
|
|
653
|
+
if (boundClass && fixedIdx >= 0) {
|
|
654
|
+
at(boundClass.sourceSpan);
|
|
655
|
+
const base = attrs.splice(fixedIdx, 1)[0].value ?? '';
|
|
656
|
+
attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, (${code(boundClass.value, loops)}), [])`, loops) });
|
|
657
|
+
}
|
|
458
658
|
return null;
|
|
659
|
+
}
|
|
459
660
|
at((ngClass ?? toggles[0]).sourceSpan);
|
|
460
|
-
const fixed =
|
|
661
|
+
const fixed = fixedIdx;
|
|
461
662
|
const base = fixed >= 0 ? attrs.splice(fixed, 1)[0].value ?? '' : '';
|
|
462
663
|
const pairs = toggles.flatMap((t) => [JSON.stringify(t.name), `(${code(t.value, loops)})`]);
|
|
463
664
|
// Beside the forms runtime's ng-* classes the toggles go through NgClass, which keeps the classes they share.
|
|
@@ -812,6 +1013,10 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
812
1013
|
out.push(...container(n, loops));
|
|
813
1014
|
continue;
|
|
814
1015
|
}
|
|
1016
|
+
if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && n.name.startsWith(':svg:')) {
|
|
1017
|
+
out.push({ kind: 'element', tag: 'ContentView', attrs: [], events: [], children: [] });
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
815
1020
|
if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && stubbedElement(n.name)) {
|
|
816
1021
|
at(n.startSourceSpan);
|
|
817
1022
|
const attrs = [];
|
|
@@ -861,7 +1066,7 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
861
1066
|
throw unsupported(`${hosted.name}'s own ElementRef or host bindings`);
|
|
862
1067
|
if (isList)
|
|
863
1068
|
throw unsupported('item templates');
|
|
864
|
-
if (n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()))
|
|
1069
|
+
if (!hosted.slots?.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()))
|
|
865
1070
|
throw unsupported('content');
|
|
866
1071
|
for (const i of n.inputs)
|
|
867
1072
|
if (hosted.inputs.has(i.name) && i.type === ng.BindingType.TwoWay)
|
|
@@ -889,29 +1094,37 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
889
1094
|
if (hosted?.inputs.has(a.name))
|
|
890
1095
|
hostProps.push({ name: a.name, value: a.value });
|
|
891
1096
|
}
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1097
|
+
const targetComponent = selectors.get(n.name);
|
|
1098
|
+
const targetSlots = targetComponent ? options.componentSlots?.get(targetComponent) : hosted?.slots;
|
|
1099
|
+
const projectsContent = !!(targetSlots?.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()));
|
|
1100
|
+
if (!projectsContent) {
|
|
1101
|
+
for (const c of n.children) {
|
|
1102
|
+
if (c instanceof ng.TmplAstText && c.value.trim())
|
|
1103
|
+
attrs.push({ name: 'text', value: c.value });
|
|
1104
|
+
if (c instanceof ng.TmplAstBoundText) {
|
|
1105
|
+
at(c.sourceSpan);
|
|
1106
|
+
attrs.push({ name: 'text', method: expr(code(c.value, scoped), scoped) });
|
|
1107
|
+
}
|
|
898
1108
|
}
|
|
899
1109
|
}
|
|
900
1110
|
// The static classes, `[class.on]="cond"` toggles and NgClass: one bound `class` naming them all.
|
|
901
1111
|
const ngClass = appOwns('ngClass') ? undefined : n.inputs.find((i) => i.name === 'ngClass' && i.type === ng.BindingType.Property) ?? n.attributes.find((a) => a.name === 'ngClass');
|
|
1112
|
+
const mergedBoundClass = !ngClass && !n.inputs.some((i) => i.type === ng.BindingType.Class) && attrs.some((a) => a.name === 'class') ? n.inputs.find((i) => i.name === 'class' && i.type === ng.BindingType.Property) : undefined;
|
|
902
1113
|
const ngClassUse = classAttr(n, attrs, loops, ngClass, !!forms?.status);
|
|
903
1114
|
const ngStyle = appOwns('ngStyle') || selectors.has(n.name) ? undefined : n.inputs.find((i) => i.name === 'ngStyle' && i.type === ng.BindingType.Property);
|
|
904
1115
|
// NgSwitch on any element: the cases below it, in its subtree, compare with its value.
|
|
905
1116
|
const switched = n.inputs.find((i) => i.name === 'ngSwitch');
|
|
906
|
-
if (found.length && selectors.has(n.name))
|
|
907
|
-
throw new Error(`${path}: the directive ${found[0].className} on the component <${n.name}> is not supported in a release build yet`);
|
|
908
1117
|
const consumed = new Set();
|
|
909
|
-
const
|
|
1118
|
+
const consumedDirOutputs = new Set();
|
|
1119
|
+
const dirRefs = new Set();
|
|
1120
|
+
const dirScopes = [];
|
|
1121
|
+
const directives = found.flatMap((d) => {
|
|
910
1122
|
if (d.structural)
|
|
911
1123
|
throw new Error(`${path}: the structural directive ${d.className} without its template (*) is not supported in a release build yet`);
|
|
912
|
-
return directiveUse(d, n, loops, consumed);
|
|
1124
|
+
return directiveUse(d, n, loops, consumed, consumedDirOutputs, dirRefs, dirScopes);
|
|
913
1125
|
});
|
|
914
|
-
|
|
1126
|
+
const allScoped = dirScopes.length ? [...scoped, ...dirScopes] : scoped;
|
|
1127
|
+
refuseUnbound(n, (name) => found.some((d) => d.inputs.has(name) || !!d.outputs?.has(name)) || !!hosted?.inputs.has(name) || !!hosted?.outputs.has(name) || (name === 'ngClass' && !!ngClass) || (name === 'ngStyle' && !!ngStyle)
|
|
915
1128
|
|| !!forms?.consumedInputs.has(name) || [...(forms?.consumedOutputs ?? [])].some((o) => o.name === name));
|
|
916
1129
|
if (ngClassUse)
|
|
917
1130
|
directives.push(ngClassUse);
|
|
@@ -922,23 +1135,23 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
922
1135
|
if (forms)
|
|
923
1136
|
directives.push(...forms.uses);
|
|
924
1137
|
if (!selectors.has(n.name) && !hosted) {
|
|
925
|
-
const ref = n.references.find((r) => r.value && !forms?.refs.has(r.name));
|
|
1138
|
+
const ref = n.references.find((r) => r.value && !forms?.refs.has(r.name) && !dirRefs.has(r.name));
|
|
926
1139
|
if (ref)
|
|
927
1140
|
throw new Error(`${path}: #${ref.name}="${ref.value}" on <${n.name}>, a reference to a directive's exportAs, is not supported in a release build yet`);
|
|
928
1141
|
}
|
|
929
1142
|
for (const i of n.inputs) {
|
|
930
|
-
if (i === switched || i === ngClass || i === ngStyle || consumed.has(i.name) || forms?.consumedInputs.has(i.name) || i.type === ng.BindingType.Class || (isList && i.name === 'itemTemplateSelector') || (link && ROUTER_LINK_INPUTS.has(i.name)))
|
|
1143
|
+
if (i === switched || i === ngClass || i === ngStyle || i === mergedBoundClass || consumed.has(i.name) || forms?.consumedInputs.has(i.name) || i.type === ng.BindingType.Class || (isList && i.name === 'itemTemplateSelector') || (link && ROUTER_LINK_INPUTS.has(i.name)))
|
|
931
1144
|
continue;
|
|
932
1145
|
at(i.sourceSpan);
|
|
933
1146
|
if (hosted?.inputs.has(i.name) && i.type === ng.BindingType.Property) {
|
|
934
|
-
hostProps.push({ name: i.name, method: expr(code(i.value,
|
|
1147
|
+
hostProps.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped) });
|
|
935
1148
|
continue;
|
|
936
1149
|
}
|
|
937
1150
|
if (i.type === ng.BindingType.Style && i.name !== 'style' && !selectors.has(n.name))
|
|
938
1151
|
continue;
|
|
939
1152
|
// `[attr.name]`: the renderer's setAttribute, which on a NativeScript view sets the property of that name.
|
|
940
|
-
if (i.type === ng.BindingType.Attribute
|
|
941
|
-
attrs.push({ name: i.name, method: expr(code(i.value,
|
|
1153
|
+
if (i.type === ng.BindingType.Attribute) {
|
|
1154
|
+
attrs.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped, true) });
|
|
942
1155
|
continue;
|
|
943
1156
|
}
|
|
944
1157
|
if (i.type !== ng.BindingType.Property && i.type !== ng.BindingType.TwoWay)
|
|
@@ -946,37 +1159,126 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
946
1159
|
// `[text]="person()?.name"`: the view takes undefined where the chain stops, as the renderer passes it, whatever the type says.
|
|
947
1160
|
const root = i.value instanceof ng.ASTWithSource ? i.value.ast : i.value;
|
|
948
1161
|
const chained = i.type === ng.BindingType.Property && !selectors.has(n.name) && (root instanceof ng.SafePropertyRead || root instanceof ng.SafeKeyedRead || root instanceof ng.SafeCall);
|
|
949
|
-
attrs.push({ name: i.name, method: expr(code(i.value,
|
|
1162
|
+
attrs.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped, chained) });
|
|
950
1163
|
}
|
|
951
1164
|
for (const o of n.outputs) {
|
|
952
|
-
if (forms?.consumedOutputs.has(o))
|
|
1165
|
+
if (forms?.consumedOutputs.has(o) || consumedDirOutputs.has(o))
|
|
953
1166
|
continue;
|
|
954
1167
|
at(o.sourceSpan);
|
|
955
1168
|
if (hosted?.outputs.has(o.name)) {
|
|
956
|
-
hostEvents.push({ name: o.name, method: handler(code(o.handler,
|
|
1169
|
+
hostEvents.push({ name: o.name, method: handler(code(o.handler, allScoped), allScoped, true), payload: true });
|
|
957
1170
|
continue;
|
|
958
1171
|
}
|
|
959
|
-
events.push({ name: o.name, method: handler(code(o.handler,
|
|
1172
|
+
events.push({ name: o.name, method: handler(code(o.handler, allScoped), allScoped, selectors.has(n.name) || !core.canonical(n.name) || registered.has(n.name.toLowerCase())), ...(selectors.has(n.name) ? { payload: true } : {}) });
|
|
960
1173
|
}
|
|
1174
|
+
const projectChildren = (compName, declared) => {
|
|
1175
|
+
const meaningful = n.children.filter((c) => !(c instanceof ng.TmplAstText) || c.value.trim());
|
|
1176
|
+
if (!meaningful.length)
|
|
1177
|
+
return undefined;
|
|
1178
|
+
const slotMatcher = new ng.SelectorMatcher();
|
|
1179
|
+
for (const sel of declared ?? []) {
|
|
1180
|
+
if (sel === 'default')
|
|
1181
|
+
continue;
|
|
1182
|
+
try {
|
|
1183
|
+
slotMatcher.addSelectables(ng.CssSelector.parse(sel), sel);
|
|
1184
|
+
}
|
|
1185
|
+
catch { }
|
|
1186
|
+
}
|
|
1187
|
+
const buckets = new Map();
|
|
1188
|
+
const push = (slot, child) => {
|
|
1189
|
+
const list = buckets.get(slot) ?? [];
|
|
1190
|
+
list.push(child);
|
|
1191
|
+
buckets.set(slot, list);
|
|
1192
|
+
};
|
|
1193
|
+
for (const ch of meaningful) {
|
|
1194
|
+
let slot = 'default';
|
|
1195
|
+
if (ch instanceof ng.TmplAstElement) {
|
|
1196
|
+
const projectAs = ch.attributes.find((a) => a.name === 'ngProjectAs')?.value;
|
|
1197
|
+
const cssList = projectAs ? ng.CssSelector.parse(projectAs) : [(() => {
|
|
1198
|
+
const css = new ng.CssSelector();
|
|
1199
|
+
css.setElement(ch.name);
|
|
1200
|
+
for (const a of ch.attributes) {
|
|
1201
|
+
css.addAttribute(a.name, a.value);
|
|
1202
|
+
if (a.name === 'class')
|
|
1203
|
+
for (const c of a.value.split(/\s+/).filter(Boolean))
|
|
1204
|
+
css.addClassName(c);
|
|
1205
|
+
}
|
|
1206
|
+
for (const b of [...ch.inputs.map((i) => i.name), ...ch.outputs.map((o) => o.name)])
|
|
1207
|
+
css.addAttribute(b, '');
|
|
1208
|
+
return css;
|
|
1209
|
+
})()];
|
|
1210
|
+
for (const css of cssList) {
|
|
1211
|
+
slotMatcher.match(css, (_s, matchedSlot) => { if (slot === 'default')
|
|
1212
|
+
slot = matchedSlot; });
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
push(slot, ch);
|
|
1216
|
+
}
|
|
1217
|
+
const cqInfo = options.componentContentQueries?.get(compName);
|
|
1218
|
+
let pushedHost = false;
|
|
1219
|
+
if (cqInfo?.queries.length) {
|
|
1220
|
+
let alias = compName;
|
|
1221
|
+
if (compName !== cls.name.text && cqInfo.file !== path) {
|
|
1222
|
+
const releaseFile = cqInfo.file.replace(/\.ts$/, '.release.ts');
|
|
1223
|
+
const names = imported.get(releaseFile) ?? new Map();
|
|
1224
|
+
imported.set(releaseFile, names);
|
|
1225
|
+
if (!names.has(compName))
|
|
1226
|
+
names.set(compName, `$Comp_${compName}`);
|
|
1227
|
+
alias = names.get(compName);
|
|
1228
|
+
}
|
|
1229
|
+
activeContentHost.push({ name: compName, alias, queries: cqInfo.queries, depth: 0 });
|
|
1230
|
+
pushedHost = true;
|
|
1231
|
+
}
|
|
1232
|
+
const slotsOut = {};
|
|
1233
|
+
try {
|
|
1234
|
+
for (const [slotName, asts] of buckets) {
|
|
1235
|
+
const built = [];
|
|
1236
|
+
for (const ch of asts) {
|
|
1237
|
+
if (ch instanceof ng.TmplAstText && ch.value.trim()) {
|
|
1238
|
+
built.push({ kind: 'element', tag: 'Label', attrs: [{ name: 'text', value: ch.value.trim() }], events: [], children: [] });
|
|
1239
|
+
}
|
|
1240
|
+
else if (ch instanceof ng.TmplAstBoundText) {
|
|
1241
|
+
at(ch.sourceSpan);
|
|
1242
|
+
built.push({ kind: 'element', tag: 'Label', attrs: [{ name: 'text', method: expr(code(ch.value, scoped), scoped) }], events: [], children: [] });
|
|
1243
|
+
}
|
|
1244
|
+
else {
|
|
1245
|
+
built.push(...nodes([ch], scoped));
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
if (built.length)
|
|
1249
|
+
slotsOut[slotName] = built;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
finally {
|
|
1253
|
+
if (pushedHost)
|
|
1254
|
+
activeContentHost.pop();
|
|
1255
|
+
}
|
|
1256
|
+
return Object.keys(slotsOut).length ? slotsOut : undefined;
|
|
1257
|
+
};
|
|
961
1258
|
const component = selectors.get(n.name);
|
|
962
1259
|
const refs = n.references.map((r) => r.name);
|
|
963
1260
|
if (component) {
|
|
964
1261
|
const hooks = queryHooks(refs, component, null, loops);
|
|
965
|
-
|
|
1262
|
+
const projected = projectChildren(component, options.componentSlots?.get(component));
|
|
1263
|
+
out.push({ kind: 'component', name: component, props: attrs, events, ...(hooks.length ? { queries: hooks } : {}), ...(projected ? { slots: projected } : {}), ...(directives.length ? { directives } : {}) });
|
|
966
1264
|
continue;
|
|
967
1265
|
}
|
|
968
|
-
if (n.name === 'page-router-outlet') {
|
|
969
|
-
// The outlet's Frame takes its name, and the static attributes @nativescript/angular sets on that Frame.
|
|
970
|
-
const
|
|
1266
|
+
if (n.name === 'page-router-outlet' || n.name === 'router-outlet') {
|
|
1267
|
+
// The outlet's Frame takes its name, and the static View/Frame attributes @nativescript/angular sets on that Frame.
|
|
1268
|
+
const FRAME_STATIC_ATTRS = new Set(['actionBarVisibility', 'class', 'id', 'style', 'row', 'col', 'rowSpan', 'colSpan', 'dock', 'visibility', 'automationText', 'testID', 'width', 'height', 'backgroundColor']);
|
|
1269
|
+
const passed = (a) => FRAME_STATIC_ATTRS.has(a.name);
|
|
971
1270
|
const other = [...n.inputs.map((i) => `[${i.name}]`), ...n.outputs.map((o) => `(${o.name})`), ...n.references.map((r) => `#${r.name}`), ...n.attributes.filter((a) => a.name !== 'name' && !passed(a)).map((a) => `${a.name}="${a.value}"`)];
|
|
972
1271
|
if (other.length)
|
|
973
|
-
throw new Error(`${path}: ${other[0]} on
|
|
974
|
-
// `actionBarVisibility="auto"` is the Frame's default.
|
|
1272
|
+
throw new Error(`${path}: ${other[0]} on <${n.name}> is not supported in a release build yet`);
|
|
1273
|
+
// `actionBarVisibility="auto"` is the Frame's default; `<router-outlet>` is an embedded nested outlet without an ActionBar unless specified.
|
|
975
1274
|
const frameAttrs = n.attributes.filter((a) => passed(a) && !(a.name === 'actionBarVisibility' && a.value === 'auto')).map((a) => ({ name: a.name, value: a.value }));
|
|
1275
|
+
if (n.name === 'router-outlet' && !n.attributes.some((a) => a.name === 'actionBarVisibility'))
|
|
1276
|
+
frameAttrs.push({ name: 'actionBarVisibility', value: 'never' });
|
|
976
1277
|
out.push({ kind: 'element', tag: 'Frame', attrs: [{ name: 'router', value: n.attributes.find((a) => a.name === 'name')?.value ?? 'primary' }, ...frameAttrs], events: [], children: [] });
|
|
977
1278
|
continue;
|
|
978
1279
|
}
|
|
979
|
-
|
|
1280
|
+
// An unregistered custom element matched by an in-scope @Directive (e.g. `<hlm-input-group>`) renders as a container host.
|
|
1281
|
+
const tag = elementOf(n.name) ?? (found.length ? (elementOf('div') ?? 'ContentView') : undefined);
|
|
980
1282
|
if (!tag)
|
|
981
1283
|
throw new Error(`${path}: <${n.name}> is not a @nativescript/core element the release build knows`);
|
|
982
1284
|
checkMeta(n);
|
|
@@ -984,8 +1286,31 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
984
1286
|
// A reference on a host names its component; ElementRef and the view's class read the element.
|
|
985
1287
|
const matches = queryHooks(refs.filter((r) => !forms?.refs.has(r)), hosted?.name ?? null, tag, loops);
|
|
986
1288
|
const hooks = matches.filter((h) => h.on !== 'instance');
|
|
1289
|
+
for (const r of n.references) {
|
|
1290
|
+
if (r.value || forms?.refs.has(r.name) || dirRefs.has(r.name) || !elementRefFields.has(r.name))
|
|
1291
|
+
continue;
|
|
1292
|
+
const field = elementRefFields.get(r.name);
|
|
1293
|
+
hooks.push({ set: handlerOf(`this.${field} = $q`, [...loops, { item: '$q', param: '$q: any' }]), on: 'view' });
|
|
1294
|
+
}
|
|
987
1295
|
const own = matches.filter((h) => h.on === 'instance');
|
|
988
|
-
const below = () =>
|
|
1296
|
+
const below = () => {
|
|
1297
|
+
if (isList)
|
|
1298
|
+
return listTemplates(n, attrs, scoped);
|
|
1299
|
+
if (hosted) {
|
|
1300
|
+
const hostedProjected = hosted.slots?.length ? projectChildren(hosted.name, hosted.slots) : undefined;
|
|
1301
|
+
return [{ kind: 'component', name: hosted.name, props: hostProps, events: hostEvents, ...(own.length ? { queries: own } : {}), ...(hostedProjected ? { slots: hostedProjected } : {}) }];
|
|
1302
|
+
}
|
|
1303
|
+
const ch = activeContentHost.at(-1);
|
|
1304
|
+
if (ch)
|
|
1305
|
+
ch.depth++;
|
|
1306
|
+
try {
|
|
1307
|
+
return nodes(n.children, scoped);
|
|
1308
|
+
}
|
|
1309
|
+
finally {
|
|
1310
|
+
if (ch)
|
|
1311
|
+
ch.depth--;
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
989
1314
|
// A form or group directive is the ControlContainer of the forms directives below it.
|
|
990
1315
|
const children = () => {
|
|
991
1316
|
if (forms?.container)
|
|
@@ -1014,18 +1339,32 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1014
1339
|
continue;
|
|
1015
1340
|
}
|
|
1016
1341
|
if (n instanceof ng.TmplAstIfBlock) {
|
|
1342
|
+
const prevGuards = [];
|
|
1017
1343
|
out.push({ kind: 'if', branches: n.branches.map((b) => {
|
|
1018
1344
|
at(b.startSourceSpan);
|
|
1019
|
-
// `@if (x; as y)`: y is the condition's value in the branch.
|
|
1345
|
+
// `@if (x; as y)`: y is the condition's value in the branch (non-null because the branch only runs when truthy).
|
|
1020
1346
|
const alias = b.expressionAlias;
|
|
1021
1347
|
// The condition is read before its alias exists: `@if (person(); as person)` names the value of the `person` it reads.
|
|
1022
|
-
const
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
const
|
|
1026
|
-
if (alias)
|
|
1027
|
-
aliases.
|
|
1028
|
-
|
|
1348
|
+
const rawCond = b.expression ? code(b.expression, loops) : null;
|
|
1349
|
+
const cond = rawCond !== null ? test(rawCond, loops) : null;
|
|
1350
|
+
const rewrittenCond = rawCond !== null ? core.rewrite(clean(rawCond), local(loops)) : null;
|
|
1351
|
+
const pureGuard = rewrittenCond !== null && !/[=]|[\w$]\s*\(/.test(rewrittenCond.replace(/[!=]==?/g, '')) && /(?:===|!==|==|!=|\btypeof\b|\binstanceof\b|\bin\b)/.test(rewrittenCond) ? rewrittenCond : null;
|
|
1352
|
+
if (alias && rewrittenCond !== null)
|
|
1353
|
+
aliases.set(alias.name, `(${rewrittenCond})!`);
|
|
1354
|
+
const savedNarrowing = narrowing;
|
|
1355
|
+
narrowing = [...savedNarrowing, ...prevGuards.map((g) => `!(${g})`), ...(pureGuard ? [pureGuard] : [])];
|
|
1356
|
+
let body;
|
|
1357
|
+
try {
|
|
1358
|
+
body = nodes(b.children, loops);
|
|
1359
|
+
}
|
|
1360
|
+
finally {
|
|
1361
|
+
narrowing = savedNarrowing;
|
|
1362
|
+
if (alias)
|
|
1363
|
+
aliases.delete(alias.name);
|
|
1364
|
+
}
|
|
1365
|
+
if (pureGuard)
|
|
1366
|
+
prevGuards.push(pureGuard);
|
|
1367
|
+
return { cond, body };
|
|
1029
1368
|
}) });
|
|
1030
1369
|
continue;
|
|
1031
1370
|
}
|
|
@@ -1068,6 +1407,14 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1068
1407
|
out.push({ kind: 'if', branches: [...branches.filter((b) => b.cond), ...branches.filter((b) => !b.cond)] });
|
|
1069
1408
|
continue;
|
|
1070
1409
|
}
|
|
1410
|
+
if (n instanceof ng.TmplAstContent) {
|
|
1411
|
+
at(n.sourceSpan);
|
|
1412
|
+
const name = !n.selector || n.selector === '*' ? 'default' : n.selector;
|
|
1413
|
+
slotNames.add(name);
|
|
1414
|
+
const fallback = n.children?.length ? nodes(n.children, loops) : [];
|
|
1415
|
+
out.push({ kind: 'slot', name, ...(fallback.length ? { fallback } : {}) });
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1071
1418
|
// Text in an element is its `text` (@nativescript/angular's renderer sets it on the parent): a template's text nodes bind there.
|
|
1072
1419
|
if (n instanceof ng.TmplAstText || n instanceof ng.TmplAstBoundText)
|
|
1073
1420
|
continue;
|
|
@@ -1214,21 +1561,31 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1214
1561
|
throw new Error(`${path}: (${n.outputs[0].name}) on <ng-container> is not supported in a release build yet`);
|
|
1215
1562
|
if (n.references.length)
|
|
1216
1563
|
throw new Error(`${path}: #${n.references[0].name} on <ng-container> is not supported in a release build yet`);
|
|
1217
|
-
refuseUnbound(n, (name) => ['ngTemplateOutlet', 'ngTemplateOutletContext'].includes(name));
|
|
1564
|
+
refuseUnbound(n, (name) => ['ngTemplateOutlet', 'ngTemplateOutletContext', 'ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(name));
|
|
1218
1565
|
const selected = matched('ng-container', n.attributes.map((a) => [a.name, a.value]), n.inputs.map((i) => i.name));
|
|
1219
1566
|
if (selected.length)
|
|
1220
1567
|
throw new Error(`${path}: the directive ${selected[0].className} on <ng-container> is not supported in a release build yet`);
|
|
1221
1568
|
const bound = new Map(n.inputs.map((i) => [i.name, i]));
|
|
1222
1569
|
for (const name of bound.keys()) {
|
|
1223
|
-
if (!['ngSwitch', 'ngTemplateOutlet', 'ngTemplateOutletContext'].includes(name))
|
|
1570
|
+
if (!['ngSwitch', 'ngTemplateOutlet', 'ngTemplateOutletContext', 'ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(name))
|
|
1224
1571
|
throw new Error(`${path}: [${name}] on <ng-container> is not supported in a release build yet`);
|
|
1225
1572
|
}
|
|
1226
1573
|
if (bound.has('ngTemplateOutletContext') && !bound.has('ngTemplateOutlet'))
|
|
1227
1574
|
throw new Error(`${path}: [ngTemplateOutletContext] without [ngTemplateOutlet]`);
|
|
1575
|
+
if ((bound.has('ngComponentOutletInjector') || bound.has('ngComponentOutletInputs')) && !bound.has('ngComponentOutlet'))
|
|
1576
|
+
throw new Error(`${path}: [ngComponentOutletInjector]/[ngComponentOutletInputs] without [ngComponentOutlet]`);
|
|
1228
1577
|
const children = () => nodes(n.children, loops);
|
|
1229
1578
|
const own = bound.has('ngSwitch') ? switching(n, bound.get('ngSwitch').value, loops, children) : children();
|
|
1230
1579
|
const outletted = bound.has('ngTemplateOutlet') ? outlet(bound.get('ngTemplateOutlet').value, bound.get('ngTemplateOutletContext')?.value, loops) : [];
|
|
1231
|
-
|
|
1580
|
+
const compOutletted = bound.has('ngComponentOutlet')
|
|
1581
|
+
? [{
|
|
1582
|
+
kind: 'componentOutlet',
|
|
1583
|
+
component: expr(code(bound.get('ngComponentOutlet').value, loops), loops, true),
|
|
1584
|
+
...(bound.has('ngComponentOutletInjector') ? { injector: expr(code(bound.get('ngComponentOutletInjector').value, loops), loops, true) } : {}),
|
|
1585
|
+
...(bound.has('ngComponentOutletInputs') ? { inputs: expr(code(bound.get('ngComponentOutletInputs').value, loops), loops, true) } : {}),
|
|
1586
|
+
}]
|
|
1587
|
+
: [];
|
|
1588
|
+
return [...own, ...outletted, ...compOutletted];
|
|
1232
1589
|
};
|
|
1233
1590
|
/** The open `[ngSwitch]`es, innermost last: the method reading each one's value, and its cases' values as written. */
|
|
1234
1591
|
const switches = [];
|
|
@@ -1284,10 +1641,40 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1284
1641
|
: expr(sw.cases.length ? `!(${sw.cases.map((c) => `(${subject}) === (${code(c, sw.loops)})`).join(' || ')})` : 'true', loops);
|
|
1285
1642
|
return [{ kind: 'if', branches: [{ cond, body: nodes(t.children, loops) }] }];
|
|
1286
1643
|
};
|
|
1644
|
+
const dynamicTemplates = new Map();
|
|
1645
|
+
const dynamicRefNames = new Set();
|
|
1646
|
+
const expandingTemplates = new Set();
|
|
1647
|
+
const ctxLoopFor = (t, ctxVar = '$ctx') => {
|
|
1648
|
+
const ctxNames = {};
|
|
1649
|
+
for (const v of t.variables) {
|
|
1650
|
+
const key = v.value || '$implicit';
|
|
1651
|
+
ctxNames[v.name] = `(${ctxVar} as any)?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
|
|
1652
|
+
}
|
|
1653
|
+
return { item: ctxVar, param: `${ctxVar}: any`, names: ctxNames };
|
|
1654
|
+
};
|
|
1655
|
+
const ensureDynamicTemplate = (refName) => {
|
|
1656
|
+
const field = `$tpl_${refName}`;
|
|
1657
|
+
if (!dynamicTemplates.has(refName) && !dynamicRefNames.has(refName)) {
|
|
1658
|
+
const t = references.get(refName);
|
|
1659
|
+
usesTemplateRef = true;
|
|
1660
|
+
const entry = { field, ctxParam: '$ctx', body: [] };
|
|
1661
|
+
dynamicTemplates.set(refName, entry);
|
|
1662
|
+
methods.push(` readonly ${field} = new $TemplateRef();`);
|
|
1663
|
+
scope.names.set(refName, `this.${field}`);
|
|
1664
|
+
const savedNarrowing = narrowing;
|
|
1665
|
+
narrowing = [];
|
|
1666
|
+
try {
|
|
1667
|
+
entry.body = nodes(t.children, [ctxLoopFor(t)]);
|
|
1668
|
+
}
|
|
1669
|
+
finally {
|
|
1670
|
+
narrowing = savedNarrowing;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
return `this.${field}`;
|
|
1674
|
+
};
|
|
1287
1675
|
/**
|
|
1288
|
-
* `[ngTemplateOutlet]` (NgTemplateOutlet):
|
|
1289
|
-
*
|
|
1290
|
-
* the latest one given. A template chosen by a condition (`a ? one : two`) is an `if`; null renders nothing.
|
|
1676
|
+
* `[ngTemplateOutlet]` (NgTemplateOutlet): static non-recursive `<ng-template #name>` references inline directly;
|
|
1677
|
+
* dynamic expressions (`rendererFor(...)`, signals, `TemplateRef` inputs) or recursive references lower to `templateOutlet`.
|
|
1291
1678
|
*/
|
|
1292
1679
|
const outlet = (tpl, context, loops) => {
|
|
1293
1680
|
const root = tpl instanceof ng.ASTWithSource ? tpl.ast : tpl;
|
|
@@ -1309,21 +1696,31 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1309
1696
|
return [{ kind: 'if', branches: [{ cond: test(template.slice(ast.condition.sourceSpan.start, ast.condition.sourceSpan.end), loops), body: render(ast.trueExp) }, { cond: null, body: render(ast.falseExp) }] }];
|
|
1310
1697
|
const name = ast instanceof ng.PropertyRead && ast.receiver instanceof ng.ImplicitReceiver ? ast.name : null;
|
|
1311
1698
|
const t = name !== null ? references.get(name) : undefined;
|
|
1312
|
-
if (
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1699
|
+
if (t && t.tagName === 'ng-template' && !dynamicTemplates.has(name) && !dynamicRefNames.has(name) && !expandingTemplates.has(name)) {
|
|
1700
|
+
expandingTemplates.add(name);
|
|
1701
|
+
const saved = new Map(t.variables.map((v) => [v.name, aliases.get(v.name)]));
|
|
1702
|
+
for (const v of t.variables)
|
|
1703
|
+
aliases.set(v.name, read(v.value || '$implicit'));
|
|
1704
|
+
try {
|
|
1705
|
+
return nodes(t.children, loops);
|
|
1706
|
+
}
|
|
1707
|
+
finally {
|
|
1708
|
+
expandingTemplates.delete(name);
|
|
1709
|
+
for (const [k, v] of saved)
|
|
1710
|
+
if (v === undefined)
|
|
1711
|
+
aliases.delete(k);
|
|
1712
|
+
else
|
|
1713
|
+
aliases.set(k, v);
|
|
1714
|
+
}
|
|
1326
1715
|
}
|
|
1716
|
+
// Dynamic or recursive template outlet: bind referenced `<ng-template #name>` to a `$tpl_` field and mount via `TemplateOutlet`.
|
|
1717
|
+
if (t && t.tagName === 'ng-template')
|
|
1718
|
+
ensureDynamicTemplate(name);
|
|
1719
|
+
return [{
|
|
1720
|
+
kind: 'templateOutlet',
|
|
1721
|
+
template: expr(code(ast, loops), loops, true),
|
|
1722
|
+
...(context ? { context: expr(code(context, loops), loops, true) } : {}),
|
|
1723
|
+
}];
|
|
1327
1724
|
};
|
|
1328
1725
|
return render(root);
|
|
1329
1726
|
};
|
|
@@ -1410,19 +1807,89 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1410
1807
|
// The element `*ngTemplateOutlet` is written on is the directive's own template, which it never renders.
|
|
1411
1808
|
return outlet(outletOf.value, bound('ngTemplateOutletContext')?.value, loops);
|
|
1412
1809
|
}
|
|
1810
|
+
const compOutletOf = bound('ngComponentOutlet');
|
|
1811
|
+
if (compOutletOf) {
|
|
1812
|
+
for (const a of directive)
|
|
1813
|
+
if (!['ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(a.name))
|
|
1814
|
+
throw new Error(`${path}: *ngComponentOutlet's ${a.name} is not supported in a release build yet`);
|
|
1815
|
+
const inj = bound('ngComponentOutletInjector');
|
|
1816
|
+
const inp = bound('ngComponentOutletInputs');
|
|
1817
|
+
return [{
|
|
1818
|
+
kind: 'componentOutlet',
|
|
1819
|
+
component: expr(code(compOutletOf.value, loops), loops, true),
|
|
1820
|
+
...(inj ? { injector: expr(code(inj.value, loops), loops, true) } : {}),
|
|
1821
|
+
...(inp ? { inputs: expr(code(inp.value, loops), loops, true) } : {}),
|
|
1822
|
+
}];
|
|
1823
|
+
}
|
|
1413
1824
|
const caseOf = bound('ngSwitchCase');
|
|
1414
1825
|
if (caseOf || directive.some((a) => a.name === 'ngSwitchDefault')) {
|
|
1415
1826
|
if (directive.length !== 1)
|
|
1416
1827
|
throw new Error(`${path}: ${directive.map((a) => a.name).join(', ')} on one template is not supported in a release build yet`);
|
|
1417
1828
|
return switchCase(t, caseOf, loops);
|
|
1418
1829
|
}
|
|
1419
|
-
const
|
|
1420
|
-
|
|
1421
|
-
|
|
1830
|
+
const matchedDirs = matched(t.tagName ?? 'ng-template', t.attributes.map((a) => [a.name, a.value]), directive.map((a) => a.name));
|
|
1831
|
+
const structuralDirective = matchedDirs.find((d) => d.structural) ?? (t.tagName !== 'ng-template' ? matchedDirs[0] : undefined);
|
|
1832
|
+
if (structuralDirective) {
|
|
1833
|
+
const names = imported.get(structuralDirective.file) ?? new Map();
|
|
1834
|
+
imported.set(structuralDirective.file, names);
|
|
1835
|
+
if (!names.has(structuralDirective.className))
|
|
1836
|
+
names.set(structuralDirective.className, `$Dir_${structuralDirective.className}`);
|
|
1837
|
+
const alias = names.get(structuralDirective.className);
|
|
1838
|
+
const typeArgs = structuralDirective.typeParams ? `<${Array(structuralDirective.typeParams).fill('any').join(', ')}>` : '';
|
|
1839
|
+
const dName = `$d${directiveCount++}`;
|
|
1840
|
+
const make = expr(structuralDirective.create ? `${alias}.$create()` : `new ${alias}()`, loops);
|
|
1841
|
+
const dInner = [...loops, { item: dName, param: `${dName}: ${alias}${typeArgs}` }];
|
|
1842
|
+
const dValued = [...dInner, { item: '$v', param: '$v: any' }];
|
|
1843
|
+
const setter = (member) => handlerOf(`${structuralDirective.transforms?.has(member) ? `${dName}.$set_${member}($v)` : `${dName}.${member}${structuralDirective.signals.has(member) ? '.$assign($v)' : ' = $v'}`}${structuralDirective.hooks.has('ngOnChanges') ? `; ${dName}.$change(${JSON.stringify(member)}, $v)` : ''}`, dValued);
|
|
1844
|
+
const dInputs = [];
|
|
1845
|
+
for (const [inName, member] of structuralDirective.inputs) {
|
|
1846
|
+
const b = directive.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === inName);
|
|
1847
|
+
const ta = directive.find((a) => a instanceof ng.TmplAstTextAttribute && a.name === inName);
|
|
1848
|
+
if (b)
|
|
1849
|
+
dInputs.push({ set: setter(member), method: expr(code(b.value, loops), loops, true) });
|
|
1850
|
+
else if (ta)
|
|
1851
|
+
dInputs.push({ set: setter(member), value: ta.value });
|
|
1852
|
+
}
|
|
1853
|
+
const dHook = (h) => (structuralDirective.hooks.has(h) ? handlerOf(`${dName}.${h}()`, dInner) : undefined);
|
|
1854
|
+
const dHooks = Object.fromEntries(['init:ngOnInit', 'doCheck:ngDoCheck', 'destroy:ngOnDestroy', 'afterContentInit:ngAfterContentInit', 'afterContentChecked:ngAfterContentChecked', 'afterViewInit:ngAfterViewInit', 'afterViewChecked:ngAfterViewChecked'].flatMap((e) => {
|
|
1855
|
+
const [field, h] = e.split(':');
|
|
1856
|
+
const m = dHook(h);
|
|
1857
|
+
return m ? [[field, m]] : [];
|
|
1858
|
+
}));
|
|
1859
|
+
const ctxVar = `$ctx${loops.length}`;
|
|
1860
|
+
const ctxNames = {};
|
|
1861
|
+
for (const v of t.variables) {
|
|
1862
|
+
const key = v.value || '$implicit';
|
|
1863
|
+
ctxNames[v.name] = `(${ctxVar} as any)?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
|
|
1864
|
+
}
|
|
1865
|
+
const ctxLoops = [...loops, { item: ctxVar, param: `${ctxVar}: any`, names: ctxNames }];
|
|
1866
|
+
const body = nodes(t.children, ctxLoops);
|
|
1867
|
+
return [{
|
|
1868
|
+
kind: 'structural',
|
|
1869
|
+
directive: { name: dName, make, inputs: dInputs, listeners: [], bindings: [], attributes: [], ...dHooks, ...(structuralDirective.hooks.has('ngOnChanges') ? { changes: true } : {}) },
|
|
1870
|
+
ctxParam: ctxVar,
|
|
1871
|
+
body,
|
|
1872
|
+
}];
|
|
1873
|
+
}
|
|
1422
1874
|
if (!ngIf && !ngForOf) {
|
|
1423
|
-
// An `<ng-template #name>` renders only where an `else` names it.
|
|
1424
|
-
if (t.tagName === 'ng-template' && t.references.length && !directive.length)
|
|
1425
|
-
|
|
1875
|
+
// An `<ng-template #name>` renders only where an `else` names it, or binds its body in-place when dynamically referenced.
|
|
1876
|
+
if (t.tagName === 'ng-template' && t.references.length && !directive.length) {
|
|
1877
|
+
const boundNodes = [];
|
|
1878
|
+
const ctxVar = `$ctx${loops.length}`;
|
|
1879
|
+
for (const r of t.references) {
|
|
1880
|
+
if (!dynamicRefNames.has(r.name))
|
|
1881
|
+
continue;
|
|
1882
|
+
const savedNarrowing = narrowing;
|
|
1883
|
+
narrowing = [];
|
|
1884
|
+
try {
|
|
1885
|
+
boundNodes.push({ kind: 'bindTemplate', field: `$tpl_${r.name}`, ctxParam: ctxVar, body: nodes(t.children, [...loops, ctxLoopFor(t, ctxVar)]) });
|
|
1886
|
+
}
|
|
1887
|
+
finally {
|
|
1888
|
+
narrowing = savedNarrowing;
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
return boundNodes;
|
|
1892
|
+
}
|
|
1426
1893
|
throw new Error(`${path}: <${t.tagName}> with ${directive.map((a) => a.name).join(', ') || 'no directive'} is not supported in a release build yet`);
|
|
1427
1894
|
}
|
|
1428
1895
|
if (ngIf) {
|
|
@@ -1441,7 +1908,7 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1441
1908
|
});
|
|
1442
1909
|
const cond = test(condition, loops);
|
|
1443
1910
|
for (const v of renamed)
|
|
1444
|
-
aliases.set(v, core.rewrite(clean(condition), local(loops)));
|
|
1911
|
+
aliases.set(v, `(${core.rewrite(clean(condition), local(loops))})!`);
|
|
1445
1912
|
const body = nodes(t.children, loops);
|
|
1446
1913
|
for (const v of renamed)
|
|
1447
1914
|
aliases.delete(v);
|
|
@@ -1495,6 +1962,102 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1495
1962
|
}
|
|
1496
1963
|
};
|
|
1497
1964
|
findReferences(parsed.nodes);
|
|
1965
|
+
// Pre-register `<ng-template #name>` refs read inside `@let` expressions, passed to element/directive inputs
|
|
1966
|
+
// (e.g. `[hlmDropdownMenuTrigger]="boardMenu"`), or transitively/recursively referenced, so `bindTemplate` compiles in-place.
|
|
1967
|
+
const collectRefReads = (list, into, includeDirectOutlet) => {
|
|
1968
|
+
const checkSrc = (src) => {
|
|
1969
|
+
for (const refName of references.keys())
|
|
1970
|
+
if (new RegExp(`\\b${refName}\\b`).test(src))
|
|
1971
|
+
into.add(refName);
|
|
1972
|
+
};
|
|
1973
|
+
for (const n of list) {
|
|
1974
|
+
if (n instanceof ng.TmplAstLetDeclaration)
|
|
1975
|
+
checkSrc(sourceOf(n.value));
|
|
1976
|
+
else if (n instanceof ng.TmplAstTemplate) {
|
|
1977
|
+
for (const a of [...n.templateAttrs, ...n.inputs]) {
|
|
1978
|
+
if (!(a instanceof ng.TmplAstBoundAttribute))
|
|
1979
|
+
continue;
|
|
1980
|
+
if (!includeDirectOutlet && (a.name === 'ngIfElse' || a.name === 'ngTemplateOutlet'))
|
|
1981
|
+
continue;
|
|
1982
|
+
checkSrc(sourceOf(a.value));
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
else if (n instanceof ng.TmplAstElement) {
|
|
1986
|
+
for (const i of n.inputs) {
|
|
1987
|
+
if (!includeDirectOutlet && i.name === 'ngTemplateOutlet')
|
|
1988
|
+
continue;
|
|
1989
|
+
checkSrc(sourceOf(i.value));
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
|
|
1993
|
+
collectRefReads(n.children, into, includeDirectOutlet);
|
|
1994
|
+
if (n instanceof ng.TmplAstIfBlock)
|
|
1995
|
+
for (const b of n.branches)
|
|
1996
|
+
collectRefReads(b.children, into, includeDirectOutlet);
|
|
1997
|
+
if (n instanceof ng.TmplAstForLoopBlock && n.empty)
|
|
1998
|
+
collectRefReads(n.empty.children, into, includeDirectOutlet);
|
|
1999
|
+
if (n instanceof ng.TmplAstSwitchBlock)
|
|
2000
|
+
for (const g of n.groups)
|
|
2001
|
+
collectRefReads(g.children, into, includeDirectOutlet);
|
|
2002
|
+
}
|
|
2003
|
+
};
|
|
2004
|
+
collectRefReads(parsed.nodes, dynamicRefNames, false);
|
|
2005
|
+
// Transitive closure: any `<ng-template #b>` referenced inside an already-dynamic `<ng-template #a>`, or self-recursive templates.
|
|
2006
|
+
for (const [refName, tpl] of references) {
|
|
2007
|
+
const inside = new Set();
|
|
2008
|
+
collectRefReads(tpl.children, inside, true);
|
|
2009
|
+
if (inside.has(refName))
|
|
2010
|
+
dynamicRefNames.add(refName);
|
|
2011
|
+
}
|
|
2012
|
+
let grew = true;
|
|
2013
|
+
while (grew) {
|
|
2014
|
+
grew = false;
|
|
2015
|
+
for (const refName of [...dynamicRefNames]) {
|
|
2016
|
+
const tpl = references.get(refName);
|
|
2017
|
+
if (!tpl)
|
|
2018
|
+
continue;
|
|
2019
|
+
const inside = new Set();
|
|
2020
|
+
collectRefReads(tpl.children, inside, true);
|
|
2021
|
+
for (const r of inside)
|
|
2022
|
+
if (!dynamicRefNames.has(r)) {
|
|
2023
|
+
dynamicRefNames.add(r);
|
|
2024
|
+
grew = true;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
for (const refName of dynamicRefNames) {
|
|
2029
|
+
usesTemplateRef = true;
|
|
2030
|
+
const field = `$tpl_${refName}`;
|
|
2031
|
+
methods.push(` readonly ${field} = new $TemplateRef();`);
|
|
2032
|
+
scope.names.set(refName, `this.${field}`);
|
|
2033
|
+
}
|
|
2034
|
+
// Plain element template references (`#promoInput` on `<input>`, read in handlers/bindings like `(click)="apply(promoInput.value)"`).
|
|
2035
|
+
const elementRefFields = new Map();
|
|
2036
|
+
const collectElementRefs = (list) => {
|
|
2037
|
+
for (const n of list) {
|
|
2038
|
+
if (n instanceof ng.TmplAstElement) {
|
|
2039
|
+
for (const r of n.references) {
|
|
2040
|
+
if (!r.value && !references.has(r.name) && !scope.names.has(r.name) && !elementRefFields.has(r.name)) {
|
|
2041
|
+
const field = `$ref_${r.name}`;
|
|
2042
|
+
elementRefFields.set(r.name, field);
|
|
2043
|
+
methods.push(` ${field}: any = undefined;`);
|
|
2044
|
+
scope.names.set(r.name, `this.${field}`);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
|
|
2049
|
+
collectElementRefs(n.children);
|
|
2050
|
+
if (n instanceof ng.TmplAstIfBlock)
|
|
2051
|
+
for (const b of n.branches)
|
|
2052
|
+
collectElementRefs(b.children);
|
|
2053
|
+
if (n instanceof ng.TmplAstForLoopBlock && n.empty)
|
|
2054
|
+
collectElementRefs(n.empty.children);
|
|
2055
|
+
if (n instanceof ng.TmplAstSwitchBlock)
|
|
2056
|
+
for (const g of n.groups)
|
|
2057
|
+
collectElementRefs(g.children);
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
collectElementRefs(parsed.nodes);
|
|
1498
2061
|
const ownElements = (list) => {
|
|
1499
2062
|
for (const n of list) {
|
|
1500
2063
|
if (!(n instanceof ng.TmplAstElement))
|
|
@@ -1509,6 +2072,212 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1509
2072
|
if (q.static && q.ref && staticRefs.has(q.ref))
|
|
1510
2073
|
staticQueries.add(q);
|
|
1511
2074
|
const tree = nodes(parsed.nodes, []);
|
|
2075
|
+
// `@Component({ host: { ... } })`: static attributes, property/attribute/class bindings and listeners applied to the component's root element(s).
|
|
2076
|
+
if (hostMeta) {
|
|
2077
|
+
if (!ts.isObjectLiteralExpression(hostMeta))
|
|
2078
|
+
throw new Error(`${path}: @Component's host is read as an object literal in a release build`);
|
|
2079
|
+
const hostStaticAttrs = [];
|
|
2080
|
+
const hostBoundAttrs = [];
|
|
2081
|
+
const hostClassToggles = [];
|
|
2082
|
+
const hostBoundClass = [];
|
|
2083
|
+
const hostEvents = [];
|
|
2084
|
+
for (const p of hostMeta.properties) {
|
|
2085
|
+
if (!ts.isPropertyAssignment(p) || !ts.isStringLiteralLike(p.initializer))
|
|
2086
|
+
throw new Error(`${path}: @Component's host entries are strings in a release build`);
|
|
2087
|
+
const key = ts.isStringLiteralLike(p.name) ? p.name.text : p.name.getText();
|
|
2088
|
+
const val = p.initializer.text;
|
|
2089
|
+
if (/^\(.*\)$/.test(key)) {
|
|
2090
|
+
const ev = key.slice(1, -1);
|
|
2091
|
+
if (ev.includes(':'))
|
|
2092
|
+
throw new Error(`${path}: host listener (${ev}), a global target, is not supported in a release build yet`);
|
|
2093
|
+
hostEvents.push({ name: ev, code: val });
|
|
2094
|
+
}
|
|
2095
|
+
else if (/^\[.*\]$/.test(key)) {
|
|
2096
|
+
const propName = key.slice(1, -1);
|
|
2097
|
+
if (propName === 'class')
|
|
2098
|
+
hostBoundClass.push(val);
|
|
2099
|
+
else if (propName.startsWith('class.'))
|
|
2100
|
+
hostClassToggles.push([propName.slice(6), val]);
|
|
2101
|
+
else if (propName.startsWith('attr.'))
|
|
2102
|
+
hostBoundAttrs.push({ name: propName.slice(5), code: val });
|
|
2103
|
+
else
|
|
2104
|
+
hostBoundAttrs.push({ name: propName, code: val });
|
|
2105
|
+
}
|
|
2106
|
+
else {
|
|
2107
|
+
hostStaticAttrs.push({ name: key, value: val });
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
const hostStaticClass = hostStaticAttrs.filter((a) => a.name === 'class').map((a) => a.value).join(' ').trim();
|
|
2111
|
+
const otherHostStatic = hostStaticAttrs.filter((a) => a.name !== 'class');
|
|
2112
|
+
const hostBoundAttrMethods = hostBoundAttrs.map((b) => ({ name: b.name, method: expr(b.code, [], true) }));
|
|
2113
|
+
const hostEventMethods = hostEvents.map((e) => ({ name: e.name, method: handler(e.code, [], true) }));
|
|
2114
|
+
const applyHost = (el) => {
|
|
2115
|
+
for (const a of otherHostStatic)
|
|
2116
|
+
if (!el.attrs.some((x) => x.name === a.name))
|
|
2117
|
+
el.attrs.push({ name: a.name, value: a.value });
|
|
2118
|
+
for (const b of hostBoundAttrMethods)
|
|
2119
|
+
el.attrs.push(b);
|
|
2120
|
+
for (const e of hostEventMethods)
|
|
2121
|
+
el.events.push(e);
|
|
2122
|
+
if (hostStaticClass || hostBoundClass.length || hostClassToggles.length) {
|
|
2123
|
+
const idx = el.attrs.findIndex((a) => a.name === 'class');
|
|
2124
|
+
const existing = idx >= 0 ? el.attrs[idx] : undefined;
|
|
2125
|
+
if (!hostBoundClass.length && !hostClassToggles.length) {
|
|
2126
|
+
if (existing && 'value' in existing)
|
|
2127
|
+
existing.value = [hostStaticClass, existing.value].filter(Boolean).join(' ');
|
|
2128
|
+
else if (!existing)
|
|
2129
|
+
el.attrs.push({ name: 'class', value: hostStaticClass });
|
|
2130
|
+
}
|
|
2131
|
+
else {
|
|
2132
|
+
const base = [hostStaticClass, existing && 'value' in existing ? existing.value : ''].filter(Boolean).join(' ');
|
|
2133
|
+
if (idx >= 0 && existing && 'value' in existing)
|
|
2134
|
+
el.attrs.splice(idx, 1);
|
|
2135
|
+
const dynamicVal = hostBoundClass.length === 1 ? `(${hostBoundClass[0]})` : hostBoundClass.length > 1 ? `[${hostBoundClass.map((c) => `(${c})`).join(', ')}]` : 'null';
|
|
2136
|
+
const pairs = hostClassToggles.flatMap(([k, v]) => [JSON.stringify(k), `(${v})`]);
|
|
2137
|
+
el.attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, ${dynamicVal}, [${pairs.join(', ')}])`, []) });
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
};
|
|
2141
|
+
for (const rootNode of tree)
|
|
2142
|
+
if (rootNode.kind === 'element')
|
|
2143
|
+
applyHost(rootNode);
|
|
2144
|
+
}
|
|
2145
|
+
// `@Component({ hostDirectives: [...] })`: Directive Composition API — attach host directives to root element(s) and forward exposed inputs/outputs.
|
|
2146
|
+
const hdOutputFields = {};
|
|
2147
|
+
let hdNeedsInput = false;
|
|
2148
|
+
let hdNeedsOutput = false;
|
|
2149
|
+
if (hostDirectivesMeta) {
|
|
2150
|
+
if (!ts.isArrayLiteralExpression(hostDirectivesMeta))
|
|
2151
|
+
throw new Error(`${path}: @Component's hostDirectives is read as an array literal in a release build`);
|
|
2152
|
+
const unwrapDir = (e) => {
|
|
2153
|
+
if (ts.isIdentifier(e))
|
|
2154
|
+
return e.text;
|
|
2155
|
+
if (ts.isCallExpression(e) && e.expression.getText() === 'forwardRef' && e.arguments[0] && ts.isArrowFunction(e.arguments[0]) && ts.isIdentifier(e.arguments[0].body)) {
|
|
2156
|
+
return e.arguments[0].body.text;
|
|
2157
|
+
}
|
|
2158
|
+
return null;
|
|
2159
|
+
};
|
|
2160
|
+
const stringList = (e, label) => {
|
|
2161
|
+
if (!e)
|
|
2162
|
+
return [];
|
|
2163
|
+
if (!ts.isArrayLiteralExpression(e))
|
|
2164
|
+
throw new Error(`${path}: hostDirectives ${label} must be an array of string literals in a release build`);
|
|
2165
|
+
return e.elements.map((el) => {
|
|
2166
|
+
if (!ts.isStringLiteralLike(el))
|
|
2167
|
+
throw new Error(`${path}: hostDirectives ${label} entries must be string literals in a release build`);
|
|
2168
|
+
return el.text;
|
|
2169
|
+
});
|
|
2170
|
+
};
|
|
2171
|
+
let hdFieldCount = 0;
|
|
2172
|
+
const hdUses = [];
|
|
2173
|
+
for (const el of hostDirectivesMeta.elements) {
|
|
2174
|
+
let dirName = null;
|
|
2175
|
+
let hdInputs = [];
|
|
2176
|
+
let hdOutputs = [];
|
|
2177
|
+
if (ts.isObjectLiteralExpression(el)) {
|
|
2178
|
+
const get = (k) => el.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
|
|
2179
|
+
const dirExpr = get('directive');
|
|
2180
|
+
dirName = dirExpr ? unwrapDir(dirExpr) : null;
|
|
2181
|
+
hdInputs = stringList(get('inputs'), 'inputs');
|
|
2182
|
+
hdOutputs = stringList(get('outputs'), 'outputs');
|
|
2183
|
+
}
|
|
2184
|
+
else {
|
|
2185
|
+
dirName = unwrapDir(el);
|
|
2186
|
+
}
|
|
2187
|
+
if (!dirName)
|
|
2188
|
+
throw new Error(`${path}: @Component's hostDirectives entry ${el.getText().split('\n')[0]} needs a directive class name in a release build`);
|
|
2189
|
+
const decl = options.directives?.find((d) => d.className === dirName);
|
|
2190
|
+
const hdTypeArgs = decl?.typeParams ? `<${Array(decl.typeParams).fill('any').join(', ')}>` : '';
|
|
2191
|
+
const dName = `$d${directiveCount++}`;
|
|
2192
|
+
const make = expr(decl?.create ? `${dirName}.$create()` : `new ${dirName}()`, []);
|
|
2193
|
+
const inner = [{ item: dName, param: `${dName}: ${dirName}${hdTypeArgs}` }];
|
|
2194
|
+
const valued = [...inner, { item: '$v', param: '$v: any' }];
|
|
2195
|
+
const dirInputs = [];
|
|
2196
|
+
for (const mapping of hdInputs) {
|
|
2197
|
+
const [internal, alias] = mapping.split(':').map((s) => s.trim());
|
|
2198
|
+
const pub = alias || internal;
|
|
2199
|
+
let readExpr;
|
|
2200
|
+
if (members.has(pub)) {
|
|
2201
|
+
readExpr = props.includes(pub) ? `this.${pub}()` : `this.${pub}`;
|
|
2202
|
+
}
|
|
2203
|
+
else {
|
|
2204
|
+
const field = `$hdIn${hdFieldCount++}`;
|
|
2205
|
+
methods.push(` readonly ${field} = input<any>(undefined);`);
|
|
2206
|
+
hdNeedsInput = true;
|
|
2207
|
+
props.push(field);
|
|
2208
|
+
optional.push(field);
|
|
2209
|
+
inputAliases[field] = pub;
|
|
2210
|
+
readExpr = `this.${field}()`;
|
|
2211
|
+
}
|
|
2212
|
+
const member = decl?.inputs.get(internal) ?? internal;
|
|
2213
|
+
const setStmt = decl
|
|
2214
|
+
? `if ($v !== undefined) { ${dName}.${member}${decl.signals.has(member) ? '.$assign($v)' : ' = $v'}${decl.hooks.has('ngOnChanges') ? `; ${dName}.$change(${JSON.stringify(member)}, $v)` : ''}; }`
|
|
2215
|
+
: `if ($v !== undefined) { const $cur: any = (${dName} as any)[${JSON.stringify(member)}]; if ($cur && typeof $cur.$assign === 'function') { $cur.$assign($v); } else { (${dName} as any)[${JSON.stringify(member)}] = $v; } }`;
|
|
2216
|
+
dirInputs.push({ set: handlerOf(setStmt, valued), method: expr(readExpr, [], true) });
|
|
2217
|
+
}
|
|
2218
|
+
const dirOutputs = [];
|
|
2219
|
+
for (const mapping of hdOutputs) {
|
|
2220
|
+
const [internal, alias] = mapping.split(':').map((s) => s.trim());
|
|
2221
|
+
const pub = alias || internal;
|
|
2222
|
+
const field = `$hdOut${hdFieldCount++}`;
|
|
2223
|
+
methods.push(` readonly ${field} = output<any>();`);
|
|
2224
|
+
hdNeedsOutput = true;
|
|
2225
|
+
outputs.push(pub);
|
|
2226
|
+
hdOutputFields[pub] = field;
|
|
2227
|
+
dirOutputs.push({ name: internal, method: handlerOf(`this.${field}.emit($event)`, [...inner, { item: '$event', param: '$event: any' }]) });
|
|
2228
|
+
}
|
|
2229
|
+
const own = { names: new Map((decl?.members ?? []).map((m) => [m, `${dName}.${m}`])) };
|
|
2230
|
+
const listeners = (decl?.listeners ?? []).map((l) => ({ event: l.event, method: handlerOf(core.rewrite(l.code, { names: new Map([...own.names, ['$event', '$event']]) }, 'statements'), [...inner, { item: '$event', param: '$event: any' }]) }));
|
|
2231
|
+
const bindings = (decl?.bindings ?? []).map((b) => ({ prop: b.prop, method: expr(core.rewrite(b.code, own), inner, true) }));
|
|
2232
|
+
const dHook = (h) => (decl?.hooks.has(h) ? handlerOf(`${dName}.${h}()`, inner) : undefined);
|
|
2233
|
+
const hooks = Object.fromEntries(['init:ngOnInit', 'doCheck:ngDoCheck', 'destroy:ngOnDestroy', 'afterContentInit:ngAfterContentInit', 'afterContentChecked:ngAfterContentChecked', 'afterViewInit:ngAfterViewInit', 'afterViewChecked:ngAfterViewChecked'].flatMap((e) => {
|
|
2234
|
+
const [field, h] = e.split(':');
|
|
2235
|
+
const m = dHook(h);
|
|
2236
|
+
return m ? [[field, m]] : [];
|
|
2237
|
+
}));
|
|
2238
|
+
hdUses.push({
|
|
2239
|
+
name: dName,
|
|
2240
|
+
make,
|
|
2241
|
+
inputs: dirInputs,
|
|
2242
|
+
listeners,
|
|
2243
|
+
bindings,
|
|
2244
|
+
attributes: decl?.attributes ?? [],
|
|
2245
|
+
...hooks,
|
|
2246
|
+
...(decl?.hooks.has('ngOnChanges') ? { changes: true } : {}),
|
|
2247
|
+
...(dirOutputs.length ? { outputs: dirOutputs } : {}),
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
if (hdUses.length) {
|
|
2251
|
+
for (const rootNode of tree) {
|
|
2252
|
+
if (rootNode.kind === 'element')
|
|
2253
|
+
rootNode.directives = [...hdUses, ...(rootNode.directives ?? [])];
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
// Content queries (`contentChild` / `contentChildren` / `@ContentChild` / `@ContentChildren`): public setters called by parent slot projections.
|
|
2258
|
+
for (const cq of contentQueries) {
|
|
2259
|
+
const paramType = cq.typeArg ?? 'any';
|
|
2260
|
+
if (cq.signal && !cq.many) {
|
|
2261
|
+
methods.push(` $cqSet_${cq.field}(v: ${paramType}) { this.${cq.field}.set(v); }`);
|
|
2262
|
+
methods.push(` $cqUnset_${cq.field}(_v?: ${paramType}) { this.${cq.field}.set(undefined as any); }`);
|
|
2263
|
+
}
|
|
2264
|
+
else if (cq.signal && cq.many) {
|
|
2265
|
+
methods.push(` $cqSet_${cq.field}(v: ${paramType}) { this.${cq.field}.update((xs) => [...xs, v]); }`);
|
|
2266
|
+
methods.push(` $cqUnset_${cq.field}(v: ${paramType}) { this.${cq.field}.update((xs) => xs.filter((x) => x !== v)); }`);
|
|
2267
|
+
}
|
|
2268
|
+
else if (!cq.many) {
|
|
2269
|
+
methods.push(` $cqSet_${cq.field}(v: any) { this.${cq.field} = v; }`);
|
|
2270
|
+
}
|
|
2271
|
+
else {
|
|
2272
|
+
methods.push(` $cqSet_${cq.field}(k: any, v: any) { this.${cq.field}.$add(k, v); }`);
|
|
2273
|
+
methods.push(` $cqUnset_${cq.field}(k: any) { this.${cq.field}.$remove(k); }`);
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
// Signal inputs with `{ transform }`: emit `$set_<prop>` that runs the transform before writing the input signal.
|
|
2277
|
+
for (const [field, fn] of inputTransforms) {
|
|
2278
|
+
const call = /^[A-Za-z_$][\w$.]*$/.test(fn.trim()) ? `${fn.trim()}(value)` : `(${fn})(value)`;
|
|
2279
|
+
methods.push(` $set_${field}(value: any) { this.${field}.$assign(${call}); }`);
|
|
2280
|
+
}
|
|
1512
2281
|
// The component's source, with the template's methods added to its class and the event type imported.
|
|
1513
2282
|
const end = cls.members.end;
|
|
1514
2283
|
// ngOnChanges: the parent's bindings record each input they set (`$change`), and one check after them calls the hook
|
|
@@ -1520,40 +2289,60 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1520
2289
|
methods.push(...changesMembers(onChanges.parameters.length > 0));
|
|
1521
2290
|
}
|
|
1522
2291
|
const cached = [...sites.values()].some((x) => x.cache);
|
|
1523
|
-
let imports =
|
|
1524
|
-
if (
|
|
2292
|
+
let imports = '';
|
|
2293
|
+
if (cached && !declares(sf, '$PurePipeCache'))
|
|
2294
|
+
imports += "import { PurePipeCache as $PurePipeCache } from '@angular#kit';\n";
|
|
2295
|
+
if (lets && !declares(sf, '$LetSlot'))
|
|
2296
|
+
imports += "import { LetSlot as $LetSlot } from '@angular#kit';\n";
|
|
2297
|
+
if (!declares(sf, '$EventData'))
|
|
2298
|
+
imports += "import { type EventData as $EventData } from '@nativescript/release';\n";
|
|
2299
|
+
if (usesElementRef && !declares(sf, '$ElementRef'))
|
|
1525
2300
|
imports += `import { ElementRef as $ElementRef } from '@angular/core';\n`;
|
|
1526
|
-
if (usesUnset)
|
|
2301
|
+
if (usesUnset && !declares(sf, '$unsetValue'))
|
|
1527
2302
|
imports += `import { unsetValue as $unsetValue } from '@nativescript/core';\n`;
|
|
1528
|
-
if (
|
|
2303
|
+
if (hasProviders && !declares(sf, 'NodeInjector'))
|
|
1529
2304
|
imports += `import { NodeInjector } from '@angular#kit';\n`;
|
|
2305
|
+
if (hdNeedsInput && !importsAs(sf, 'input', '@angular/core'))
|
|
2306
|
+
imports += `import { input } from '@angular/core';\n`;
|
|
2307
|
+
if (hdNeedsOutput && !importsAs(sf, 'output', '@angular/core'))
|
|
2308
|
+
imports += `import { output } from '@angular/core';\n`;
|
|
1530
2309
|
if (onChanges) {
|
|
1531
|
-
|
|
2310
|
+
if (!declares(sf, '$SimpleChange'))
|
|
2311
|
+
imports += `import { SimpleChange as $SimpleChange } from '@angular/core';\n`;
|
|
1532
2312
|
if (!importsAs(sf, 'signal', '@angular/core')) {
|
|
1533
2313
|
if (declares(sf, 'signal'))
|
|
1534
2314
|
throw new Error(`${path}: ngOnChanges needs Angular's signal, which this file's own "signal" hides`);
|
|
1535
2315
|
imports += `import { signal } from '@angular/core';\n`;
|
|
1536
2316
|
}
|
|
1537
2317
|
}
|
|
1538
|
-
if (queries.some((q) => q.many)) {
|
|
2318
|
+
if ((queries.some((q) => q.many && !q.signal) || contentQueries.some((q) => q.many && !q.signal)) && !declares(sf, '$QueryList')) {
|
|
1539
2319
|
usesRuntime = true;
|
|
1540
2320
|
const from = options.runtimeModule ?? RUNTIME;
|
|
1541
2321
|
imports += `import { QueryList as $QueryList } from '${isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from}';\n`;
|
|
1542
2322
|
}
|
|
1543
2323
|
for (const [from, names] of imported) {
|
|
2324
|
+
const needed = [...names].filter(([, a]) => !declares(sf, a));
|
|
2325
|
+
if (!needed.length)
|
|
2326
|
+
continue;
|
|
1544
2327
|
const spec = isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from;
|
|
1545
|
-
imports += `import { ${
|
|
2328
|
+
imports += `import { ${needed.map(([c, a]) => `${c} as ${a}`).join(', ')} } from '${spec}';\n`;
|
|
2329
|
+
}
|
|
2330
|
+
if (usesTemplateRef && !declares(sf, '$TemplateRef'))
|
|
2331
|
+
imports += `import { TemplateRef as $TemplateRef } from '@angular/core';\n`;
|
|
2332
|
+
if ((routed || usesInject) && !importsAs(sf, 'inject', '@angular/core')) {
|
|
2333
|
+
if (declares(sf, 'inject'))
|
|
2334
|
+
throw new Error(`${path}: ${routed ? 'nsRouterLink' : 'a pipe constructor'} needs Angular's inject, which this file's own "inject" hides`);
|
|
2335
|
+
imports += `import { inject } from '@angular/core';\n`;
|
|
1546
2336
|
}
|
|
1547
2337
|
if (routed) {
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
imports += `import { inject } from '@angular/core';\n`;
|
|
1553
|
-
}
|
|
1554
|
-
imports += `import { ActivatedRoute as $ActivatedRoute } from '@angular/router';\nimport { RouterExtensions as $RouterExtensions } from '@nativescript/angular';\n`;
|
|
2338
|
+
if (!declares(sf, '$ActivatedRoute'))
|
|
2339
|
+
imports += `import { ActivatedRoute as $ActivatedRoute } from '@angular/router';\n`;
|
|
2340
|
+
if (!declares(sf, '$RouterExtensions'))
|
|
2341
|
+
imports += `import { RouterExtensions as $RouterExtensions } from '@nativescript/angular';\n`;
|
|
1555
2342
|
methods.push(' readonly $router = inject($RouterExtensions);', ' readonly $route = inject($ActivatedRoute);');
|
|
1556
2343
|
}
|
|
2344
|
+
const importLineCount = imports ? imports.split('\n').length - 1 : 0;
|
|
2345
|
+
prependedLines += importLineCount;
|
|
1557
2346
|
const head = imports + text.slice(0, end) + '\n';
|
|
1558
2347
|
const source = head + methods.join('\n') + '\n' + text.slice(end);
|
|
1559
2348
|
// Each template method's lines in the virtual file, at its binding's line in the template it was written in.
|
|
@@ -1572,7 +2361,38 @@ export function angularComponent(path, text, selectors, options = {}) {
|
|
|
1572
2361
|
});
|
|
1573
2362
|
const { styles, scope: styleScope } = angularStyles(path, prop);
|
|
1574
2363
|
const scoped = styleScope ? core.scopeTemplate(tree, styleScope.content).map((n) => (n.kind === 'element' ? { ...n, attrs: [...n.attrs, { name: styleScope.host, value: '' }] } : n)) : tree;
|
|
1575
|
-
|
|
2364
|
+
const allSetters = new Set([...(classic?.setters ?? []), ...inputTransforms.keys(), ...inheritedSetters]);
|
|
2365
|
+
const component = {
|
|
2366
|
+
name: cls.name.text,
|
|
2367
|
+
file: path.replace(/\.ts$/, '.release.ts'),
|
|
2368
|
+
source,
|
|
2369
|
+
...(usesRuntime ? { usesRuntime } : {}),
|
|
2370
|
+
props,
|
|
2371
|
+
optional,
|
|
2372
|
+
outputs,
|
|
2373
|
+
...(Object.keys(hdOutputFields).length ? { outputFields: hdOutputFields } : {}),
|
|
2374
|
+
template: scoped,
|
|
2375
|
+
...(dynamicTemplates.size ? { templates: [...dynamicTemplates.values()] } : {}),
|
|
2376
|
+
selector,
|
|
2377
|
+
styles,
|
|
2378
|
+
...(slotNames.size ? { slots: [...slotNames] } : {}),
|
|
2379
|
+
...(init ? { init: 'ngOnInit' } : {}),
|
|
2380
|
+
...(init && lateInit ? { lateInit } : {}),
|
|
2381
|
+
...(hook('ngDoCheck') ? { doCheck: 'ngDoCheck' } : {}),
|
|
2382
|
+
...(hook('ngAfterContentInit') ? { afterContentInit: 'ngAfterContentInit' } : {}),
|
|
2383
|
+
...(hook('ngAfterContentChecked') ? { afterContentChecked: 'ngAfterContentChecked' } : {}),
|
|
2384
|
+
...(hook('ngAfterViewInit') ? { afterViewInit: 'ngAfterViewInit' } : {}),
|
|
2385
|
+
...(hook('ngAfterViewChecked') ? { afterViewChecked: 'ngAfterViewChecked' } : {}),
|
|
2386
|
+
...(hook('ngOnDestroy') ? { destroy: 'ngOnDestroy' } : {}),
|
|
2387
|
+
...(onChanges ? { changes: true } : {}),
|
|
2388
|
+
...(onPush ? { onPush } : {}),
|
|
2389
|
+
...(classic?.host ? { host: '$host' } : {}),
|
|
2390
|
+
...(hasProviders ? { injector: '$injector' } : {}),
|
|
2391
|
+
...(allSetters.size ? { setters: [...allSetters] } : {}),
|
|
2392
|
+
...(Object.keys(inputAliases).length ? { propAliases: inputAliases } : {}),
|
|
2393
|
+
...(lines.length ? { templateLines: { file: templateFile, lines } } : {}),
|
|
2394
|
+
};
|
|
2395
|
+
return { component, nextText: source, prependedLines };
|
|
1576
2396
|
}
|
|
1577
2397
|
/**
|
|
1578
2398
|
* The component's `styles`, `styleUrl` and `styleUrls`, as NativeScript Angular adds them: Sass compiled by the app's own
|
|
@@ -1679,10 +2499,17 @@ function relativeSpecifier(dir, file) {
|
|
|
1679
2499
|
* The `@Pipe` classes of the app's and its libraries' files, by the name templates use: whether each is pure (Angular's
|
|
1680
2500
|
* default) and what making one takes.
|
|
1681
2501
|
*/
|
|
1682
|
-
export function angularPipes(files, read) {
|
|
2502
|
+
export function angularPipes(files, read, modulesDir) {
|
|
1683
2503
|
const out = new Map();
|
|
2504
|
+
const importedPkgs = new Set();
|
|
1684
2505
|
for (const file of files) {
|
|
1685
2506
|
const text = read(file);
|
|
2507
|
+
if (modulesDir) {
|
|
2508
|
+
for (const m of text.matchAll(/\bfrom\s*['"]((?:@[\w.-]+\/)?[\w.-]+(?:\/[\w.-]+)*)['"]/g)) {
|
|
2509
|
+
if (!m[1].startsWith('.') && !m[1].startsWith('@angular/'))
|
|
2510
|
+
importedPkgs.add(m[1]);
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
1686
2513
|
if (!text.includes('@Pipe'))
|
|
1687
2514
|
continue;
|
|
1688
2515
|
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
@@ -1707,6 +2534,61 @@ export function angularPipes(files, read) {
|
|
|
1707
2534
|
});
|
|
1708
2535
|
}
|
|
1709
2536
|
}
|
|
2537
|
+
// Discover compiled Angular library pipes from `.d.ts` `ɵɵPipeDeclaration<ClassName, "pipeName", pure>`.
|
|
2538
|
+
if (modulesDir) {
|
|
2539
|
+
const walkDts = (dir, acc = []) => {
|
|
2540
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory())
|
|
2541
|
+
return acc;
|
|
2542
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
2543
|
+
const p = join(dir, entry.name);
|
|
2544
|
+
if (entry.isDirectory() && entry.name !== 'node_modules')
|
|
2545
|
+
walkDts(p, acc);
|
|
2546
|
+
else if (entry.name.endsWith('.d.ts') && !entry.name.endsWith('.ngtypecheck.d.ts'))
|
|
2547
|
+
acc.push(p);
|
|
2548
|
+
}
|
|
2549
|
+
return acc;
|
|
2550
|
+
};
|
|
2551
|
+
for (const rawSpec of importedPkgs) {
|
|
2552
|
+
const spec = rawSpec.split('?', 1)[0];
|
|
2553
|
+
const pkgDir = join(modulesDir, spec);
|
|
2554
|
+
if (!existsSync(pkgDir) || !statSync(pkgDir).isDirectory())
|
|
2555
|
+
continue;
|
|
2556
|
+
for (const dts of walkDts(pkgDir)) {
|
|
2557
|
+
const dtsText = readFileSync(dts, 'utf8');
|
|
2558
|
+
if (!dtsText.includes('ɵɵPipeDeclaration'))
|
|
2559
|
+
continue;
|
|
2560
|
+
const sf = ts.createSourceFile(dts, dtsText, ts.ScriptTarget.Latest, true);
|
|
2561
|
+
const importSources = new Map();
|
|
2562
|
+
for (const s of sf.statements) {
|
|
2563
|
+
if (ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.importClause?.namedBindings && ts.isNamedImports(s.importClause.namedBindings)) {
|
|
2564
|
+
const from = s.moduleSpecifier.text.startsWith('.') ? spec : s.moduleSpecifier.text;
|
|
2565
|
+
for (const el of s.importClause.namedBindings.elements)
|
|
2566
|
+
importSources.set(el.name.text, from);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
for (const st of sf.statements) {
|
|
2570
|
+
if (!ts.isClassDeclaration(st) || !st.name)
|
|
2571
|
+
continue;
|
|
2572
|
+
const pipeProp = st.members.find((m) => ts.isPropertyDeclaration(m) && m.name.getText() === 'ɵpipe');
|
|
2573
|
+
const pipeMatch = pipeProp?.type && /ɵɵPipeDeclaration<\s*[^,]+,\s*["']([^"']+)["'](?:\s*,\s*(true|false))?/.exec(pipeProp.type.getText(sf));
|
|
2574
|
+
if (!pipeMatch || out.has(pipeMatch[1]))
|
|
2575
|
+
continue;
|
|
2576
|
+
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
2577
|
+
const deps = ctor?.parameters.map((p) => {
|
|
2578
|
+
const typeName = p.type && ts.isTypeReferenceNode(p.type) ? p.type.typeName.getText(sf) : '';
|
|
2579
|
+
return { name: typeName, from: importSources.get(typeName) ?? spec };
|
|
2580
|
+
}).filter((d) => !!d.name);
|
|
2581
|
+
out.set(pipeMatch[1], {
|
|
2582
|
+
className: st.name.text,
|
|
2583
|
+
file: spec,
|
|
2584
|
+
pure: pipeMatch[2] !== 'false',
|
|
2585
|
+
...(deps?.length ? { deps } : {}),
|
|
2586
|
+
...(st.members.some((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnDestroy') ? { destroy: true } : {}),
|
|
2587
|
+
});
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
1710
2592
|
return out;
|
|
1711
2593
|
}
|
|
1712
2594
|
/**
|
|
@@ -1738,18 +2620,21 @@ export function angularDirectives(files, read) {
|
|
|
1738
2620
|
if (!call)
|
|
1739
2621
|
continue;
|
|
1740
2622
|
const where = `${file}: the directive ${st.name.text}`;
|
|
1741
|
-
if (
|
|
2623
|
+
if (meta && !ts.isObjectLiteralExpression(meta))
|
|
1742
2624
|
throw new Error(`${where} needs a selector`);
|
|
1743
|
-
const get = (k) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
|
|
2625
|
+
const get = (k) => (meta && ts.isObjectLiteralExpression(meta) ? meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
|
|
1744
2626
|
const selector = get('selector');
|
|
1745
|
-
if (
|
|
2627
|
+
if (selector && !ts.isStringLiteralLike(selector))
|
|
1746
2628
|
throw new Error(`${where} needs a string selector in a release build`);
|
|
1747
2629
|
if (!(ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
1748
2630
|
throw new Error(`${where} is not exported`);
|
|
1749
|
-
const
|
|
1750
|
-
|
|
2631
|
+
const exportAsRaw = get('exportAs');
|
|
2632
|
+
const exportAs = exportAsRaw && ts.isStringLiteralLike(exportAsRaw) ? exportAsRaw.text.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
|
|
2633
|
+
const typeParams = (st.typeParameters ?? []).filter((tp) => !tp.default).length;
|
|
2634
|
+
const d = { className: st.name.text, file, selector: selector && ts.isStringLiteralLike(selector) ? selector.text : '', inputs: new Map(), listeners: [], bindings: [], attributes: [], create: false, hooks: new Set(), structural: false, signals: new Set(), members: st.members.flatMap((m) => (m.name && ts.isIdentifier(m.name) ? [m.name.text] : [])), ...(exportAs?.length ? { exportAs } : {}), ...(typeParams ? { typeParams } : {}) };
|
|
2635
|
+
for (const p of meta && ts.isObjectLiteralExpression(meta) ? meta.properties : []) {
|
|
1751
2636
|
const key = ts.isPropertyAssignment(p) ? p.name.getText() : p.getText();
|
|
1752
|
-
if (!['selector', 'inputs', 'host', 'standalone', 'jit'].includes(key))
|
|
2637
|
+
if (!['selector', 'inputs', 'host', 'standalone', 'jit', 'hostDirectives', 'providers', 'exportAs'].includes(key))
|
|
1753
2638
|
throw new Error(`${where}: its ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
|
|
1754
2639
|
}
|
|
1755
2640
|
const inputs = get('inputs');
|
|
@@ -1775,17 +2660,35 @@ export function angularDirectives(files, read) {
|
|
|
1775
2660
|
for (const m of st.members) {
|
|
1776
2661
|
const name = m.name && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined;
|
|
1777
2662
|
const made = ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer) ? m.initializer.expression.getText() : '';
|
|
1778
|
-
if (made === 'input' && name) {
|
|
1779
|
-
const
|
|
1780
|
-
const
|
|
2663
|
+
if ((made === 'input' || made === 'input.required' || made === 'model' || made === 'model.required') && name) {
|
|
2664
|
+
const callExpr = m.initializer;
|
|
2665
|
+
const options = callExpr.arguments[made.endsWith('.required') ? 0 : 1];
|
|
2666
|
+
const bad = options && (!ts.isObjectLiteralExpression(options) ? options : options.properties.find((p) => !ts.isPropertyAssignment(p) || !['alias', 'debugName', 'transform'].includes(p.name.getText())));
|
|
1781
2667
|
if (bad)
|
|
1782
|
-
throw new Error(`${where}:
|
|
1783
|
-
const
|
|
1784
|
-
|
|
2668
|
+
throw new Error(`${where}: ${made}()'s ${ts.isObjectLiteralElementLike(bad) && bad.name ? bad.name.getText() : bad.getText()} (${name}) is not supported in a release build yet`);
|
|
2669
|
+
const optProp = (k) => (options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
|
|
2670
|
+
const alias = optProp('alias');
|
|
2671
|
+
const pubName = alias && ts.isStringLiteralLike(alias) ? alias.text : name;
|
|
2672
|
+
d.inputs.set(pubName, name);
|
|
1785
2673
|
d.signals.add(name);
|
|
2674
|
+
const transform = optProp('transform');
|
|
2675
|
+
if (transform)
|
|
2676
|
+
(d.transforms ??= new Map()).set(name, transform.getText(sf));
|
|
2677
|
+
if (made === 'model' || made === 'model.required')
|
|
2678
|
+
(d.outputs ??= new Map()).set(`${pubName}Change`, name);
|
|
2679
|
+
}
|
|
2680
|
+
else if (made === 'output' && name) {
|
|
2681
|
+
const callExpr = m.initializer;
|
|
2682
|
+
const options = callExpr.arguments[0];
|
|
2683
|
+
const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
|
|
2684
|
+
(d.outputs ??= new Map()).set(alias && ts.isStringLiteralLike(alias) ? alias.text : name, name);
|
|
1786
2685
|
}
|
|
1787
|
-
else if (/^(
|
|
2686
|
+
else if (/^(viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(made) && name) {
|
|
2687
|
+
// Signal queries compile as signals on the directive class.
|
|
2688
|
+
}
|
|
2689
|
+
else if (/^(input|model|output|viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(made)) {
|
|
1788
2690
|
throw new Error(`${where}: ${made}() (${name}) in a directive is not supported in a release build yet`);
|
|
2691
|
+
}
|
|
1789
2692
|
if (ts.isMethodDeclaration(m) && name && /^ng(OnInit|OnChanges|AfterViewInit|OnDestroy|DoCheck|AfterContentInit|AfterContentChecked|AfterViewChecked)$/.test(name)) {
|
|
1790
2693
|
d.hooks.add(name);
|
|
1791
2694
|
}
|
|
@@ -1799,6 +2702,10 @@ export function angularDirectives(files, read) {
|
|
|
1799
2702
|
const alias = arg && ts.isStringLiteralLike(arg) ? arg.text : arg && ts.isObjectLiteralExpression(arg) ? arg.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer?.text : undefined;
|
|
1800
2703
|
d.inputs.set(alias ?? name, name);
|
|
1801
2704
|
}
|
|
2705
|
+
else if (which === 'Output') {
|
|
2706
|
+
const alias = arg && ts.isStringLiteralLike(arg) ? arg.text : undefined;
|
|
2707
|
+
(d.outputs ??= new Map()).set(alias ?? name, name);
|
|
2708
|
+
}
|
|
1802
2709
|
else if (which === 'HostListener') {
|
|
1803
2710
|
if (!arg || !ts.isStringLiteralLike(arg) || !ts.isMethodDeclaration(m))
|
|
1804
2711
|
throw new Error(`${where}: @HostListener takes an event name, on a method`);
|
|
@@ -1812,13 +2719,23 @@ export function angularDirectives(files, read) {
|
|
|
1812
2719
|
const prop = arg && ts.isStringLiteralLike(arg) ? arg.text : name;
|
|
1813
2720
|
d.bindings.push({ prop, code: name });
|
|
1814
2721
|
}
|
|
1815
|
-
else
|
|
2722
|
+
else if (!['ContentChild', 'ContentChildren', 'ViewChild', 'ViewChildren'].includes(which)) {
|
|
1816
2723
|
throw new Error(`${where}: @${which} is not supported in a release build yet`);
|
|
2724
|
+
}
|
|
1817
2725
|
}
|
|
1818
2726
|
}
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
2727
|
+
const plainBindings = [];
|
|
2728
|
+
for (const b of d.bindings) {
|
|
2729
|
+
if (b.prop.startsWith('attr.'))
|
|
2730
|
+
plainBindings.push({ prop: b.prop.slice(5), code: b.code });
|
|
2731
|
+
else if (b.prop.startsWith('style.'))
|
|
2732
|
+
(d.styleBindings ??= []).push({ prop: b.prop.slice(6), code: b.code });
|
|
2733
|
+
else if (b.prop.startsWith('class.'))
|
|
2734
|
+
(d.classBindings ??= []).push({ name: b.prop.slice(6), code: b.code });
|
|
2735
|
+
else
|
|
2736
|
+
plainBindings.push(b);
|
|
2737
|
+
}
|
|
2738
|
+
d.bindings = plainBindings;
|
|
1822
2739
|
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
1823
2740
|
d.create = !!ctor?.parameters.length;
|
|
1824
2741
|
d.structural = /\bTemplateRef\b/.test(ctor?.getText() ?? '') || /inject\(\s*TemplateRef\b/.test(st.getText());
|
|
@@ -1846,16 +2763,41 @@ export function declarableSource(path, text) {
|
|
|
1846
2763
|
const own = ts.getDecorators(st)?.find((d) => ts.isCallExpression(d.expression) && ['Pipe', 'Directive'].includes(d.expression.expression.getText()));
|
|
1847
2764
|
if (!own)
|
|
1848
2765
|
continue;
|
|
1849
|
-
edits.push({ start: own.getStart(), end: own.getEnd(), text: '' });
|
|
1850
|
-
// A directive's member decorators (@Input, @HostListener, @HostBinding) are the template compiler's to read
|
|
1851
|
-
|
|
2766
|
+
edits.push({ start: own.getStart(), end: own.getEnd(), text: st.typeParameters?.length ? '/* @ng-declarable */' : '' });
|
|
2767
|
+
// A directive's member decorators (@Input, @HostListener, @HostBinding) are the template compiler's to read,
|
|
2768
|
+
// and a concrete directive's `protected` members must be accessible to host bindings/listeners generated in host components.
|
|
2769
|
+
const isAbstract = (ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.AbstractKeyword);
|
|
2770
|
+
for (const m of st.members) {
|
|
1852
2771
|
for (const d of ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : [])
|
|
1853
2772
|
edits.push({ start: d.getStart(), end: d.getEnd(), text: '' });
|
|
2773
|
+
if (!isAbstract) {
|
|
2774
|
+
for (const mod of ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : []) {
|
|
2775
|
+
if (mod.kind === ts.SyntaxKind.ProtectedKeyword)
|
|
2776
|
+
edits.push({ start: mod.getStart(), end: mod.getEnd(), text: 'public' });
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
1854
2780
|
const onChanges = st.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnChanges');
|
|
1855
2781
|
if (onChanges) {
|
|
1856
2782
|
changes = true;
|
|
1857
2783
|
edits.push({ start: st.members.end, end: st.members.end, text: '\n' + changesMembers(onChanges.parameters.length > 0).join('\n') + '\n' });
|
|
1858
2784
|
}
|
|
2785
|
+
// Emit `$set_<prop>` helpers for directive signal inputs with `{ transform }`.
|
|
2786
|
+
for (const m of st.members) {
|
|
2787
|
+
if (!ts.isPropertyDeclaration(m) || !m.initializer || !ts.isCallExpression(m.initializer))
|
|
2788
|
+
continue;
|
|
2789
|
+
const made = m.initializer.expression.getText();
|
|
2790
|
+
if (made !== 'input' && made !== 'input.required')
|
|
2791
|
+
continue;
|
|
2792
|
+
const mName = m.name && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined;
|
|
2793
|
+
const opts = m.initializer.arguments[made === 'input.required' ? 0 : 1];
|
|
2794
|
+
const tr = opts && ts.isObjectLiteralExpression(opts) ? opts.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'transform')?.initializer : undefined;
|
|
2795
|
+
if (mName && tr) {
|
|
2796
|
+
const fn = tr.getText(sf).trim();
|
|
2797
|
+
const call = /^[A-Za-z_$][\w$.]*$/.test(fn) ? `${fn}(value)` : `(${fn})(value)`;
|
|
2798
|
+
edits.push({ start: st.members.end, end: st.members.end, text: `\n $set_${mName}(value: any): void { this.${mName}.$assign(${call}); }\n` });
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
1859
2801
|
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
1860
2802
|
if (!ctor?.parameters.length)
|
|
1861
2803
|
continue;
|
|
@@ -1922,6 +2864,7 @@ function classicClass(path, text, cls) {
|
|
|
1922
2864
|
const aliases = new Map();
|
|
1923
2865
|
const optional = new Set();
|
|
1924
2866
|
const queries = [];
|
|
2867
|
+
const contentQueries = [];
|
|
1925
2868
|
const used = new Set();
|
|
1926
2869
|
const injected = [];
|
|
1927
2870
|
let ctor;
|
|
@@ -1984,9 +2927,10 @@ function classicClass(path, text, cls) {
|
|
|
1984
2927
|
edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = output<${init.typeArguments?.[0]?.getText() ?? 'void'}>();` });
|
|
1985
2928
|
used.add('output');
|
|
1986
2929
|
}
|
|
1987
|
-
else if (which === 'ViewChild' || which === 'ViewChildren') {
|
|
2930
|
+
else if (which === 'ViewChild' || which === 'ViewChildren' || which === 'ContentChild' || which === 'ContentChildren') {
|
|
2931
|
+
const isContent = which === 'ContentChild' || which === 'ContentChildren';
|
|
1988
2932
|
const [what, options] = d.arguments;
|
|
1989
|
-
const query = { field: name, read: null, static: false, many: which === 'ViewChildren' };
|
|
2933
|
+
const query = { field: name, read: null, static: false, many: which === 'ViewChildren' || which === 'ContentChildren', ...(isContent ? { descendants: which === 'ContentChild' } : {}) };
|
|
1990
2934
|
if (what && ts.isStringLiteralLike(what)) {
|
|
1991
2935
|
if (what.text.includes(','))
|
|
1992
2936
|
throw new Error(`${path}: @${which}('${what.text}'), a query of several names, is not supported in a release build yet`);
|
|
@@ -2001,6 +2945,8 @@ function classicClass(path, text, cls) {
|
|
|
2001
2945
|
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
2002
2946
|
if (key === 'static' && value)
|
|
2003
2947
|
query.static = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
2948
|
+
else if (key === 'descendants' && isContent && value)
|
|
2949
|
+
query.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
2004
2950
|
else if (key === 'read' && value && ts.isIdentifier(value))
|
|
2005
2951
|
query.read = value.text;
|
|
2006
2952
|
else
|
|
@@ -2008,9 +2954,9 @@ function classicClass(path, text, cls) {
|
|
|
2008
2954
|
}
|
|
2009
2955
|
if (options && !ts.isObjectLiteralExpression(options))
|
|
2010
2956
|
throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
|
|
2011
|
-
if (query.read && /^(ViewContainerRef|
|
|
2957
|
+
if (query.read && /^(ViewContainerRef|ChangeDetectorRef|Injector)$/.test(query.read))
|
|
2012
2958
|
throw new Error(`${path}: @${which}'s read: ${query.read} (${name}) is not supported in a release build yet`);
|
|
2013
|
-
queries.push(query);
|
|
2959
|
+
(isContent ? contentQueries : queries).push(query);
|
|
2014
2960
|
const decorator = ts.getDecorators(m)[0];
|
|
2015
2961
|
if (query.many) {
|
|
2016
2962
|
// A QueryList the template's matches are added to and removed from, in the order they render.
|
|
@@ -2045,6 +2991,55 @@ function classicClass(path, text, cls) {
|
|
|
2045
2991
|
}
|
|
2046
2992
|
if (decorators.length)
|
|
2047
2993
|
throw new Error(`${path}: @${decorators[0].getText()} is not supported in a release build yet`);
|
|
2994
|
+
if (ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer)) {
|
|
2995
|
+
const callee = m.initializer.expression.getText();
|
|
2996
|
+
if (callee === 'viewChild' || callee === 'viewChild.required' || callee === 'viewChildren' || callee === 'contentChild' || callee === 'contentChild.required' || callee === 'contentChildren') {
|
|
2997
|
+
const isContent = callee.startsWith('content');
|
|
2998
|
+
const isMany = callee === 'viewChildren' || callee === 'contentChildren';
|
|
2999
|
+
const isRequired = callee.endsWith('.required');
|
|
3000
|
+
const name = m.name.getText();
|
|
3001
|
+
const [what, options] = m.initializer.arguments;
|
|
3002
|
+
const query = { field: name, read: null, static: false, many: isMany, signal: true, ...(isContent ? { descendants: !isMany } : {}) };
|
|
3003
|
+
if (what && ts.isStringLiteralLike(what)) {
|
|
3004
|
+
if (what.text.includes(','))
|
|
3005
|
+
throw new Error(`${path}: ${callee}('${what.text}'), a query of several names, is not supported in a release build yet`);
|
|
3006
|
+
query.ref = what.text.trim();
|
|
3007
|
+
}
|
|
3008
|
+
else if (what && ts.isIdentifier(what))
|
|
3009
|
+
query.type = what.text;
|
|
3010
|
+
else
|
|
3011
|
+
throw new Error(`${path}: ${callee}() (${name}) needs a ref name or class in a release build`);
|
|
3012
|
+
for (const p of options && ts.isObjectLiteralExpression(options) ? options.properties : []) {
|
|
3013
|
+
const key = p.name?.getText();
|
|
3014
|
+
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
3015
|
+
if (key === 'read' && value && (ts.isIdentifier(value) || (ts.isExpressionWithTypeArguments(value) && ts.isIdentifier(value.expression)))) {
|
|
3016
|
+
query.read = ts.isIdentifier(value) ? value.text : value.expression.text;
|
|
3017
|
+
}
|
|
3018
|
+
else if (key === 'descendants' && isContent && value) {
|
|
3019
|
+
query.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
3020
|
+
}
|
|
3021
|
+
else if (key === 'debugName')
|
|
3022
|
+
continue;
|
|
3023
|
+
else
|
|
3024
|
+
throw new Error(`${path}: ${callee}()'s ${p.getText()} (${name}) is not supported in a release build yet`);
|
|
3025
|
+
}
|
|
3026
|
+
if (options && !ts.isObjectLiteralExpression(options))
|
|
3027
|
+
throw new Error(`${path}: ${callee}() (${name}) options are read as an object literal in a release build`);
|
|
3028
|
+
if (query.read && /^(ViewContainerRef|ChangeDetectorRef|Injector)$/.test(query.read))
|
|
3029
|
+
throw new Error(`${path}: ${callee}()'s read: ${query.read} (${name}) is not supported in a release build yet`);
|
|
3030
|
+
const typeArg = m.initializer.typeArguments?.[0]?.getText() ?? (query.read === 'ElementRef' ? 'ElementRef' : query.type ?? 'any');
|
|
3031
|
+
query.typeArg = typeArg;
|
|
3032
|
+
(isContent ? contentQueries : queries).push(query);
|
|
3033
|
+
const sigInit = isMany
|
|
3034
|
+
? `signal<${typeArg}[]>([])`
|
|
3035
|
+
: isRequired
|
|
3036
|
+
? `signal<${typeArg}>(undefined as any)`
|
|
3037
|
+
: `signal<${typeArg} | undefined>(undefined)`;
|
|
3038
|
+
edits.push({ start: m.initializer.getStart(), end: m.initializer.getEnd(), text: sigInit });
|
|
3039
|
+
used.add('signal');
|
|
3040
|
+
continue;
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
2048
3043
|
if (ts.isConstructorDeclaration(m)) {
|
|
2049
3044
|
// A body without parameters is the translator's: it runs after the field initializers, as TypeScript runs it.
|
|
2050
3045
|
if (!m.parameters.length)
|
|
@@ -2158,7 +3153,8 @@ function classicClass(path, text, cls) {
|
|
|
2158
3153
|
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
2159
3154
|
const imported = new Set(cls.getSourceFile().statements.flatMap((st) => ts.isImportDeclaration(st) && st.importClause?.namedBindings && ts.isNamedImports(st.importClause.namedBindings) ? st.importClause.namedBindings.elements.map((e) => e.name.text) : []));
|
|
2160
3155
|
const missing = [...used].filter((u) => !imported.has(u));
|
|
2161
|
-
|
|
3156
|
+
const prependedLines = missing.length ? 1 : 0;
|
|
3157
|
+
return { text: (missing.length ? `import { ${missing.join(', ')} } from '@angular/core';\n` : '') + out, prependedLines, inputs, setters, aliases, optional, queries, contentQueries, host };
|
|
2162
3158
|
}
|
|
2163
3159
|
function literalType(e) {
|
|
2164
3160
|
if (!e)
|
|
@@ -2185,10 +3181,36 @@ function literalKey(code, path) {
|
|
|
2185
3181
|
export function declarablesIn(path, text, app = false) {
|
|
2186
3182
|
const classes = [];
|
|
2187
3183
|
const modules = new Map();
|
|
2188
|
-
|
|
3184
|
+
const hasImportArrays = /export\s+const\s+\w+\s*=\s*\[/.test(text);
|
|
3185
|
+
if (!/@(Pipe|NgModule)\b/.test(text) && !hasImportArrays)
|
|
2189
3186
|
return { classes, modules };
|
|
2190
3187
|
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
|
|
3188
|
+
const unwrap = (e) => (ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isParenthesizedExpression(e) ? unwrap(e.expression) : e);
|
|
2191
3189
|
for (const st of sf.statements) {
|
|
3190
|
+
if (ts.isVariableStatement(st) && (ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
3191
|
+
for (const d of st.declarationList.declarations) {
|
|
3192
|
+
if (!ts.isIdentifier(d.name) || !d.initializer)
|
|
3193
|
+
continue;
|
|
3194
|
+
const arr = unwrap(d.initializer);
|
|
3195
|
+
if (!ts.isArrayLiteralExpression(arr) || !arr.elements.length)
|
|
3196
|
+
continue;
|
|
3197
|
+
const names = [];
|
|
3198
|
+
let ok = true;
|
|
3199
|
+
for (const el of arr.elements) {
|
|
3200
|
+
if (ts.isIdentifier(el))
|
|
3201
|
+
names.push(el.text);
|
|
3202
|
+
else if (ts.isSpreadElement(el) && ts.isIdentifier(el.expression))
|
|
3203
|
+
names.push(el.expression.text);
|
|
3204
|
+
else {
|
|
3205
|
+
ok = false;
|
|
3206
|
+
break;
|
|
3207
|
+
}
|
|
3208
|
+
}
|
|
3209
|
+
if (ok && names.length)
|
|
3210
|
+
modules.set(d.name.text, names);
|
|
3211
|
+
}
|
|
3212
|
+
continue;
|
|
3213
|
+
}
|
|
2192
3214
|
if (!ts.isClassDeclaration(st) || !st.name)
|
|
2193
3215
|
continue;
|
|
2194
3216
|
if (decorator(st, 'Pipe'))
|
|
@@ -2202,7 +3224,7 @@ export function declarablesIn(path, text, app = false) {
|
|
|
2202
3224
|
throw new Error(`${path}: the NgModule ${st.name.text}'s ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
|
|
2203
3225
|
}
|
|
2204
3226
|
modules.set(st.name.text, meta.properties.flatMap((p) => (ts.isPropertyAssignment(p) && ['declarations', 'imports', 'exports'].includes(p.name.getText()) && ts.isArrayLiteralExpression(p.initializer)
|
|
2205
|
-
? p.initializer.elements.
|
|
3227
|
+
? p.initializer.elements.flatMap((e) => ts.isIdentifier(e) ? [e.text] : ts.isSpreadElement(e) && ts.isIdentifier(e.expression) ? [e.expression.text] : []) : [])));
|
|
2206
3228
|
}
|
|
2207
3229
|
}
|
|
2208
3230
|
return { classes, modules };
|
|
@@ -2214,14 +3236,13 @@ function publicMembers(path, cls, classic) {
|
|
|
2214
3236
|
const optional = [];
|
|
2215
3237
|
const outputs = [];
|
|
2216
3238
|
const inputAliases = {};
|
|
3239
|
+
const inputTransforms = new Map();
|
|
2217
3240
|
for (const m of cls.members) {
|
|
2218
3241
|
if (!m.name || !ts.isIdentifier(m.name))
|
|
2219
3242
|
continue;
|
|
2220
3243
|
members.add(m.name.text);
|
|
2221
3244
|
if (ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer)) {
|
|
2222
3245
|
const callee = m.initializer.expression.getText();
|
|
2223
|
-
if (/^(viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(callee))
|
|
2224
|
-
throw new Error(`${path}: the signal query ${callee}() (${m.name.text}) is not supported in a release build yet`);
|
|
2225
3246
|
const optionsOf = (k, allowed) => {
|
|
2226
3247
|
const o = m.initializer.arguments[k];
|
|
2227
3248
|
if (!o)
|
|
@@ -2235,11 +3256,15 @@ function publicMembers(path, cls, classic) {
|
|
|
2235
3256
|
optionsOf(0, []);
|
|
2236
3257
|
if (callee === 'input' || callee === 'input.required' || callee === 'model' || callee === 'model.required') {
|
|
2237
3258
|
props.push(m.name.text);
|
|
2238
|
-
// `input(init, { alias })`, `input.required({ alias })`: the name the parent binds.
|
|
2239
|
-
const
|
|
3259
|
+
// `input(init, { alias, transform })`, `input.required({ alias, transform })`: the name the parent binds and optional transform.
|
|
3260
|
+
const isInput = callee === 'input' || callee === 'input.required';
|
|
3261
|
+
const options = optionsOf(callee === 'input' || callee === 'model' ? 1 : 0, isInput ? ['alias', 'debugName', 'transform'] : ['alias', 'debugName']);
|
|
2240
3262
|
const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
|
|
2241
3263
|
if (alias && ts.isStringLiteralLike(alias))
|
|
2242
3264
|
inputAliases[m.name.text] = alias.text;
|
|
3265
|
+
const transform = isInput && options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'transform')?.initializer : undefined;
|
|
3266
|
+
if (transform)
|
|
3267
|
+
inputTransforms.set(m.name.text, transform.getText());
|
|
2243
3268
|
}
|
|
2244
3269
|
// An input with a default value (or `input<T>()` with implicit undefined) is one a parent may leave out.
|
|
2245
3270
|
if (callee === 'input' || callee === 'model')
|
|
@@ -2254,50 +3279,158 @@ function publicMembers(path, cls, classic) {
|
|
|
2254
3279
|
props.push(name);
|
|
2255
3280
|
optional.push(name);
|
|
2256
3281
|
}
|
|
2257
|
-
return { members, props, optional, outputs, inputAliases };
|
|
3282
|
+
return { members, props, optional, outputs, inputAliases, inputTransforms };
|
|
3283
|
+
}
|
|
3284
|
+
/** Every attribute-selected component in `path` as an element hosting it sees it. */
|
|
3285
|
+
export function hostedComponents(path, text) {
|
|
3286
|
+
const out = [];
|
|
3287
|
+
for (const found of componentsOf(path, text)) {
|
|
3288
|
+
if (!found.selector || !ng.CssSelector.parse(found.selector).some((s) => s.attrs.length || s.classNames.length))
|
|
3289
|
+
continue;
|
|
3290
|
+
let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
3291
|
+
const named = (f) => f.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === found.name);
|
|
3292
|
+
let cls = named(sf);
|
|
3293
|
+
const meta = decorator(cls, 'Component').arguments[0];
|
|
3294
|
+
const hostMeta = !!meta && ts.isObjectLiteralExpression(meta) && meta.properties.some((p) => p.name?.getText() === 'host');
|
|
3295
|
+
const hostDecorators = cls.members.some((m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).some((d) => /^(HostBinding|HostListener)\b/.test(d.expression.getText())));
|
|
3296
|
+
const classic = classicClass(path, text, cls);
|
|
3297
|
+
if (classic)
|
|
3298
|
+
cls = named((sf = ts.createSourceFile(path, classic.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
|
|
3299
|
+
const api = publicMembers(path, cls, classic);
|
|
3300
|
+
const models = cls.members.filter((m) => ts.isPropertyDeclaration(m) && !!m.initializer && ts.isCallExpression(m.initializer) && /^model(\.required)?$/.test(m.initializer.expression.getText())).map((m) => m.name.getText());
|
|
3301
|
+
out.push({
|
|
3302
|
+
name: found.name,
|
|
3303
|
+
selector: found.selector,
|
|
3304
|
+
inputs: new Set(api.props.map((p) => api.inputAliases[p] ?? p)),
|
|
3305
|
+
outputs: new Set(api.outputs),
|
|
3306
|
+
models: new Set(models),
|
|
3307
|
+
readsHost: hostMeta || hostDecorators || !!classic?.host || /\binject\(\s*ElementRef\b/.test(cls.getText()),
|
|
3308
|
+
...(found.slots?.length ? { slots: found.slots } : {}),
|
|
3309
|
+
});
|
|
3310
|
+
}
|
|
3311
|
+
return out;
|
|
2258
3312
|
}
|
|
2259
3313
|
/** A file's component as an element hosting it sees it, when its selector names attributes. */
|
|
2260
3314
|
export function hostedComponent(path, text) {
|
|
2261
|
-
|
|
2262
|
-
if (!found?.selector || !ng.CssSelector.parse(found.selector).some((s) => s.attrs.length || s.classNames.length))
|
|
2263
|
-
return null;
|
|
2264
|
-
let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
2265
|
-
const named = (f) => f.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === found.name);
|
|
2266
|
-
let cls = named(sf);
|
|
2267
|
-
const meta = decorator(cls, 'Component').arguments[0];
|
|
2268
|
-
const hostMeta = !!meta && ts.isObjectLiteralExpression(meta) && meta.properties.some((p) => p.name?.getText() === 'host');
|
|
2269
|
-
const hostDecorators = cls.members.some((m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).some((d) => /^(HostBinding|HostListener)\b/.test(d.expression.getText())));
|
|
2270
|
-
const classic = classicClass(path, text, cls);
|
|
2271
|
-
if (classic)
|
|
2272
|
-
cls = named((sf = ts.createSourceFile(path, classic.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
|
|
2273
|
-
const api = publicMembers(path, cls, classic);
|
|
2274
|
-
const models = cls.members.filter((m) => ts.isPropertyDeclaration(m) && !!m.initializer && ts.isCallExpression(m.initializer) && /^model(\.required)?$/.test(m.initializer.expression.getText())).map((m) => m.name.getText());
|
|
2275
|
-
return {
|
|
2276
|
-
name: found.name,
|
|
2277
|
-
selector: found.selector,
|
|
2278
|
-
inputs: new Set(api.props.map((p) => api.inputAliases[p] ?? p)),
|
|
2279
|
-
outputs: new Set(api.outputs),
|
|
2280
|
-
models: new Set(models),
|
|
2281
|
-
readsHost: hostMeta || hostDecorators || !!classic?.host || /\binject\(\s*ElementRef\b/.test(cls.getText()),
|
|
2282
|
-
};
|
|
3315
|
+
return hostedComponents(path, text)[0] ?? null;
|
|
2283
3316
|
}
|
|
2284
3317
|
/** The element names a component's selector matches (`resource, [talkResource]` is `<resource>`; its attribute is `hostedComponent`'s). */
|
|
2285
3318
|
export function selectorElements(selector) {
|
|
2286
3319
|
return ng.CssSelector.parse(selector).flatMap((s) => (s.element && s.element !== '*' && !s.attrs.length && !s.classNames.length && !s.notSelectors.length ? [s.element] : []));
|
|
2287
3320
|
}
|
|
2288
|
-
/**
|
|
2289
|
-
|
|
3321
|
+
/** Extracts `<ng-content>` slot names from a template string. */
|
|
3322
|
+
function templateSlots(path, template) {
|
|
3323
|
+
if (!template.includes('ng-content'))
|
|
3324
|
+
return [];
|
|
3325
|
+
const parsed = ng.parseTemplate(template, path + '.html', { preserveWhitespaces: false });
|
|
3326
|
+
const slots = new Set();
|
|
3327
|
+
const walk = (list) => {
|
|
3328
|
+
for (const n of list) {
|
|
3329
|
+
if (n instanceof ng.TmplAstContent)
|
|
3330
|
+
slots.add(!n.selector || n.selector === '*' ? 'default' : n.selector);
|
|
3331
|
+
if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
|
|
3332
|
+
walk(n.children);
|
|
3333
|
+
if (n instanceof ng.TmplAstIfBlock)
|
|
3334
|
+
for (const b of n.branches)
|
|
3335
|
+
walk(b.children);
|
|
3336
|
+
if (n instanceof ng.TmplAstForLoopBlock && n.empty)
|
|
3337
|
+
walk(n.empty.children);
|
|
3338
|
+
if (n instanceof ng.TmplAstSwitchBlock)
|
|
3339
|
+
for (const g of n.groups)
|
|
3340
|
+
walk(g.children);
|
|
3341
|
+
}
|
|
3342
|
+
};
|
|
3343
|
+
walk(parsed.nodes);
|
|
3344
|
+
return [...slots];
|
|
3345
|
+
}
|
|
3346
|
+
/** Extracts declared content queries (`contentChild`, `contentChildren`, `@ContentChild`, `@ContentChildren`) on `cls`. */
|
|
3347
|
+
function classContentQueries(cls) {
|
|
3348
|
+
const out = [];
|
|
3349
|
+
for (const m of cls.members) {
|
|
3350
|
+
if (!ts.isPropertyDeclaration(m) || !m.name)
|
|
3351
|
+
continue;
|
|
3352
|
+
const field = m.name.getText();
|
|
3353
|
+
const decs = ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : [];
|
|
3354
|
+
for (const dec of decs) {
|
|
3355
|
+
if (!ts.isCallExpression(dec.expression))
|
|
3356
|
+
continue;
|
|
3357
|
+
const which = dec.expression.expression.getText();
|
|
3358
|
+
if (which !== 'ContentChild' && which !== 'ContentChildren')
|
|
3359
|
+
continue;
|
|
3360
|
+
const [what, opts] = dec.expression.arguments;
|
|
3361
|
+
const q = { field, read: null, static: false, many: which === 'ContentChildren', descendants: which === 'ContentChild' };
|
|
3362
|
+
if (what && ts.isStringLiteralLike(what))
|
|
3363
|
+
q.ref = what.text.trim();
|
|
3364
|
+
else if (what && ts.isIdentifier(what))
|
|
3365
|
+
q.type = what.text;
|
|
3366
|
+
else
|
|
3367
|
+
continue;
|
|
3368
|
+
for (const p of opts && ts.isObjectLiteralExpression(opts) ? opts.properties : []) {
|
|
3369
|
+
const key = p.name?.getText();
|
|
3370
|
+
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
3371
|
+
if (key === 'descendants' && value)
|
|
3372
|
+
q.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
3373
|
+
else if (key === 'read' && value && ts.isIdentifier(value))
|
|
3374
|
+
q.read = value.text;
|
|
3375
|
+
}
|
|
3376
|
+
out.push(q);
|
|
3377
|
+
}
|
|
3378
|
+
if (m.initializer && ts.isCallExpression(m.initializer)) {
|
|
3379
|
+
const callee = m.initializer.expression.getText();
|
|
3380
|
+
if (callee === 'contentChild' || callee === 'contentChild.required' || callee === 'contentChildren') {
|
|
3381
|
+
const [what, opts] = m.initializer.arguments;
|
|
3382
|
+
const isMany = callee === 'contentChildren';
|
|
3383
|
+
const q = { field, read: null, static: false, many: isMany, signal: true, descendants: !isMany };
|
|
3384
|
+
if (what && ts.isStringLiteralLike(what))
|
|
3385
|
+
q.ref = what.text.trim();
|
|
3386
|
+
else if (what && ts.isIdentifier(what))
|
|
3387
|
+
q.type = what.text;
|
|
3388
|
+
else
|
|
3389
|
+
continue;
|
|
3390
|
+
for (const p of opts && ts.isObjectLiteralExpression(opts) ? opts.properties : []) {
|
|
3391
|
+
const key = p.name?.getText();
|
|
3392
|
+
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
3393
|
+
if (key === 'descendants' && value)
|
|
3394
|
+
q.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
3395
|
+
else if (key === 'read' && value && (ts.isIdentifier(value) || (ts.isExpressionWithTypeArguments(value) && ts.isIdentifier(value.expression)))) {
|
|
3396
|
+
q.read = ts.isIdentifier(value) ? value.text : value.expression.text;
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
out.push(q);
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
return out;
|
|
3404
|
+
}
|
|
3405
|
+
/** Every `@Component` class in `path`, with its selector, declared `<ng-content>` slots, and content queries. */
|
|
3406
|
+
export function componentsOf(path, text) {
|
|
2290
3407
|
if (!text.includes('@Component'))
|
|
2291
|
-
return
|
|
3408
|
+
return [];
|
|
2292
3409
|
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
3410
|
+
const out = [];
|
|
2293
3411
|
for (const st of sf.statements) {
|
|
2294
3412
|
const meta = ts.isClassDeclaration(st) && st.name ? decorator(st, 'Component')?.arguments[0] : undefined;
|
|
2295
|
-
if (!meta)
|
|
3413
|
+
if (!meta || !ts.isClassDeclaration(st) || !st.name)
|
|
2296
3414
|
continue;
|
|
2297
|
-
const
|
|
2298
|
-
|
|
3415
|
+
const get = (k) => (ts.isObjectLiteralExpression(meta) ? meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
|
|
3416
|
+
const selector = get('selector');
|
|
3417
|
+
const inline = get('template');
|
|
3418
|
+
const templateUrl = get('templateUrl');
|
|
3419
|
+
const tpl = inline && ts.isStringLiteralLike(inline) ? inline.text : templateUrl && ts.isStringLiteralLike(templateUrl) && existsSync(join(dirname(path), templateUrl.text)) ? readFileSync(join(dirname(path), templateUrl.text), 'utf8') : '';
|
|
3420
|
+
const slots = templateSlots(path, tpl);
|
|
3421
|
+
const contentQueries = classContentQueries(st);
|
|
3422
|
+
out.push({
|
|
3423
|
+
name: st.name.text,
|
|
3424
|
+
selector: selector && ts.isStringLiteralLike(selector) ? selector.text : undefined,
|
|
3425
|
+
...(slots.length ? { slots } : {}),
|
|
3426
|
+
...(contentQueries.length ? { contentQueries } : {}),
|
|
3427
|
+
});
|
|
2299
3428
|
}
|
|
2300
|
-
return
|
|
3429
|
+
return out;
|
|
3430
|
+
}
|
|
3431
|
+
/** A file's first `@Component` class and the selector it declares. */
|
|
3432
|
+
export function componentOf(path, text) {
|
|
3433
|
+
return componentsOf(path, text)[0] ?? null;
|
|
2301
3434
|
}
|
|
2302
3435
|
/** @nativescript/angular's platform filters (`<android>`, `<ios>`, `<apple>`) and the platforms each renders its content on. */
|
|
2303
3436
|
const PLATFORM_FILTERS = { android: ['android'], ios: ['ios'], apple: ['ios'] };
|
|
@@ -2310,16 +3443,23 @@ const ROUTER_LINK_SUPPORTED = new Set(['nsRouterLink', 'relativeTo', 'clearHisto
|
|
|
2310
3443
|
* `@Component({ providers })`: the component's own injector, made by its first field and current until its constructor
|
|
2311
3444
|
* returns, so that its fields and constructor inject from it as its view does.
|
|
2312
3445
|
*/
|
|
2313
|
-
function withInjector(path, text, cls, providers) {
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
3446
|
+
function withInjector(path, text, cls, providers, viewProviders) {
|
|
3447
|
+
const hasExtends = !!cls.heritageClauses?.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
|
|
3448
|
+
const lists = [
|
|
3449
|
+
...(providers ? [{ expr: providers, field: 'providers' }] : []),
|
|
3450
|
+
...(viewProviders ? [{ expr: viewProviders, field: 'viewProviders' }] : []),
|
|
3451
|
+
];
|
|
3452
|
+
const items = [];
|
|
3453
|
+
for (const { expr: list, field } of lists) {
|
|
3454
|
+
if (!ts.isArrayLiteralExpression(list))
|
|
3455
|
+
throw new Error(`${path}: @Component's ${field} are read as an array literal in a release build`);
|
|
3456
|
+
for (const e of list.elements) {
|
|
3457
|
+
checkProvider(path, e, field);
|
|
3458
|
+
items.push(e.getText());
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
const leave = 'this.$injector.provideSelf(this); this.$injector.leave();';
|
|
3462
|
+
const edits = [{ at: cls.members.pos, text: `\n readonly $injector = NodeInjector.enter([${items.join(', ')}]);` }];
|
|
2323
3463
|
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
2324
3464
|
if (ctor?.body) {
|
|
2325
3465
|
const returns = (n) => {
|
|
@@ -2334,7 +3474,7 @@ function withInjector(path, text, cls, providers) {
|
|
|
2334
3474
|
edits.push({ at: ctor.body.getEnd() - 1, text: `${leave} ` });
|
|
2335
3475
|
}
|
|
2336
3476
|
else
|
|
2337
|
-
edits.push({ at: cls.members.end, text: `\n constructor() { ${leave} }\n` });
|
|
3477
|
+
edits.push({ at: cls.members.end, text: `\n constructor() { ${hasExtends ? 'super(); ' : ''}${leave} }\n` });
|
|
2338
3478
|
let out = text;
|
|
2339
3479
|
for (const e of edits.sort((a, b) => b.at - a.at))
|
|
2340
3480
|
out = out.slice(0, e.at) + e.text + out.slice(e.at);
|
|
@@ -2358,11 +3498,16 @@ function refuseScopedInjection(path, cls) {
|
|
|
2358
3498
|
};
|
|
2359
3499
|
cls.members.forEach(visit);
|
|
2360
3500
|
}
|
|
2361
|
-
/** A component provider the release build makes: a class,
|
|
2362
|
-
function checkProvider(path, e) {
|
|
2363
|
-
const what = `${path}: the provider ${e.getText().split('\n')[0]} in @Component's
|
|
2364
|
-
if (ts.isIdentifier(e))
|
|
3501
|
+
/** A component provider the release build makes: a class, `{ provide, useClass | useValue | useFactory | useExisting }`, a provider helper call (`provideIcons(...)`), a spread, or a nested array. */
|
|
3502
|
+
function checkProvider(path, e, field = 'providers') {
|
|
3503
|
+
const what = `${path}: the provider ${e.getText().split('\n')[0]} in @Component's ${field}`;
|
|
3504
|
+
if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e) || ts.isCallExpression(e) || ts.isSpreadElement(e))
|
|
2365
3505
|
return;
|
|
3506
|
+
if (ts.isArrayLiteralExpression(e)) {
|
|
3507
|
+
for (const inner of e.elements)
|
|
3508
|
+
checkProvider(path, inner, field);
|
|
3509
|
+
return;
|
|
3510
|
+
}
|
|
2366
3511
|
if (!ts.isObjectLiteralExpression(e))
|
|
2367
3512
|
throw new Error(`${what} is not supported in a release build yet`);
|
|
2368
3513
|
const fields = new Map();
|
|
@@ -2375,7 +3520,7 @@ function checkProvider(path, e) {
|
|
|
2375
3520
|
throw new Error(`${what} is read as \`{ provide: token, useClass: X }\` in a release build`);
|
|
2376
3521
|
}
|
|
2377
3522
|
for (const k of fields.keys())
|
|
2378
|
-
if (!['provide', 'useClass', 'useValue', 'useFactory', 'useExisting', 'deps'].includes(k))
|
|
3523
|
+
if (!['provide', 'useClass', 'useValue', 'useFactory', 'useExisting', 'deps', 'multi'].includes(k))
|
|
2379
3524
|
throw new Error(`${what}: its ${k} is not supported in a release build yet`);
|
|
2380
3525
|
const uses = ['useClass', 'useValue', 'useFactory', 'useExisting'].filter((k) => fields.has(k));
|
|
2381
3526
|
if (!fields.has('provide') || uses.length !== 1)
|
|
@@ -2392,7 +3537,7 @@ function checkProvider(path, e) {
|
|
|
2392
3537
|
*/
|
|
2393
3538
|
const COMPONENT_META = new Set([
|
|
2394
3539
|
'selector', 'template', 'templateUrl', 'styles', 'styleUrl', 'styleUrls', 'imports', 'changeDetection', 'encapsulation',
|
|
2395
|
-
'standalone', 'schemas', 'moduleId', 'jit', 'exportAs', 'animations', 'preserveWhitespaces', 'providers',
|
|
3540
|
+
'standalone', 'schemas', 'moduleId', 'jit', 'exportAs', 'animations', 'preserveWhitespaces', 'providers', 'viewProviders', 'host', 'hostDirectives',
|
|
2396
3541
|
]);
|
|
2397
3542
|
/** Decorator fields named in the plural, for messages. */
|
|
2398
3543
|
const PLURAL_FIELDS = new Set(['providers', 'viewProviders', 'inputs', 'outputs', 'queries', 'hostDirectives', 'animations', 'schemas']);
|
|
@@ -2880,6 +4025,7 @@ export function angularRouteTree(entry, read, aliased = () => undefined) {
|
|
|
2880
4025
|
};
|
|
2881
4026
|
const sf = parse(entry);
|
|
2882
4027
|
let found = null;
|
|
4028
|
+
let hasFileRouter = false;
|
|
2883
4029
|
const visit = (n) => {
|
|
2884
4030
|
if (found)
|
|
2885
4031
|
return;
|
|
@@ -2887,15 +4033,120 @@ export function angularRouteTree(entry, read, aliased = () => undefined) {
|
|
|
2887
4033
|
routerOptions(entry, n);
|
|
2888
4034
|
found = arrayNamed(entry, n.arguments[0].text);
|
|
2889
4035
|
}
|
|
4036
|
+
else if (ts.isCallExpression(n) && /(^|\.)provideFileRouter$/.test(n.expression.getText())) {
|
|
4037
|
+
hasFileRouter = true;
|
|
4038
|
+
}
|
|
2890
4039
|
ts.forEachChild(n, visit);
|
|
2891
4040
|
};
|
|
2892
4041
|
visit(sf);
|
|
4042
|
+
if (!found && hasFileRouter) {
|
|
4043
|
+
return fileRouterTree(dirname(entry), read);
|
|
4044
|
+
}
|
|
2893
4045
|
if (!found)
|
|
2894
4046
|
return null;
|
|
2895
4047
|
const { file, array } = found;
|
|
2896
4048
|
const routes = routesOf(file, array);
|
|
2897
4049
|
return { routes, files, guards: [...guards].map(([f, list]) => guardModule(f, parse(f), list)) };
|
|
2898
4050
|
}
|
|
4051
|
+
/**
|
|
4052
|
+
* AnalogJS-style file-based routing (`provideFileRouter()`): scans `<appDir>/app/pages/**\/*.{page.ts,md}`
|
|
4053
|
+
* following `index`, `[param]`, `[...rest]`, `(group)`, and layout nesting conventions.
|
|
4054
|
+
*/
|
|
4055
|
+
function fileRouterTree(appDir, read) {
|
|
4056
|
+
const pagesDir = join(appDir, 'app', 'pages');
|
|
4057
|
+
if (!existsSync(pagesDir))
|
|
4058
|
+
return { routes: [], files: new Set(), guards: [] };
|
|
4059
|
+
const pagePaths = [];
|
|
4060
|
+
const walk = (d) => {
|
|
4061
|
+
for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
4062
|
+
const p = join(d, e.name);
|
|
4063
|
+
if (e.isDirectory())
|
|
4064
|
+
walk(p);
|
|
4065
|
+
else if (e.name.endsWith('.page.ts') || e.name.endsWith('.md'))
|
|
4066
|
+
pagePaths.push(p);
|
|
4067
|
+
}
|
|
4068
|
+
};
|
|
4069
|
+
walk(pagesDir);
|
|
4070
|
+
if (!pagePaths.length)
|
|
4071
|
+
return { routes: [], files: new Set(), guards: [] };
|
|
4072
|
+
const toRawPath = (f) => f.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages)[\\/]|(\.page\.(js|ts)$)|(\.(ts|md)$)/g, '')
|
|
4073
|
+
.replace(/\[\.{3}.+\]/, '**')
|
|
4074
|
+
.replace(/\[([^\]]+)\]/g, ':$1');
|
|
4075
|
+
const toSegment = (s) => s.replace(/\bindex\b|\(.*?\)/g, '').replace(/\.|\/+/g, '/').replace(/^\/+|\/+$/g, '');
|
|
4076
|
+
const levels = new Map();
|
|
4077
|
+
const atLevel = (lvl) => levels.get(lvl) ?? (levels.set(lvl, new Map()), levels.get(lvl));
|
|
4078
|
+
for (const f of pagePaths) {
|
|
4079
|
+
const rawSegments = toRawPath(f).split('/');
|
|
4080
|
+
const lvl = rawSegments.length - 1;
|
|
4081
|
+
const rawSegment = rawSegments[lvl];
|
|
4082
|
+
atLevel(lvl).set(rawSegments.join('/'), { file: f, rawSegment, ancestors: rawSegments.slice(0, lvl), segment: toSegment(rawSegment), children: [] });
|
|
4083
|
+
}
|
|
4084
|
+
for (let lvl = Math.max(...levels.keys()); lvl > 0; lvl--) {
|
|
4085
|
+
for (const r of atLevel(lvl).values()) {
|
|
4086
|
+
const parentKey = r.ancestors.join('/');
|
|
4087
|
+
const parents = atLevel(lvl - 1);
|
|
4088
|
+
let parent = parents.get(parentKey);
|
|
4089
|
+
if (!parent) {
|
|
4090
|
+
const ps = r.ancestors[lvl - 1];
|
|
4091
|
+
parent = { file: null, rawSegment: ps, ancestors: r.ancestors.slice(0, lvl - 1), segment: toSegment(ps), children: [] };
|
|
4092
|
+
parents.set(parentKey, parent);
|
|
4093
|
+
}
|
|
4094
|
+
parent.children.push(r);
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
const deprio = (s) => s.replace(':', '~~').replace('**', '~~~~');
|
|
4098
|
+
const sortRaw = (list) => {
|
|
4099
|
+
list.sort((a, b) => {
|
|
4100
|
+
const sa = (a.children.length ? '~' : '') + deprio(a.segment);
|
|
4101
|
+
const sb = (b.children.length ? '~' : '') + deprio(b.segment);
|
|
4102
|
+
return sa > sb ? 1 : sa < sb ? -1 : 0;
|
|
4103
|
+
});
|
|
4104
|
+
for (const r of list)
|
|
4105
|
+
sortRaw(r.children);
|
|
4106
|
+
};
|
|
4107
|
+
const roots = [...atLevel(0).values()];
|
|
4108
|
+
sortRaw(roots);
|
|
4109
|
+
const toNode = (r) => {
|
|
4110
|
+
const children = r.children.length ? r.children.map(toNode) : undefined;
|
|
4111
|
+
const node = { path: r.segment };
|
|
4112
|
+
if (r.file) {
|
|
4113
|
+
if (r.file.endsWith('.md')) {
|
|
4114
|
+
node.component = 'MarkdownRouteComponent';
|
|
4115
|
+
}
|
|
4116
|
+
else {
|
|
4117
|
+
const text = read(r.file);
|
|
4118
|
+
const comps = componentsOf(r.file, text);
|
|
4119
|
+
if (comps.length) {
|
|
4120
|
+
node.component = comps[0].name;
|
|
4121
|
+
}
|
|
4122
|
+
else {
|
|
4123
|
+
const sf = ts.createSourceFile(r.file, text, ts.ScriptTarget.Latest, true);
|
|
4124
|
+
for (const st of sf.statements) {
|
|
4125
|
+
if (!ts.isVariableStatement(st))
|
|
4126
|
+
continue;
|
|
4127
|
+
for (const d of st.declarationList.declarations) {
|
|
4128
|
+
if (ts.isIdentifier(d.name) && d.name.text === 'routeMeta' && d.initializer && ts.isObjectLiteralExpression(d.initializer)) {
|
|
4129
|
+
for (const p of d.initializer.properties) {
|
|
4130
|
+
if (!ts.isPropertyAssignment(p))
|
|
4131
|
+
continue;
|
|
4132
|
+
const k = p.name.getText();
|
|
4133
|
+
if (k === 'redirectTo' && ts.isStringLiteral(p.initializer))
|
|
4134
|
+
node.redirectTo = p.initializer.text;
|
|
4135
|
+
if (k === 'pathMatch' && ts.isStringLiteral(p.initializer) && p.initializer.text === 'full')
|
|
4136
|
+
node.full = true;
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
}
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
if (children)
|
|
4145
|
+
node.children = children;
|
|
4146
|
+
return node;
|
|
4147
|
+
};
|
|
4148
|
+
return { routes: roots.map(toNode), files: new Set(), guards: [] };
|
|
4149
|
+
}
|
|
2899
4150
|
/** The components a route tree names. */
|
|
2900
4151
|
export function routedComponents(routes) {
|
|
2901
4152
|
return routes.flatMap((r) => [...(r.component ? [r.component] : []), ...routedComponents(r.children ?? [])]);
|