@angular/upgrade 19.2.1 → 19.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1240 @@
1
+ /**
2
+ * @license Angular v19.2.3
3
+ * (c) 2010-2025 Google LLC. https://angular.io/
4
+ * License: MIT
5
+ */
6
+
7
+ import { Version, ɵNG_MOD_DEF as _NG_MOD_DEF, Injector, ChangeDetectorRef, Testability, TestabilityRegistry, ApplicationRef, SimpleChange, ɵSIGNAL as _SIGNAL, NgZone, ComponentFactoryResolver } from '@angular/core';
8
+
9
+ /**
10
+ * @module
11
+ * @description
12
+ * Entry point for all public APIs of the upgrade package.
13
+ */
14
+ /**
15
+ * @publicApi
16
+ */
17
+ const VERSION = new Version('19.2.3');
18
+
19
+ function noNg() {
20
+ throw new Error('AngularJS v1.x is not loaded!');
21
+ }
22
+ const noNgElement = (() => noNg());
23
+ noNgElement.cleanData = noNg;
24
+ let angular = {
25
+ bootstrap: noNg,
26
+ module: noNg,
27
+ element: noNgElement,
28
+ injector: noNg,
29
+ version: undefined,
30
+ resumeBootstrap: noNg,
31
+ getTestability: noNg,
32
+ };
33
+ try {
34
+ if (window.hasOwnProperty('angular')) {
35
+ angular = window.angular;
36
+ }
37
+ }
38
+ catch {
39
+ // ignore in CJS mode.
40
+ }
41
+ /**
42
+ * @deprecated Use `setAngularJSGlobal` instead.
43
+ *
44
+ * @publicApi
45
+ */
46
+ function setAngularLib(ng) {
47
+ setAngularJSGlobal(ng);
48
+ }
49
+ /**
50
+ * @deprecated Use `getAngularJSGlobal` instead.
51
+ *
52
+ * @publicApi
53
+ */
54
+ function getAngularLib() {
55
+ return getAngularJSGlobal();
56
+ }
57
+ /**
58
+ * Resets the AngularJS global.
59
+ *
60
+ * Used when AngularJS is loaded lazily, and not available on `window`.
61
+ *
62
+ * @publicApi
63
+ */
64
+ function setAngularJSGlobal(ng) {
65
+ angular = ng;
66
+ }
67
+ /**
68
+ * Returns the current AngularJS global.
69
+ *
70
+ * @publicApi
71
+ */
72
+ function getAngularJSGlobal() {
73
+ return angular;
74
+ }
75
+ const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config);
76
+ // Do not declare as `module` to avoid webpack bug
77
+ // (see https://github.com/angular/angular/issues/30050).
78
+ const module_ = (prefix, dependencies) => angular.module(prefix, dependencies);
79
+ const element = ((e) => angular.element(e));
80
+ element.cleanData = (nodes) => angular.element.cleanData(nodes);
81
+ const injector = (modules, strictDi) => angular.injector(modules, strictDi);
82
+ const resumeBootstrap = () => angular.resumeBootstrap();
83
+ const getTestability = (e) => angular.getTestability(e);
84
+
85
+ var angular1 = /*#__PURE__*/Object.freeze({
86
+ __proto__: null,
87
+ bootstrap: bootstrap,
88
+ element: element,
89
+ getAngularJSGlobal: getAngularJSGlobal,
90
+ getAngularLib: getAngularLib,
91
+ getTestability: getTestability,
92
+ injector: injector,
93
+ module_: module_,
94
+ resumeBootstrap: resumeBootstrap,
95
+ setAngularJSGlobal: setAngularJSGlobal,
96
+ setAngularLib: setAngularLib
97
+ });
98
+
99
+ const $COMPILE = '$compile';
100
+ const $CONTROLLER = '$controller';
101
+ const $DELEGATE = '$delegate';
102
+ const $EXCEPTION_HANDLER = '$exceptionHandler';
103
+ const $HTTP_BACKEND = '$httpBackend';
104
+ const $INJECTOR = '$injector';
105
+ const $INTERVAL = '$interval';
106
+ const $PARSE = '$parse';
107
+ const $PROVIDE = '$provide';
108
+ const $ROOT_ELEMENT = '$rootElement';
109
+ const $ROOT_SCOPE = '$rootScope';
110
+ const $SCOPE = '$scope';
111
+ const $TEMPLATE_CACHE = '$templateCache';
112
+ const $TEMPLATE_REQUEST = '$templateRequest';
113
+ const $$TESTABILITY = '$$testability';
114
+ const COMPILER_KEY = '$$angularCompiler';
115
+ const DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount';
116
+ const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes';
117
+ const INJECTOR_KEY = '$$angularInjector';
118
+ const LAZY_MODULE_REF = '$$angularLazyModuleRef';
119
+ const NG_ZONE_KEY = '$$angularNgZone';
120
+ const UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType';
121
+ const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
122
+ const REQUIRE_NG_MODEL = '?ngModel';
123
+ const UPGRADE_MODULE_NAME = '$$UpgradeModule';
124
+
125
+ var constants = /*#__PURE__*/Object.freeze({
126
+ __proto__: null,
127
+ $$TESTABILITY: $$TESTABILITY,
128
+ $COMPILE: $COMPILE,
129
+ $CONTROLLER: $CONTROLLER,
130
+ $DELEGATE: $DELEGATE,
131
+ $EXCEPTION_HANDLER: $EXCEPTION_HANDLER,
132
+ $HTTP_BACKEND: $HTTP_BACKEND,
133
+ $INJECTOR: $INJECTOR,
134
+ $INTERVAL: $INTERVAL,
135
+ $PARSE: $PARSE,
136
+ $PROVIDE: $PROVIDE,
137
+ $ROOT_ELEMENT: $ROOT_ELEMENT,
138
+ $ROOT_SCOPE: $ROOT_SCOPE,
139
+ $SCOPE: $SCOPE,
140
+ $TEMPLATE_CACHE: $TEMPLATE_CACHE,
141
+ $TEMPLATE_REQUEST: $TEMPLATE_REQUEST,
142
+ COMPILER_KEY: COMPILER_KEY,
143
+ DOWNGRADED_MODULE_COUNT_KEY: DOWNGRADED_MODULE_COUNT_KEY,
144
+ GROUP_PROJECTABLE_NODES_KEY: GROUP_PROJECTABLE_NODES_KEY,
145
+ INJECTOR_KEY: INJECTOR_KEY,
146
+ LAZY_MODULE_REF: LAZY_MODULE_REF,
147
+ NG_ZONE_KEY: NG_ZONE_KEY,
148
+ REQUIRE_INJECTOR: REQUIRE_INJECTOR,
149
+ REQUIRE_NG_MODEL: REQUIRE_NG_MODEL,
150
+ UPGRADE_APP_TYPE_KEY: UPGRADE_APP_TYPE_KEY,
151
+ UPGRADE_MODULE_NAME: UPGRADE_MODULE_NAME
152
+ });
153
+
154
+ /**
155
+ * A `PropertyBinding` represents a mapping between a property name
156
+ * and an attribute name. It is parsed from a string of the form
157
+ * `"prop: attr"`; or simply `"propAndAttr" where the property
158
+ * and attribute have the same identifier.
159
+ */
160
+ class PropertyBinding {
161
+ prop;
162
+ attr;
163
+ bracketAttr;
164
+ bracketParenAttr;
165
+ parenAttr;
166
+ onAttr;
167
+ bindAttr;
168
+ bindonAttr;
169
+ constructor(prop, attr) {
170
+ this.prop = prop;
171
+ this.attr = attr;
172
+ this.bracketAttr = `[${this.attr}]`;
173
+ this.parenAttr = `(${this.attr})`;
174
+ this.bracketParenAttr = `[(${this.attr})]`;
175
+ const capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.slice(1);
176
+ this.onAttr = `on${capitalAttr}`;
177
+ this.bindAttr = `bind${capitalAttr}`;
178
+ this.bindonAttr = `bindon${capitalAttr}`;
179
+ }
180
+ }
181
+
182
+ const DIRECTIVE_PREFIX_REGEXP = /^(?:x|data)[:\-_]/i;
183
+ const DIRECTIVE_SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
184
+ function onError(e) {
185
+ // TODO: (misko): We seem to not have a stack trace here!
186
+ console.error(e, e.stack);
187
+ throw e;
188
+ }
189
+ /**
190
+ * Clean the jqLite/jQuery data on the element and all its descendants.
191
+ * Equivalent to how jqLite/jQuery invoke `cleanData()` on an Element when removed:
192
+ * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
193
+ * https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
194
+ *
195
+ * NOTE:
196
+ * `cleanData()` will also invoke the AngularJS `$destroy` DOM event on the element:
197
+ * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/Angular.js#L1932-L1945
198
+ *
199
+ * @param node The DOM node whose data needs to be cleaned.
200
+ */
201
+ function cleanData(node) {
202
+ element.cleanData([node]);
203
+ if (isParentNode(node)) {
204
+ element.cleanData(node.querySelectorAll('*'));
205
+ }
206
+ }
207
+ function controllerKey(name) {
208
+ return '$' + name + 'Controller';
209
+ }
210
+ /**
211
+ * Destroy an AngularJS app given the app `$injector`.
212
+ *
213
+ * NOTE: Destroying an app is not officially supported by AngularJS, but try to do our best by
214
+ * destroying `$rootScope` and clean the jqLite/jQuery data on `$rootElement` and all
215
+ * descendants.
216
+ *
217
+ * @param $injector The `$injector` of the AngularJS app to destroy.
218
+ */
219
+ function destroyApp($injector) {
220
+ const $rootElement = $injector.get($ROOT_ELEMENT);
221
+ const $rootScope = $injector.get($ROOT_SCOPE);
222
+ $rootScope.$destroy();
223
+ cleanData($rootElement[0]);
224
+ }
225
+ function directiveNormalize(name) {
226
+ return name
227
+ .replace(DIRECTIVE_PREFIX_REGEXP, '')
228
+ .replace(DIRECTIVE_SPECIAL_CHARS_REGEXP, (_, letter) => letter.toUpperCase());
229
+ }
230
+ function getTypeName(type) {
231
+ // Return the name of the type or the first line of its stringified version.
232
+ return type.overriddenName || type.name || type.toString().split('\n')[0];
233
+ }
234
+ function getDowngradedModuleCount($injector) {
235
+ return $injector.has(DOWNGRADED_MODULE_COUNT_KEY)
236
+ ? $injector.get(DOWNGRADED_MODULE_COUNT_KEY)
237
+ : 0;
238
+ }
239
+ function getUpgradeAppType($injector) {
240
+ return $injector.has(UPGRADE_APP_TYPE_KEY)
241
+ ? $injector.get(UPGRADE_APP_TYPE_KEY)
242
+ : 0 /* UpgradeAppType.None */;
243
+ }
244
+ function isFunction(value) {
245
+ return typeof value === 'function';
246
+ }
247
+ function isNgModuleType(value) {
248
+ // NgModule class should have the `ɵmod` static property attached by AOT or JIT compiler.
249
+ return isFunction(value) && !!value[_NG_MOD_DEF];
250
+ }
251
+ function isParentNode(node) {
252
+ return isFunction(node.querySelectorAll);
253
+ }
254
+ function validateInjectionKey($injector, downgradedModule, injectionKey, attemptedAction) {
255
+ const upgradeAppType = getUpgradeAppType($injector);
256
+ const downgradedModuleCount = getDowngradedModuleCount($injector);
257
+ // Check for common errors.
258
+ switch (upgradeAppType) {
259
+ case 1 /* UpgradeAppType.Dynamic */:
260
+ case 2 /* UpgradeAppType.Static */:
261
+ if (downgradedModule) {
262
+ throw new Error(`Error while ${attemptedAction}: 'downgradedModule' unexpectedly specified.\n` +
263
+ "You should not specify a value for 'downgradedModule', unless you are downgrading " +
264
+ "more than one Angular module (via 'downgradeModule()').");
265
+ }
266
+ break;
267
+ case 3 /* UpgradeAppType.Lite */:
268
+ if (!downgradedModule && downgradedModuleCount >= 2) {
269
+ throw new Error(`Error while ${attemptedAction}: 'downgradedModule' not specified.\n` +
270
+ 'This application contains more than one downgraded Angular module, thus you need to ' +
271
+ "always specify 'downgradedModule' when downgrading components and injectables.");
272
+ }
273
+ if (!$injector.has(injectionKey)) {
274
+ throw new Error(`Error while ${attemptedAction}: Unable to find the specified downgraded module.\n` +
275
+ 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
276
+ 'application?');
277
+ }
278
+ break;
279
+ default:
280
+ throw new Error(`Error while ${attemptedAction}: Not a valid '@angular/upgrade' application.\n` +
281
+ 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
282
+ 'application?');
283
+ }
284
+ }
285
+ class Deferred {
286
+ promise;
287
+ resolve;
288
+ reject;
289
+ constructor() {
290
+ this.promise = new Promise((res, rej) => {
291
+ this.resolve = res;
292
+ this.reject = rej;
293
+ });
294
+ }
295
+ }
296
+ /**
297
+ * @return Whether the passed-in component implements the subset of the
298
+ * `ControlValueAccessor` interface needed for AngularJS `ng-model`
299
+ * compatibility.
300
+ */
301
+ function supportsNgModel(component) {
302
+ return (typeof component.writeValue === 'function' && typeof component.registerOnChange === 'function');
303
+ }
304
+ /**
305
+ * Glue the AngularJS `NgModelController` (if it exists) to the component
306
+ * (if it implements the needed subset of the `ControlValueAccessor` interface).
307
+ */
308
+ function hookupNgModel(ngModel, component) {
309
+ if (ngModel && supportsNgModel(component)) {
310
+ ngModel.$render = () => {
311
+ component.writeValue(ngModel.$viewValue);
312
+ };
313
+ component.registerOnChange(ngModel.$setViewValue.bind(ngModel));
314
+ if (typeof component.registerOnTouched === 'function') {
315
+ component.registerOnTouched(ngModel.$setTouched.bind(ngModel));
316
+ }
317
+ }
318
+ }
319
+ /**
320
+ * Test two values for strict equality, accounting for the fact that `NaN !== NaN`.
321
+ */
322
+ function strictEquals(val1, val2) {
323
+ return val1 === val2 || (val1 !== val1 && val2 !== val2);
324
+ }
325
+
326
+ var util = /*#__PURE__*/Object.freeze({
327
+ __proto__: null,
328
+ Deferred: Deferred,
329
+ cleanData: cleanData,
330
+ controllerKey: controllerKey,
331
+ destroyApp: destroyApp,
332
+ directiveNormalize: directiveNormalize,
333
+ getDowngradedModuleCount: getDowngradedModuleCount,
334
+ getTypeName: getTypeName,
335
+ getUpgradeAppType: getUpgradeAppType,
336
+ hookupNgModel: hookupNgModel,
337
+ isFunction: isFunction,
338
+ isNgModuleType: isNgModuleType,
339
+ onError: onError,
340
+ strictEquals: strictEquals,
341
+ validateInjectionKey: validateInjectionKey
342
+ });
343
+
344
+ const INITIAL_VALUE = {
345
+ __UNINITIALIZED__: true,
346
+ };
347
+ class DowngradeComponentAdapter {
348
+ element;
349
+ attrs;
350
+ scope;
351
+ ngModel;
352
+ parentInjector;
353
+ $compile;
354
+ $parse;
355
+ componentFactory;
356
+ wrapCallback;
357
+ unsafelyOverwriteSignalInputs;
358
+ implementsOnChanges = false;
359
+ inputChangeCount = 0;
360
+ inputChanges = {};
361
+ componentScope;
362
+ constructor(element, attrs, scope, ngModel, parentInjector, $compile, $parse, componentFactory, wrapCallback, unsafelyOverwriteSignalInputs) {
363
+ this.element = element;
364
+ this.attrs = attrs;
365
+ this.scope = scope;
366
+ this.ngModel = ngModel;
367
+ this.parentInjector = parentInjector;
368
+ this.$compile = $compile;
369
+ this.$parse = $parse;
370
+ this.componentFactory = componentFactory;
371
+ this.wrapCallback = wrapCallback;
372
+ this.unsafelyOverwriteSignalInputs = unsafelyOverwriteSignalInputs;
373
+ this.componentScope = scope.$new();
374
+ }
375
+ compileContents() {
376
+ const compiledProjectableNodes = [];
377
+ const projectableNodes = this.groupProjectableNodes();
378
+ const linkFns = projectableNodes.map((nodes) => this.$compile(nodes));
379
+ this.element.empty();
380
+ linkFns.forEach((linkFn) => {
381
+ linkFn(this.scope, (clone) => {
382
+ compiledProjectableNodes.push(clone);
383
+ this.element.append(clone);
384
+ });
385
+ });
386
+ return compiledProjectableNodes;
387
+ }
388
+ createComponentAndSetup(projectableNodes, manuallyAttachView = false, propagateDigest = true) {
389
+ const component = this.createComponent(projectableNodes);
390
+ this.setupInputs(manuallyAttachView, propagateDigest, component);
391
+ this.setupOutputs(component.componentRef);
392
+ this.registerCleanup(component.componentRef);
393
+ return component.componentRef;
394
+ }
395
+ createComponent(projectableNodes) {
396
+ const providers = [{ provide: $SCOPE, useValue: this.componentScope }];
397
+ const childInjector = Injector.create({
398
+ providers: providers,
399
+ parent: this.parentInjector,
400
+ name: 'DowngradeComponentAdapter',
401
+ });
402
+ const componentRef = this.componentFactory.create(childInjector, projectableNodes, this.element[0]);
403
+ const viewChangeDetector = componentRef.injector.get(ChangeDetectorRef);
404
+ const changeDetector = componentRef.changeDetectorRef;
405
+ // testability hook is commonly added during component bootstrap in
406
+ // packages/core/src/application_ref.bootstrap()
407
+ // in downgraded application, component creation will take place here as well as adding the
408
+ // testability hook.
409
+ const testability = componentRef.injector.get(Testability, null);
410
+ if (testability) {
411
+ componentRef.injector
412
+ .get(TestabilityRegistry)
413
+ .registerApplication(componentRef.location.nativeElement, testability);
414
+ }
415
+ hookupNgModel(this.ngModel, componentRef.instance);
416
+ return { viewChangeDetector, componentRef, changeDetector };
417
+ }
418
+ setupInputs(manuallyAttachView, propagateDigest = true, { componentRef, changeDetector, viewChangeDetector }) {
419
+ const attrs = this.attrs;
420
+ const inputs = this.componentFactory.inputs || [];
421
+ for (const input of inputs) {
422
+ const inputBinding = new PropertyBinding(input.propName, input.templateName);
423
+ let expr = null;
424
+ if (attrs.hasOwnProperty(inputBinding.attr)) {
425
+ const observeFn = ((prop, isSignal) => {
426
+ let prevValue = INITIAL_VALUE;
427
+ return (currValue) => {
428
+ // Initially, both `$observe()` and `$watch()` will call this function.
429
+ if (!strictEquals(prevValue, currValue)) {
430
+ if (prevValue === INITIAL_VALUE) {
431
+ prevValue = currValue;
432
+ }
433
+ this.updateInput(componentRef, prop, prevValue, currValue, isSignal);
434
+ prevValue = currValue;
435
+ }
436
+ };
437
+ })(inputBinding.prop, input.isSignal);
438
+ attrs.$observe(inputBinding.attr, observeFn);
439
+ // Use `$watch()` (in addition to `$observe()`) in order to initialize the input in time
440
+ // for `ngOnChanges()`. This is necessary if we are already in a `$digest`, which means that
441
+ // `ngOnChanges()` (which is called by a watcher) will run before the `$observe()` callback.
442
+ let unwatch = this.componentScope.$watch(() => {
443
+ unwatch();
444
+ unwatch = null;
445
+ observeFn(attrs[inputBinding.attr]);
446
+ });
447
+ }
448
+ else if (attrs.hasOwnProperty(inputBinding.bindAttr)) {
449
+ expr = attrs[inputBinding.bindAttr];
450
+ }
451
+ else if (attrs.hasOwnProperty(inputBinding.bracketAttr)) {
452
+ expr = attrs[inputBinding.bracketAttr];
453
+ }
454
+ else if (attrs.hasOwnProperty(inputBinding.bindonAttr)) {
455
+ expr = attrs[inputBinding.bindonAttr];
456
+ }
457
+ else if (attrs.hasOwnProperty(inputBinding.bracketParenAttr)) {
458
+ expr = attrs[inputBinding.bracketParenAttr];
459
+ }
460
+ if (expr != null) {
461
+ const watchFn = ((prop, isSignal) => (currValue, prevValue) => this.updateInput(componentRef, prop, prevValue, currValue, isSignal))(inputBinding.prop, input.isSignal);
462
+ this.componentScope.$watch(expr, watchFn);
463
+ }
464
+ }
465
+ // Invoke `ngOnChanges()` and Change Detection (when necessary)
466
+ const detectChanges = () => changeDetector.detectChanges();
467
+ const prototype = this.componentFactory.componentType.prototype;
468
+ this.implementsOnChanges = !!(prototype && prototype.ngOnChanges);
469
+ this.componentScope.$watch(() => this.inputChangeCount, this.wrapCallback(() => {
470
+ // Invoke `ngOnChanges()`
471
+ if (this.implementsOnChanges) {
472
+ const inputChanges = this.inputChanges;
473
+ this.inputChanges = {};
474
+ componentRef.instance.ngOnChanges(inputChanges);
475
+ }
476
+ viewChangeDetector.markForCheck();
477
+ // If opted out of propagating digests, invoke change detection when inputs change.
478
+ if (!propagateDigest) {
479
+ detectChanges();
480
+ }
481
+ }));
482
+ // If not opted out of propagating digests, invoke change detection on every digest
483
+ if (propagateDigest) {
484
+ this.componentScope.$watch(this.wrapCallback(detectChanges));
485
+ }
486
+ // If necessary, attach the view so that it will be dirty-checked.
487
+ // (Allow time for the initial input values to be set and `ngOnChanges()` to be called.)
488
+ if (manuallyAttachView || !propagateDigest) {
489
+ let unwatch = this.componentScope.$watch(() => {
490
+ unwatch();
491
+ unwatch = null;
492
+ const appRef = this.parentInjector.get(ApplicationRef);
493
+ appRef.attachView(componentRef.hostView);
494
+ });
495
+ }
496
+ }
497
+ setupOutputs(componentRef) {
498
+ const attrs = this.attrs;
499
+ const outputs = this.componentFactory.outputs || [];
500
+ for (const output of outputs) {
501
+ const outputBindings = new PropertyBinding(output.propName, output.templateName);
502
+ const bindonAttr = outputBindings.bindonAttr.substring(0, outputBindings.bindonAttr.length - 6);
503
+ const bracketParenAttr = `[(${outputBindings.bracketParenAttr.substring(2, outputBindings.bracketParenAttr.length - 8)})]`;
504
+ // order below is important - first update bindings then evaluate expressions
505
+ if (attrs.hasOwnProperty(bindonAttr)) {
506
+ this.subscribeToOutput(componentRef, outputBindings, attrs[bindonAttr], true);
507
+ }
508
+ if (attrs.hasOwnProperty(bracketParenAttr)) {
509
+ this.subscribeToOutput(componentRef, outputBindings, attrs[bracketParenAttr], true);
510
+ }
511
+ if (attrs.hasOwnProperty(outputBindings.onAttr)) {
512
+ this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.onAttr]);
513
+ }
514
+ if (attrs.hasOwnProperty(outputBindings.parenAttr)) {
515
+ this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.parenAttr]);
516
+ }
517
+ }
518
+ }
519
+ subscribeToOutput(componentRef, output, expr, isAssignment = false) {
520
+ const getter = this.$parse(expr);
521
+ const setter = getter.assign;
522
+ if (isAssignment && !setter) {
523
+ throw new Error(`Expression '${expr}' is not assignable!`);
524
+ }
525
+ const emitter = componentRef.instance[output.prop];
526
+ if (emitter) {
527
+ const subscription = emitter.subscribe(isAssignment
528
+ ? (v) => setter(this.scope, v)
529
+ : (v) => getter(this.scope, { '$event': v }));
530
+ componentRef.onDestroy(() => subscription.unsubscribe());
531
+ }
532
+ else {
533
+ throw new Error(`Missing emitter '${output.prop}' on component '${getTypeName(this.componentFactory.componentType)}'!`);
534
+ }
535
+ }
536
+ registerCleanup(componentRef) {
537
+ const testabilityRegistry = componentRef.injector.get(TestabilityRegistry);
538
+ const destroyComponentRef = this.wrapCallback(() => componentRef.destroy());
539
+ let destroyed = false;
540
+ this.element.on('$destroy', () => {
541
+ // The `$destroy` event may have been triggered by the `cleanData()` call in the
542
+ // `componentScope` `$destroy` handler below. In that case, we don't want to call
543
+ // `componentScope.$destroy()` again.
544
+ if (!destroyed)
545
+ this.componentScope.$destroy();
546
+ });
547
+ this.componentScope.$on('$destroy', () => {
548
+ if (!destroyed) {
549
+ destroyed = true;
550
+ testabilityRegistry.unregisterApplication(componentRef.location.nativeElement);
551
+ // The `componentScope` might be getting destroyed, because an ancestor element is being
552
+ // removed/destroyed. If that is the case, jqLite/jQuery would normally invoke `cleanData()`
553
+ // on the removed element and all descendants.
554
+ // https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
555
+ // https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
556
+ //
557
+ // Here, however, `destroyComponentRef()` may under some circumstances remove the element
558
+ // from the DOM and therefore it will no longer be a descendant of the removed element when
559
+ // `cleanData()` is called. This would result in a memory leak, because the element's data
560
+ // and event handlers (and all objects directly or indirectly referenced by them) would be
561
+ // retained.
562
+ //
563
+ // To ensure the element is always properly cleaned up, we manually call `cleanData()` on
564
+ // this element and its descendants before destroying the `ComponentRef`.
565
+ cleanData(this.element[0]);
566
+ destroyComponentRef();
567
+ }
568
+ });
569
+ }
570
+ updateInput(componentRef, prop, prevValue, currValue, isSignal) {
571
+ if (this.implementsOnChanges) {
572
+ this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue);
573
+ }
574
+ this.inputChangeCount++;
575
+ if (isSignal && !this.unsafelyOverwriteSignalInputs) {
576
+ const node = componentRef.instance[prop][_SIGNAL];
577
+ node.applyValueToInputSignal(node, currValue);
578
+ }
579
+ else {
580
+ componentRef.instance[prop] = currValue;
581
+ }
582
+ }
583
+ groupProjectableNodes() {
584
+ let ngContentSelectors = this.componentFactory.ngContentSelectors;
585
+ return groupNodesBySelector(ngContentSelectors, this.element.contents());
586
+ }
587
+ }
588
+ /**
589
+ * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors.
590
+ */
591
+ function groupNodesBySelector(ngContentSelectors, nodes) {
592
+ const projectableNodes = [];
593
+ for (let i = 0, ii = ngContentSelectors.length; i < ii; ++i) {
594
+ projectableNodes[i] = [];
595
+ }
596
+ for (let j = 0, jj = nodes.length; j < jj; ++j) {
597
+ const node = nodes[j];
598
+ const ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors);
599
+ if (ngContentIndex != null) {
600
+ projectableNodes[ngContentIndex].push(node);
601
+ }
602
+ }
603
+ return projectableNodes;
604
+ }
605
+ function findMatchingNgContentIndex(element, ngContentSelectors) {
606
+ const ngContentIndices = [];
607
+ let wildcardNgContentIndex = -1;
608
+ for (let i = 0; i < ngContentSelectors.length; i++) {
609
+ const selector = ngContentSelectors[i];
610
+ if (selector === '*') {
611
+ wildcardNgContentIndex = i;
612
+ }
613
+ else {
614
+ if (matchesSelector(element, selector)) {
615
+ ngContentIndices.push(i);
616
+ }
617
+ }
618
+ }
619
+ ngContentIndices.sort();
620
+ if (wildcardNgContentIndex !== -1) {
621
+ ngContentIndices.push(wildcardNgContentIndex);
622
+ }
623
+ return ngContentIndices.length ? ngContentIndices[0] : null;
624
+ }
625
+ function matchesSelector(el, selector) {
626
+ const elProto = Element.prototype;
627
+ return el.nodeType === Node.ELEMENT_NODE
628
+ ? // matches is supported by all browsers from 2014 onwards except non-chromium edge
629
+ (elProto.matches ?? elProto.msMatchesSelector).call(el, selector)
630
+ : false;
631
+ }
632
+
633
+ function isThenable(obj) {
634
+ return !!obj && isFunction(obj.then);
635
+ }
636
+ /**
637
+ * Synchronous, promise-like object.
638
+ */
639
+ class SyncPromise {
640
+ value;
641
+ resolved = false;
642
+ callbacks = [];
643
+ static all(valuesOrPromises) {
644
+ const aggrPromise = new SyncPromise();
645
+ let resolvedCount = 0;
646
+ const results = [];
647
+ const resolve = (idx, value) => {
648
+ results[idx] = value;
649
+ if (++resolvedCount === valuesOrPromises.length)
650
+ aggrPromise.resolve(results);
651
+ };
652
+ valuesOrPromises.forEach((p, idx) => {
653
+ if (isThenable(p)) {
654
+ p.then((v) => resolve(idx, v));
655
+ }
656
+ else {
657
+ resolve(idx, p);
658
+ }
659
+ });
660
+ return aggrPromise;
661
+ }
662
+ resolve(value) {
663
+ // Do nothing, if already resolved.
664
+ if (this.resolved)
665
+ return;
666
+ this.value = value;
667
+ this.resolved = true;
668
+ // Run the queued callbacks.
669
+ this.callbacks.forEach((callback) => callback(value));
670
+ this.callbacks.length = 0;
671
+ }
672
+ then(callback) {
673
+ if (this.resolved) {
674
+ callback(this.value);
675
+ }
676
+ else {
677
+ this.callbacks.push(callback);
678
+ }
679
+ }
680
+ }
681
+
682
+ /**
683
+ * @description
684
+ *
685
+ * A helper function that allows an Angular component to be used from AngularJS.
686
+ *
687
+ * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
688
+ * library for hybrid upgrade apps that support AOT compilation*
689
+ *
690
+ * This helper function returns a factory function to be used for registering
691
+ * an AngularJS wrapper directive for "downgrading" an Angular component.
692
+ *
693
+ * @usageNotes
694
+ * ### Examples
695
+ *
696
+ * Let's assume that you have an Angular component called `ng2Heroes` that needs
697
+ * to be made available in AngularJS templates.
698
+ *
699
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes"}
700
+ *
701
+ * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
702
+ * that will make this Angular component available inside AngularJS templates.
703
+ * The `downgradeComponent()` function returns a factory function that we
704
+ * can use to define the AngularJS directive that wraps the "downgraded" component.
705
+ *
706
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-wrapper"}
707
+ *
708
+ * For more details and examples on downgrading Angular components to AngularJS components please
709
+ * visit the [Upgrade guide](https://angular.io/guide/upgrade#using-angular-components-from-angularjs-code).
710
+ *
711
+ * @param info contains information about the Component that is being downgraded:
712
+ *
713
+ * - `component: Type<any>`: The type of the Component that will be downgraded
714
+ * - `downgradedModule?: string`: The name of the downgraded module (if any) that the component
715
+ * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose
716
+ * corresponding Angular module will be bootstrapped, when the component needs to be instantiated.
717
+ * <br />
718
+ * (This option is only necessary when using `downgradeModule()` to downgrade more than one
719
+ * Angular module.)
720
+ * - `propagateDigest?: boolean`: Whether to perform {@link /api/core/ChangeDetectorRef#detectChanges detectChanges} on the
721
+ * component on every {@link https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest $digest}.
722
+ * If set to `false`, change detection will still be performed when any of the component's inputs changes.
723
+ * (Default: true)
724
+ *
725
+ * @returns a factory function that can be used to register the component in an
726
+ * AngularJS module.
727
+ *
728
+ * @publicApi
729
+ */
730
+ function downgradeComponent(info) {
731
+ const directiveFactory = function ($compile, $injector, $parse) {
732
+ const unsafelyOverwriteSignalInputs = info.unsafelyOverwriteSignalInputs ?? false;
733
+ // When using `downgradeModule()`, we need to handle certain things specially. For example:
734
+ // - We always need to attach the component view to the `ApplicationRef` for it to be
735
+ // dirty-checked.
736
+ // - We need to ensure callbacks to Angular APIs (e.g. change detection) are run inside the
737
+ // Angular zone.
738
+ // NOTE: This is not needed, when using `UpgradeModule`, because `$digest()` will be run
739
+ // inside the Angular zone (except if explicitly escaped, in which case we shouldn't
740
+ // force it back in).
741
+ const isNgUpgradeLite = getUpgradeAppType($injector) === 3 /* UpgradeAppType.Lite */;
742
+ const wrapCallback = !isNgUpgradeLite
743
+ ? (cb) => cb
744
+ : (cb) => () => (NgZone.isInAngularZone() ? cb() : ngZone.run(cb));
745
+ let ngZone;
746
+ // When downgrading multiple modules, special handling is needed wrt injectors.
747
+ const hasMultipleDowngradedModules = isNgUpgradeLite && getDowngradedModuleCount($injector) > 1;
748
+ return {
749
+ restrict: 'E',
750
+ terminal: true,
751
+ require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL],
752
+ // Controller needs to be set so that `angular-component-router.js` (from beta Angular 2)
753
+ // configuration properties can be made available. See:
754
+ // See G3: javascript/angular2/angular1_router_lib.js
755
+ // https://github.com/angular/angular.js/blob/47bf11ee94664367a26ed8c91b9b586d3dd420f5/src/ng/compile.js#L1670-L1691.
756
+ controller: function () { },
757
+ link: (scope, element, attrs, required) => {
758
+ // We might have to compile the contents asynchronously, because this might have been
759
+ // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have
760
+ // been compiled.
761
+ const ngModel = required[1];
762
+ const parentInjector = required[0];
763
+ let moduleInjector = undefined;
764
+ let ranAsync = false;
765
+ if (!parentInjector || hasMultipleDowngradedModules) {
766
+ const downgradedModule = info.downgradedModule || '';
767
+ const lazyModuleRefKey = `${LAZY_MODULE_REF}${downgradedModule}`;
768
+ const attemptedAction = `instantiating component '${getTypeName(info.component)}'`;
769
+ validateInjectionKey($injector, downgradedModule, lazyModuleRefKey, attemptedAction);
770
+ const lazyModuleRef = $injector.get(lazyModuleRefKey);
771
+ moduleInjector = lazyModuleRef.injector ?? lazyModuleRef.promise;
772
+ }
773
+ // Notes:
774
+ //
775
+ // There are two injectors: `finalModuleInjector` and `finalParentInjector` (they might be
776
+ // the same instance, but that is irrelevant):
777
+ // - `finalModuleInjector` is used to retrieve `ComponentFactoryResolver`, thus it must be
778
+ // on the same tree as the `NgModule` that declares this downgraded component.
779
+ // - `finalParentInjector` is used for all other injection purposes.
780
+ // (Note that Angular knows to only traverse the component-tree part of that injector,
781
+ // when looking for an injectable and then switch to the module injector.)
782
+ //
783
+ // There are basically three cases:
784
+ // - If there is no parent component (thus no `parentInjector`), we bootstrap the downgraded
785
+ // `NgModule` and use its injector as both `finalModuleInjector` and
786
+ // `finalParentInjector`.
787
+ // - If there is a parent component (and thus a `parentInjector`) and we are sure that it
788
+ // belongs to the same `NgModule` as this downgraded component (e.g. because there is only
789
+ // one downgraded module, we use that `parentInjector` as both `finalModuleInjector` and
790
+ // `finalParentInjector`.
791
+ // - If there is a parent component, but it may belong to a different `NgModule`, then we
792
+ // use the `parentInjector` as `finalParentInjector` and this downgraded component's
793
+ // declaring `NgModule`'s injector as `finalModuleInjector`.
794
+ // Note 1: If the `NgModule` is already bootstrapped, we just get its injector (we don't
795
+ // bootstrap again).
796
+ // Note 2: It is possible that (while there are multiple downgraded modules) this
797
+ // downgraded component and its parent component both belong to the same NgModule.
798
+ // In that case, we could have used the `parentInjector` as both
799
+ // `finalModuleInjector` and `finalParentInjector`, but (for simplicity) we are
800
+ // treating this case as if they belong to different `NgModule`s. That doesn't
801
+ // really affect anything, since `parentInjector` has `moduleInjector` as ancestor
802
+ // and trying to resolve `ComponentFactoryResolver` from either one will return
803
+ // the same instance.
804
+ // If there is a parent component, use its injector as parent injector.
805
+ // If this is a "top-level" Angular component, use the module injector.
806
+ const finalParentInjector = parentInjector || moduleInjector;
807
+ // If this is a "top-level" Angular component or the parent component may belong to a
808
+ // different `NgModule`, use the module injector for module-specific dependencies.
809
+ // If there is a parent component that belongs to the same `NgModule`, use its injector.
810
+ const finalModuleInjector = moduleInjector || parentInjector;
811
+ const doDowngrade = (injector, moduleInjector) => {
812
+ // Retrieve `ComponentFactoryResolver` from the injector tied to the `NgModule` this
813
+ // component belongs to.
814
+ const componentFactoryResolver = moduleInjector.get(ComponentFactoryResolver);
815
+ const componentFactory = componentFactoryResolver.resolveComponentFactory(info.component);
816
+ if (!componentFactory) {
817
+ throw new Error(`Expecting ComponentFactory for: ${getTypeName(info.component)}`);
818
+ }
819
+ const injectorPromise = new ParentInjectorPromise(element);
820
+ const facade = new DowngradeComponentAdapter(element, attrs, scope, ngModel, injector, $compile, $parse, componentFactory, wrapCallback, unsafelyOverwriteSignalInputs);
821
+ const projectableNodes = facade.compileContents();
822
+ const componentRef = facade.createComponentAndSetup(projectableNodes, isNgUpgradeLite, info.propagateDigest);
823
+ injectorPromise.resolve(componentRef.injector);
824
+ if (ranAsync) {
825
+ // If this is run async, it is possible that it is not run inside a
826
+ // digest and initial input values will not be detected.
827
+ scope.$evalAsync(() => { });
828
+ }
829
+ };
830
+ const downgradeFn = !isNgUpgradeLite
831
+ ? doDowngrade
832
+ : (pInjector, mInjector) => {
833
+ if (!ngZone) {
834
+ ngZone = pInjector.get(NgZone);
835
+ }
836
+ wrapCallback(() => doDowngrade(pInjector, mInjector))();
837
+ };
838
+ // NOTE:
839
+ // Not using `ParentInjectorPromise.all()` (which is inherited from `SyncPromise`), because
840
+ // Closure Compiler (or some related tool) complains:
841
+ // `TypeError: ...$src$downgrade_component_ParentInjectorPromise.all is not a function`
842
+ SyncPromise.all([finalParentInjector, finalModuleInjector]).then(([pInjector, mInjector]) => downgradeFn(pInjector, mInjector));
843
+ ranAsync = true;
844
+ },
845
+ };
846
+ };
847
+ // bracket-notation because of closure - see #14441
848
+ directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE];
849
+ return directiveFactory;
850
+ }
851
+ /**
852
+ * Synchronous promise-like object to wrap parent injectors,
853
+ * to preserve the synchronous nature of AngularJS's `$compile`.
854
+ */
855
+ class ParentInjectorPromise extends SyncPromise {
856
+ element;
857
+ injectorKey = controllerKey(INJECTOR_KEY);
858
+ constructor(element) {
859
+ super();
860
+ this.element = element;
861
+ // Store the promise on the element.
862
+ element.data(this.injectorKey, this);
863
+ }
864
+ resolve(injector) {
865
+ // Store the real injector on the element.
866
+ this.element.data(this.injectorKey, injector);
867
+ // Release the element to prevent memory leaks.
868
+ this.element = null;
869
+ // Resolve the promise.
870
+ super.resolve(injector);
871
+ }
872
+ }
873
+
874
+ /**
875
+ * @description
876
+ *
877
+ * A helper function to allow an Angular service to be accessible from AngularJS.
878
+ *
879
+ * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
880
+ * library for hybrid upgrade apps that support AOT compilation*
881
+ *
882
+ * This helper function returns a factory function that provides access to the Angular
883
+ * service identified by the `token` parameter.
884
+ *
885
+ * @usageNotes
886
+ * ### Examples
887
+ *
888
+ * First ensure that the service to be downgraded is provided in an `NgModule`
889
+ * that will be part of the upgrade application. For example, let's assume we have
890
+ * defined `HeroesService`
891
+ *
892
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-service"}
893
+ *
894
+ * and that we have included this in our upgrade app `NgModule`
895
+ *
896
+ * {@example upgrade/static/ts/full/module.ts region="ng2-module"}
897
+ *
898
+ * Now we can register the `downgradeInjectable` factory function for the service
899
+ * on an AngularJS module.
900
+ *
901
+ * {@example upgrade/static/ts/full/module.ts region="downgrade-ng2-heroes-service"}
902
+ *
903
+ * Inside an AngularJS component's controller we can get hold of the
904
+ * downgraded service via the name we gave when downgrading.
905
+ *
906
+ * {@example upgrade/static/ts/full/module.ts region="example-app"}
907
+ *
908
+ * <div class="docs-alert docs-alert-important">
909
+ *
910
+ * When using `downgradeModule()`, downgraded injectables will not be available until the Angular
911
+ * module that provides them is instantiated. In order to be safe, you need to ensure that the
912
+ * downgraded injectables are not used anywhere _outside_ the part of the app where it is
913
+ * guaranteed that their module has been instantiated.
914
+ *
915
+ * For example, it is _OK_ to use a downgraded service in an upgraded component that is only used
916
+ * from a downgraded Angular component provided by the same Angular module as the injectable, but
917
+ * it is _not OK_ to use it in an AngularJS component that may be used independently of Angular or
918
+ * use it in a downgraded Angular component from a different module.
919
+ *
920
+ * </div>
921
+ *
922
+ * @param token an `InjectionToken` that identifies a service provided from Angular.
923
+ * @param downgradedModule the name of the downgraded module (if any) that the injectable
924
+ * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose injector will
925
+ * be used for instantiating the injectable.<br />
926
+ * (This option is only necessary when using `downgradeModule()` to downgrade more than one Angular
927
+ * module.)
928
+ *
929
+ * @returns a [factory function](https://docs.angularjs.org/guide/di) that can be
930
+ * used to register the service on an AngularJS module.
931
+ *
932
+ * @publicApi
933
+ */
934
+ function downgradeInjectable(token, downgradedModule = '') {
935
+ const factory = function ($injector) {
936
+ const injectorKey = `${INJECTOR_KEY}${downgradedModule}`;
937
+ const injectableName = isFunction(token) ? getTypeName(token) : String(token);
938
+ const attemptedAction = `instantiating injectable '${injectableName}'`;
939
+ validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);
940
+ try {
941
+ const injector = $injector.get(injectorKey);
942
+ return injector.get(token);
943
+ }
944
+ catch (err) {
945
+ throw new Error(`Error while ${attemptedAction}: ${err.message || err}`);
946
+ }
947
+ };
948
+ factory['$inject'] = [$INJECTOR];
949
+ return factory;
950
+ }
951
+
952
+ /**
953
+ * The Trusted Types policy, or null if Trusted Types are not
954
+ * enabled/supported, or undefined if the policy has not been created yet.
955
+ */
956
+ let policy;
957
+ /**
958
+ * Returns the Trusted Types policy, or null if Trusted Types are not
959
+ * enabled/supported. The first call to this function will create the policy.
960
+ */
961
+ function getPolicy() {
962
+ if (policy === undefined) {
963
+ policy = null;
964
+ const windowWithTrustedTypes = window;
965
+ if (windowWithTrustedTypes.trustedTypes) {
966
+ try {
967
+ policy = windowWithTrustedTypes.trustedTypes.createPolicy('angular#unsafe-upgrade', {
968
+ createHTML: (s) => s,
969
+ });
970
+ }
971
+ catch {
972
+ // trustedTypes.createPolicy throws if called with a name that is
973
+ // already registered, even in report-only mode. Until the API changes,
974
+ // catch the error not to break the applications functionally. In such
975
+ // cases, the code will fall back to using strings.
976
+ }
977
+ }
978
+ }
979
+ return policy;
980
+ }
981
+ /**
982
+ * Unsafely promote a legacy AngularJS template to a TrustedHTML, falling back
983
+ * to strings when Trusted Types are not available.
984
+ * @security This is a security-sensitive function; any use of this function
985
+ * must go through security review. In particular, the template string should
986
+ * always be under full control of the application author, as untrusted input
987
+ * can cause an XSS vulnerability.
988
+ */
989
+ function trustedHTMLFromLegacyTemplate(html) {
990
+ return getPolicy()?.createHTML(html) || html;
991
+ }
992
+
993
+ // Constants
994
+ const REQUIRE_PREFIX_RE = /^(\^\^?)?(\?)?(\^\^?)?/;
995
+ // Classes
996
+ class UpgradeHelper {
997
+ name;
998
+ $injector;
999
+ element;
1000
+ $element;
1001
+ directive;
1002
+ $compile;
1003
+ $controller;
1004
+ constructor(injector, name, elementRef, directive) {
1005
+ this.name = name;
1006
+ this.$injector = injector.get($INJECTOR);
1007
+ this.$compile = this.$injector.get($COMPILE);
1008
+ this.$controller = this.$injector.get($CONTROLLER);
1009
+ this.element = elementRef.nativeElement;
1010
+ this.$element = element(this.element);
1011
+ this.directive = directive ?? UpgradeHelper.getDirective(this.$injector, name);
1012
+ }
1013
+ static getDirective($injector, name) {
1014
+ const directives = $injector.get(name + 'Directive');
1015
+ if (directives.length > 1) {
1016
+ throw new Error(`Only support single directive definition for: ${name}`);
1017
+ }
1018
+ const directive = directives[0];
1019
+ // AngularJS will transform `link: xyz` to `compile: () => xyz`. So we can only tell there was a
1020
+ // user-defined `compile` if there is no `link`. In other cases, we will just ignore `compile`.
1021
+ if (directive.compile && !directive.link)
1022
+ notSupported(name, 'compile');
1023
+ if (directive.replace)
1024
+ notSupported(name, 'replace');
1025
+ if (directive.terminal)
1026
+ notSupported(name, 'terminal');
1027
+ return directive;
1028
+ }
1029
+ static getTemplate($injector, directive, fetchRemoteTemplate = false, $element) {
1030
+ if (directive.template !== undefined) {
1031
+ return trustedHTMLFromLegacyTemplate(getOrCall(directive.template, $element));
1032
+ }
1033
+ else if (directive.templateUrl) {
1034
+ const $templateCache = $injector.get($TEMPLATE_CACHE);
1035
+ const url = getOrCall(directive.templateUrl, $element);
1036
+ const template = $templateCache.get(url);
1037
+ if (template !== undefined) {
1038
+ return trustedHTMLFromLegacyTemplate(template);
1039
+ }
1040
+ else if (!fetchRemoteTemplate) {
1041
+ throw new Error('loading directive templates asynchronously is not supported');
1042
+ }
1043
+ return new Promise((resolve, reject) => {
1044
+ const $httpBackend = $injector.get($HTTP_BACKEND);
1045
+ $httpBackend('GET', url, null, (status, response) => {
1046
+ if (status === 200) {
1047
+ resolve(trustedHTMLFromLegacyTemplate($templateCache.put(url, response)));
1048
+ }
1049
+ else {
1050
+ reject(`GET component template from '${url}' returned '${status}: ${response}'`);
1051
+ }
1052
+ });
1053
+ });
1054
+ }
1055
+ else {
1056
+ throw new Error(`Directive '${directive.name}' is not a component, it is missing template.`);
1057
+ }
1058
+ }
1059
+ buildController(controllerType, $scope) {
1060
+ // TODO: Document that we do not pre-assign bindings on the controller instance.
1061
+ // Quoted properties below so that this code can be optimized with Closure Compiler.
1062
+ const locals = { '$scope': $scope, '$element': this.$element };
1063
+ const controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
1064
+ this.$element.data?.(controllerKey(this.directive.name), controller);
1065
+ return controller;
1066
+ }
1067
+ compileTemplate(template) {
1068
+ if (template === undefined) {
1069
+ template = UpgradeHelper.getTemplate(this.$injector, this.directive, false, this.$element);
1070
+ }
1071
+ return this.compileHtml(template);
1072
+ }
1073
+ onDestroy($scope, controllerInstance) {
1074
+ if (controllerInstance && isFunction(controllerInstance.$onDestroy)) {
1075
+ controllerInstance.$onDestroy();
1076
+ }
1077
+ $scope.$destroy();
1078
+ cleanData(this.element);
1079
+ }
1080
+ prepareTransclusion() {
1081
+ const transclude = this.directive.transclude;
1082
+ const contentChildNodes = this.extractChildNodes();
1083
+ const attachChildrenFn = (scope, cloneAttachFn) => {
1084
+ // Since AngularJS v1.5.8, `cloneAttachFn` will try to destroy the transclusion scope if
1085
+ // `$template` is empty. Since the transcluded content comes from Angular, not AngularJS,
1086
+ // there will be no transclusion scope here.
1087
+ // Provide a dummy `scope.$destroy()` method to prevent `cloneAttachFn` from throwing.
1088
+ scope = scope || { $destroy: () => undefined };
1089
+ return cloneAttachFn($template, scope);
1090
+ };
1091
+ let $template = contentChildNodes;
1092
+ if (transclude) {
1093
+ const slots = Object.create(null);
1094
+ if (typeof transclude === 'object') {
1095
+ $template = [];
1096
+ const slotMap = Object.create(null);
1097
+ const filledSlots = Object.create(null);
1098
+ // Parse the element selectors.
1099
+ Object.keys(transclude).forEach((slotName) => {
1100
+ let selector = transclude[slotName];
1101
+ const optional = selector.charAt(0) === '?';
1102
+ selector = optional ? selector.substring(1) : selector;
1103
+ slotMap[selector] = slotName;
1104
+ slots[slotName] = null; // `null`: Defined but not yet filled.
1105
+ filledSlots[slotName] = optional; // Consider optional slots as filled.
1106
+ });
1107
+ // Add the matching elements into their slot.
1108
+ contentChildNodes.forEach((node) => {
1109
+ const slotName = slotMap[directiveNormalize(node.nodeName.toLowerCase())];
1110
+ if (slotName) {
1111
+ filledSlots[slotName] = true;
1112
+ slots[slotName] = slots[slotName] || [];
1113
+ slots[slotName].push(node);
1114
+ }
1115
+ else {
1116
+ $template.push(node);
1117
+ }
1118
+ });
1119
+ // Check for required slots that were not filled.
1120
+ Object.keys(filledSlots).forEach((slotName) => {
1121
+ if (!filledSlots[slotName]) {
1122
+ throw new Error(`Required transclusion slot '${slotName}' on directive: ${this.name}`);
1123
+ }
1124
+ });
1125
+ Object.keys(slots)
1126
+ .filter((slotName) => slots[slotName])
1127
+ .forEach((slotName) => {
1128
+ const nodes = slots[slotName];
1129
+ slots[slotName] = (scope, cloneAttach) => {
1130
+ return cloneAttach(nodes, scope);
1131
+ };
1132
+ });
1133
+ }
1134
+ // Attach `$$slots` to default slot transclude fn.
1135
+ attachChildrenFn.$$slots = slots;
1136
+ // AngularJS v1.6+ ignores empty or whitespace-only transcluded text nodes. But Angular
1137
+ // removes all text content after the first interpolation and updates it later, after
1138
+ // evaluating the expressions. This would result in AngularJS failing to recognize text
1139
+ // nodes that start with an interpolation as transcluded content and use the fallback
1140
+ // content instead.
1141
+ // To avoid this issue, we add a
1142
+ // [zero-width non-joiner character](https://en.wikipedia.org/wiki/Zero-width_non-joiner)
1143
+ // to empty text nodes (which can only be a result of Angular removing their initial content).
1144
+ // NOTE: Transcluded text content that starts with whitespace followed by an interpolation
1145
+ // will still fail to be detected by AngularJS v1.6+
1146
+ $template.forEach((node) => {
1147
+ if (node.nodeType === Node.TEXT_NODE && !node.nodeValue) {
1148
+ node.nodeValue = '\u200C';
1149
+ }
1150
+ });
1151
+ }
1152
+ return attachChildrenFn;
1153
+ }
1154
+ resolveAndBindRequiredControllers(controllerInstance) {
1155
+ const directiveRequire = this.getDirectiveRequire();
1156
+ const requiredControllers = this.resolveRequire(directiveRequire);
1157
+ if (controllerInstance && this.directive.bindToController && isMap(directiveRequire)) {
1158
+ const requiredControllersMap = requiredControllers;
1159
+ Object.keys(requiredControllersMap).forEach((key) => {
1160
+ controllerInstance[key] = requiredControllersMap[key];
1161
+ });
1162
+ }
1163
+ return requiredControllers;
1164
+ }
1165
+ compileHtml(html) {
1166
+ this.element.innerHTML = html;
1167
+ return this.$compile(this.element.childNodes);
1168
+ }
1169
+ extractChildNodes() {
1170
+ const childNodes = [];
1171
+ let childNode;
1172
+ while ((childNode = this.element.firstChild)) {
1173
+ childNode.remove();
1174
+ childNodes.push(childNode);
1175
+ }
1176
+ return childNodes;
1177
+ }
1178
+ getDirectiveRequire() {
1179
+ const require = this.directive.require || (this.directive.controller && this.directive.name);
1180
+ if (isMap(require)) {
1181
+ Object.entries(require).forEach(([key, value]) => {
1182
+ const match = value.match(REQUIRE_PREFIX_RE);
1183
+ const name = value.substring(match[0].length);
1184
+ if (!name) {
1185
+ require[key] = match[0] + key;
1186
+ }
1187
+ });
1188
+ }
1189
+ return require;
1190
+ }
1191
+ resolveRequire(require) {
1192
+ if (!require) {
1193
+ return null;
1194
+ }
1195
+ else if (Array.isArray(require)) {
1196
+ return require.map((req) => this.resolveRequire(req));
1197
+ }
1198
+ else if (typeof require === 'object') {
1199
+ const value = {};
1200
+ Object.keys(require).forEach((key) => (value[key] = this.resolveRequire(require[key])));
1201
+ return value;
1202
+ }
1203
+ else if (typeof require === 'string') {
1204
+ const match = require.match(REQUIRE_PREFIX_RE);
1205
+ const inheritType = match[1] || match[3];
1206
+ const name = require.substring(match[0].length);
1207
+ const isOptional = !!match[2];
1208
+ const searchParents = !!inheritType;
1209
+ const startOnParent = inheritType === '^^';
1210
+ const ctrlKey = controllerKey(name);
1211
+ const elem = startOnParent ? this.$element.parent() : this.$element;
1212
+ const value = searchParents ? elem.inheritedData(ctrlKey) : elem.data(ctrlKey);
1213
+ if (!value && !isOptional) {
1214
+ throw new Error(`Unable to find required '${require}' in upgraded directive '${this.name}'.`);
1215
+ }
1216
+ return value;
1217
+ }
1218
+ else {
1219
+ throw new Error(`Unrecognized 'require' syntax on upgraded directive '${this.name}': ${require}`);
1220
+ }
1221
+ }
1222
+ }
1223
+ function getOrCall(property, ...args) {
1224
+ return isFunction(property) ? property(...args) : property;
1225
+ }
1226
+ // NOTE: Only works for `typeof T !== 'object'`.
1227
+ function isMap(value) {
1228
+ return value && !Array.isArray(value) && typeof value === 'object';
1229
+ }
1230
+ function notSupported(name, feature) {
1231
+ throw new Error(`Upgraded directive '${name}' contains unsupported feature: '${feature}'.`);
1232
+ }
1233
+
1234
+ var upgrade_helper = /*#__PURE__*/Object.freeze({
1235
+ __proto__: null,
1236
+ UpgradeHelper: UpgradeHelper
1237
+ });
1238
+
1239
+ export { $SCOPE as $, setAngularLib as A, angular1 as B, COMPILER_KEY as C, Deferred as D, constants as E, upgrade_helper as F, util as G, INJECTOR_KEY as I, LAZY_MODULE_REF as L, NG_ZONE_KEY as N, UpgradeHelper as U, VERSION as V, $INJECTOR as a, bootstrap as b, controllerKey as c, downgradeComponent as d, element as e, downgradeInjectable as f, UPGRADE_APP_TYPE_KEY as g, $ROOT_SCOPE as h, isFunction as i, $$TESTABILITY as j, $COMPILE as k, destroyApp as l, module_ as m, UPGRADE_MODULE_NAME as n, onError as o, $PROVIDE as p, DOWNGRADED_MODULE_COUNT_KEY as q, getDowngradedModuleCount as r, strictEquals as s, trustedHTMLFromLegacyTemplate as t, isNgModuleType as u, $DELEGATE as v, $INTERVAL as w, getAngularJSGlobal as x, getAngularLib as y, setAngularJSGlobal as z };
1240
+ //# sourceMappingURL=upgrade_helper-DMR5pJ--.mjs.map