@eui/core 22.0.0-alpha.84 → 22.0.0-alpha.85

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 (123) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/docs/changelog.html +34 -0
  3. package/docs/classes/ServiceResolver.html +722 -0
  4. package/docs/interfaces/AstLike.html +477 -0
  5. package/docs/interfaces/Edit-12.html +15 -15
  6. package/docs/interfaces/Edit-13.html +1 -1
  7. package/docs/interfaces/Edit-14.html +59 -8
  8. package/docs/interfaces/Edit-15.html +15 -15
  9. package/docs/interfaces/Edit-16.html +15 -15
  10. package/docs/interfaces/Edit-17.html +395 -0
  11. package/docs/interfaces/Edit-18.html +395 -0
  12. package/docs/interfaces/Edit-19.html +395 -0
  13. package/docs/interfaces/Edit-20.html +395 -0
  14. package/docs/interfaces/Edit-21.html +395 -0
  15. package/docs/interfaces/Edit-22.html +446 -0
  16. package/docs/interfaces/MigrateAllSchema.html +45 -0
  17. package/docs/interfaces/ProvisionResult.html +407 -0
  18. package/docs/interfaces/RefInfo.html +323 -0
  19. package/docs/interfaces/Refs-1.html +443 -0
  20. package/docs/interfaces/Refs.html +413 -0
  21. package/docs/interfaces/RewriteResult.html +356 -0
  22. package/docs/interfaces/Schema-19.html +1 -1
  23. package/docs/interfaces/Schema-20.html +1 -1
  24. package/docs/interfaces/Schema-21.html +1 -1
  25. package/docs/interfaces/Schema-22.html +1 -1
  26. package/docs/interfaces/Schema-23.html +1 -1
  27. package/docs/interfaces/Schema-24.html +1 -1
  28. package/docs/interfaces/Schema-25.html +46 -1
  29. package/docs/interfaces/Schema-26.html +20 -1
  30. package/docs/interfaces/Schema-27.html +1 -1
  31. package/docs/interfaces/Schema-28.html +1 -1
  32. package/docs/interfaces/Schema-29.html +1 -1
  33. package/docs/interfaces/Schema-30.html +1 -1
  34. package/docs/interfaces/Schema-31.html +1 -1
  35. package/docs/interfaces/Schema-32.html +1 -1
  36. package/docs/interfaces/Schema-33.html +1 -1
  37. package/docs/interfaces/Schema-34.html +11 -1
  38. package/docs/interfaces/Schema-35.html +1 -1
  39. package/docs/interfaces/Schema-36.html +1 -1
  40. package/docs/interfaces/Schema-37.html +1 -1
  41. package/docs/interfaces/Schema-38.html +368 -0
  42. package/docs/interfaces/Schema-39.html +368 -0
  43. package/docs/interfaces/Schema-40.html +380 -0
  44. package/docs/interfaces/Schema-41.html +368 -0
  45. package/docs/interfaces/Schema-42.html +368 -0
  46. package/docs/interfaces/Schema-43.html +368 -0
  47. package/docs/interfaces/TemplateScan.html +373 -0
  48. package/docs/interfaces/TextChange-1.html +395 -0
  49. package/docs/interfaces/TextChange.html +1 -1
  50. package/docs/interfaces/TrackedComponent.html +652 -0
  51. package/docs/interfaces/TsEnv.html +395 -0
  52. package/docs/js/menu-wc.js +69 -0
  53. package/docs/js/search/search_index.js +2 -2
  54. package/docs/json/documentation.json +32357 -14721
  55. package/docs/llms.txt +726 -14
  56. package/docs/miscellaneous/functions.html +17029 -5497
  57. package/docs/miscellaneous/typealiases.html +160 -0
  58. package/docs/miscellaneous/variables.html +6095 -3062
  59. package/docs/overview.html +2 -2
  60. package/docs/properties.html +1 -1
  61. package/fesm2022/eui-core.mjs +106 -113
  62. package/fesm2022/eui-core.mjs.map +1 -1
  63. package/migrations.json +45 -3
  64. package/package.json +2 -3
  65. package/schematics/collection.json +46 -8
  66. package/schematics/migrate-all/index.d.ts +1 -0
  67. package/schematics/migrate-all/index.js +7 -1
  68. package/schematics/migrate-all/index.js.map +1 -1
  69. package/schematics/migrate-all/schema.json +6 -0
  70. package/schematics/migrate-eui-autocomplete/index.d.ts +7 -0
  71. package/schematics/migrate-eui-autocomplete/index.js +552 -0
  72. package/schematics/migrate-eui-autocomplete/index.js.map +1 -0
  73. package/schematics/migrate-eui-autocomplete/schema.json +19 -0
  74. package/schematics/migrate-eui-date-range-selector/index.d.ts +8 -1
  75. package/schematics/migrate-eui-date-range-selector/index.js +32 -2
  76. package/schematics/migrate-eui-date-range-selector/index.js.map +1 -1
  77. package/schematics/migrate-eui-datepicker/adapter-provision.d.ts +16 -0
  78. package/schematics/migrate-eui-datepicker/adapter-provision.js +278 -0
  79. package/schematics/migrate-eui-datepicker/adapter-provision.js.map +1 -0
  80. package/schematics/migrate-eui-datepicker/component-refs.d.ts +51 -0
  81. package/schematics/migrate-eui-datepicker/component-refs.js +552 -0
  82. package/schematics/migrate-eui-datepicker/component-refs.js.map +1 -0
  83. package/schematics/migrate-eui-datepicker/formats.d.ts +8 -0
  84. package/schematics/migrate-eui-datepicker/formats.js +73 -0
  85. package/schematics/migrate-eui-datepicker/formats.js.map +1 -0
  86. package/schematics/migrate-eui-datepicker/index.d.ts +7 -3
  87. package/schematics/migrate-eui-datepicker/index.js +76 -56
  88. package/schematics/migrate-eui-datepicker/index.js.map +1 -1
  89. package/schematics/migrate-eui-datepicker/schema.json +6 -0
  90. package/schematics/migrate-eui-dialog/index.d.ts +23 -0
  91. package/schematics/migrate-eui-dialog/index.js +401 -0
  92. package/schematics/migrate-eui-dialog/index.js.map +1 -0
  93. package/schematics/migrate-eui-dialog/schema.json +19 -0
  94. package/schematics/migrate-eui-popover/index.js +44 -8
  95. package/schematics/migrate-eui-popover/index.js.map +1 -1
  96. package/schematics/migrate-eui-popover/signals.d.ts +13 -0
  97. package/schematics/migrate-eui-popover/signals.js +430 -0
  98. package/schematics/migrate-eui-popover/signals.js.map +1 -0
  99. package/schematics/migrate-eui-slider/index.d.ts +13 -0
  100. package/schematics/migrate-eui-slider/index.js +410 -0
  101. package/schematics/migrate-eui-slider/index.js.map +1 -0
  102. package/schematics/migrate-eui-slider/schema.json +19 -0
  103. package/schematics/migrate-eui-tab-signals/index.d.ts +7 -0
  104. package/schematics/migrate-eui-tab-signals/index.js +382 -0
  105. package/schematics/migrate-eui-tab-signals/index.js.map +1 -0
  106. package/schematics/migrate-eui-tab-signals/schema.json +19 -0
  107. package/schematics/migrate-eui-timepicker/index.d.ts +19 -0
  108. package/schematics/migrate-eui-timepicker/index.js +38 -0
  109. package/schematics/migrate-eui-timepicker/index.js.map +1 -0
  110. package/schematics/migrate-eui-timepicker/schema.json +19 -0
  111. package/schematics/migrate-eui-tooltip/index.js +270 -8
  112. package/schematics/migrate-eui-tooltip/index.js.map +1 -1
  113. package/schematics/migrate-ngx-translate-18/index.d.ts +16 -0
  114. package/schematics/migrate-ngx-translate-18/index.js +970 -0
  115. package/schematics/migrate-ngx-translate-18/index.js.map +1 -0
  116. package/schematics/migrate-ngx-translate-18/schema.json +19 -0
  117. package/schematics/migrate-to-signals/index.js +402 -59
  118. package/schematics/migrate-to-signals/index.js.map +1 -1
  119. package/schematics/migrate-to-signals/signal-map.d.ts +20 -0
  120. package/schematics/migrate-to-signals/signal-map.js +182 -3
  121. package/schematics/migrate-to-signals/signal-map.js.map +1 -1
  122. package/types/eui-core.d.ts +13 -6
  123. package/types/eui-core.d.ts.map +1 -1
@@ -0,0 +1,970 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.migrateNgxTranslate18 = migrateNgxTranslate18;
37
+ // code-quality-audit-disabled: IDENTICAL_OPERANDS false positives, the scanner regex matches a prefix of the right operand (e.g. `x && x.y`, `name.text === text`, `c.id !== id`), no identical operands in this file
38
+ const compiler_1 = require("@angular/compiler");
39
+ const core_1 = require("@angular-devkit/core");
40
+ const ts = __importStar(require("typescript"));
41
+ const dry_run_1 = require("../utils/dry-run");
42
+ const todo_comment_1 = require("../utils/todo-comment");
43
+ const CORE = '@ngx-translate/core';
44
+ const HTTP_LOADER = '@ngx-translate/http-loader';
45
+ const TOKEN_PROVIDERS = {
46
+ TranslateLoader: 'provideTranslateLoader',
47
+ TranslateCompiler: 'provideTranslateCompiler',
48
+ TranslateParser: 'provideTranslateParser',
49
+ MissingTranslationHandler: 'provideMissingTranslationHandler',
50
+ };
51
+ const PLUGIN_KEYS = ['loader', 'compiler', 'parser', 'missingTranslationHandler'];
52
+ const MEMBER_RENAMES = {
53
+ setDefaultLang: 'setFallbackLang',
54
+ getDefaultLang: 'getFallbackLang',
55
+ onDefaultLangChange: 'onFallbackLangChange',
56
+ };
57
+ const ASSIGN_OPS = new Set([
58
+ ts.SyntaxKind.EqualsToken,
59
+ ts.SyntaxKind.PlusEqualsToken,
60
+ ts.SyntaxKind.MinusEqualsToken,
61
+ ts.SyntaxKind.QuestionQuestionEqualsToken,
62
+ ts.SyntaxKind.BarBarEqualsToken,
63
+ ts.SyntaxKind.AmpersandAmpersandEqualsToken,
64
+ ]);
65
+ function migrateNgxTranslate18(options = {}) {
66
+ return (tree, context) => {
67
+ const scanPath = options.path ? '/' + options.path.replace(/^\.?\//, '').replace(/\/$/, '') : '';
68
+ const tsFiles = [];
69
+ const htmlFiles = [];
70
+ visitDir(tree.getDir(scanPath || '/'), (path) => (path.endsWith('.html') ? htmlFiles : tsFiles).push(path));
71
+ const projectUsesNgx = tsFiles.some((f) => tree.read(f)?.toString('utf-8').includes(CORE));
72
+ const read = (p) => tree.read(p)?.toString('utf-8');
73
+ // forChild({ extend: true }) services merge translations; setTranslation(lang, t) callers need a review then.
74
+ const projectHasExtend = tsFiles.some((f) => {
75
+ const s = read(f);
76
+ return !!s && s.includes('forChild') && /extend\s*:\s*true/.test(s);
77
+ });
78
+ let fileCount = 0;
79
+ const write = (path, original, result) => {
80
+ if (result === original)
81
+ return;
82
+ if (options.dryRun)
83
+ (0, dry_run_1.logDryRun)(context, `Would migrate @ngx-translate/core usages in ${path}`);
84
+ else
85
+ tree.overwrite(path, result);
86
+ fileCount++;
87
+ };
88
+ for (const path of tsFiles) {
89
+ const original = read(path);
90
+ if (!original)
91
+ continue;
92
+ const hasCore = original.includes(CORE) || original.includes(HTTP_LOADER);
93
+ if (!hasCore && !(original.includes('template') && original.includes('translate')))
94
+ continue;
95
+ write(path, original, migrateTypeScript(original, path, context, { projectHasExtend, projectUsesNgx, read }));
96
+ }
97
+ for (const path of htmlFiles) {
98
+ const original = read(path);
99
+ if (!original || !/translate|currentLang/.test(original))
100
+ continue;
101
+ const members = membersForExternalTemplate(path, tsFiles, read);
102
+ const scan = scanTemplate(original, path, context, {
103
+ members,
104
+ allowKeyRewrite: true,
105
+ checkAttributes: projectUsesNgx,
106
+ where: (o) => `${path}:${lineOf(original, o)}`,
107
+ });
108
+ write(path, original, applyEdits(original, scan.edits));
109
+ }
110
+ context.logger.info(`Migrated @ngx-translate/core usages in ${fileCount} file(s).`);
111
+ if (options.dryRun)
112
+ (0, dry_run_1.logDryRunNote)(context);
113
+ return tree;
114
+ };
115
+ }
116
+ function scanTemplate(source, filePath, context, opts) {
117
+ const result = { edits: [], usage: { pipe: false, directive: false } };
118
+ let parsed;
119
+ try {
120
+ parsed = (0, compiler_1.parseTemplate)(source, filePath, { preserveWhitespaces: true });
121
+ }
122
+ catch {
123
+ return result;
124
+ }
125
+ if (parsed.errors && parsed.errors.length > 0)
126
+ return result;
127
+ const seenWarnings = new Set();
128
+ const warn = (offset, message) => {
129
+ const text = `${opts.where(offset)} - Manual action needed: ${message}`;
130
+ if (opts.quiet || seenWarnings.has(text))
131
+ return;
132
+ seenWarnings.add(text);
133
+ context.logger.warn(text);
134
+ };
135
+ const writes = new Set();
136
+ const isSvc = (r) => r instanceof compiler_1.PropertyRead && r.receiver instanceof compiler_1.ImplicitReceiver && opts.members.has(r.name);
137
+ const visitor = new (class extends compiler_1.CombinedRecursiveAstVisitor {
138
+ visitBinary(ast, context) {
139
+ if (ast.operation.endsWith('=') && !['==', '===', '!=', '!==', '<=', '>='].includes(ast.operation)) {
140
+ const left = ast.left;
141
+ if ((left instanceof compiler_1.PropertyRead || left instanceof compiler_1.SafePropertyRead) && left.name === 'currentLang' && isSvc(left.receiver)) {
142
+ writes.add(left);
143
+ warn(left.sourceSpan.start, 'TranslateService.currentLang is a read-only Signal in @ngx-translate/core v18; use translate.use(lang) instead of assigning it.');
144
+ }
145
+ }
146
+ super.visitBinary(ast, context);
147
+ }
148
+ visitPropertyRead(ast, context) {
149
+ this.rewriteCurrentLang(ast);
150
+ super.visitPropertyRead(ast, context);
151
+ }
152
+ visitSafePropertyRead(ast, context) {
153
+ this.rewriteCurrentLang(ast);
154
+ super.visitSafePropertyRead(ast, context);
155
+ }
156
+ visitPipe(ast, context) {
157
+ if (ast.name === 'translate')
158
+ result.usage.pipe = true;
159
+ super.visitPipe(ast, context);
160
+ }
161
+ visitElement(el) {
162
+ this.checkTranslateAttribute(el);
163
+ super.visitElement(el);
164
+ }
165
+ visitTemplate(t) {
166
+ if ([...t.attributes, ...t.inputs, ...t.templateAttrs].some((a) => a.name === 'translate' || a.name === 'ngx-translate')) {
167
+ result.usage.directive = true;
168
+ }
169
+ super.visitTemplate(t);
170
+ }
171
+ rewriteCurrentLang(ast) {
172
+ if (ast.name !== 'currentLang' || writes.has(ast) || !isSvc(ast.receiver))
173
+ return;
174
+ const end = ast.nameSpan.end;
175
+ if (/^\s*\(/.test(source.slice(end)))
176
+ return; // already a call
177
+ result.edits.push({ start: end, end, replacement: '()' });
178
+ }
179
+ checkTranslateAttribute(el) {
180
+ if (opts.checkAttributes === false)
181
+ return;
182
+ const textAttr = el.attributes.find((a) => a.name === 'translate' || a.name === 'ngx-translate');
183
+ const bound = el.inputs.find((i) => i.name === 'translate' && i.type === compiler_1.BindingType.Property);
184
+ if (textAttr || bound)
185
+ result.usage.directive = true;
186
+ const at = el.startSourceSpan.start.offset;
187
+ const todo = (message) => {
188
+ warn(at, `<${el.name}> ${message}`);
189
+ const edit = (0, todo_comment_1.createTodoEdit)(source, at, message);
190
+ if (edit)
191
+ result.edits.push(edit);
192
+ };
193
+ // 7: [translate]="'KEY'" now sets textContent: element children are overwritten.
194
+ if (bound && el.children.some((c) => !(c instanceof compiler_1.TmplAstText))) {
195
+ todo('with [translate] the element content is replaced by the translation (textContent) in @ngx-translate/core v18, child elements are lost. Restructure the markup.');
196
+ return;
197
+ }
198
+ // 8: <el translate>KEY</el> (text as key) is deprecated.
199
+ if (!textAttr || textAttr.name !== 'translate' || textAttr.value !== '' || bound)
200
+ return;
201
+ const meaningful = el.children.filter((c) => !(c instanceof compiler_1.TmplAstText && c.value.trim() === ''));
202
+ if (meaningful.length === 0)
203
+ return;
204
+ const only = meaningful[0];
205
+ const isPlain = meaningful.length === 1 &&
206
+ el.children.length === 1 &&
207
+ only instanceof compiler_1.TmplAstText &&
208
+ !!el.endSourceSpan &&
209
+ source.slice(el.startSourceSpan.end.offset, el.endSourceSpan.start.offset) === only.value &&
210
+ !/["'`&<>{}\\]/.test(only.value);
211
+ if (!isPlain) {
212
+ todo('uses its text content as translation key, which is deprecated and not safely convertible here (interpolation or nested elements). Use [translate]="\'KEY\'", the translate pipe or *translateBlock.');
213
+ return;
214
+ }
215
+ if (!opts.allowKeyRewrite) {
216
+ warn(at, `<${el.name}> text as translation key is deprecated; replace with [translate]="'KEY'" (not rewritten inside a quoted inline template).`);
217
+ return;
218
+ }
219
+ const key = only.value.trim();
220
+ result.edits.push({
221
+ start: textAttr.sourceSpan.start.offset,
222
+ end: textAttr.sourceSpan.end.offset,
223
+ replacement: `[translate]="'${key}'"`,
224
+ });
225
+ result.edits.push({ start: el.startSourceSpan.end.offset, end: el.endSourceSpan.start.offset, replacement: '' });
226
+ }
227
+ })();
228
+ for (const node of parsed.nodes)
229
+ visitor.visit(node);
230
+ return result;
231
+ }
232
+ /** Members typed/injected as TranslateService of the component whose templateUrl points at `htmlPath`. */
233
+ function membersForExternalTemplate(htmlPath, tsFiles, read) {
234
+ const dir = dirOf(htmlPath);
235
+ for (const f of tsFiles) {
236
+ if (dirOf(f) !== dir || f.endsWith('.spec.ts'))
237
+ continue;
238
+ const src = read(f);
239
+ if (!src || !src.includes('templateUrl') || !src.includes(CORE))
240
+ continue;
241
+ const sf = ts.createSourceFile(f, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
242
+ const helper = new ServiceResolver(sf);
243
+ for (const stmt of sf.statements) {
244
+ if (!ts.isClassDeclaration(stmt))
245
+ continue;
246
+ const url = componentProp(stmt, 'templateUrl');
247
+ if (url && ts.isStringLiteralLike(url.initializer) && resolveUrl(dir, url.initializer.text) === (0, core_1.normalize)(htmlPath)) {
248
+ return helper.members(stmt);
249
+ }
250
+ }
251
+ }
252
+ return new Set();
253
+ }
254
+ function componentObject(cls) {
255
+ for (const d of ts.getDecorators(cls) ?? []) {
256
+ if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === 'Component') {
257
+ const arg = d.expression.arguments[0];
258
+ if (arg && ts.isObjectLiteralExpression(arg))
259
+ return arg;
260
+ }
261
+ }
262
+ return undefined;
263
+ }
264
+ function componentProp(cls, name) {
265
+ return componentObject(cls)?.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name);
266
+ }
267
+ // ---------------------------------------------------------------------------------------------------------------------
268
+ // TranslateService receiver resolution
269
+ // ---------------------------------------------------------------------------------------------------------------------
270
+ class ServiceResolver {
271
+ sf;
272
+ svcName;
273
+ cache = new Map();
274
+ constructor(sf, typeName = 'TranslateService') {
275
+ this.sf = sf;
276
+ this.svcName = importedLocalName(sf, typeName);
277
+ }
278
+ isType(t) {
279
+ return !!this.svcName && !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === this.svcName;
280
+ }
281
+ isInject(e) {
282
+ if (!this.svcName || !e)
283
+ return false;
284
+ const x = unwrap(e);
285
+ if (!ts.isCallExpression(x))
286
+ return false;
287
+ const c = x.expression;
288
+ const named = (ts.isIdentifier(c) && c.text === 'inject') || (ts.isPropertyAccessExpression(c) && c.name.text === 'inject');
289
+ const a = x.arguments[0];
290
+ return named && !!a && ts.isIdentifier(a) && a.text === this.svcName;
291
+ }
292
+ members(cls) {
293
+ const cached = this.cache.get(cls);
294
+ if (cached)
295
+ return cached;
296
+ const set = new Set();
297
+ for (const m of cls.members) {
298
+ if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && (this.isType(m.type) || this.isInject(m.initializer)))
299
+ set.add(m.name.text);
300
+ if (ts.isConstructorDeclaration(m)) {
301
+ for (const p of m.parameters) {
302
+ const isProp = ts.getModifiers(p)?.some((x) => [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(x.kind));
303
+ if (isProp && ts.isIdentifier(p.name) && this.isType(p.type))
304
+ set.add(p.name.text);
305
+ }
306
+ }
307
+ }
308
+ this.cache.set(cls, set);
309
+ return set;
310
+ }
311
+ /** true: declared as TranslateService, false: declared as something else, undefined: not found. */
312
+ bare(id) {
313
+ for (let cur = id.parent; cur; cur = cur.parent) {
314
+ let decls = [];
315
+ if (ts.isFunctionLike(cur))
316
+ decls = cur.parameters;
317
+ else if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur)) {
318
+ decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);
319
+ }
320
+ else if (ts.isCatchClause(cur) && cur.variableDeclaration)
321
+ decls = [cur.variableDeclaration];
322
+ else if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) &&
323
+ cur.initializer &&
324
+ ts.isVariableDeclarationList(cur.initializer)) {
325
+ decls = cur.initializer.declarations;
326
+ }
327
+ const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);
328
+ if (d)
329
+ return this.isType(d.type) || (ts.isVariableDeclaration(d) && this.isInject(d.initializer));
330
+ }
331
+ return undefined;
332
+ }
333
+ isService(expr) {
334
+ const e = unwrap(expr);
335
+ if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) {
336
+ for (let cur = e.parent; cur; cur = cur.parent) {
337
+ if (ts.isClassLike(cur))
338
+ return this.members(cur).has(e.name.text);
339
+ }
340
+ return false;
341
+ }
342
+ return ts.isIdentifier(e) && this.bare(e) === true;
343
+ }
344
+ }
345
+ function unwrap(e) {
346
+ while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e))
347
+ e = e.expression;
348
+ return e;
349
+ }
350
+ /** Local name of a non-type-only named import of `imported` from @ngx-translate/core. */
351
+ function importedLocalName(sf, imported, module = CORE) {
352
+ for (const stmt of sf.statements) {
353
+ if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== module)
354
+ continue;
355
+ const nb = stmt.importClause?.namedBindings;
356
+ if (!nb || !ts.isNamedImports(nb))
357
+ continue;
358
+ for (const el of nb.elements)
359
+ if ((el.propertyName ?? el.name).text === imported)
360
+ return el.name.text;
361
+ }
362
+ return undefined;
363
+ }
364
+ function migrateTypeScript(source, filePath, context, env) {
365
+ const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
366
+ const resolver = new ServiceResolver(sf);
367
+ const edits = [];
368
+ const todos = new Map();
369
+ const needed = new Set();
370
+ const touched = new Set();
371
+ const handled = new Set();
372
+ const moves = new Map();
373
+ const moduleName = importedLocalName(sf, 'TranslateModule') === 'TranslateModule' ? 'TranslateModule' : undefined;
374
+ const setValueName = importedLocalName(sf, 'setValue') === 'setValue' ? 'setValue' : undefined;
375
+ const defaultEvent = importedLocalName(sf, 'DefaultLangChangeEvent') === 'DefaultLangChangeEvent';
376
+ const tokenImported = (t) => importedLocalName(sf, t) === t;
377
+ const providerNames = new Set(['provideTranslateService'].filter((n) => importedLocalName(sf, n) === n));
378
+ let importProvidersTouched = false;
379
+ const seenWarnings = new Set();
380
+ const warnOnce = (text) => {
381
+ if (seenWarnings.has(text))
382
+ return;
383
+ seenWarnings.add(text);
384
+ context.logger.warn(text);
385
+ };
386
+ const storeResolver = new ServiceResolver(sf, 'TranslateStore');
387
+ const httpNames = new Set(['provideTranslateHttpLoader', 'TranslateHttpLoader'].map((n) => importedLocalName(sf, n, HTTP_LOADER)).filter((n) => !!n));
388
+ const iServiceName = importedLocalName(sf, 'ITranslateService');
389
+ const lineNo = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
390
+ const flag = (node, message, comment = true) => {
391
+ warnOnce(`${filePath}:${lineNo(node)} - Manual action needed: ${message}`);
392
+ if (!comment)
393
+ return;
394
+ const anchor = anchorOf(node);
395
+ const key = anchor.getStart(sf);
396
+ const entry = todos.get(key) ?? { anchor, messages: [] };
397
+ const clean = sanitize(message);
398
+ if (!entry.messages.includes(clean))
399
+ entry.messages.push(clean);
400
+ todos.set(key, entry);
401
+ };
402
+ const nameOf = (n) => n && (ts.isIdentifier(n) || ts.isStringLiteral(n)) ? n.text : undefined;
403
+ const propOf = (obj, name) => obj.properties.find((p) => !!p.name && nameOf(p.name) === name);
404
+ // ----- config object transforms (defaultLanguage, useDefaultLang, plugin providers, extend/isolate) -----
405
+ const CHILD_UNSUPPORTED = ['defaultLanguage', 'fallbackLang', 'lang', 'langs', 'useDefaultLang'];
406
+ const transformConfig = (obj, dropChildProps, out, childTarget = false) => {
407
+ const drop = new Set();
408
+ for (const p of obj.properties) {
409
+ const name = nameOf(p.name);
410
+ if (!name)
411
+ continue;
412
+ if (childTarget && CHILD_UNSUPPORTED.includes(name) && ts.isPropertyAssignment(p)) {
413
+ drop.add(p);
414
+ flag(p, `${name} was removed: ChildTranslateServiceConfig has no such option, child services inherit the parent's fallbackLang and language. Set it on the root provideTranslateService() if needed.`);
415
+ continue;
416
+ }
417
+ if (name === 'defaultLanguage') {
418
+ if (ts.isPropertyAssignment(p))
419
+ out.push({
420
+ start: p.name.getStart(sf),
421
+ end: p.name.getEnd(),
422
+ replacement: 'fallbackLang',
423
+ });
424
+ else if (ts.isShorthandPropertyAssignment(p))
425
+ out.push({
426
+ start: p.getStart(sf),
427
+ end: p.getEnd(),
428
+ replacement: 'fallbackLang: defaultLanguage',
429
+ });
430
+ }
431
+ else if (name === 'useDefaultLang' && ts.isPropertyAssignment(p)) {
432
+ if (p.initializer.kind === ts.SyntaxKind.TrueKeyword) {
433
+ drop.add(p);
434
+ }
435
+ else {
436
+ flag(p, 'useDefaultLang was removed in @ngx-translate/core v18 and is kept only because its value is false: v18 always falls back to fallbackLang when it is set. Remove the leftover property manually (it does not compile as is); drop fallbackLang too if you relied on useDefaultLang: false.');
437
+ }
438
+ }
439
+ else if (dropChildProps && (name === 'extend' || name === 'isolate') && ts.isPropertyAssignment(p)) {
440
+ drop.add(p);
441
+ }
442
+ else if (PLUGIN_KEYS.includes(name) && ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {
443
+ const init = p.initializer;
444
+ const provide = propOf(init, 'provide');
445
+ const token = provide && ts.isPropertyAssignment(provide) && ts.isIdentifier(provide.initializer) ? provide.initializer.text : undefined;
446
+ if (!token || !TOKEN_PROVIDERS[token])
447
+ continue;
448
+ const useClass = propOf(init, 'useClass');
449
+ if (init.properties.length === 2 && useClass && ts.isPropertyAssignment(useClass) && tokenImported(token)) {
450
+ const fn = TOKEN_PROVIDERS[token];
451
+ out.push({
452
+ start: init.getStart(sf),
453
+ end: init.getEnd(),
454
+ replacement: `${fn}(${useClass.initializer.getText(sf)})`,
455
+ });
456
+ needed.add(fn);
457
+ touched.add(token);
458
+ }
459
+ else {
460
+ flag(p, `the ${token} provider uses a form other than { provide, useClass } (useFactory/useValue/deps). Convert it manually to ${TOKEN_PROVIDERS[token]}(...).`);
461
+ }
462
+ }
463
+ }
464
+ if (drop.size > 0)
465
+ out.push(...removeArrayElements(obj, new Set([...drop].map((d) => obj.properties.indexOf(d))), sf));
466
+ return drop.size;
467
+ };
468
+ // ----- TranslateModule.forRoot / forChild -----
469
+ const convertModuleCall = (call) => {
470
+ const callee = call.expression;
471
+ handled.add(callee.expression);
472
+ const method = callee.name.text;
473
+ const args = call.arguments;
474
+ const undecidable = (why) => flag(call, `TranslateModule.${method}() was left unchanged: ${why}. Use provideTranslateService() / provideChildTranslateService() manually.`);
475
+ if (args.length > 1 || (args.length === 1 && !ts.isObjectLiteralExpression(args[0])))
476
+ return undecidable('its config is not an object literal');
477
+ const obj = args[0];
478
+ let fn = method === 'forRoot' ? 'provideTranslateService' : 'provideChildTranslateService';
479
+ let hadExtendTrue = false;
480
+ if (method === 'forChild' && obj) {
481
+ for (const p of obj.properties) {
482
+ const name = p.name ? nameOf(p.name) : undefined;
483
+ if (ts.isSpreadAssignment(p))
484
+ return undecidable('its config contains a spread');
485
+ if (name !== 'isolate' && name !== 'extend')
486
+ continue;
487
+ const init = ts.isPropertyAssignment(p) ? p.initializer.kind : undefined;
488
+ if (init !== ts.SyntaxKind.TrueKeyword && init !== ts.SyntaxKind.FalseKeyword)
489
+ return undecidable(`${name} is not a boolean literal`);
490
+ if (name === 'isolate' && init === ts.SyntaxKind.TrueKeyword)
491
+ fn = 'provideTranslateService';
492
+ if (name === 'extend' && init === ts.SyntaxKind.TrueKeyword)
493
+ hadExtendTrue = true;
494
+ }
495
+ }
496
+ // the placement is decided first, so nothing is emitted for an unmovable call
497
+ const parent = call.parent;
498
+ let move;
499
+ let unwrapImportProviders;
500
+ if (ts.isArrayLiteralExpression(parent) && ts.isPropertyAssignment(parent.parent) && nameOf(parent.parent.name) === 'imports' && ts.isObjectLiteralExpression(parent.parent.parent)) {
501
+ const owner = parent.parent.parent;
502
+ const decorator = owner.parent;
503
+ if (ts.isCallExpression(decorator) && ts.isIdentifier(decorator.expression) && decorator.expression.text === 'Component') {
504
+ return undecidable('a standalone @Component cannot take environment providers; provide it in the application/route providers instead');
505
+ }
506
+ move = owner;
507
+ }
508
+ else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'importProvidersFrom') {
509
+ if (parent.arguments.length !== 1)
510
+ return undecidable('it is combined with other sources in importProvidersFrom()');
511
+ unwrapImportProviders = parent;
512
+ }
513
+ const local = [];
514
+ const removed = obj ? transformConfig(obj, method === 'forChild', local, fn === 'provideChildTranslateService') : 0;
515
+ const keepConfig = !!obj && obj.properties.length - removed > 0;
516
+ const cfgText = keepConfig ? applyEdits(source.slice(obj.getStart(sf), obj.getEnd()), shift(local, -obj.getStart(sf))) : '';
517
+ const text = `${fn}(${cfgText})`;
518
+ needed.add(fn);
519
+ touched.add('TranslateModule');
520
+ if (method === 'forChild') {
521
+ warnOnce(`${filePath}:${lineNo(call)} - forChild() was converted to ${fn}(): v18 child services use their own store with parent fallback, review isolation semantics.${hadExtendTrue ? ' extend: true was removed: setTranslation(lang, t) no longer merges, pass true as third argument where needed.' : ''}`);
522
+ }
523
+ if (move) {
524
+ const g = moves.get(move) ?? { calls: [], texts: [] };
525
+ g.calls.push(call);
526
+ g.texts.push(text);
527
+ moves.set(move, g);
528
+ }
529
+ else if (unwrapImportProviders) {
530
+ edits.push({ start: unwrapImportProviders.getStart(sf), end: unwrapImportProviders.getEnd(), replacement: text });
531
+ importProvidersTouched = true;
532
+ }
533
+ else {
534
+ edits.push({ start: call.getStart(sf), end: call.getEnd(), replacement: text });
535
+ }
536
+ };
537
+ // ----- bare TranslateModule in imports/exports -----
538
+ const convertBareModule = (id, arr, owner) => {
539
+ handled.add(id);
540
+ const callNode = owner.parent;
541
+ const kind = ts.isCallExpression(callNode) && ts.isIdentifier(callNode.expression) ? callNode.expression.text : '';
542
+ let names = ['TranslatePipe', 'TranslateDirective'];
543
+ if (kind === 'Component') {
544
+ const u = componentUsage(owner);
545
+ if (u)
546
+ names = [u.pipe ? 'TranslatePipe' : '', u.directive ? 'TranslateDirective' : ''].filter(Boolean);
547
+ }
548
+ const present = new Set(arr.elements.filter(ts.isIdentifier).map((e) => e.text));
549
+ const add = names.filter((n) => !present.has(n));
550
+ touched.add('TranslateModule');
551
+ for (const n of names)
552
+ needed.add(n);
553
+ if (add.length > 0) {
554
+ edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: add.join(', ') });
555
+ }
556
+ else {
557
+ edits.push(...removeArrayElements(arr, new Set([arr.elements.indexOf(id)]), sf));
558
+ }
559
+ };
560
+ const componentUsage = (owner) => {
561
+ const tpl = propOf(owner, 'template');
562
+ const url = propOf(owner, 'templateUrl');
563
+ const quiet = { members: new Set(), allowKeyRewrite: false, where: () => '', quiet: true };
564
+ if (tpl && ts.isPropertyAssignment(tpl) && (ts.isNoSubstitutionTemplateLiteral(tpl.initializer) || ts.isStringLiteral(tpl.initializer))) {
565
+ const lit = tpl.initializer;
566
+ return scanTemplate(source.slice(lit.getStart(sf) + 1, lit.getEnd() - 1), filePath, context, quiet).usage;
567
+ }
568
+ if (url && ts.isPropertyAssignment(url) && ts.isStringLiteralLike(url.initializer)) {
569
+ const target = resolveUrl(dirOf(filePath), url.initializer.text);
570
+ const html = env.read(target);
571
+ if (html !== undefined)
572
+ return scanTemplate(html, target, context, quiet).usage;
573
+ }
574
+ return null;
575
+ };
576
+ // ----- visitor -----
577
+ const visit = (node) => {
578
+ if (ts.isImportDeclaration(node))
579
+ return;
580
+ if (ts.isCallExpression(node))
581
+ visitCall(node);
582
+ else if (ts.isPropertyAccessExpression(node))
583
+ visitMember(node);
584
+ else if (ts.isVariableDeclaration(node))
585
+ visitAlias(node.name, node.initializer, node);
586
+ else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken)
587
+ visitAlias(undefined, node.right, node);
588
+ else if (ts.isIdentifier(node))
589
+ visitIdentifier(node);
590
+ else if (ts.isClassDeclaration(node))
591
+ visitInlineTemplate(node);
592
+ ts.forEachChild(node, visit);
593
+ };
594
+ const visitCall = (call) => {
595
+ const c = call.expression;
596
+ if (moduleName && ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === moduleName && (c.name.text === 'forRoot' || c.name.text === 'forChild')) {
597
+ convertModuleCall(call);
598
+ return;
599
+ }
600
+ if (ts.isIdentifier(c) && providerNames.has(c.text) && call.arguments[0] && ts.isObjectLiteralExpression(call.arguments[0])) {
601
+ transformConfig(call.arguments[0], false, edits);
602
+ }
603
+ if (setValueName && ts.isIdentifier(c) && c.text === setValueName) {
604
+ const a0 = call.arguments[0];
605
+ const assignable = !!a0 && (ts.isIdentifier(a0) || ts.isPropertyAccessExpression(a0) || ts.isElementAccessExpression(a0));
606
+ if (ts.isExpressionStatement(call.parent) && call.arguments.length === 3 && assignable) {
607
+ edits.push({ start: c.getStart(sf), end: c.getEnd(), replacement: `${a0.getText(sf)} = insertValue` });
608
+ needed.add('insertValue');
609
+ touched.add('setValue');
610
+ }
611
+ else {
612
+ flag(call, 'setValue() was replaced by insertValue(), which returns a new object instead of mutating its argument. Use `target = insertValue(target, key, value)` manually.');
613
+ }
614
+ }
615
+ if (ts.isPropertyAccessExpression(c) && resolver.isService(c.expression)) {
616
+ if (c.name.text === 'getCurrentLang') {
617
+ flag(call, 'getCurrentLang() returns Language | null in @ngx-translate/core v18 (null before a language is set). Handle the null case, e.g. `?? fallback`.');
618
+ }
619
+ else if (c.name.text === 'setTranslation' && call.arguments.length === 2 && env.projectHasExtend) {
620
+ flag(call, 'setTranslation(lang, translations) no longer merges for services that used forChild({ extend: true }); pass `true` as third argument if you relied on merging.');
621
+ }
622
+ }
623
+ };
624
+ const visitMember = (n) => {
625
+ const member = n.name.text;
626
+ if ((member === 'onTranslationChange' || member === 'getValue') && storeResolver.isService(n.expression)) {
627
+ edits.push({
628
+ start: n.name.getStart(sf),
629
+ end: n.name.getEnd(),
630
+ replacement: member === 'getValue' ? 'getTranslationValue' : 'translationChange$',
631
+ });
632
+ return;
633
+ }
634
+ const isTracked = ['currentLang', 'langs', 'defaultLang', ...Object.keys(MEMBER_RENAMES)].includes(member);
635
+ if (!isTracked || !resolver.isService(n.expression))
636
+ return;
637
+ const parent = n.parent;
638
+ if (MEMBER_RENAMES[member]) {
639
+ edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: MEMBER_RENAMES[member] });
640
+ return;
641
+ }
642
+ if (ts.isCallExpression(parent) && parent.expression === n)
643
+ return; // already `currentLang()` etc.
644
+ const isWrite = (ts.isBinaryExpression(parent) && parent.left === n && ASSIGN_OPS.has(parent.operatorToken.kind)) ||
645
+ ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&
646
+ (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) ||
647
+ ts.isDeleteExpression(parent);
648
+ if (isWrite) {
649
+ flag(n, `${member} cannot be assigned in @ngx-translate/core v18 (read-only Signal / removed). Use use(), setFallbackLang() or setTranslation() instead.`);
650
+ return;
651
+ }
652
+ if (member === 'currentLang')
653
+ edits.push({ start: n.getEnd(), end: n.getEnd(), replacement: '()' });
654
+ else if (member === 'langs')
655
+ edits.push({
656
+ start: n.name.getStart(sf),
657
+ end: n.name.getEnd(),
658
+ replacement: 'getLangs()',
659
+ });
660
+ else
661
+ edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: 'fallbackLang()' });
662
+ };
663
+ const visitAlias = (name, init, at) => {
664
+ if (!init)
665
+ return;
666
+ if (!resolver.isService(init) && !(name && ts.isObjectBindingPattern(name) && resolver.isInject(init)))
667
+ return;
668
+ if (name && ts.isIdentifier(name) && ts.isVariableDeclaration(at) && resolver.isType(at.type))
669
+ return; // typed alias is tracked
670
+ flag(at, 'TranslateService is aliased or destructured here, so currentLang/default*/langs usages through it are not migrated automatically. Review them against the v18 API (currentLang() signal, fallbackLang, getLangs()).');
671
+ };
672
+ const visitIdentifier = (id) => {
673
+ const p = id.parent;
674
+ if ((ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id))
675
+ return;
676
+ if (httpNames.has(id.text)) {
677
+ const call = ts.isCallExpression(p) && p.expression === id ? p : undefined;
678
+ const cfg = call?.arguments[0];
679
+ const hasFlag = !!cfg && ts.isObjectLiteralExpression(cfg) && !!propOf(cfg, 'failOnError');
680
+ if (!hasFlag) {
681
+ flag(id, 'the v18 http-loader no longer fails the whole language load when a translation file request fails (it logs a warning and uses {}). Pass failOnError: true to provideTranslateHttpLoader() if you rely on the v17 behaviour.');
682
+ }
683
+ }
684
+ if (iServiceName && id.text === iServiceName && ts.isExpressionWithTypeArguments(p) && ts.isHeritageClause(p.parent) && p.parent.token === ts.SyntaxKind.ImplementsKeyword) {
685
+ flag(id, 'ITranslateService gained isLoading: Signal<boolean> in @ngx-translate/core v18. Add isLoading = signal(false).asReadonly() to this class.');
686
+ }
687
+ if (defaultEvent && id.text === 'DefaultLangChangeEvent') {
688
+ edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: 'FallbackLangChangeEvent' });
689
+ needed.add('FallbackLangChangeEvent');
690
+ touched.add('DefaultLangChangeEvent');
691
+ }
692
+ if (moduleName && id.text === moduleName && !handled.has(id)) {
693
+ // `TranslateModule` as an element of imports / exports
694
+ if (ts.isArrayLiteralExpression(p) && ts.isPropertyAssignment(p.parent) && ['imports', 'exports'].includes(nameOf(p.parent.name) ?? '') && ts.isObjectLiteralExpression(p.parent.parent)) {
695
+ convertBareModule(id, p, p.parent.parent);
696
+ }
697
+ }
698
+ };
699
+ const visitInlineTemplate = (cls) => {
700
+ const tpl = componentProp(cls, 'template');
701
+ if (!tpl)
702
+ return;
703
+ const lit = tpl.initializer;
704
+ if (!ts.isNoSubstitutionTemplateLiteral(lit) && !ts.isStringLiteral(lit))
705
+ return;
706
+ const start = lit.getStart(sf) + 1;
707
+ const raw = source.slice(start, lit.getEnd() - 1);
708
+ if (!/translate|currentLang/.test(raw))
709
+ return;
710
+ const baseLine = sf.getLineAndCharacterOfPosition(start).line;
711
+ const scan = scanTemplate(raw, filePath, context, {
712
+ members: resolver.members(cls),
713
+ allowKeyRewrite: ts.isNoSubstitutionTemplateLiteral(lit),
714
+ checkAttributes: env.projectUsesNgx,
715
+ where: (o) => `${filePath}:${baseLine + lineOf(raw, o)}`,
716
+ });
717
+ edits.push(...shift(scan.edits, start));
718
+ };
719
+ visit(sf);
720
+ // moved forRoot/forChild calls: imports -> providers
721
+ for (const [obj, g] of moves) {
722
+ const importsProp = propOf(obj, 'imports');
723
+ const arr = importsProp.initializer;
724
+ const providersProp = propOf(obj, 'providers');
725
+ if (providersProp && !(ts.isPropertyAssignment(providersProp) && ts.isArrayLiteralExpression(providersProp.initializer))) {
726
+ for (const call of g.calls)
727
+ flag(call, 'the providers property is not an array literal, so the converted provider could not be moved there. Move it manually.');
728
+ continue;
729
+ }
730
+ const texts = g.texts.join(', ');
731
+ const movedIdx = new Set(g.calls.map((c) => arr.elements.indexOf(c)));
732
+ const keepsOthers = arr.elements.length > movedIdx.size;
733
+ if (providersProp) {
734
+ const parr = providersProp.initializer;
735
+ if (parr.elements.length > 0) {
736
+ edits.push({
737
+ start: parr.elements[parr.elements.length - 1].getEnd(),
738
+ end: parr.elements[parr.elements.length - 1].getEnd(),
739
+ replacement: `, ${texts}`,
740
+ });
741
+ }
742
+ else {
743
+ edits.push({ start: parr.getStart(sf) + 1, end: parr.getEnd() - 1, replacement: texts });
744
+ }
745
+ if (keepsOthers)
746
+ edits.push(...removeArrayElements(arr, movedIdx, sf));
747
+ else
748
+ removeObjectProperty(importsProp, sf, edits);
749
+ }
750
+ else if (!keepsOthers) {
751
+ edits.push({ start: importsProp.getStart(sf), end: importsProp.getEnd(), replacement: `providers: [${texts}]` });
752
+ }
753
+ else {
754
+ edits.push(...removeArrayElements(arr, movedIdx, sf));
755
+ const multiline = source.slice(obj.getStart(sf), importsProp.getEnd()).includes('\n');
756
+ const indent = multiline ? /[ \t]*$/.exec(source.slice(0, importsProp.getStart(sf)))[0] : '';
757
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
758
+ edits.push({
759
+ start: importsProp.getEnd(),
760
+ end: importsProp.getEnd(),
761
+ replacement: multiline ? `,${eol}${indent}providers: [${texts}]` : `, providers: [${texts}]`,
762
+ });
763
+ }
764
+ }
765
+ // remaining references to the removed module
766
+ if (moduleName) {
767
+ const mark = (n) => {
768
+ if (ts.isImportDeclaration(n))
769
+ return;
770
+ if (ts.isIdentifier(n) && n.text === moduleName && !handled.has(n) && !isPropertyName(n)) {
771
+ flag(n, 'TranslateModule was removed in @ngx-translate/core v18. Use provideTranslateService() / provideChildTranslateService() and import TranslatePipe / TranslateDirective directly.');
772
+ }
773
+ ts.forEachChild(n, mark);
774
+ };
775
+ mark(sf);
776
+ }
777
+ // TODO comments, one line above the anchor, never duplicated
778
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
779
+ for (const { anchor, messages } of todos.values()) {
780
+ const start = anchor.getStart(sf);
781
+ const lineStart = source.lastIndexOf('\n', start - 1) + 1;
782
+ const indent = /^[ \t]*/.exec(source.slice(lineStart))[0];
783
+ const above = new Set();
784
+ const lines = source.slice(0, lineStart).split(/\r?\n/);
785
+ for (let i = lines.length - 2; i >= 0 && lines[i].trim().startsWith('// ' + todo_comment_1.TODO_PREFIX); i--)
786
+ above.add(lines[i].trim());
787
+ const fresh = messages.map((m) => `// ${todo_comment_1.TODO_PREFIX} ${m}`).filter((l) => !above.has(l));
788
+ if (fresh.length > 0)
789
+ edits.push({
790
+ start: lineStart,
791
+ end: lineStart,
792
+ replacement: fresh.map((l) => `${indent}${l}${eol}`).join(''),
793
+ });
794
+ }
795
+ let result = applyEdits(source, edits);
796
+ if (result === source)
797
+ return source;
798
+ result = fixImports(result, filePath, CORE, needed, touched);
799
+ if (importProvidersTouched)
800
+ result = fixImports(result, filePath, '@angular/core', new Set(), new Set(['importProvidersFrom']));
801
+ return result;
802
+ }
803
+ // ---------------------------------------------------------------------------------------------------------------------
804
+ // Imports
805
+ // ---------------------------------------------------------------------------------------------------------------------
806
+ const RENAME_IN_PLACE = {
807
+ DefaultLangChangeEvent: 'FallbackLangChangeEvent',
808
+ setValue: 'insertValue',
809
+ };
810
+ /**
811
+ * Drops `touched` specifiers that are no longer referenced (renaming in place when a rename is known) and
812
+ * appends the `needed` names to the first named import of `moduleName`.
813
+ */
814
+ function fixImports(text, filePath, moduleName, needed, touched) {
815
+ const sf = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
816
+ const referenced = (name) => {
817
+ let found = false;
818
+ const walk = (n) => {
819
+ if (found || ts.isImportDeclaration(n))
820
+ return;
821
+ if (ts.isIdentifier(n) && n.text === name && !isPropertyName(n))
822
+ found = true;
823
+ ts.forEachChild(n, walk);
824
+ };
825
+ walk(sf);
826
+ return found;
827
+ };
828
+ const decls = sf.statements.filter((s) => ts.isImportDeclaration(s) &&
829
+ ts.isStringLiteral(s.moduleSpecifier) &&
830
+ s.moduleSpecifier.text === moduleName &&
831
+ !!s.importClause?.namedBindings &&
832
+ ts.isNamedImports(s.importClause.namedBindings) &&
833
+ !s.importClause.isTypeOnly);
834
+ if (decls.length === 0)
835
+ return text;
836
+ const all = new Set();
837
+ for (const d of decls)
838
+ for (const e of d.importClause.namedBindings.elements)
839
+ all.add(e.name.text);
840
+ const placed = new Set();
841
+ const edits = [];
842
+ const pendingNeeded = [...needed];
843
+ decls.forEach((d, di) => {
844
+ const named = d.importClause.namedBindings;
845
+ const items = [];
846
+ for (const e of named.elements) {
847
+ const name = e.name.text;
848
+ if (touched.has(name) && !e.propertyName && !referenced(name)) {
849
+ const to = RENAME_IN_PLACE[name];
850
+ if (to && needed.has(to) && !all.has(to) && !placed.has(to)) {
851
+ items.push(to);
852
+ placed.add(to);
853
+ }
854
+ continue;
855
+ }
856
+ items.push(e.getText(sf));
857
+ }
858
+ if (di === 0) {
859
+ for (const n of pendingNeeded)
860
+ if (!all.has(n) && !placed.has(n) && !items.includes(n))
861
+ items.push(n);
862
+ }
863
+ const before = named.elements.map((e) => e.getText(sf));
864
+ if (items.length === before.length && items.every((v, i) => v === before[i]))
865
+ return;
866
+ if (items.length === 0 && !d.importClause.name) {
867
+ let end = d.getEnd();
868
+ if (text[end] === '\r')
869
+ end++;
870
+ if (text[end] === '\n')
871
+ end++;
872
+ edits.push({ start: d.getStart(sf), end, replacement: '' });
873
+ }
874
+ else {
875
+ const multiline = named.getText(sf).includes('\n');
876
+ const body = multiline ? `{\n ${items.join(',\n ')},\n}` : `{ ${items.join(', ')} }`;
877
+ edits.push({ start: named.getStart(sf), end: named.getEnd(), replacement: body });
878
+ }
879
+ });
880
+ return applyEdits(text, edits);
881
+ }
882
+ // ---------------------------------------------------------------------------------------------------------------------
883
+ // Utilities
884
+ // ---------------------------------------------------------------------------------------------------------------------
885
+ function isPropertyName(id) {
886
+ const p = id.parent;
887
+ return (ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id);
888
+ }
889
+ function sanitize(message) {
890
+ return message.replace(/\s+/g, ' ').trim();
891
+ }
892
+ /** Nearest ancestor that is a statement, class member or object property: the TODO goes on the line above it. */
893
+ function anchorOf(node) {
894
+ let cur = node;
895
+ while (cur.parent) {
896
+ const p = cur.parent;
897
+ if (ts.isSourceFile(p) || ts.isBlock(p) || ts.isModuleBlock(p) || ts.isClassLike(p) || ts.isObjectLiteralExpression(p) || ts.isCaseClause(p) || ts.isDefaultClause(p)) {
898
+ return cur;
899
+ }
900
+ cur = p;
901
+ }
902
+ return cur;
903
+ }
904
+ const dirOf = (p) => (0, core_1.dirname)((0, core_1.normalize)(p));
905
+ const resolveUrl = (dir, url) => (0, core_1.normalize)((0, core_1.join)((0, core_1.normalize)(dir), url));
906
+ function lineOf(source, offset) {
907
+ return source.slice(0, offset).split('\n').length;
908
+ }
909
+ function shift(edits, by) {
910
+ return edits.map((e) => ({ ...e, start: e.start + by, end: e.end + by }));
911
+ }
912
+ /** Removes one object property together with its separating comma. */
913
+ function removeObjectProperty(prop, sf, edits) {
914
+ const obj = prop.parent;
915
+ const props = obj.properties;
916
+ const idx = props.indexOf(prop);
917
+ const text = sf.getFullText();
918
+ let start = prop.getStart(sf);
919
+ let end = prop.getEnd();
920
+ if (idx < props.length - 1) {
921
+ end = props[idx + 1].getStart(sf);
922
+ }
923
+ else if (idx > 0) {
924
+ start = props[idx - 1].getEnd();
925
+ }
926
+ else if (text[end] === ',') {
927
+ end++;
928
+ }
929
+ edits.push({ start, end, replacement: '' });
930
+ }
931
+ /** Removes the array elements at `indices`; non-overlapping ranges even for neighbouring elements. */
932
+ function removeArrayElements(arr, indices, sf) {
933
+ const els = ts.isArrayLiteralExpression(arr) ? arr.elements : arr.properties;
934
+ const keptIdx = els.findIndex((_, i) => !indices.has(i));
935
+ if (keptIdx === -1)
936
+ return [{ start: arr.getStart(sf) + 1, end: arr.getEnd() - 1, replacement: '' }];
937
+ const out = [];
938
+ if (keptIdx > 0)
939
+ out.push({ start: els[0].getStart(sf), end: els[keptIdx].getStart(sf), replacement: '' });
940
+ for (let i = keptIdx + 1; i < els.length; i++) {
941
+ if (indices.has(i))
942
+ out.push({ start: els[i - 1].getEnd(), end: els[i].getEnd(), replacement: '' });
943
+ }
944
+ return out;
945
+ }
946
+ function applyEdits(source, edits) {
947
+ const seen = new Map();
948
+ for (const e of edits)
949
+ seen.set(`${e.start}:${e.end}:${e.replacement}`, e);
950
+ let result = source;
951
+ for (const e of [...seen.values()].sort((a, b) => b.start - a.start || b.end - a.end)) {
952
+ result = result.slice(0, e.start) + e.replacement + result.slice(e.end);
953
+ }
954
+ return result;
955
+ }
956
+ function visitDir(dir, callback) {
957
+ for (const file of dir.subfiles) {
958
+ if (file.endsWith('.d.ts'))
959
+ continue;
960
+ if (!file.endsWith('.ts') && !file.endsWith('.html'))
961
+ continue;
962
+ callback(`${dir.path}/${file}`);
963
+ }
964
+ for (const sub of dir.subdirs) {
965
+ if (sub === 'node_modules' || sub === 'dist')
966
+ continue;
967
+ visitDir(dir.dir(sub), callback);
968
+ }
969
+ }
970
+ //# sourceMappingURL=index.js.map