@analogjs/vite-plugin-angular 3.0.0-beta.28 → 3.0.0-beta.29

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 (32) hide show
  1. package/package.json +1 -1
  2. package/src/lib/compiler/compile.d.ts +1 -1
  3. package/src/lib/compiler/compile.js +134 -134
  4. package/src/lib/compiler/compile.js.map +1 -1
  5. package/src/lib/compiler/defer.d.ts +2 -3
  6. package/src/lib/compiler/defer.js +11 -13
  7. package/src/lib/compiler/defer.js.map +1 -1
  8. package/src/lib/compiler/dts-reader.d.ts +1 -1
  9. package/src/lib/compiler/dts-reader.js +6 -6
  10. package/src/lib/compiler/dts-reader.js.map +1 -1
  11. package/src/lib/compiler/jit-transform.js +2 -2
  12. package/src/lib/compiler/jit-transform.js.map +1 -1
  13. package/src/lib/compiler/js-emitter.d.ts +0 -3
  14. package/src/lib/compiler/js-emitter.js +3 -21
  15. package/src/lib/compiler/js-emitter.js.map +1 -1
  16. package/src/lib/compiler/registry.d.ts +1 -1
  17. package/src/lib/compiler/registry.js +2 -2
  18. package/src/lib/compiler/registry.js.map +1 -1
  19. package/src/lib/compiler/resource-inliner.d.ts +1 -1
  20. package/src/lib/compiler/resource-inliner.js +2 -2
  21. package/src/lib/compiler/resource-inliner.js.map +1 -1
  22. package/src/lib/compiler/style-ast.d.ts +1 -1
  23. package/src/lib/compiler/style-ast.js +2 -2
  24. package/src/lib/compiler/style-ast.js.map +1 -1
  25. package/src/lib/compiler/type-elision.d.ts +4 -3
  26. package/src/lib/compiler/type-elision.js +10 -11
  27. package/src/lib/compiler/type-elision.js.map +1 -1
  28. package/src/lib/compiler/utils.d.ts +14 -7
  29. package/src/lib/compiler/utils.js +38 -9
  30. package/src/lib/compiler/utils.js.map +1 -1
  31. package/src/lib/fast-compile-plugin.js +5 -5
  32. package/src/lib/fast-compile-plugin.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/vite-plugin-angular",
3
- "version": "3.0.0-beta.28",
3
+ "version": "3.0.0-beta.29",
4
4
  "description": "Vite Plugin for Angular",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,5 +1,5 @@
1
1
  import MagicString from "magic-string";
2
- import { parseSync } from "oxc-parser";
2
+ import type { parseSync } from "oxc-parser";
3
3
  import { ComponentRegistry } from "./registry.js";
4
4
  /**
5
5
  * COMPLETE EXHAUSTIVE ANGULAR LITE COMPILER
@@ -1,8 +1,8 @@
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";
@@ -12,12 +12,23 @@ import * as fs from "node:fs";
12
12
  import * as path$1 from "node:path";
13
13
  import * as o from "@angular/compiler";
14
14
  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";
15
- import { parseSync } from "oxc-parser";
16
- import * as ts from "typescript";
17
15
  import MagicString from "magic-string";
18
16
  //#region packages/vite-plugin-angular/src/lib/compiler/compile.ts
19
- function hasExportModifier(node) {
20
- return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true;
17
+ function toTopLevelStatement(stmt) {
18
+ const isExport = (stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration") && stmt.declaration;
19
+ const decl = isExport ? stmt.declaration : stmt;
20
+ return {
21
+ decl,
22
+ exported: !!isExport,
23
+ start: Math.min(stmt.start, decl.decorators?.[0]?.start ?? stmt.start),
24
+ end: stmt.end
25
+ };
26
+ }
27
+ /** Get the callee name of a decorator call, e.g. `Component` for `@Component(...)`. */
28
+ function decoratorCallName(dec, sourceCode) {
29
+ const callee = dec.expression;
30
+ if (callee?.type !== "CallExpression") return void 0;
31
+ return sourceCode.slice(callee.callee.start, callee.callee.end);
21
32
  }
22
33
  /**
23
34
  * Normalize a `providers` / `viewProviders` metadata value into the single
@@ -35,37 +46,59 @@ function providersToExpr(value) {
35
46
  if (Array.isArray(value)) return value.length ? new o.LiteralArrayExpr(value) : null;
36
47
  return value;
37
48
  }
49
+ var LAZY_SCOPE_TYPES = /* @__PURE__ */ new Set([
50
+ "FunctionDeclaration",
51
+ "FunctionExpression",
52
+ "ArrowFunctionExpression",
53
+ "ClassDeclaration",
54
+ "ClassExpression",
55
+ "TSFunctionType",
56
+ "TSConstructorType",
57
+ "TSMethodSignature",
58
+ "TSCallSignatureDeclaration",
59
+ "TSConstructSignatureDeclaration"
60
+ ]);
38
61
  /**
39
62
  * Collect identifier names referenced in eagerly-evaluated code only.
40
63
  * Skips function/arrow/class bodies so that lazy references
41
64
  * (e.g. `const TOKEN = () => LaterClass`) are not treated as dependencies.
65
+ * The root node's own children are always walked.
42
66
  */
43
- function collectIdentifiers(node) {
67
+ function collectIdentifiers(root) {
44
68
  const ids = /* @__PURE__ */ new Set();
45
- function walk(n) {
46
- if (ts.isIdentifier(n)) ids.add(n.text);
47
- if (ts.isFunctionLike(n) || ts.isClassLike(n)) return;
48
- ts.forEachChild(n, walk);
49
- }
50
- ts.forEachChild(node, walk);
69
+ walkOxc(root, (n) => {
70
+ if (n.type === "Identifier") ids.add(n.name);
71
+ return n === root || !LAZY_SCOPE_TYPES.has(n.type);
72
+ });
51
73
  return ids;
52
74
  }
53
- /** Extract the names defined by a top-level statement. */
54
- function getDefinedNames(stmt) {
55
- if (ts.isVariableStatement(stmt)) {
75
+ /** Extract the names defined by a top-level declaration. */
76
+ function getDefinedNames(decl) {
77
+ if (decl.type === "VariableDeclaration") {
56
78
  const names = [];
57
- for (const decl of stmt.declarationList.declarations) collectBindingNames(decl.name, names);
79
+ for (const d of decl.declarations) collectBindingNames(d.id, names);
58
80
  return names;
59
81
  }
60
- if (ts.isFunctionDeclaration(stmt) && stmt.name) return [stmt.name.text];
61
- if (ts.isClassDeclaration(stmt) && stmt.name) return [stmt.name.text];
82
+ if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id) return [decl.id.name];
62
83
  return [];
63
84
  }
64
- /** Recursively collect all bound identifiers from a binding name/pattern. */
65
- function collectBindingNames(name, out) {
66
- if (ts.isIdentifier(name)) out.push(name.text);
67
- else if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
68
- for (const el of name.elements) if (!ts.isOmittedExpression(el)) collectBindingNames(el.name, out);
85
+ /** Recursively collect all bound identifiers from a binding pattern. */
86
+ function collectBindingNames(pattern, out) {
87
+ if (!pattern) return;
88
+ switch (pattern.type) {
89
+ case "Identifier":
90
+ out.push(pattern.name);
91
+ break;
92
+ case "ObjectPattern":
93
+ for (const prop of pattern.properties) collectBindingNames(prop.type === "RestElement" ? prop.argument : prop.value, out);
94
+ break;
95
+ case "ArrayPattern":
96
+ for (const el of pattern.elements) collectBindingNames(el, out);
97
+ break;
98
+ case "RestElement":
99
+ collectBindingNames(pattern.argument, out);
100
+ break;
101
+ case "AssignmentPattern": collectBindingNames(pattern.left, out);
69
102
  }
70
103
  }
71
104
  function compile(sourceCode, fileName, optionsOrRegistry) {
@@ -77,8 +110,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
77
110
  const isPartial = opts.compilationMode === "partial";
78
111
  const startTimeMs = debugCompile.enabled ? performance.now() : 0;
79
112
  debugCompile("compile %s (mode=%s, registry=%d entries)", fileName, isPartial ? "partial" : "full", registry?.size ?? 0);
80
- const origSourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.Latest, false);
81
- const oxcProgram = opts.oxcProgram ?? parseSync(fileName, sourceCode).program;
113
+ const oxcProgram = opts.oxcProgram ?? parseOxc(fileName, sourceCode).program;
82
114
  const oxcClassMap = /* @__PURE__ */ new Map();
83
115
  for (const stmt of oxcProgram.body) {
84
116
  const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
@@ -93,18 +125,18 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
93
125
  const typeOnlyImports = detectTypeOnlyImportNames(sourceCode, oxcProgram);
94
126
  const importSpecifierByName = /* @__PURE__ */ new Map();
95
127
  const importedNames = /* @__PURE__ */ new Set();
96
- for (const stmt of origSourceFile.statements) {
97
- if (!ts.isImportDeclaration(stmt) || !stmt.importClause?.namedBindings || !ts.isNamedImports(stmt.importClause.namedBindings)) continue;
98
- const moduleSpecifier = stmt.moduleSpecifier.text;
99
- const isDeclarationTypeOnly = stmt.importClause.isTypeOnly;
100
- for (const element of stmt.importClause.namedBindings.elements) {
101
- const localName = element.name.text;
128
+ for (const stmt of oxcProgram.body) {
129
+ if (stmt.type !== "ImportDeclaration") continue;
130
+ const moduleSpecifier = stmt.source.value;
131
+ const isDeclarationTypeOnly = stmt.importKind === "type";
132
+ for (const element of stmt.specifiers) {
133
+ if (element.type !== "ImportSpecifier") continue;
134
+ const localName = element.local.name;
102
135
  importedNames.add(localName);
103
136
  importSpecifierByName.set(localName, moduleSpecifier);
104
- if (isDeclarationTypeOnly || element.isTypeOnly) typeOnlyImports.add(localName);
137
+ if (isDeclarationTypeOnly || element.importKind === "type") typeOnlyImports.add(localName);
105
138
  }
106
139
  }
107
- const sourceFile = injectAngularImport(origSourceFile);
108
140
  const localSelectors = /* @__PURE__ */ new Map();
109
141
  if (!registry) for (const [clsName, oxcNode] of oxcClassMap) {
110
142
  const decs = oxcNode.decorators || [];
@@ -114,20 +146,16 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
114
146
  }
115
147
  }
116
148
  const bindingParser = isPartial ? void 0 : makeBindingParser();
117
- setEmitterSourceFile(origSourceFile);
118
149
  setEmitterSourceCode(sourceCode);
119
150
  const classResults = [];
151
+ const topLevelClasses = new Set(oxcProgram.body.map((stmt) => toTopLevelStatement(stmt).decl));
120
152
  const syntheticImports = /* @__PURE__ */ new Map();
121
- for (const node of findAllClasses(origSourceFile)) {
122
- const decorators = ts.getDecorators(node);
153
+ for (const node of findAllClasses(oxcProgram)) {
154
+ const decorators = node.decorators;
123
155
  if (!decorators || decorators.length === 0) continue;
124
- const className = node.name?.text;
156
+ const className = node.id?.name;
125
157
  if (!className) continue;
126
- const angularDecorators = decorators.filter((dec) => {
127
- if (!ts.isCallExpression(dec.expression)) return false;
128
- const name = dec.expression.expression.getText(origSourceFile);
129
- return ANGULAR_DECORATORS.has(name);
130
- });
158
+ const angularDecorators = decorators.filter((dec) => ANGULAR_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? ""));
131
159
  if (angularDecorators.length === 0) continue;
132
160
  const ivyCode = [];
133
161
  let targetType = FactoryTarget.Injectable;
@@ -136,31 +164,13 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
136
164
  value: new o.WrappedNodeExpr(className),
137
165
  type: new o.WrappedNodeExpr(className)
138
166
  };
139
- const extendsClause = node.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
140
- const usesInheritance = !!extendsClause && extendsClause.types.length > 0;
141
- const oxcNode = oxcClassMap.get(className);
167
+ const usesInheritance = !!node.superClass;
142
168
  let classCompileError = null;
143
169
  angularDecorators.forEach((dec) => {
144
- const decoratorName = dec.expression.expression.getText(origSourceFile);
145
- const oxcDec = oxcNode?.decorators?.find((d) => {
146
- const expr = d.expression;
147
- return expr?.type === "CallExpression" && expr.callee?.name === decoratorName;
148
- });
149
- const meta = extractMetadata(oxcDec, sourceCode, stringConsts);
150
- const sigs = oxcNode ? detectSignals(oxcNode, sourceCode) : {
151
- inputs: {},
152
- outputs: {},
153
- viewQueries: [],
154
- contentQueries: []
155
- };
156
- const fields = oxcNode ? detectFieldDecorators(oxcNode, sourceCode) : {
157
- inputs: {},
158
- outputs: {},
159
- viewQueries: [],
160
- contentQueries: [],
161
- hostProperties: {},
162
- hostListeners: {}
163
- };
170
+ const decoratorName = decoratorCallName(dec, sourceCode);
171
+ const meta = extractMetadata(dec, sourceCode, stringConsts);
172
+ const sigs = detectSignals(node, sourceCode);
173
+ const fields = detectFieldDecorators(node, sourceCode);
164
174
  const hostBindings = parseHostBindings(meta.hostRaw || {});
165
175
  const hostMetadata = {
166
176
  attributes: hostBindings.attributes,
@@ -424,7 +434,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
424
434
  usesInheritance,
425
435
  defer: {
426
436
  mode: 0,
427
- blocks: buildDeferDependencyMap(parsedTemplate, sourceFile, registry, localSelectors).blocks
437
+ blocks: buildDeferDependencyMap(parsedTemplate, oxcProgram, registry, localSelectors).blocks
428
438
  },
429
439
  declarationListEmitMode: 1,
430
440
  i18nUseExternalIds: opts.i18nUseExternalIds ?? false,
@@ -620,7 +630,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
620
630
  }
621
631
  });
622
632
  if (classCompileError) throw classCompileError;
623
- const deps = oxcNode ? extractConstructorDeps(oxcNode, sourceCode, typeOnlyImports) : [];
633
+ const deps = extractConstructorDeps(node, sourceCode, typeOnlyImports);
624
634
  if (deps === null) {
625
635
  const baseVar = `ɵ${className}_BaseFactory`;
626
636
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ (() => { let ${baseVar}; return function ${className}_Factory(__ngFactoryType__) { return (${baseVar} || (${baseVar} = i0.ɵɵgetInheritedFactory(${className})))(__ngFactoryType__ || ${className}); }; })()`);
@@ -641,38 +651,39 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
641
651
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ ${emitAngularExpr(fac.expression)}`);
642
652
  }
643
653
  }
644
- const ctorParameters = oxcNode ? buildCtorParameters(oxcNode, sourceCode, typeOnlyImports) : null;
645
- const propDecorators = oxcNode ? buildPropDecorators(oxcNode, sourceCode, "i0.") : null;
654
+ const ctorParameters = buildCtorParameters(node, sourceCode, typeOnlyImports);
655
+ const propDecorators = buildPropDecorators(node, sourceCode, "i0.");
656
+ const scopedMetadata = [];
646
657
  angularDecorators.forEach((dec) => {
647
- const call = dec.expression;
648
- const decName = call.expression.getText(origSourceFile);
649
- const decArgsNode = call.arguments[0];
658
+ const decName = decoratorCallName(dec, sourceCode);
659
+ const decArgsNode = dec.expression.arguments[0];
660
+ const textOf = (n) => sourceCode.slice(n.start, n.end);
650
661
  const resources = resolvedResources.get(dec);
651
662
  let metadataArgsExpr = null;
652
663
  if (decArgsNode) {
653
- if (resources && ts.isObjectLiteralExpression(decArgsNode)) {
664
+ if (resources && decArgsNode.type === "ObjectExpression") {
654
665
  const rewrittenProps = [];
655
666
  let needsTransform = false;
656
667
  for (const prop of decArgsNode.properties) {
657
- if (!ts.isPropertyAssignment(prop)) {
658
- rewrittenProps.push(prop.getText(origSourceFile));
668
+ if (prop.type !== "Property" || prop.shorthand || prop.method || prop.kind !== "init") {
669
+ rewrittenProps.push(textOf(prop));
659
670
  continue;
660
671
  }
661
- const propName = prop.name?.getText(origSourceFile);
672
+ const propName = textOf(prop.key);
662
673
  if (propName === "templateUrl" && resources.template) {
663
674
  rewrittenProps.push(`template: ${JSON.stringify(resources.template)}`);
664
675
  needsTransform = true;
665
676
  } else if ((propName === "styleUrl" || propName === "styleUrls") && resources.styles?.length) {
666
677
  rewrittenProps.push(`styles: [${resources.styles.map((s) => JSON.stringify(s)).join(", ")}]`);
667
678
  needsTransform = true;
668
- } else rewrittenProps.push(prop.getText(origSourceFile));
679
+ } else rewrittenProps.push(textOf(prop));
669
680
  }
670
- metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : decArgsNode.getText(origSourceFile);
671
- } else metadataArgsExpr = decArgsNode.getText(origSourceFile);
681
+ metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : textOf(decArgsNode);
682
+ } else metadataArgsExpr = textOf(decArgsNode);
672
683
  }
673
684
  try {
674
685
  const classMetaInput = {
675
- type: new o.WrappedNodeExpr(ts.factory.createIdentifier(className)),
686
+ type: new o.WrappedNodeExpr(className),
676
687
  decorators: new o.LiteralArrayExpr([new o.LiteralMapExpr([{
677
688
  key: "type",
678
689
  value: new o.WrappedNodeExpr(decName),
@@ -686,25 +697,20 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
686
697
  propDecorators: propDecorators ? new o.WrappedNodeExpr(propDecorators) : null
687
698
  };
688
699
  const classMetadataExpr = isPartial ? compileDeclareClassMetadata(classMetaInput) : compileClassMetadata(classMetaInput);
689
- constantPool.statements.push(new o.ExpressionStatement(classMetadataExpr));
700
+ const metadataStmt = new o.ExpressionStatement(classMetadataExpr);
701
+ if (topLevelClasses.has(node)) constantPool.statements.push(metadataStmt);
702
+ else scopedMetadata.push(metadataStmt);
690
703
  } catch (e) {
691
704
  if (debugCompile.enabled) debugCompile("compileClassMetadata failed for %s in %s: %s", className, fileName, e?.message);
692
705
  }
693
706
  });
694
707
  const memberDecorators = [];
695
- for (const member of node.members) {
696
- const mDecorators = ts.getDecorators(member);
697
- if (!mDecorators) continue;
698
- for (const dec of mDecorators) {
699
- if (!ts.isCallExpression(dec.expression)) continue;
700
- const decName = dec.expression.expression.getText(origSourceFile);
701
- if (FIELD_DECORATORS.has(decName)) memberDecorators.push(dec);
702
- }
703
- }
708
+ for (const member of node.body.body) for (const dec of member.decorators ?? []) if (FIELD_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? "")) memberDecorators.push(dec);
704
709
  classResults.push({
705
710
  ivyCode,
706
711
  decorators: [...angularDecorators, ...memberDecorators],
707
- classEnd: node.getEnd()
712
+ classEnd: node.end,
713
+ scopedMetadata
708
714
  });
709
715
  }
710
716
  const ms = new MagicString(sourceCode, { filename: fileName });
@@ -714,45 +720,40 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
714
720
  importedNames.add(name);
715
721
  }
716
722
  if (classResults.length > 0) {
723
+ const statements = oxcProgram.body.map(toTopLevelStatement);
717
724
  let firstClassPos = Infinity;
718
725
  const nonHoistableNames = /* @__PURE__ */ new Set();
719
- for (const stmt of origSourceFile.statements) if (ts.isClassDeclaration(stmt)) {
720
- firstClassPos = stmt.getStart(origSourceFile);
721
- if (stmt.name) nonHoistableNames.add(stmt.name.text);
726
+ for (const { decl, start } of statements) if (decl.type === "ClassDeclaration") {
727
+ firstClassPos = start;
728
+ if (decl.id) nonHoistableNames.add(decl.id.name);
722
729
  break;
723
730
  }
724
- for (const stmt of origSourceFile.statements) {
725
- if (stmt.getStart(origSourceFile) <= firstClassPos) continue;
726
- if (ts.isClassDeclaration(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
727
- if (ts.isEnumDeclaration(stmt)) nonHoistableNames.add(stmt.name.text);
728
- if (ts.isVariableStatement(stmt) && hasExportModifier(stmt)) for (const decl of stmt.declarationList.declarations) {
729
- const names = [];
730
- collectBindingNames(decl.name, names);
731
- for (const n of names) nonHoistableNames.add(n);
732
- }
733
- if (ts.isFunctionDeclaration(stmt) && hasExportModifier(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
731
+ for (const { decl, exported, start } of statements) {
732
+ if (start <= firstClassPos) continue;
733
+ if (decl.type === "ClassDeclaration" || decl.type === "TSEnumDeclaration") {
734
+ if (decl.id) nonHoistableNames.add(decl.id.name);
735
+ } else if (exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration")) for (const n of getDefinedNames(decl)) nonHoistableNames.add(n);
734
736
  }
735
- for (const stmt of origSourceFile.statements) {
736
- const stmtStart = stmt.getStart(origSourceFile);
737
- if (stmtStart <= firstClassPos) continue;
738
- if (!(ts.isVariableStatement(stmt) && !hasExportModifier(stmt) || ts.isFunctionDeclaration(stmt) && !hasExportModifier(stmt))) continue;
739
- const referencedIds = collectIdentifiers(stmt);
737
+ for (const { decl, exported, start, end } of statements) {
738
+ if (start <= firstClassPos) continue;
739
+ if (!(!exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration"))) continue;
740
+ const referencedIds = collectIdentifiers(decl);
740
741
  let referencesNonHoistable = false;
741
742
  for (const id of referencedIds) if (nonHoistableNames.has(id)) {
742
743
  referencesNonHoistable = true;
743
744
  break;
744
745
  }
745
- if (referencesNonHoistable) for (const name of getDefinedNames(stmt)) nonHoistableNames.add(name);
746
+ if (referencesNonHoistable) for (const name of getDefinedNames(decl)) nonHoistableNames.add(name);
746
747
  else {
747
- ms.appendLeft(stmt.getEnd(), "\n");
748
- ms.move(stmtStart, stmt.getEnd(), firstClassPos);
748
+ ms.appendLeft(end, "\n");
749
+ ms.move(start, end, firstClassPos);
749
750
  }
750
751
  }
751
752
  }
752
753
  for (const cr of classResults) {
753
754
  for (const dec of cr.decorators) {
754
- const start = dec.getStart(origSourceFile);
755
- let trimEnd = dec.getEnd();
755
+ const start = dec.start;
756
+ let trimEnd = dec.end;
756
757
  while (trimEnd < sourceCode.length && (sourceCode[trimEnd] === " " || sourceCode[trimEnd] === "\n" || sourceCode[trimEnd] === "\r")) trimEnd++;
757
758
  ms.remove(start, trimEnd);
758
759
  }
@@ -760,6 +761,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
760
761
  const memberCode = cr.ivyCode.map((c) => " " + c + ";").join("\n");
761
762
  ms.appendLeft(cr.classEnd - 1, "\n" + memberCode + "\n");
762
763
  }
764
+ for (const stmt of cr.scopedMetadata) ms.appendLeft(cr.classEnd, `\n/*@__PURE__*/ ${emitAngularStmt(stmt)}`);
763
765
  }
764
766
  const helpers = [];
765
767
  const sideEffects = [];
@@ -768,25 +770,26 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
768
770
  if (s instanceof o.ExpressionStatement && s.expr instanceof o.InvokeFunctionExpr) sideEffects.push(`/*@__PURE__*/ ${code}`);
769
771
  else helpers.push(code);
770
772
  }
773
+ if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
774
+ if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
775
+ const helperCode = helpers.join("\n");
776
+ const willElide = detectTypeOnlyImportNames(ms.toString() + "\n" + helperCode);
771
777
  if (helpers.length > 0) {
772
- const willElide = detectTypeOnlyImportNames(ms.toString());
773
778
  let insertPos = 0;
774
- for (const stmt of origSourceFile.statements) if (ts.isImportDeclaration(stmt)) {
775
- if (willElide.size > 0 && stmt.importClause) {
776
- const clause = stmt.importClause;
777
- const namedBindings = clause.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : void 0;
778
- const defaultName = clause.name;
779
- if ((!defaultName || willElide.has(defaultName.text)) && (!namedBindings || namedBindings.every((el) => el.isTypeOnly || willElide.has(el.name.text)))) continue;
780
- }
781
- insertPos = stmt.getEnd();
782
- } else if (ts.isVariableStatement(stmt) && !stmt.getText(origSourceFile).includes("class")) insertPos = stmt.getEnd();
783
- else if (!ts.isExportAssignment(stmt)) break;
784
- if (insertPos === 0) ms.appendLeft(0, helpers.join("\n") + "\n");
785
- else ms.appendRight(insertPos, "\n" + helpers.join("\n") + "\n");
779
+ for (const stmt of oxcProgram.body) {
780
+ const { decl } = toTopLevelStatement(stmt);
781
+ if (stmt.type === "ImportDeclaration") {
782
+ if (willElide.size > 0 && stmt.specifiers.length > 0) {
783
+ if (stmt.specifiers.every((spec) => spec.type === "ImportNamespaceSpecifier" || spec.importKind === "type" || willElide.has(spec.local.name))) continue;
784
+ }
785
+ insertPos = stmt.end;
786
+ } else if (decl.type === "VariableDeclaration" && !sourceCode.slice(stmt.start, stmt.end).includes("class")) insertPos = stmt.end;
787
+ else if (stmt.type !== "TSExportAssignment" && !(stmt.type === "ExportDefaultDeclaration" && decl.type !== "ClassDeclaration" && decl.type !== "FunctionDeclaration")) break;
788
+ }
789
+ if (insertPos === 0) ms.appendLeft(0, helperCode + "\n");
790
+ else ms.appendRight(insertPos, "\n" + helperCode + "\n");
786
791
  }
787
- if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
788
- if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
789
- elideTypeOnlyImportsMagicString(ms, oxcProgram);
792
+ elideTypeOnlyImportsMagicString(ms, oxcProgram, willElide);
790
793
  const map = ms.generateMap({
791
794
  source: fileName,
792
795
  file: fileName + ".js",
@@ -800,9 +803,6 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
800
803
  resourceDependencies
801
804
  };
802
805
  }
803
- function injectAngularImport(sf) {
804
- 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]);
805
- }
806
806
  //#endregion
807
807
  export { compile };
808
808