@analogjs/vite-plugin-angular 3.0.0-beta.3 → 3.0.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/ngp/LICENSE +21 -0
  2. package/ngp/api.mjs +46048 -0
  3. package/ngp/build.json +4 -0
  4. package/ngp/ng_analyze.cjs +504 -0
  5. package/ngp/ng_analyze_bg.wasm +0 -0
  6. package/package.json +1 -1
  7. package/src/lib/angular-build-optimizer-plugin.js +6 -3
  8. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  9. package/src/lib/angular-vite-plugin.d.ts +20 -5
  10. package/src/lib/angular-vite-plugin.js +30 -14
  11. package/src/lib/angular-vite-plugin.js.map +1 -1
  12. package/src/lib/compilation-api/compilation-api-plugin.js +3 -0
  13. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  14. package/src/lib/compiler/compile.d.ts +1 -1
  15. package/src/lib/compiler/compile.js +158 -143
  16. package/src/lib/compiler/compile.js.map +1 -1
  17. package/src/lib/compiler/defer.d.ts +2 -3
  18. package/src/lib/compiler/defer.js +11 -13
  19. package/src/lib/compiler/defer.js.map +1 -1
  20. package/src/lib/compiler/dts-reader.d.ts +6 -1
  21. package/src/lib/compiler/dts-reader.js +15 -9
  22. package/src/lib/compiler/dts-reader.js.map +1 -1
  23. package/src/lib/compiler/hmr.d.ts +4 -0
  24. package/src/lib/compiler/hmr.js +7 -2
  25. package/src/lib/compiler/hmr.js.map +1 -1
  26. package/src/lib/compiler/index.d.ts +2 -2
  27. package/src/lib/compiler/index.js +4 -4
  28. package/src/lib/compiler/jit-metadata.d.ts +3 -1
  29. package/src/lib/compiler/jit-metadata.js +10 -8
  30. package/src/lib/compiler/jit-metadata.js.map +1 -1
  31. package/src/lib/compiler/jit-transform.js +2 -2
  32. package/src/lib/compiler/jit-transform.js.map +1 -1
  33. package/src/lib/compiler/js-emitter.d.ts +0 -3
  34. package/src/lib/compiler/js-emitter.js +3 -21
  35. package/src/lib/compiler/js-emitter.js.map +1 -1
  36. package/src/lib/compiler/registry.d.ts +7 -1
  37. package/src/lib/compiler/registry.js +23 -3
  38. package/src/lib/compiler/registry.js.map +1 -1
  39. package/src/lib/compiler/resource-inliner.d.ts +8 -9
  40. package/src/lib/compiler/resource-inliner.js +10 -18
  41. package/src/lib/compiler/resource-inliner.js.map +1 -1
  42. package/src/lib/compiler/style-ast.d.ts +9 -1
  43. package/src/lib/compiler/style-ast.js +26 -5
  44. package/src/lib/compiler/style-ast.js.map +1 -1
  45. package/src/lib/compiler/type-elision.d.ts +4 -3
  46. package/src/lib/compiler/type-elision.js +10 -11
  47. package/src/lib/compiler/type-elision.js.map +1 -1
  48. package/src/lib/compiler/utils.d.ts +14 -7
  49. package/src/lib/compiler/utils.js +38 -9
  50. package/src/lib/compiler/utils.js.map +1 -1
  51. package/src/lib/fast-compile-plugin.d.ts +3 -0
  52. package/src/lib/fast-compile-plugin.js +124 -38
  53. package/src/lib/fast-compile-plugin.js.map +1 -1
  54. package/src/lib/host.d.ts +2 -0
  55. package/src/lib/host.js +2 -0
  56. package/src/lib/host.js.map +1 -1
  57. package/src/lib/live-reload-plugin.d.ts +4 -3
  58. package/src/lib/live-reload-plugin.js +4 -3
  59. package/src/lib/live-reload-plugin.js.map +1 -1
  60. package/src/lib/ngp-compile-plugin.d.ts +3 -0
  61. package/src/lib/ngp-compile-plugin.js +344 -0
  62. package/src/lib/ngp-compile-plugin.js.map +1 -0
  63. package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -1
  64. package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
  65. package/src/lib/utils/hmr-component-updates.d.ts +7 -0
  66. package/src/lib/utils/hmr-component-updates.js +87 -0
  67. package/src/lib/utils/hmr-component-updates.js.map +1 -0
  68. package/src/lib/utils/lsp-type-checker.d.ts +55 -0
  69. package/src/lib/utils/lsp-type-checker.js +502 -0
  70. package/src/lib/utils/lsp-type-checker.js.map +1 -0
  71. package/src/lib/utils/plugin-config.d.ts +9 -0
  72. package/src/lib/utils/plugin-config.js +10 -1
  73. package/src/lib/utils/plugin-config.js.map +1 -1
  74. package/src/lib/utils/stylesheet-warning.d.ts +2 -0
  75. package/src/lib/utils/stylesheet-warning.js +8 -0
  76. package/src/lib/utils/stylesheet-warning.js.map +1 -0
@@ -1,22 +1,35 @@
1
1
  import { ANGULAR_DECORATORS, FIELD_DECORATORS } from "./constants.js";
2
- import { findAllClasses, resolveSyntheticImportSpecifier } from "./utils.js";
2
+ import { findAllClasses, parseOxc, resolveSyntheticImportSpecifier, walkOxc } from "./utils.js";
3
3
  import { angularVersionAtLeast } from "./angular-version.js";
4
4
  import { detectTypeOnlyImportNames, elideTypeOnlyImportsMagicString } from "./type-elision.js";
5
- import { emitAngularExpr, emitAngularStmt, setEmitterSourceCode, setEmitterSourceFile } from "./js-emitter.js";
5
+ import { emitAngularExpr, emitAngularStmt, setEmitterSourceCode } from "./js-emitter.js";
6
6
  import { lowerClassFields } from "./class-field-lowering.js";
7
7
  import { collectStringConstants, detectFieldDecorators, detectSignals, extractConstructorDeps, extractMetadata } from "./metadata.js";
8
8
  import { buildDeferDependencyMap } from "./defer.js";
9
+ import { buildCtorParameters, buildPropDecorators } from "./jit-metadata.js";
9
10
  import { debugCompile } from "./debug.js";
11
+ import { inlineStyleRanges } from "./style-ast.js";
10
12
  import * as fs from "node:fs";
11
13
  import * as path$1 from "node:path";
12
14
  import * as o from "@angular/compiler";
13
15
  import { ConstantPool, FactoryTarget, ParseLocation, ParseSourceFile, ParseSourceSpan, R3NgModuleMetadataKind, R3SelectorScopeMode, compileClassMetadata, compileComponentFromMetadata, compileDeclareClassMetadata, compileDeclareComponentFromMetadata, compileDeclareDirectiveFromMetadata, compileDeclareFactoryFunction, compileDeclareInjectableFromMetadata, compileDeclareInjectorFromMetadata, compileDeclareNgModuleFromMetadata, compileDeclarePipeFromMetadata, compileDirectiveFromMetadata, compileFactoryFunction, compileInjector, compileNgModule, compilePipeFromMetadata, makeBindingParser, parseHostBindings, parseTemplate } from "@angular/compiler";
14
- import { parseSync } from "oxc-parser";
15
- import * as ts from "typescript";
16
16
  import MagicString from "magic-string";
17
17
  //#region packages/vite-plugin-angular/src/lib/compiler/compile.ts
18
- function hasExportModifier(node) {
19
- return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true;
18
+ function toTopLevelStatement(stmt) {
19
+ const isExport = (stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration") && stmt.declaration;
20
+ const decl = isExport ? stmt.declaration : stmt;
21
+ return {
22
+ decl,
23
+ exported: !!isExport,
24
+ start: Math.min(stmt.start, decl.decorators?.[0]?.start ?? stmt.start),
25
+ end: stmt.end
26
+ };
27
+ }
28
+ /** Get the callee name of a decorator call, e.g. `Component` for `@Component(...)`. */
29
+ function decoratorCallName(dec, sourceCode) {
30
+ const callee = dec.expression;
31
+ if (callee?.type !== "CallExpression") return void 0;
32
+ return sourceCode.slice(callee.callee.start, callee.callee.end);
20
33
  }
21
34
  /**
22
35
  * Normalize a `providers` / `viewProviders` metadata value into the single
@@ -34,37 +47,59 @@ function providersToExpr(value) {
34
47
  if (Array.isArray(value)) return value.length ? new o.LiteralArrayExpr(value) : null;
35
48
  return value;
36
49
  }
50
+ var LAZY_SCOPE_TYPES = /* @__PURE__ */ new Set([
51
+ "FunctionDeclaration",
52
+ "FunctionExpression",
53
+ "ArrowFunctionExpression",
54
+ "ClassDeclaration",
55
+ "ClassExpression",
56
+ "TSFunctionType",
57
+ "TSConstructorType",
58
+ "TSMethodSignature",
59
+ "TSCallSignatureDeclaration",
60
+ "TSConstructSignatureDeclaration"
61
+ ]);
37
62
  /**
38
63
  * Collect identifier names referenced in eagerly-evaluated code only.
39
64
  * Skips function/arrow/class bodies so that lazy references
40
65
  * (e.g. `const TOKEN = () => LaterClass`) are not treated as dependencies.
66
+ * The root node's own children are always walked.
41
67
  */
42
- function collectIdentifiers(node) {
68
+ function collectIdentifiers(root) {
43
69
  const ids = /* @__PURE__ */ new Set();
44
- function walk(n) {
45
- if (ts.isIdentifier(n)) ids.add(n.text);
46
- if (ts.isFunctionLike(n) || ts.isClassLike(n)) return;
47
- ts.forEachChild(n, walk);
48
- }
49
- ts.forEachChild(node, walk);
70
+ walkOxc(root, (n) => {
71
+ if (n.type === "Identifier") ids.add(n.name);
72
+ return n === root || !LAZY_SCOPE_TYPES.has(n.type);
73
+ });
50
74
  return ids;
51
75
  }
52
- /** Extract the names defined by a top-level statement. */
53
- function getDefinedNames(stmt) {
54
- if (ts.isVariableStatement(stmt)) {
76
+ /** Extract the names defined by a top-level declaration. */
77
+ function getDefinedNames(decl) {
78
+ if (decl.type === "VariableDeclaration") {
55
79
  const names = [];
56
- for (const decl of stmt.declarationList.declarations) collectBindingNames(decl.name, names);
80
+ for (const d of decl.declarations) collectBindingNames(d.id, names);
57
81
  return names;
58
82
  }
59
- if (ts.isFunctionDeclaration(stmt) && stmt.name) return [stmt.name.text];
60
- if (ts.isClassDeclaration(stmt) && stmt.name) return [stmt.name.text];
83
+ if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id) return [decl.id.name];
61
84
  return [];
62
85
  }
63
- /** Recursively collect all bound identifiers from a binding name/pattern. */
64
- function collectBindingNames(name, out) {
65
- if (ts.isIdentifier(name)) out.push(name.text);
66
- else if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
67
- for (const el of name.elements) if (!ts.isOmittedExpression(el)) collectBindingNames(el.name, out);
86
+ /** Recursively collect all bound identifiers from a binding pattern. */
87
+ function collectBindingNames(pattern, out) {
88
+ if (!pattern) return;
89
+ switch (pattern.type) {
90
+ case "Identifier":
91
+ out.push(pattern.name);
92
+ break;
93
+ case "ObjectPattern":
94
+ for (const prop of pattern.properties) collectBindingNames(prop.type === "RestElement" ? prop.argument : prop.value, out);
95
+ break;
96
+ case "ArrayPattern":
97
+ for (const el of pattern.elements) collectBindingNames(el, out);
98
+ break;
99
+ case "RestElement":
100
+ collectBindingNames(pattern.argument, out);
101
+ break;
102
+ case "AssignmentPattern": collectBindingNames(pattern.left, out);
68
103
  }
69
104
  }
70
105
  function compile(sourceCode, fileName, optionsOrRegistry) {
@@ -76,8 +111,8 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
76
111
  const isPartial = opts.compilationMode === "partial";
77
112
  const startTimeMs = debugCompile.enabled ? performance.now() : 0;
78
113
  debugCompile("compile %s (mode=%s, registry=%d entries)", fileName, isPartial ? "partial" : "full", registry?.size ?? 0);
79
- const origSourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.Latest, false);
80
- const oxcProgram = opts.oxcProgram ?? parseSync(fileName, sourceCode).program;
114
+ const oxcProgram = opts.oxcProgram ?? parseOxc(fileName, sourceCode).program;
115
+ const styleRanges = resolvedInlineStyles && inlineStyleRanges(oxcProgram);
81
116
  const oxcClassMap = /* @__PURE__ */ new Map();
82
117
  for (const stmt of oxcProgram.body) {
83
118
  const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
@@ -92,18 +127,21 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
92
127
  const typeOnlyImports = detectTypeOnlyImportNames(sourceCode, oxcProgram);
93
128
  const importSpecifierByName = /* @__PURE__ */ new Map();
94
129
  const importedNames = /* @__PURE__ */ new Set();
95
- for (const stmt of origSourceFile.statements) {
96
- if (!ts.isImportDeclaration(stmt) || !stmt.importClause?.namedBindings || !ts.isNamedImports(stmt.importClause.namedBindings)) continue;
97
- const moduleSpecifier = stmt.moduleSpecifier.text;
98
- const isDeclarationTypeOnly = stmt.importClause.isTypeOnly;
99
- for (const element of stmt.importClause.namedBindings.elements) {
100
- const localName = element.name.text;
101
- importedNames.add(localName);
130
+ const typeOnlyImportedNames = /* @__PURE__ */ new Set();
131
+ for (const stmt of oxcProgram.body) {
132
+ if (stmt.type !== "ImportDeclaration") continue;
133
+ const moduleSpecifier = stmt.source.value;
134
+ const isDeclarationTypeOnly = stmt.importKind === "type";
135
+ for (const element of stmt.specifiers) {
136
+ if (element.type !== "ImportSpecifier") continue;
137
+ const localName = element.local.name;
102
138
  importSpecifierByName.set(localName, moduleSpecifier);
103
- if (isDeclarationTypeOnly || element.isTypeOnly) typeOnlyImports.add(localName);
139
+ if (isDeclarationTypeOnly || element.importKind === "type") {
140
+ typeOnlyImports.add(localName);
141
+ typeOnlyImportedNames.add(localName);
142
+ } else importedNames.add(localName);
104
143
  }
105
144
  }
106
- const sourceFile = injectAngularImport(origSourceFile);
107
145
  const localSelectors = /* @__PURE__ */ new Map();
108
146
  if (!registry) for (const [clsName, oxcNode] of oxcClassMap) {
109
147
  const decs = oxcNode.decorators || [];
@@ -113,20 +151,17 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
113
151
  }
114
152
  }
115
153
  const bindingParser = isPartial ? void 0 : makeBindingParser();
116
- setEmitterSourceFile(origSourceFile);
117
154
  setEmitterSourceCode(sourceCode);
118
155
  const classResults = [];
156
+ const topLevelClasses = new Set(oxcProgram.body.map((stmt) => toTopLevelStatement(stmt).decl));
119
157
  const syntheticImports = /* @__PURE__ */ new Map();
120
- for (const node of findAllClasses(origSourceFile)) {
121
- const decorators = ts.getDecorators(node);
158
+ const dependencyLocalName = (name) => typeOnlyImportedNames.has(name) ? `ɵngDep_${name}` : name;
159
+ for (const node of findAllClasses(oxcProgram)) {
160
+ const decorators = node.decorators;
122
161
  if (!decorators || decorators.length === 0) continue;
123
- const className = node.name?.text;
162
+ const className = node.id?.name;
124
163
  if (!className) continue;
125
- const angularDecorators = decorators.filter((dec) => {
126
- if (!ts.isCallExpression(dec.expression)) return false;
127
- const name = dec.expression.expression.getText(origSourceFile);
128
- return ANGULAR_DECORATORS.has(name);
129
- });
164
+ const angularDecorators = decorators.filter((dec) => ANGULAR_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? ""));
130
165
  if (angularDecorators.length === 0) continue;
131
166
  const ivyCode = [];
132
167
  let targetType = FactoryTarget.Injectable;
@@ -135,31 +170,13 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
135
170
  value: new o.WrappedNodeExpr(className),
136
171
  type: new o.WrappedNodeExpr(className)
137
172
  };
138
- const extendsClause = node.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
139
- const usesInheritance = !!extendsClause && extendsClause.types.length > 0;
140
- const oxcNode = oxcClassMap.get(className);
173
+ const usesInheritance = !!node.superClass;
141
174
  let classCompileError = null;
142
175
  angularDecorators.forEach((dec) => {
143
- const decoratorName = dec.expression.expression.getText(origSourceFile);
144
- const oxcDec = oxcNode?.decorators?.find((d) => {
145
- const expr = d.expression;
146
- return expr?.type === "CallExpression" && expr.callee?.name === decoratorName;
147
- });
148
- const meta = extractMetadata(oxcDec, sourceCode, stringConsts);
149
- const sigs = oxcNode ? detectSignals(oxcNode, sourceCode) : {
150
- inputs: {},
151
- outputs: {},
152
- viewQueries: [],
153
- contentQueries: []
154
- };
155
- const fields = oxcNode ? detectFieldDecorators(oxcNode, sourceCode) : {
156
- inputs: {},
157
- outputs: {},
158
- viewQueries: [],
159
- contentQueries: [],
160
- hostProperties: {},
161
- hostListeners: {}
162
- };
176
+ const decoratorName = decoratorCallName(dec, sourceCode);
177
+ const meta = extractMetadata(dec, sourceCode, stringConsts);
178
+ const sigs = detectSignals(node, sourceCode);
179
+ const fields = detectFieldDecorators(node, sourceCode);
163
180
  const hostBindings = parseHostBindings(meta.hostRaw || {});
164
181
  const hostMetadata = {
165
182
  attributes: hostBindings.attributes,
@@ -206,7 +223,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
206
223
  for (const memberName of expanded) {
207
224
  const memberEntry = registry?.get(memberName);
208
225
  if (!memberEntry || memberEntry.kind === "tuple") continue;
209
- const memberRef = new o.WrappedNodeExpr(memberName);
226
+ const memberRef = new o.WrappedNodeExpr(dependencyLocalName(memberName));
210
227
  if (!importedNames.has(memberName)) {
211
228
  const memberSpecifier = resolveSyntheticImportSpecifier(fileName, memberEntry, tupleSpecifier);
212
229
  if (memberSpecifier) syntheticImports.set(memberName, memberSpecifier);
@@ -247,7 +264,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
247
264
  const exportedEntry = registry?.get(exportedName);
248
265
  if (exportedEntry) {
249
266
  const kind = exportedEntry.kind === "pipe" ? 1 : 0;
250
- const exportedRef = new o.WrappedNodeExpr(exportedName);
267
+ const exportedRef = new o.WrappedNodeExpr(dependencyLocalName(exportedName));
251
268
  const exportedSpecifier = resolveSyntheticImportSpecifier(fileName, exportedEntry, moduleSpecifier);
252
269
  if (exportedSpecifier) syntheticImports.set(exportedName, exportedSpecifier);
253
270
  const decl = {
@@ -326,7 +343,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
326
343
  }
327
344
  const kind = entry.kind === "pipe" ? 1 : 0;
328
345
  const decl = {
329
- type: new o.WrappedNodeExpr(name),
346
+ type: new o.WrappedNodeExpr(dependencyLocalName(name)),
330
347
  selector: entry.selector || `_unresolved-${name}`,
331
348
  kind,
332
349
  ...kind === 1 ? { name: entry.pipeName } : {}
@@ -354,8 +371,10 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
354
371
  } catch {
355
372
  console.warn(`[fast-compile] Could not read style file "${url}" for ${className}`);
356
373
  }
357
- if (resolvedInlineStyles) {
358
- for (const [idx, css] of resolvedInlineStyles) if (idx < meta.styles.length) meta.styles[idx] = css;
374
+ const styleRange = styleRanges?.get(dec);
375
+ if (resolvedInlineStyles && styleRange) for (let k = 0; k < styleRange.count; k++) {
376
+ const css = resolvedInlineStyles.get(styleRange.start + k);
377
+ if (css !== void 0) meta.styles[k] = css;
359
378
  }
360
379
  resolvedResources.set(dec, {
361
380
  template: templateContent || void 0,
@@ -423,7 +442,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
423
442
  usesInheritance,
424
443
  defer: {
425
444
  mode: 0,
426
- blocks: buildDeferDependencyMap(parsedTemplate, sourceFile, registry, localSelectors).blocks
445
+ blocks: buildDeferDependencyMap(parsedTemplate, oxcProgram, registry, localSelectors).blocks
427
446
  },
428
447
  declarationListEmitMode: 1,
429
448
  i18nUseExternalIds: opts.i18nUseExternalIds ?? false,
@@ -619,7 +638,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
619
638
  }
620
639
  });
621
640
  if (classCompileError) throw classCompileError;
622
- const deps = oxcNode ? extractConstructorDeps(oxcNode, sourceCode, typeOnlyImports) : [];
641
+ const deps = extractConstructorDeps(node, sourceCode, typeOnlyImports);
623
642
  if (deps === null) {
624
643
  const baseVar = `ɵ${className}_BaseFactory`;
625
644
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ (() => { let ${baseVar}; return function ${className}_Factory(__ngFactoryType__) { return (${baseVar} || (${baseVar} = i0.ɵɵgetInheritedFactory(${className})))(__ngFactoryType__ || ${className}); }; })()`);
@@ -640,36 +659,39 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
640
659
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ ${emitAngularExpr(fac.expression)}`);
641
660
  }
642
661
  }
662
+ const ctorParameters = buildCtorParameters(node, sourceCode, typeOnlyImports);
663
+ const propDecorators = buildPropDecorators(node, sourceCode, "i0.");
664
+ const scopedMetadata = [];
643
665
  angularDecorators.forEach((dec) => {
644
- const call = dec.expression;
645
- const decName = call.expression.getText(origSourceFile);
646
- const decArgsNode = call.arguments[0];
666
+ const decName = decoratorCallName(dec, sourceCode);
667
+ const decArgsNode = dec.expression.arguments[0];
668
+ const textOf = (n) => sourceCode.slice(n.start, n.end);
647
669
  const resources = resolvedResources.get(dec);
648
670
  let metadataArgsExpr = null;
649
671
  if (decArgsNode) {
650
- if (resources && ts.isObjectLiteralExpression(decArgsNode)) {
672
+ if (resources && decArgsNode.type === "ObjectExpression") {
651
673
  const rewrittenProps = [];
652
674
  let needsTransform = false;
653
675
  for (const prop of decArgsNode.properties) {
654
- if (!ts.isPropertyAssignment(prop)) {
655
- rewrittenProps.push(prop.getText(origSourceFile));
676
+ if (prop.type !== "Property" || prop.shorthand || prop.method || prop.kind !== "init") {
677
+ rewrittenProps.push(textOf(prop));
656
678
  continue;
657
679
  }
658
- const propName = prop.name?.getText(origSourceFile);
680
+ const propName = textOf(prop.key);
659
681
  if (propName === "templateUrl" && resources.template) {
660
682
  rewrittenProps.push(`template: ${JSON.stringify(resources.template)}`);
661
683
  needsTransform = true;
662
684
  } else if ((propName === "styleUrl" || propName === "styleUrls") && resources.styles?.length) {
663
685
  rewrittenProps.push(`styles: [${resources.styles.map((s) => JSON.stringify(s)).join(", ")}]`);
664
686
  needsTransform = true;
665
- } else rewrittenProps.push(prop.getText(origSourceFile));
687
+ } else rewrittenProps.push(textOf(prop));
666
688
  }
667
- metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : decArgsNode.getText(origSourceFile);
668
- } else metadataArgsExpr = decArgsNode.getText(origSourceFile);
689
+ metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : textOf(decArgsNode);
690
+ } else metadataArgsExpr = textOf(decArgsNode);
669
691
  }
670
692
  try {
671
693
  const classMetaInput = {
672
- type: new o.WrappedNodeExpr(ts.factory.createIdentifier(className)),
694
+ type: new o.WrappedNodeExpr(className),
673
695
  decorators: new o.LiteralArrayExpr([new o.LiteralMapExpr([{
674
696
  key: "type",
675
697
  value: new o.WrappedNodeExpr(decName),
@@ -679,77 +701,71 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
679
701
  value: new o.LiteralArrayExpr([new o.WrappedNodeExpr(metadataArgsExpr)]),
680
702
  quoted: false
681
703
  }] : []])]),
682
- ctorParameters: null,
683
- propDecorators: null
704
+ ctorParameters: ctorParameters ? new o.WrappedNodeExpr(`() => [${ctorParameters}]`) : null,
705
+ propDecorators: propDecorators ? new o.WrappedNodeExpr(propDecorators) : null
684
706
  };
685
707
  const classMetadataExpr = isPartial ? compileDeclareClassMetadata(classMetaInput) : compileClassMetadata(classMetaInput);
686
- constantPool.statements.push(new o.ExpressionStatement(classMetadataExpr));
708
+ const metadataStmt = new o.ExpressionStatement(classMetadataExpr);
709
+ if (topLevelClasses.has(node)) constantPool.statements.push(metadataStmt);
710
+ else scopedMetadata.push(metadataStmt);
687
711
  } catch (e) {
688
712
  if (debugCompile.enabled) debugCompile("compileClassMetadata failed for %s in %s: %s", className, fileName, e?.message);
689
713
  }
690
714
  });
691
715
  const memberDecorators = [];
692
- for (const member of node.members) {
693
- const mDecorators = ts.getDecorators(member);
694
- if (!mDecorators) continue;
695
- for (const dec of mDecorators) {
696
- if (!ts.isCallExpression(dec.expression)) continue;
697
- const decName = dec.expression.expression.getText(origSourceFile);
698
- if (FIELD_DECORATORS.has(decName)) memberDecorators.push(dec);
699
- }
700
- }
716
+ for (const member of node.body.body) for (const dec of member.decorators ?? []) if (FIELD_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? "")) memberDecorators.push(dec);
701
717
  classResults.push({
702
718
  ivyCode,
703
719
  decorators: [...angularDecorators, ...memberDecorators],
704
- classEnd: node.getEnd()
720
+ classEnd: node.end,
721
+ scopedMetadata
705
722
  });
706
723
  }
707
724
  const ms = new MagicString(sourceCode, { filename: fileName });
708
725
  if (!sourceCode.includes("import * as i0 from")) ms.prepend("import * as i0 from \"@angular/core\";\n");
709
- for (const [name, specifier] of syntheticImports) if (!importedNames.has(name)) {
710
- ms.prepend(`import { ${name} } from "${specifier}";\n`);
711
- importedNames.add(name);
726
+ for (const [name, specifier] of syntheticImports) {
727
+ const localName = dependencyLocalName(name);
728
+ if (!importedNames.has(localName)) {
729
+ const binding = localName === name ? name : `${name} as ${localName}`;
730
+ ms.prepend(`import { ${binding} } from "${specifier}";\n`);
731
+ importedNames.add(localName);
732
+ }
712
733
  }
713
734
  if (classResults.length > 0) {
735
+ const statements = oxcProgram.body.map(toTopLevelStatement);
714
736
  let firstClassPos = Infinity;
715
737
  const nonHoistableNames = /* @__PURE__ */ new Set();
716
- for (const stmt of origSourceFile.statements) if (ts.isClassDeclaration(stmt)) {
717
- firstClassPos = stmt.getStart(origSourceFile);
718
- if (stmt.name) nonHoistableNames.add(stmt.name.text);
738
+ for (const { decl, start } of statements) if (decl.type === "ClassDeclaration") {
739
+ firstClassPos = start;
740
+ if (decl.id) nonHoistableNames.add(decl.id.name);
719
741
  break;
720
742
  }
721
- for (const stmt of origSourceFile.statements) {
722
- if (stmt.getStart(origSourceFile) <= firstClassPos) continue;
723
- if (ts.isClassDeclaration(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
724
- if (ts.isEnumDeclaration(stmt)) nonHoistableNames.add(stmt.name.text);
725
- if (ts.isVariableStatement(stmt) && hasExportModifier(stmt)) for (const decl of stmt.declarationList.declarations) {
726
- const names = [];
727
- collectBindingNames(decl.name, names);
728
- for (const n of names) nonHoistableNames.add(n);
729
- }
730
- if (ts.isFunctionDeclaration(stmt) && hasExportModifier(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
743
+ for (const { decl, exported, start } of statements) {
744
+ if (start <= firstClassPos) continue;
745
+ if (decl.type === "ClassDeclaration" || decl.type === "TSEnumDeclaration") {
746
+ if (decl.id) nonHoistableNames.add(decl.id.name);
747
+ } else if (exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration")) for (const n of getDefinedNames(decl)) nonHoistableNames.add(n);
731
748
  }
732
- for (const stmt of origSourceFile.statements) {
733
- const stmtStart = stmt.getStart(origSourceFile);
734
- if (stmtStart <= firstClassPos) continue;
735
- if (!(ts.isVariableStatement(stmt) && !hasExportModifier(stmt) || ts.isFunctionDeclaration(stmt) && !hasExportModifier(stmt))) continue;
736
- const referencedIds = collectIdentifiers(stmt);
749
+ for (const { decl, exported, start, end } of statements) {
750
+ if (start <= firstClassPos) continue;
751
+ if (!(!exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration"))) continue;
752
+ const referencedIds = collectIdentifiers(decl);
737
753
  let referencesNonHoistable = false;
738
754
  for (const id of referencedIds) if (nonHoistableNames.has(id)) {
739
755
  referencesNonHoistable = true;
740
756
  break;
741
757
  }
742
- if (referencesNonHoistable) for (const name of getDefinedNames(stmt)) nonHoistableNames.add(name);
758
+ if (referencesNonHoistable) for (const name of getDefinedNames(decl)) nonHoistableNames.add(name);
743
759
  else {
744
- ms.appendLeft(stmt.getEnd(), "\n");
745
- ms.move(stmtStart, stmt.getEnd(), firstClassPos);
760
+ ms.appendLeft(end, "\n");
761
+ ms.move(start, end, firstClassPos);
746
762
  }
747
763
  }
748
764
  }
749
765
  for (const cr of classResults) {
750
766
  for (const dec of cr.decorators) {
751
- const start = dec.getStart(origSourceFile);
752
- let trimEnd = dec.getEnd();
767
+ const start = dec.start;
768
+ let trimEnd = dec.end;
753
769
  while (trimEnd < sourceCode.length && (sourceCode[trimEnd] === " " || sourceCode[trimEnd] === "\n" || sourceCode[trimEnd] === "\r")) trimEnd++;
754
770
  ms.remove(start, trimEnd);
755
771
  }
@@ -757,6 +773,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
757
773
  const memberCode = cr.ivyCode.map((c) => " " + c + ";").join("\n");
758
774
  ms.appendLeft(cr.classEnd - 1, "\n" + memberCode + "\n");
759
775
  }
776
+ for (const stmt of cr.scopedMetadata) ms.appendLeft(cr.classEnd, `\n/*@__PURE__*/ ${emitAngularStmt(stmt)}`);
760
777
  }
761
778
  const helpers = [];
762
779
  const sideEffects = [];
@@ -765,25 +782,26 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
765
782
  if (s instanceof o.ExpressionStatement && s.expr instanceof o.InvokeFunctionExpr) sideEffects.push(`/*@__PURE__*/ ${code}`);
766
783
  else helpers.push(code);
767
784
  }
785
+ if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
786
+ if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
787
+ const helperCode = helpers.join("\n");
788
+ const willElide = detectTypeOnlyImportNames(ms.toString() + "\n" + helperCode);
768
789
  if (helpers.length > 0) {
769
- const willElide = detectTypeOnlyImportNames(ms.toString());
770
790
  let insertPos = 0;
771
- for (const stmt of origSourceFile.statements) if (ts.isImportDeclaration(stmt)) {
772
- if (willElide.size > 0 && stmt.importClause) {
773
- const clause = stmt.importClause;
774
- const namedBindings = clause.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : void 0;
775
- const defaultName = clause.name;
776
- if ((!defaultName || willElide.has(defaultName.text)) && (!namedBindings || namedBindings.every((el) => el.isTypeOnly || willElide.has(el.name.text)))) continue;
777
- }
778
- insertPos = stmt.getEnd();
779
- } else if (ts.isVariableStatement(stmt) && !stmt.getText(origSourceFile).includes("class")) insertPos = stmt.getEnd();
780
- else if (!ts.isExportAssignment(stmt)) break;
781
- if (insertPos === 0) ms.appendLeft(0, helpers.join("\n") + "\n");
782
- else ms.appendRight(insertPos, "\n" + helpers.join("\n") + "\n");
791
+ for (const stmt of oxcProgram.body) {
792
+ const { decl } = toTopLevelStatement(stmt);
793
+ if (stmt.type === "ImportDeclaration") {
794
+ if (willElide.size > 0 && stmt.specifiers.length > 0) {
795
+ if (stmt.specifiers.every((spec) => spec.type === "ImportNamespaceSpecifier" || spec.importKind === "type" || willElide.has(spec.local.name))) continue;
796
+ }
797
+ insertPos = stmt.end;
798
+ } else if (decl.type === "VariableDeclaration" && !sourceCode.slice(stmt.start, stmt.end).includes("class")) insertPos = stmt.end;
799
+ else if (stmt.type !== "TSExportAssignment" && !(stmt.type === "ExportDefaultDeclaration" && decl.type !== "ClassDeclaration" && decl.type !== "FunctionDeclaration")) break;
800
+ }
801
+ if (insertPos === 0) ms.appendLeft(0, helperCode + "\n");
802
+ else ms.appendRight(insertPos, "\n" + helperCode + "\n");
783
803
  }
784
- if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
785
- if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
786
- elideTypeOnlyImportsMagicString(ms, oxcProgram);
804
+ elideTypeOnlyImportsMagicString(ms, oxcProgram, willElide);
787
805
  const map = ms.generateMap({
788
806
  source: fileName,
789
807
  file: fileName + ".js",
@@ -797,9 +815,6 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
797
815
  resourceDependencies
798
816
  };
799
817
  }
800
- function injectAngularImport(sf) {
801
- return ts.factory.updateSourceFile(sf, [ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamespaceImport(ts.factory.createIdentifier("i0"))), ts.factory.createStringLiteral("@angular/core")), ...sf.statements]);
802
- }
803
818
  //#endregion
804
819
  export { compile };
805
820