Primeiro commit do projeto Angular
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2010-2026 Google LLC. https://angular.dev/license
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# Angular
|
||||
|
||||
The sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.
|
||||
|
||||
Usage information and reference details can be found in [Angular documentation](https://angular.dev/overview).
|
||||
|
||||
License: MIT
|
||||
+1
@@ -0,0 +1 @@
|
||||
(()=>{function p(t,n,r,o,e,i,f,m){return{eventType:t,event:n,targetElement:r,eic:o,timeStamp:e,eia:i,eirp:f,eiack:m}}function u(t){let n=[],r=e=>{n.push(e)};return{c:t,q:n,et:[],etc:[],d:r,h:e=>{r(p(e.type,e,e.target,t,Date.now()))}}}function s(t,n,r){for(let o=0;o<n.length;o++){let e=n[o];(r?t.etc:t.et).push(e),t.c.addEventListener(e,t.h,r)}}function c(t,n,r,o,e=window){let i=u(t);e._ejsas||(e._ejsas={}),e._ejsas[n]=i,s(i,r),s(i,o,!0)}window.__jsaction_bootstrap=c;})();
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
const Attribute = {
|
||||
JSACTION: 'jsaction'
|
||||
};
|
||||
|
||||
export { Attribute };
|
||||
//# sourceMappingURL=_attribute-chunk.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_attribute-chunk.mjs","sources":["../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/core/primitives/event-dispatch/src/attribute.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nexport const Attribute = {\n /**\n * The jsaction attribute defines a mapping of a DOM event to a\n * generic event (aka jsaction), to which the actual event handlers\n * that implement the behavior of the application are bound. The\n * value is a semicolon separated list of colon separated pairs of\n * an optional DOM event name and a jsaction name. If the optional\n * DOM event name is omitted, 'click' is assumed. The jsaction names\n * are dot separated pairs of a namespace and a simple jsaction\n * name.\n *\n * See grammar in README.md for expected syntax in the attribute value.\n */\n JSACTION: 'jsaction' as const,\n};\n"],"names":["Attribute","JSACTION"],"mappings":";;;;;;AAQO,MAAMA,SAAS,GAAG;AAavBC,EAAAA,QAAQ,EAAE;;;;;"}
|
||||
+18610
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+423
@@ -0,0 +1,423 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
let activeConsumer = null;
|
||||
let inNotificationPhase = false;
|
||||
let epoch = 1;
|
||||
let postProducerCreatedFn = null;
|
||||
const SIGNAL = /* @__PURE__ */Symbol('SIGNAL');
|
||||
function setActiveConsumer(consumer) {
|
||||
const prev = activeConsumer;
|
||||
activeConsumer = consumer;
|
||||
return prev;
|
||||
}
|
||||
function getActiveConsumer() {
|
||||
return activeConsumer;
|
||||
}
|
||||
function isInNotificationPhase() {
|
||||
return inNotificationPhase;
|
||||
}
|
||||
function isReactive(value) {
|
||||
return value[SIGNAL] !== undefined;
|
||||
}
|
||||
const REACTIVE_NODE = {
|
||||
version: 0,
|
||||
lastCleanEpoch: 0,
|
||||
dirty: false,
|
||||
producers: undefined,
|
||||
producersTail: undefined,
|
||||
consumers: undefined,
|
||||
consumersTail: undefined,
|
||||
recomputing: false,
|
||||
consumerAllowSignalWrites: false,
|
||||
consumerIsAlwaysLive: false,
|
||||
kind: 'unknown',
|
||||
producerMustRecompute: () => false,
|
||||
producerRecomputeValue: () => {},
|
||||
consumerMarkedDirty: () => {},
|
||||
consumerOnSignalRead: () => {}
|
||||
};
|
||||
function producerAccessed(node) {
|
||||
if (inNotificationPhase) {
|
||||
throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? `Assertion error: signal read during notification phase` : '');
|
||||
}
|
||||
if (activeConsumer === null) {
|
||||
return;
|
||||
}
|
||||
activeConsumer.consumerOnSignalRead(node);
|
||||
const prevProducerLink = activeConsumer.producersTail;
|
||||
if (prevProducerLink !== undefined && prevProducerLink.producer === node) {
|
||||
return;
|
||||
}
|
||||
let nextProducerLink = undefined;
|
||||
const isRecomputing = activeConsumer.recomputing;
|
||||
if (isRecomputing) {
|
||||
nextProducerLink = prevProducerLink !== undefined ? prevProducerLink.nextProducer : activeConsumer.producers;
|
||||
if (nextProducerLink !== undefined && nextProducerLink.producer === node) {
|
||||
activeConsumer.producersTail = nextProducerLink;
|
||||
nextProducerLink.lastReadVersion = node.version;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const prevConsumerLink = node.consumersTail;
|
||||
if (prevConsumerLink !== undefined && prevConsumerLink.consumer === activeConsumer && (!isRecomputing || isValidLink(prevConsumerLink, activeConsumer))) {
|
||||
return;
|
||||
}
|
||||
const isLive = consumerIsLive(activeConsumer);
|
||||
const newLink = {
|
||||
producer: node,
|
||||
consumer: activeConsumer,
|
||||
nextProducer: nextProducerLink,
|
||||
prevConsumer: prevConsumerLink,
|
||||
lastReadVersion: node.version,
|
||||
nextConsumer: undefined
|
||||
};
|
||||
activeConsumer.producersTail = newLink;
|
||||
if (prevProducerLink !== undefined) {
|
||||
prevProducerLink.nextProducer = newLink;
|
||||
} else {
|
||||
activeConsumer.producers = newLink;
|
||||
}
|
||||
if (isLive) {
|
||||
producerAddLiveConsumer(node, newLink);
|
||||
}
|
||||
}
|
||||
function producerIncrementEpoch() {
|
||||
epoch++;
|
||||
}
|
||||
function producerUpdateValueVersion(node) {
|
||||
if (consumerIsLive(node) && !node.dirty) {
|
||||
return;
|
||||
}
|
||||
if (!node.dirty && node.lastCleanEpoch === epoch) {
|
||||
return;
|
||||
}
|
||||
if (!node.producerMustRecompute(node) && !consumerPollProducersForChange(node)) {
|
||||
producerMarkClean(node);
|
||||
return;
|
||||
}
|
||||
node.producerRecomputeValue(node);
|
||||
producerMarkClean(node);
|
||||
}
|
||||
function producerNotifyConsumers(node) {
|
||||
if (node.consumers === undefined) {
|
||||
return;
|
||||
}
|
||||
const prev = inNotificationPhase;
|
||||
inNotificationPhase = true;
|
||||
try {
|
||||
for (let link = node.consumers; link !== undefined; link = link.nextConsumer) {
|
||||
const consumer = link.consumer;
|
||||
if (!consumer.dirty) {
|
||||
consumerMarkDirty(consumer);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
inNotificationPhase = prev;
|
||||
}
|
||||
}
|
||||
function producerUpdatesAllowed() {
|
||||
return activeConsumer?.consumerAllowSignalWrites !== false;
|
||||
}
|
||||
function consumerMarkDirty(node) {
|
||||
node.dirty = true;
|
||||
producerNotifyConsumers(node);
|
||||
node.consumerMarkedDirty?.(node);
|
||||
}
|
||||
function producerMarkClean(node) {
|
||||
node.dirty = false;
|
||||
node.lastCleanEpoch = epoch;
|
||||
}
|
||||
function consumerBeforeComputation(node) {
|
||||
if (node) resetConsumerBeforeComputation(node);
|
||||
return setActiveConsumer(node);
|
||||
}
|
||||
function resetConsumerBeforeComputation(node) {
|
||||
node.producersTail = undefined;
|
||||
node.recomputing = true;
|
||||
}
|
||||
function consumerAfterComputation(node, prevConsumer) {
|
||||
setActiveConsumer(prevConsumer);
|
||||
if (node) finalizeConsumerAfterComputation(node);
|
||||
}
|
||||
function finalizeConsumerAfterComputation(node) {
|
||||
node.recomputing = false;
|
||||
const producersTail = node.producersTail;
|
||||
let toRemove = producersTail !== undefined ? producersTail.nextProducer : node.producers;
|
||||
if (toRemove !== undefined) {
|
||||
if (consumerIsLive(node)) {
|
||||
do {
|
||||
toRemove = producerRemoveLiveConsumerLink(toRemove);
|
||||
} while (toRemove !== undefined);
|
||||
}
|
||||
if (producersTail !== undefined) {
|
||||
producersTail.nextProducer = undefined;
|
||||
} else {
|
||||
node.producers = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
function consumerPollProducersForChange(node) {
|
||||
for (let link = node.producers; link !== undefined; link = link.nextProducer) {
|
||||
const producer = link.producer;
|
||||
const seenVersion = link.lastReadVersion;
|
||||
if (seenVersion !== producer.version) {
|
||||
return true;
|
||||
}
|
||||
producerUpdateValueVersion(producer);
|
||||
if (seenVersion !== producer.version) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function consumerDestroy(node) {
|
||||
if (consumerIsLive(node)) {
|
||||
let link = node.producers;
|
||||
while (link !== undefined) {
|
||||
link = producerRemoveLiveConsumerLink(link);
|
||||
}
|
||||
}
|
||||
node.producers = undefined;
|
||||
node.producersTail = undefined;
|
||||
node.consumers = undefined;
|
||||
node.consumersTail = undefined;
|
||||
}
|
||||
function producerAddLiveConsumer(node, link) {
|
||||
const consumersTail = node.consumersTail;
|
||||
const wasLive = consumerIsLive(node);
|
||||
if (consumersTail !== undefined) {
|
||||
link.nextConsumer = consumersTail.nextConsumer;
|
||||
consumersTail.nextConsumer = link;
|
||||
} else {
|
||||
link.nextConsumer = undefined;
|
||||
node.consumers = link;
|
||||
}
|
||||
link.prevConsumer = consumersTail;
|
||||
node.consumersTail = link;
|
||||
if (!wasLive) {
|
||||
for (let link = node.producers; link !== undefined; link = link.nextProducer) {
|
||||
producerAddLiveConsumer(link.producer, link);
|
||||
}
|
||||
}
|
||||
}
|
||||
function producerRemoveLiveConsumerLink(link) {
|
||||
const producer = link.producer;
|
||||
const nextProducer = link.nextProducer;
|
||||
const nextConsumer = link.nextConsumer;
|
||||
const prevConsumer = link.prevConsumer;
|
||||
link.nextConsumer = undefined;
|
||||
link.prevConsumer = undefined;
|
||||
if (nextConsumer !== undefined) {
|
||||
nextConsumer.prevConsumer = prevConsumer;
|
||||
} else {
|
||||
producer.consumersTail = prevConsumer;
|
||||
}
|
||||
if (prevConsumer !== undefined) {
|
||||
prevConsumer.nextConsumer = nextConsumer;
|
||||
} else {
|
||||
producer.consumers = nextConsumer;
|
||||
if (!consumerIsLive(producer)) {
|
||||
let producerLink = producer.producers;
|
||||
while (producerLink !== undefined) {
|
||||
producerLink = producerRemoveLiveConsumerLink(producerLink);
|
||||
}
|
||||
}
|
||||
}
|
||||
return nextProducer;
|
||||
}
|
||||
function consumerIsLive(node) {
|
||||
return node.consumerIsAlwaysLive || node.consumers !== undefined;
|
||||
}
|
||||
function runPostProducerCreatedFn(node) {
|
||||
postProducerCreatedFn?.(node);
|
||||
}
|
||||
function setPostProducerCreatedFn(fn) {
|
||||
const prev = postProducerCreatedFn;
|
||||
postProducerCreatedFn = fn;
|
||||
return prev;
|
||||
}
|
||||
function isValidLink(checkLink, consumer) {
|
||||
const producersTail = consumer.producersTail;
|
||||
if (producersTail !== undefined) {
|
||||
let link = consumer.producers;
|
||||
do {
|
||||
if (link === checkLink) {
|
||||
return true;
|
||||
}
|
||||
if (link === producersTail) {
|
||||
break;
|
||||
}
|
||||
link = link.nextProducer;
|
||||
} while (link !== undefined);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function defaultEquals(a, b) {
|
||||
return Object.is(a, b);
|
||||
}
|
||||
|
||||
function createComputed(computation, equal) {
|
||||
const node = Object.create(COMPUTED_NODE);
|
||||
node.computation = computation;
|
||||
if (equal !== undefined) {
|
||||
node.equal = equal;
|
||||
}
|
||||
const computed = () => {
|
||||
producerUpdateValueVersion(node);
|
||||
producerAccessed(node);
|
||||
if (node.value === ERRORED) {
|
||||
throw node.error;
|
||||
}
|
||||
return node.value;
|
||||
};
|
||||
computed[SIGNAL] = node;
|
||||
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
|
||||
const debugName = node.debugName ? ' (' + node.debugName + ')' : '';
|
||||
computed.toString = () => `[Computed${debugName}: ${String(node.value)}]`;
|
||||
}
|
||||
runPostProducerCreatedFn(node);
|
||||
return computed;
|
||||
}
|
||||
const UNSET = /* @__PURE__ */Symbol('UNSET');
|
||||
const COMPUTING = /* @__PURE__ */Symbol('COMPUTING');
|
||||
const ERRORED = /* @__PURE__ */Symbol('ERRORED');
|
||||
const COMPUTED_NODE = /* @__PURE__ */(() => {
|
||||
return {
|
||||
...REACTIVE_NODE,
|
||||
value: UNSET,
|
||||
dirty: true,
|
||||
error: null,
|
||||
equal: defaultEquals,
|
||||
kind: 'computed',
|
||||
producerMustRecompute(node) {
|
||||
return node.value === UNSET || node.value === COMPUTING;
|
||||
},
|
||||
producerRecomputeValue(node) {
|
||||
if (node.value === COMPUTING) {
|
||||
throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? 'Detected cycle in computations.' : '');
|
||||
}
|
||||
const oldValue = node.value;
|
||||
node.value = COMPUTING;
|
||||
const prevConsumer = consumerBeforeComputation(node);
|
||||
let newValue;
|
||||
let wasEqual = false;
|
||||
try {
|
||||
newValue = node.computation();
|
||||
setActiveConsumer(null);
|
||||
wasEqual = oldValue !== UNSET && oldValue !== ERRORED && newValue !== ERRORED && node.equal(oldValue, newValue);
|
||||
} catch (err) {
|
||||
newValue = ERRORED;
|
||||
node.error = err;
|
||||
} finally {
|
||||
consumerAfterComputation(node, prevConsumer);
|
||||
}
|
||||
if (wasEqual) {
|
||||
node.value = oldValue;
|
||||
return;
|
||||
}
|
||||
node.value = newValue;
|
||||
node.version++;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
function defaultThrowError() {
|
||||
throw new Error();
|
||||
}
|
||||
let throwInvalidWriteToSignalErrorFn = defaultThrowError;
|
||||
function throwInvalidWriteToSignalError(node) {
|
||||
throwInvalidWriteToSignalErrorFn(node);
|
||||
}
|
||||
function setThrowInvalidWriteToSignalError(fn) {
|
||||
throwInvalidWriteToSignalErrorFn = fn;
|
||||
}
|
||||
|
||||
let postSignalSetFn = null;
|
||||
function createSignal(initialValue, equal) {
|
||||
const node = Object.create(SIGNAL_NODE);
|
||||
node.value = initialValue;
|
||||
if (equal !== undefined) {
|
||||
node.equal = equal;
|
||||
}
|
||||
const getter = () => signalGetFn(node);
|
||||
getter[SIGNAL] = node;
|
||||
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
|
||||
const debugName = node.debugName ? ' (' + node.debugName + ')' : '';
|
||||
getter.toString = () => `[Signal${debugName}: ${String(node.value)}]`;
|
||||
}
|
||||
runPostProducerCreatedFn(node);
|
||||
const set = newValue => signalSetFn(node, newValue);
|
||||
const update = updateFn => signalUpdateFn(node, updateFn);
|
||||
return [getter, set, update];
|
||||
}
|
||||
function setPostSignalSetFn(fn) {
|
||||
const prev = postSignalSetFn;
|
||||
postSignalSetFn = fn;
|
||||
return prev;
|
||||
}
|
||||
function signalGetFn(node) {
|
||||
producerAccessed(node);
|
||||
return node.value;
|
||||
}
|
||||
function signalSetFn(node, newValue) {
|
||||
if (!producerUpdatesAllowed()) {
|
||||
throwInvalidWriteToSignalError(node);
|
||||
}
|
||||
if (!node.equal(node.value, newValue)) {
|
||||
node.value = newValue;
|
||||
signalValueChanged(node);
|
||||
}
|
||||
}
|
||||
function signalUpdateFn(node, updater) {
|
||||
if (!producerUpdatesAllowed()) {
|
||||
throwInvalidWriteToSignalError(node);
|
||||
}
|
||||
signalSetFn(node, updater(node.value));
|
||||
}
|
||||
function runPostSignalSetFn(node) {
|
||||
postSignalSetFn?.(node);
|
||||
}
|
||||
const SIGNAL_NODE = /* @__PURE__ */(() => {
|
||||
return {
|
||||
...REACTIVE_NODE,
|
||||
equal: defaultEquals,
|
||||
value: undefined,
|
||||
kind: 'signal'
|
||||
};
|
||||
})();
|
||||
function signalValueChanged(node) {
|
||||
node.version++;
|
||||
producerIncrementEpoch();
|
||||
producerNotifyConsumers(node);
|
||||
postSignalSetFn?.(node);
|
||||
}
|
||||
|
||||
const BASE_EFFECT_NODE = /* @__PURE__ */(() => ({
|
||||
...REACTIVE_NODE,
|
||||
consumerIsAlwaysLive: true,
|
||||
consumerAllowSignalWrites: true,
|
||||
dirty: true,
|
||||
kind: 'effect'
|
||||
}))();
|
||||
function runEffect(node) {
|
||||
node.dirty = false;
|
||||
if (node.version > 0 && !consumerPollProducersForChange(node)) {
|
||||
return;
|
||||
}
|
||||
node.version++;
|
||||
const prevNode = consumerBeforeComputation(node);
|
||||
try {
|
||||
node.cleanup();
|
||||
node.fn();
|
||||
} finally {
|
||||
consumerAfterComputation(node, prevNode);
|
||||
}
|
||||
}
|
||||
|
||||
export { BASE_EFFECT_NODE, COMPUTING, ERRORED, REACTIVE_NODE, SIGNAL, SIGNAL_NODE, UNSET, consumerAfterComputation, consumerBeforeComputation, consumerDestroy, consumerMarkDirty, consumerPollProducersForChange, createComputed, createSignal, defaultEquals, finalizeConsumerAfterComputation, getActiveConsumer, isInNotificationPhase, isReactive, producerAccessed, producerIncrementEpoch, producerMarkClean, producerNotifyConsumers, producerUpdateValueVersion, producerUpdatesAllowed, resetConsumerBeforeComputation, runEffect, runPostProducerCreatedFn, runPostSignalSetFn, setActiveConsumer, setPostProducerCreatedFn, setPostSignalSetFn, setThrowInvalidWriteToSignalError, signalGetFn, signalSetFn, signalUpdateFn };
|
||||
//# sourceMappingURL=_effect-chunk.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2977
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
let _currentInjector = undefined;
|
||||
function getCurrentInjector() {
|
||||
return _currentInjector;
|
||||
}
|
||||
function setCurrentInjector(injector) {
|
||||
const former = _currentInjector;
|
||||
_currentInjector = injector;
|
||||
return former;
|
||||
}
|
||||
function inject(token, options) {
|
||||
const currentInjector = getCurrentInjector();
|
||||
if (!currentInjector) {
|
||||
throw new Error('Current injector is not set.');
|
||||
}
|
||||
if (!token.ɵprov) {
|
||||
throw new Error('Token is not an injectable');
|
||||
}
|
||||
return currentInjector.retrieve(token, options);
|
||||
}
|
||||
|
||||
const NOT_FOUND = Symbol('NotFound');
|
||||
class NotFoundError extends Error {
|
||||
name = 'ɵNotFound';
|
||||
constructor(message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
function isNotFound(e) {
|
||||
return e === NOT_FOUND || e?.name === 'ɵNotFound';
|
||||
}
|
||||
|
||||
export { NOT_FOUND, NotFoundError, getCurrentInjector, inject, isNotFound, setCurrentInjector };
|
||||
//# sourceMappingURL=_not_found-chunk.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_not_found-chunk.mjs","sources":["../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/core/primitives/di/src/injector.ts","../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/core/primitives/di/src/not_found.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {Constructor, InjectionToken} from './injection_token';\nimport {NotFound} from './not_found';\n\nexport interface Injector {\n retrieve<T>(token: InjectionToken<T>, options?: unknown): T | NotFound;\n}\n\n/**\n * Current injector value used by `inject`.\n * - `undefined`: it is an error to call `inject`\n * - `null`: `inject` can be called but there is no injector (limp-mode).\n * - Injector instance: Use the injector for resolution.\n */\nlet _currentInjector: Injector | undefined | null = undefined;\n\nexport function getCurrentInjector(): Injector | undefined | null {\n return _currentInjector;\n}\n\nexport function setCurrentInjector(\n injector: Injector | null | undefined,\n): Injector | undefined | null {\n const former = _currentInjector;\n _currentInjector = injector;\n return former;\n}\n\nexport function inject<T>(token: InjectionToken<T> | Constructor<T>): T;\nexport function inject<T>(\n token: InjectionToken<T> | Constructor<T>,\n options?: unknown,\n): T | NotFound {\n const currentInjector = getCurrentInjector();\n if (!currentInjector) {\n throw new Error('Current injector is not set.');\n }\n if (!(token as InjectionToken<T>).ɵprov) {\n throw new Error('Token is not an injectable');\n }\n return currentInjector.retrieve(token as InjectionToken<T>, options);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * Value returned if the key-value pair couldn't be found in the context\n * hierarchy.\n */\nexport const NOT_FOUND: unique symbol = Symbol('NotFound');\n\n/**\n * Error thrown when the key-value pair couldn't be found in the context\n * hierarchy. Context can be attached below.\n */\nexport class NotFoundError extends Error {\n override readonly name: string = 'ɵNotFound';\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Type guard for checking if an unknown value is a NotFound.\n */\nexport function isNotFound(e: unknown): e is NotFound {\n return e === NOT_FOUND || (e as NotFoundError)?.name === 'ɵNotFound';\n}\n\n/**\n * Type union of NotFound and NotFoundError.\n */\nexport type NotFound = typeof NOT_FOUND | NotFoundError;\n"],"names":["_currentInjector","undefined","getCurrentInjector","setCurrentInjector","injector","former","inject","token","options","currentInjector","Error","ɵprov","retrieve","NOT_FOUND","Symbol","NotFoundError","name","constructor","message","isNotFound","e"],"mappings":";;;;;;AAqBA,IAAIA,gBAAgB,GAAgCC,SAAS;SAE7CC,kBAAkBA,GAAA;AAChC,EAAA,OAAOF,gBAAgB;AACzB;AAEM,SAAUG,kBAAkBA,CAChCC,QAAqC,EAAA;EAErC,MAAMC,MAAM,GAAGL,gBAAgB;AAC/BA,EAAAA,gBAAgB,GAAGI,QAAQ;AAC3B,EAAA,OAAOC,MAAM;AACf;AAGgB,SAAAC,MAAMA,CACpBC,KAAyC,EACzCC,OAAiB,EAAA;AAEjB,EAAA,MAAMC,eAAe,GAAGP,kBAAkB,EAAE;EAC5C,IAAI,CAACO,eAAe,EAAE;AACpB,IAAA,MAAM,IAAIC,KAAK,CAAC,8BAA8B,CAAC;AACjD;AACA,EAAA,IAAI,CAAEH,KAA2B,CAACI,KAAK,EAAE;AACvC,IAAA,MAAM,IAAID,KAAK,CAAC,4BAA4B,CAAC;AAC/C;AACA,EAAA,OAAOD,eAAe,CAACG,QAAQ,CAACL,KAA0B,EAAEC,OAAO,CAAC;AACtE;;MCpCaK,SAAS,GAAkBC,MAAM,CAAC,UAAU;AAMnD,MAAOC,aAAc,SAAQL,KAAK,CAAA;AACpBM,EAAAA,IAAI,GAAW,WAAW;EAC5CC,WAAAA,CAAYC,OAAe,EAAA;IACzB,KAAK,CAACA,OAAO,CAAC;AAChB;AACD;AAKK,SAAUC,UAAUA,CAACC,CAAU,EAAA;EACnC,OAAOA,CAAC,KAAKP,SAAS,IAAKO,CAAmB,EAAEJ,IAAI,KAAK,WAAW;AACtE;;;;"}
|
||||
+410
@@ -0,0 +1,410 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { inject, ErrorHandler, DestroyRef, RuntimeError, formatRuntimeError, signalAsReadonlyFn, assertInInjectionContext, Injector, effect, PendingTasks, signal } from './_effect-chunk2.mjs';
|
||||
import { setActiveConsumer, createComputed, SIGNAL } from './_effect-chunk.mjs';
|
||||
import { untracked as untracked$1, createLinkedSignal, linkedSignalSetFn, linkedSignalUpdateFn } from './_untracked-chunk.mjs';
|
||||
|
||||
class OutputEmitterRef {
|
||||
destroyed = false;
|
||||
listeners = null;
|
||||
errorHandler = inject(ErrorHandler, {
|
||||
optional: true
|
||||
});
|
||||
destroyRef = inject(DestroyRef);
|
||||
constructor() {
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.destroyed = true;
|
||||
this.listeners = null;
|
||||
});
|
||||
}
|
||||
subscribe(callback) {
|
||||
if (this.destroyed) {
|
||||
throw new RuntimeError(953, ngDevMode && 'Unexpected subscription to destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');
|
||||
}
|
||||
(this.listeners ??= []).push(callback);
|
||||
return {
|
||||
unsubscribe: () => {
|
||||
const idx = this.listeners?.indexOf(callback);
|
||||
if (idx !== undefined && idx !== -1) {
|
||||
this.listeners?.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
emit(value) {
|
||||
if (this.destroyed) {
|
||||
console.warn(formatRuntimeError(953, ngDevMode && 'Unexpected emit for destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.'));
|
||||
return;
|
||||
}
|
||||
if (this.listeners === null) {
|
||||
return;
|
||||
}
|
||||
const previousConsumer = setActiveConsumer(null);
|
||||
try {
|
||||
for (const listenerFn of this.listeners) {
|
||||
try {
|
||||
listenerFn(value);
|
||||
} catch (err) {
|
||||
this.errorHandler?.handleError(err);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setActiveConsumer(previousConsumer);
|
||||
}
|
||||
}
|
||||
}
|
||||
function getOutputDestroyRef(ref) {
|
||||
return ref.destroyRef;
|
||||
}
|
||||
|
||||
function untracked(nonReactiveReadsFn) {
|
||||
return untracked$1(nonReactiveReadsFn);
|
||||
}
|
||||
|
||||
function computed(computation, options) {
|
||||
const getter = createComputed(computation, options?.equal);
|
||||
if (ngDevMode) {
|
||||
getter.toString = () => `[Computed: ${getter()}]`;
|
||||
getter[SIGNAL].debugName = options?.debugName;
|
||||
}
|
||||
return getter;
|
||||
}
|
||||
|
||||
const identityFn = v => v;
|
||||
function linkedSignal(optionsOrComputation, options) {
|
||||
if (typeof optionsOrComputation === 'function') {
|
||||
const getter = createLinkedSignal(optionsOrComputation, identityFn, options?.equal);
|
||||
return upgradeLinkedSignalGetter(getter, options?.debugName);
|
||||
} else {
|
||||
const getter = createLinkedSignal(optionsOrComputation.source, optionsOrComputation.computation, optionsOrComputation.equal);
|
||||
return upgradeLinkedSignalGetter(getter, optionsOrComputation.debugName);
|
||||
}
|
||||
}
|
||||
function upgradeLinkedSignalGetter(getter, debugName) {
|
||||
if (ngDevMode) {
|
||||
getter.toString = () => `[LinkedSignal: ${getter()}]`;
|
||||
getter[SIGNAL].debugName = debugName;
|
||||
}
|
||||
const node = getter[SIGNAL];
|
||||
const upgradedGetter = getter;
|
||||
upgradedGetter.set = newValue => linkedSignalSetFn(node, newValue);
|
||||
upgradedGetter.update = updateFn => linkedSignalUpdateFn(node, updateFn);
|
||||
upgradedGetter.asReadonly = signalAsReadonlyFn.bind(getter);
|
||||
return upgradedGetter;
|
||||
}
|
||||
|
||||
function resource(options) {
|
||||
if (ngDevMode && !options?.injector) {
|
||||
assertInInjectionContext(resource);
|
||||
}
|
||||
const oldNameForParams = options.request;
|
||||
const params = options.params ?? oldNameForParams ?? (() => null);
|
||||
return new ResourceImpl(params, getLoader(options), options.defaultValue, options.equal ? wrapEqualityFn(options.equal) : undefined, options.debugName, options.injector ?? inject(Injector));
|
||||
}
|
||||
class BaseWritableResource {
|
||||
value;
|
||||
isLoading;
|
||||
constructor(value, debugName) {
|
||||
this.value = value;
|
||||
this.value.set = this.set.bind(this);
|
||||
this.value.update = this.update.bind(this);
|
||||
this.value.asReadonly = signalAsReadonlyFn;
|
||||
this.isLoading = computed(() => this.status() === 'loading' || this.status() === 'reloading', ngDevMode ? createDebugNameObject(debugName, 'isLoading') : undefined);
|
||||
}
|
||||
isError = computed(() => this.status() === 'error');
|
||||
update(updateFn) {
|
||||
this.set(updateFn(untracked(this.value)));
|
||||
}
|
||||
isValueDefined = computed(() => {
|
||||
if (this.isError()) {
|
||||
return false;
|
||||
}
|
||||
return this.value() !== undefined;
|
||||
});
|
||||
_snapshot;
|
||||
get snapshot() {
|
||||
return this._snapshot ??= computed(() => {
|
||||
const status = this.status();
|
||||
if (status === 'error') {
|
||||
return {
|
||||
status: 'error',
|
||||
error: this.error()
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status,
|
||||
value: this.value()
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
hasValue() {
|
||||
return this.isValueDefined();
|
||||
}
|
||||
asReadonly() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class ResourceImpl extends BaseWritableResource {
|
||||
loaderFn;
|
||||
equal;
|
||||
debugName;
|
||||
pendingTasks;
|
||||
state;
|
||||
extRequest;
|
||||
effectRef;
|
||||
pendingController;
|
||||
resolvePendingTask = undefined;
|
||||
destroyed = false;
|
||||
unregisterOnDestroy;
|
||||
status;
|
||||
error;
|
||||
constructor(request, loaderFn, defaultValue, equal, debugName, injector, getInitialStream) {
|
||||
super(computed(() => {
|
||||
const streamValue = this.state().stream?.();
|
||||
if (!streamValue) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (this.state().status === 'loading' && this.error()) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (!isResolved(streamValue)) {
|
||||
throw new ResourceValueError(this.error());
|
||||
}
|
||||
return streamValue.value;
|
||||
}, {
|
||||
equal,
|
||||
...(ngDevMode ? createDebugNameObject(debugName, 'value') : undefined)
|
||||
}), debugName);
|
||||
this.loaderFn = loaderFn;
|
||||
this.equal = equal;
|
||||
this.debugName = debugName;
|
||||
this.extRequest = linkedSignal({
|
||||
source: request,
|
||||
computation: request => ({
|
||||
request,
|
||||
reload: 0
|
||||
}),
|
||||
...(ngDevMode ? createDebugNameObject(debugName, 'extRequest') : undefined)
|
||||
});
|
||||
this.state = linkedSignal({
|
||||
source: this.extRequest,
|
||||
computation: (extRequest, previous) => {
|
||||
if (!previous) {
|
||||
const initialStream = getInitialStream?.(extRequest.request);
|
||||
getInitialStream = undefined;
|
||||
const status = extRequest.request === undefined ? 'idle' : initialStream ? 'resolved' : 'loading';
|
||||
return {
|
||||
extRequest,
|
||||
status,
|
||||
previousStatus: 'idle',
|
||||
stream: initialStream
|
||||
};
|
||||
} else {
|
||||
const status = extRequest.request === undefined ? 'idle' : 'loading';
|
||||
return {
|
||||
extRequest,
|
||||
status,
|
||||
previousStatus: projectStatusOfState(previous.value),
|
||||
stream: previous.value.extRequest.request === extRequest.request ? previous.value.stream : undefined
|
||||
};
|
||||
}
|
||||
},
|
||||
...(ngDevMode ? createDebugNameObject(debugName, 'state') : undefined)
|
||||
});
|
||||
this.effectRef = effect(this.loadEffect.bind(this), {
|
||||
injector,
|
||||
manualCleanup: true,
|
||||
...(ngDevMode ? createDebugNameObject(debugName, 'loadEffect') : undefined)
|
||||
});
|
||||
this.pendingTasks = injector.get(PendingTasks);
|
||||
this.unregisterOnDestroy = injector.get(DestroyRef).onDestroy(() => this.destroy());
|
||||
this.status = computed(() => projectStatusOfState(this.state()), ngDevMode ? createDebugNameObject(debugName, 'status') : undefined);
|
||||
this.error = computed(() => {
|
||||
const stream = this.state().stream?.();
|
||||
return stream && !isResolved(stream) ? stream.error : undefined;
|
||||
}, ngDevMode ? createDebugNameObject(debugName, 'error') : undefined);
|
||||
}
|
||||
set(value) {
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
const error = untracked(this.error);
|
||||
const state = untracked(this.state);
|
||||
if (!error) {
|
||||
const current = untracked(this.value);
|
||||
if (state.status === 'local' && (this.equal ? this.equal(current, value) : current === value)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.state.set({
|
||||
extRequest: state.extRequest,
|
||||
status: 'local',
|
||||
previousStatus: 'local',
|
||||
stream: signal({
|
||||
value
|
||||
}, ngDevMode ? createDebugNameObject(this.debugName, 'stream') : undefined)
|
||||
});
|
||||
this.abortInProgressLoad();
|
||||
}
|
||||
reload() {
|
||||
const {
|
||||
status
|
||||
} = untracked(this.state);
|
||||
if (status === 'idle' || status === 'loading') {
|
||||
return false;
|
||||
}
|
||||
this.extRequest.update(({
|
||||
request,
|
||||
reload
|
||||
}) => ({
|
||||
request,
|
||||
reload: reload + 1
|
||||
}));
|
||||
return true;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
this.unregisterOnDestroy();
|
||||
this.effectRef.destroy();
|
||||
this.abortInProgressLoad();
|
||||
this.state.set({
|
||||
extRequest: {
|
||||
request: undefined,
|
||||
reload: 0
|
||||
},
|
||||
status: 'idle',
|
||||
previousStatus: 'idle',
|
||||
stream: undefined
|
||||
});
|
||||
}
|
||||
async loadEffect() {
|
||||
const extRequest = this.extRequest();
|
||||
const {
|
||||
status: currentStatus,
|
||||
previousStatus
|
||||
} = untracked(this.state);
|
||||
if (extRequest.request === undefined) {
|
||||
return;
|
||||
} else if (currentStatus !== 'loading') {
|
||||
return;
|
||||
}
|
||||
this.abortInProgressLoad();
|
||||
let resolvePendingTask = this.resolvePendingTask = this.pendingTasks.add();
|
||||
const {
|
||||
signal: abortSignal
|
||||
} = this.pendingController = new AbortController();
|
||||
try {
|
||||
const stream = await untracked(() => {
|
||||
return this.loaderFn({
|
||||
params: extRequest.request,
|
||||
request: extRequest.request,
|
||||
abortSignal,
|
||||
previous: {
|
||||
status: previousStatus
|
||||
}
|
||||
});
|
||||
});
|
||||
if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
|
||||
return;
|
||||
}
|
||||
this.state.set({
|
||||
extRequest,
|
||||
status: 'resolved',
|
||||
previousStatus: 'resolved',
|
||||
stream
|
||||
});
|
||||
} catch (err) {
|
||||
if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
|
||||
return;
|
||||
}
|
||||
this.state.set({
|
||||
extRequest,
|
||||
status: 'resolved',
|
||||
previousStatus: 'error',
|
||||
stream: signal({
|
||||
error: encapsulateResourceError(err)
|
||||
}, ngDevMode ? createDebugNameObject(this.debugName, 'stream') : undefined)
|
||||
});
|
||||
} finally {
|
||||
resolvePendingTask?.();
|
||||
resolvePendingTask = undefined;
|
||||
}
|
||||
}
|
||||
abortInProgressLoad() {
|
||||
untracked(() => this.pendingController?.abort());
|
||||
this.pendingController = undefined;
|
||||
this.resolvePendingTask?.();
|
||||
this.resolvePendingTask = undefined;
|
||||
}
|
||||
}
|
||||
function wrapEqualityFn(equal) {
|
||||
return (a, b) => a === undefined || b === undefined ? a === b : equal(a, b);
|
||||
}
|
||||
function getLoader(options) {
|
||||
if (isStreamingResourceOptions(options)) {
|
||||
return options.stream;
|
||||
}
|
||||
return async params => {
|
||||
try {
|
||||
return signal({
|
||||
value: await options.loader(params)
|
||||
}, ngDevMode ? createDebugNameObject(options.debugName, 'stream') : undefined);
|
||||
} catch (err) {
|
||||
return signal({
|
||||
error: encapsulateResourceError(err)
|
||||
}, ngDevMode ? createDebugNameObject(options.debugName, 'stream') : undefined);
|
||||
}
|
||||
};
|
||||
}
|
||||
function isStreamingResourceOptions(options) {
|
||||
return !!options.stream;
|
||||
}
|
||||
function projectStatusOfState(state) {
|
||||
switch (state.status) {
|
||||
case 'loading':
|
||||
return state.extRequest.reload === 0 ? 'loading' : 'reloading';
|
||||
case 'resolved':
|
||||
return isResolved(state.stream()) ? 'resolved' : 'error';
|
||||
default:
|
||||
return state.status;
|
||||
}
|
||||
}
|
||||
function isResolved(state) {
|
||||
return state.error === undefined;
|
||||
}
|
||||
function createDebugNameObject(resourceDebugName, internalSignalDebugName) {
|
||||
return {
|
||||
debugName: `Resource${resourceDebugName ? '#' + resourceDebugName : ''}.${internalSignalDebugName}`
|
||||
};
|
||||
}
|
||||
function encapsulateResourceError(error) {
|
||||
if (isErrorLike(error)) {
|
||||
return error;
|
||||
}
|
||||
return new ResourceWrappedError(error);
|
||||
}
|
||||
function isErrorLike(error) {
|
||||
return error instanceof Error || typeof error === 'object' && typeof error.name === 'string' && typeof error.message === 'string';
|
||||
}
|
||||
class ResourceValueError extends Error {
|
||||
constructor(error) {
|
||||
super(ngDevMode ? `Resource is currently in an error state (see Error.cause for details): ${error.message}` : error.message, {
|
||||
cause: error
|
||||
});
|
||||
}
|
||||
}
|
||||
class ResourceWrappedError extends Error {
|
||||
constructor(error) {
|
||||
super(ngDevMode ? `Resource returned an error that's not an Error instance: ${String(error)}. Check this error's .cause for the actual error.` : String(error), {
|
||||
cause: error
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { OutputEmitterRef, ResourceImpl, ResourceValueError, computed, encapsulateResourceError, getOutputDestroyRef, linkedSignal, resource, untracked };
|
||||
//# sourceMappingURL=_resource-chunk.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+99
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { SIGNAL, runPostProducerCreatedFn, producerUpdateValueVersion, signalSetFn, producerMarkClean, ERRORED, signalUpdateFn, REACTIVE_NODE, UNSET, defaultEquals, COMPUTING, consumerBeforeComputation, consumerAfterComputation, producerAccessed, setActiveConsumer } from './_effect-chunk.mjs';
|
||||
|
||||
function createLinkedSignal(sourceFn, computationFn, equalityFn) {
|
||||
const node = Object.create(LINKED_SIGNAL_NODE);
|
||||
node.source = sourceFn;
|
||||
node.computation = computationFn;
|
||||
if (equalityFn != undefined) {
|
||||
node.equal = equalityFn;
|
||||
}
|
||||
const linkedSignalGetter = () => {
|
||||
producerUpdateValueVersion(node);
|
||||
producerAccessed(node);
|
||||
if (node.value === ERRORED) {
|
||||
throw node.error;
|
||||
}
|
||||
return node.value;
|
||||
};
|
||||
const getter = linkedSignalGetter;
|
||||
getter[SIGNAL] = node;
|
||||
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
|
||||
const debugName = node.debugName ? ' (' + node.debugName + ')' : '';
|
||||
getter.toString = () => `[LinkedSignal${debugName}: ${String(node.value)}]`;
|
||||
}
|
||||
runPostProducerCreatedFn(node);
|
||||
return getter;
|
||||
}
|
||||
function linkedSignalSetFn(node, newValue) {
|
||||
producerUpdateValueVersion(node);
|
||||
signalSetFn(node, newValue);
|
||||
producerMarkClean(node);
|
||||
}
|
||||
function linkedSignalUpdateFn(node, updater) {
|
||||
producerUpdateValueVersion(node);
|
||||
if (node.value === ERRORED) {
|
||||
throw node.error;
|
||||
}
|
||||
signalUpdateFn(node, updater);
|
||||
producerMarkClean(node);
|
||||
}
|
||||
const LINKED_SIGNAL_NODE = /* @__PURE__ */(() => {
|
||||
return {
|
||||
...REACTIVE_NODE,
|
||||
value: UNSET,
|
||||
dirty: true,
|
||||
error: null,
|
||||
equal: defaultEquals,
|
||||
kind: 'linkedSignal',
|
||||
producerMustRecompute(node) {
|
||||
return node.value === UNSET || node.value === COMPUTING;
|
||||
},
|
||||
producerRecomputeValue(node) {
|
||||
if (node.value === COMPUTING) {
|
||||
throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? 'Detected cycle in computations.' : '');
|
||||
}
|
||||
const oldValue = node.value;
|
||||
node.value = COMPUTING;
|
||||
const prevConsumer = consumerBeforeComputation(node);
|
||||
let newValue;
|
||||
try {
|
||||
const newSourceValue = node.source();
|
||||
const prev = oldValue === UNSET || oldValue === ERRORED ? undefined : {
|
||||
source: node.sourceValue,
|
||||
value: oldValue
|
||||
};
|
||||
newValue = node.computation(newSourceValue, prev);
|
||||
node.sourceValue = newSourceValue;
|
||||
} catch (err) {
|
||||
newValue = ERRORED;
|
||||
node.error = err;
|
||||
} finally {
|
||||
consumerAfterComputation(node, prevConsumer);
|
||||
}
|
||||
if (oldValue !== UNSET && newValue !== ERRORED && node.equal(oldValue, newValue)) {
|
||||
node.value = oldValue;
|
||||
return;
|
||||
}
|
||||
node.value = newValue;
|
||||
node.version++;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
function untracked(nonReactiveReadsFn) {
|
||||
const prevConsumer = setActiveConsumer(null);
|
||||
try {
|
||||
return nonReactiveReadsFn();
|
||||
} finally {
|
||||
setActiveConsumer(prevConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
export { createLinkedSignal, linkedSignalSetFn, linkedSignalUpdateFn, untracked };
|
||||
//# sourceMappingURL=_untracked-chunk.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
function setAlternateWeakRefImpl(impl) {}
|
||||
|
||||
export { setAlternateWeakRefImpl };
|
||||
//# sourceMappingURL=_weak_ref-chunk.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_weak_ref-chunk.mjs","sources":["../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/core/primitives/signals/src/weak_ref.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nexport function setAlternateWeakRefImpl(impl: unknown) {\n // TODO: remove this function\n}\n"],"names":["setAlternateWeakRefImpl","impl"],"mappings":";;;;;;AAQM,SAAUA,uBAAuBA,CAACC,IAAa,EAAA;;;;"}
|
||||
+2952
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+23
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
export { NOT_FOUND, NotFoundError, getCurrentInjector, inject, isNotFound, setCurrentInjector } from './_not_found-chunk.mjs';
|
||||
|
||||
function defineInjectable(opts) {
|
||||
return {
|
||||
token: opts.token,
|
||||
providedIn: opts.providedIn || null,
|
||||
factory: opts.factory,
|
||||
value: undefined
|
||||
};
|
||||
}
|
||||
function registerInjectable(ctor, declaration) {
|
||||
ctor.ɵprov = declaration;
|
||||
return ctor;
|
||||
}
|
||||
|
||||
export { defineInjectable, registerInjectable };
|
||||
//# sourceMappingURL=primitives-di.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"primitives-di.mjs","sources":["../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/core/primitives/di/src/injection_token.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {Type} from './type';\n/**\n * Information about how a type or `InjectionToken` interfaces with the DI\n * system. This describes:\n *\n * 1. *How* the type is provided\n * The declaration must specify only one of the following:\n * - A `value` which is a predefined instance of the type.\n * - A `factory` which defines how to create the given type `T`, possibly\n * requesting injection of other types if necessary.\n * - Neither, in which case the type is expected to already be present in the\n * injector hierarchy. This is used for internal use cases.\n *\n * 2. *Where* the type is stored (if it is stored)\n * - The `providedIn` parameter specifies which injector the type belongs to.\n * - The `token` is used as the key to store the type in the injector.\n */\nexport interface ɵɵInjectableDeclaration<T> {\n /**\n * Specifies that the given type belongs to a particular `Injector`,\n * `NgModule`, or a special scope (e.g. `'root'`).\n *\n * `any` is deprecated and will be removed soon.\n *\n * A value of `null` indicates that the injectable does not belong to any\n * scope, and won't be stored in any injector. For declarations with a\n * factory, this will create a new instance of the type each time it is\n * requested.\n */\n providedIn: Type<any> | 'root' | 'platform' | 'any' | null;\n\n /**\n * The token to which this definition belongs.\n *\n * Note that this may not be the same as the type that the `factory` will create.\n */\n token: unknown;\n\n /**\n * Factory method to execute to create an instance of the injectable.\n */\n factory?: (t?: Type<any>) => T;\n\n /**\n * In a case of no explicit injector, a location where the instance of the injectable is stored.\n */\n value?: T;\n}\n\n/**\n * A `Type` which has a `ɵprov: ɵɵInjectableDeclaration` static field.\n *\n * `InjectableType`s contain their own Dependency Injection metadata and are usable in an\n * `InjectorDef`-based `StaticInjector`.\n *\n * @publicApi\n */\nexport interface InjectionToken<T> {\n ɵprov: ɵɵInjectableDeclaration<T>;\n}\n\nexport function defineInjectable<T>(opts: {\n token: unknown;\n providedIn?: Type<any> | 'root' | 'platform' | 'any' | 'environment' | null;\n factory: () => T;\n}): ɵɵInjectableDeclaration<T> {\n return {\n token: opts.token,\n providedIn: (opts.providedIn as any) || null,\n factory: opts.factory,\n value: undefined,\n } as ɵɵInjectableDeclaration<T>;\n}\n\nexport type Constructor<T> = Function & {prototype: T};\n\nexport function registerInjectable<T>(\n ctor: unknown,\n declaration: ɵɵInjectableDeclaration<T>,\n): InjectionToken<T> {\n (ctor as unknown as InjectionToken<T>).ɵprov = declaration;\n return ctor as Constructor<T> & InjectionToken<T>;\n}\n"],"names":["defineInjectable","opts","token","providedIn","factory","value","undefined","registerInjectable","ctor","declaration","ɵprov"],"mappings":";;;;;;;;AAqEM,SAAUA,gBAAgBA,CAAIC,IAInC,EAAA;EACC,OAAO;IACLC,KAAK,EAAED,IAAI,CAACC,KAAK;AACjBC,IAAAA,UAAU,EAAGF,IAAI,CAACE,UAAkB,IAAI,IAAI;IAC5CC,OAAO,EAAEH,IAAI,CAACG,OAAO;AACrBC,IAAAA,KAAK,EAAEC;GACsB;AACjC;AAIgB,SAAAC,kBAAkBA,CAChCC,IAAa,EACbC,WAAuC,EAAA;EAEtCD,IAAqC,CAACE,KAAK,GAAGD,WAAW;AAC1D,EAAA,OAAOD,IAA0C;AACnD;;;;"}
|
||||
+788
@@ -0,0 +1,788 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { Attribute } from './_attribute-chunk.mjs';
|
||||
|
||||
const Property = {
|
||||
JSACTION: '__jsaction',
|
||||
OWNER: '__owner'
|
||||
};
|
||||
|
||||
const parseCache = {};
|
||||
function get(element) {
|
||||
return element[Property.JSACTION];
|
||||
}
|
||||
function getDefaulted(element) {
|
||||
const cache = get(element) ?? {};
|
||||
set(element, cache);
|
||||
return cache;
|
||||
}
|
||||
function set(element, actionMap) {
|
||||
element[Property.JSACTION] = actionMap;
|
||||
}
|
||||
function getParsed(text) {
|
||||
return parseCache[text];
|
||||
}
|
||||
function setParsed(text, parsed) {
|
||||
parseCache[text] = parsed;
|
||||
}
|
||||
|
||||
const EventType = {
|
||||
AUXCLICK: 'auxclick',
|
||||
CHANGE: 'change',
|
||||
CLICK: 'click',
|
||||
CLICKMOD: 'clickmod',
|
||||
CLICKONLY: 'clickonly',
|
||||
DBLCLICK: 'dblclick',
|
||||
FOCUS: 'focus',
|
||||
FOCUSIN: 'focusin',
|
||||
BLUR: 'blur',
|
||||
FOCUSOUT: 'focusout',
|
||||
SUBMIT: 'submit',
|
||||
KEYDOWN: 'keydown',
|
||||
KEYPRESS: 'keypress',
|
||||
KEYUP: 'keyup',
|
||||
MOUSEUP: 'mouseup',
|
||||
MOUSEDOWN: 'mousedown',
|
||||
MOUSEOVER: 'mouseover',
|
||||
MOUSEOUT: 'mouseout',
|
||||
MOUSEENTER: 'mouseenter',
|
||||
MOUSELEAVE: 'mouseleave',
|
||||
MOUSEMOVE: 'mousemove',
|
||||
POINTERUP: 'pointerup',
|
||||
POINTERDOWN: 'pointerdown',
|
||||
POINTEROVER: 'pointerover',
|
||||
POINTEROUT: 'pointerout',
|
||||
POINTERENTER: 'pointerenter',
|
||||
POINTERLEAVE: 'pointerleave',
|
||||
POINTERMOVE: 'pointermove',
|
||||
POINTERCANCEL: 'pointercancel',
|
||||
GOTPOINTERCAPTURE: 'gotpointercapture',
|
||||
LOSTPOINTERCAPTURE: 'lostpointercapture',
|
||||
ERROR: 'error',
|
||||
LOAD: 'load',
|
||||
UNLOAD: 'unload',
|
||||
TOUCHSTART: 'touchstart',
|
||||
TOUCHEND: 'touchend',
|
||||
TOUCHMOVE: 'touchmove',
|
||||
INPUT: 'input',
|
||||
SCROLL: 'scroll',
|
||||
TOGGLE: 'toggle',
|
||||
CUSTOM: '_custom'
|
||||
};
|
||||
const MOUSE_SPECIAL_EVENT_TYPES = [EventType.MOUSEENTER, EventType.MOUSELEAVE, 'pointerenter', 'pointerleave'];
|
||||
const BUBBLE_EVENT_TYPES = [EventType.CLICK, EventType.DBLCLICK, EventType.FOCUSIN, EventType.FOCUSOUT, EventType.KEYDOWN, EventType.KEYUP, EventType.KEYPRESS, EventType.MOUSEOVER, EventType.MOUSEOUT, EventType.SUBMIT, EventType.TOUCHSTART, EventType.TOUCHEND, EventType.TOUCHMOVE, 'touchcancel', 'auxclick', 'change', 'compositionstart', 'compositionupdate', 'compositionend', 'beforeinput', 'input', 'select', 'copy', 'cut', 'paste', 'mousedown', 'mouseup', 'wheel', 'contextmenu', 'dragover', 'dragenter', 'dragleave', 'drop', 'dragstart', 'dragend', 'pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'pointerover', 'pointerout', 'gotpointercapture', 'lostpointercapture', 'ended', 'loadedmetadata', 'pagehide', 'pageshow', 'visibilitychange', 'beforematch'];
|
||||
const CAPTURE_EVENT_TYPES = [EventType.FOCUS, EventType.BLUR, EventType.ERROR, EventType.LOAD, EventType.TOGGLE];
|
||||
const isCaptureEventType = eventType => CAPTURE_EVENT_TYPES.indexOf(eventType) >= 0;
|
||||
const EARLY_EVENT_TYPES = BUBBLE_EVENT_TYPES.concat(CAPTURE_EVENT_TYPES);
|
||||
const isEarlyEventType = eventType => EARLY_EVENT_TYPES.indexOf(eventType) >= 0;
|
||||
|
||||
function getBrowserEventType(eventType) {
|
||||
if (eventType === EventType.MOUSEENTER) {
|
||||
return EventType.MOUSEOVER;
|
||||
} else if (eventType === EventType.MOUSELEAVE) {
|
||||
return EventType.MOUSEOUT;
|
||||
} else if (eventType === EventType.POINTERENTER) {
|
||||
return EventType.POINTEROVER;
|
||||
} else if (eventType === EventType.POINTERLEAVE) {
|
||||
return EventType.POINTEROUT;
|
||||
}
|
||||
return eventType;
|
||||
}
|
||||
function addEventListener(element, eventType, handler, passive) {
|
||||
let capture = false;
|
||||
if (isCaptureEventType(eventType)) {
|
||||
capture = true;
|
||||
}
|
||||
const options = typeof passive === 'boolean' ? {
|
||||
capture,
|
||||
passive
|
||||
} : capture;
|
||||
element.addEventListener(eventType, handler, options);
|
||||
return {
|
||||
eventType,
|
||||
handler,
|
||||
capture,
|
||||
passive
|
||||
};
|
||||
}
|
||||
function removeEventListener(element, info) {
|
||||
if (element.removeEventListener) {
|
||||
const options = typeof info.passive === 'boolean' ? {
|
||||
capture: info.capture
|
||||
} : info.capture;
|
||||
element.removeEventListener(info.eventType, info.handler, options);
|
||||
} else if (element.detachEvent) {
|
||||
element.detachEvent(`on${info.eventType}`, info.handler);
|
||||
}
|
||||
}
|
||||
function preventDefault(e) {
|
||||
e.preventDefault ? e.preventDefault() : e.returnValue = false;
|
||||
}
|
||||
let isMac = typeof navigator !== 'undefined' && /Macintosh/.test(navigator.userAgent);
|
||||
function isMiddleClick(e) {
|
||||
return (e.which === 2 || e.which == null && e.button === 4
|
||||
);
|
||||
}
|
||||
function isModifiedClickEvent(e) {
|
||||
return (isMac && e.metaKey || !isMac && e.ctrlKey || isMiddleClick(e) || e.shiftKey
|
||||
);
|
||||
}
|
||||
function isMouseSpecialEvent(e, type, element) {
|
||||
const related = e.relatedTarget;
|
||||
return (e.type === EventType.MOUSEOVER && type === EventType.MOUSEENTER || e.type === EventType.MOUSEOUT && type === EventType.MOUSELEAVE || e.type === EventType.POINTEROVER && type === EventType.POINTERENTER || e.type === EventType.POINTEROUT && type === EventType.POINTERLEAVE) && (!related || related !== element && !element.contains(related));
|
||||
}
|
||||
function createMouseSpecialEvent(e, target) {
|
||||
const copy = {};
|
||||
for (const property in e) {
|
||||
if (property === 'srcElement' || property === 'target') {
|
||||
continue;
|
||||
}
|
||||
const key = property;
|
||||
const value = e[key];
|
||||
if (typeof value === 'function') {
|
||||
continue;
|
||||
}
|
||||
copy[key] = value;
|
||||
}
|
||||
if (e.type === EventType.MOUSEOVER) {
|
||||
copy['type'] = EventType.MOUSEENTER;
|
||||
} else if (e.type === EventType.MOUSEOUT) {
|
||||
copy['type'] = EventType.MOUSELEAVE;
|
||||
} else if (e.type === EventType.POINTEROVER) {
|
||||
copy['type'] = EventType.POINTERENTER;
|
||||
} else {
|
||||
copy['type'] = EventType.POINTERLEAVE;
|
||||
}
|
||||
copy['target'] = copy['srcElement'] = target;
|
||||
copy['bubbles'] = false;
|
||||
copy['_originalEvent'] = e;
|
||||
return copy;
|
||||
}
|
||||
|
||||
const isIos = typeof navigator !== 'undefined' && /iPhone|iPad|iPod/.test(navigator.userAgent);
|
||||
class EventContractContainer {
|
||||
element;
|
||||
handlerInfos = [];
|
||||
constructor(element) {
|
||||
this.element = element;
|
||||
}
|
||||
addEventListener(eventType, getHandler, passive) {
|
||||
if (isIos) {
|
||||
this.element.style.cursor = 'pointer';
|
||||
}
|
||||
this.handlerInfos.push(addEventListener(this.element, eventType, getHandler(this.element), passive));
|
||||
}
|
||||
cleanUp() {
|
||||
for (let i = 0; i < this.handlerInfos.length; i++) {
|
||||
removeEventListener(this.element, this.handlerInfos[i]);
|
||||
}
|
||||
this.handlerInfos = [];
|
||||
}
|
||||
}
|
||||
|
||||
const Char = {
|
||||
NAMESPACE_ACTION_SEPARATOR: '.',
|
||||
EVENT_ACTION_SEPARATOR: ':'
|
||||
};
|
||||
|
||||
function getEventType(eventInfo) {
|
||||
return eventInfo.eventType;
|
||||
}
|
||||
function setEventType(eventInfo, eventType) {
|
||||
eventInfo.eventType = eventType;
|
||||
}
|
||||
function getEvent(eventInfo) {
|
||||
return eventInfo.event;
|
||||
}
|
||||
function setEvent(eventInfo, event) {
|
||||
eventInfo.event = event;
|
||||
}
|
||||
function getTargetElement(eventInfo) {
|
||||
return eventInfo.targetElement;
|
||||
}
|
||||
function setTargetElement(eventInfo, targetElement) {
|
||||
eventInfo.targetElement = targetElement;
|
||||
}
|
||||
function getContainer(eventInfo) {
|
||||
return eventInfo.eic;
|
||||
}
|
||||
function setContainer(eventInfo, container) {
|
||||
eventInfo.eic = container;
|
||||
}
|
||||
function getTimestamp(eventInfo) {
|
||||
return eventInfo.timeStamp;
|
||||
}
|
||||
function setTimestamp(eventInfo, timestamp) {
|
||||
eventInfo.timeStamp = timestamp;
|
||||
}
|
||||
function getAction(eventInfo) {
|
||||
return eventInfo.eia;
|
||||
}
|
||||
function setAction(eventInfo, actionName, actionElement) {
|
||||
eventInfo.eia = [actionName, actionElement];
|
||||
}
|
||||
function unsetAction(eventInfo) {
|
||||
eventInfo.eia = undefined;
|
||||
}
|
||||
function getActionElement(actionInfo) {
|
||||
return actionInfo[1];
|
||||
}
|
||||
function getIsReplay(eventInfo) {
|
||||
return eventInfo.eirp;
|
||||
}
|
||||
function setIsReplay(eventInfo, replay) {
|
||||
eventInfo.eirp = replay;
|
||||
}
|
||||
function getResolved(eventInfo) {
|
||||
return eventInfo.eir;
|
||||
}
|
||||
function setResolved(eventInfo, resolved) {
|
||||
eventInfo.eir = resolved;
|
||||
}
|
||||
function cloneEventInfo(eventInfo) {
|
||||
return {
|
||||
eventType: eventInfo.eventType,
|
||||
event: eventInfo.event,
|
||||
targetElement: eventInfo.targetElement,
|
||||
eic: eventInfo.eic,
|
||||
eia: eventInfo.eia,
|
||||
timeStamp: eventInfo.timeStamp,
|
||||
eirp: eventInfo.eirp,
|
||||
eiack: eventInfo.eiack,
|
||||
eir: eventInfo.eir
|
||||
};
|
||||
}
|
||||
function createEventInfoFromParameters(eventType, event, targetElement, container, timestamp, action, isReplay, a11yClickKey) {
|
||||
return {
|
||||
eventType,
|
||||
event,
|
||||
targetElement,
|
||||
eic: container,
|
||||
timeStamp: timestamp,
|
||||
eia: action,
|
||||
eirp: isReplay,
|
||||
eiack: a11yClickKey
|
||||
};
|
||||
}
|
||||
class EventInfoWrapper {
|
||||
eventInfo;
|
||||
constructor(eventInfo) {
|
||||
this.eventInfo = eventInfo;
|
||||
}
|
||||
getEventType() {
|
||||
return getEventType(this.eventInfo);
|
||||
}
|
||||
setEventType(eventType) {
|
||||
setEventType(this.eventInfo, eventType);
|
||||
}
|
||||
getEvent() {
|
||||
return getEvent(this.eventInfo);
|
||||
}
|
||||
setEvent(event) {
|
||||
setEvent(this.eventInfo, event);
|
||||
}
|
||||
getTargetElement() {
|
||||
return getTargetElement(this.eventInfo);
|
||||
}
|
||||
setTargetElement(targetElement) {
|
||||
setTargetElement(this.eventInfo, targetElement);
|
||||
}
|
||||
getContainer() {
|
||||
return getContainer(this.eventInfo);
|
||||
}
|
||||
setContainer(container) {
|
||||
setContainer(this.eventInfo, container);
|
||||
}
|
||||
getTimestamp() {
|
||||
return getTimestamp(this.eventInfo);
|
||||
}
|
||||
setTimestamp(timestamp) {
|
||||
setTimestamp(this.eventInfo, timestamp);
|
||||
}
|
||||
getAction() {
|
||||
const action = getAction(this.eventInfo);
|
||||
if (!action) return undefined;
|
||||
return {
|
||||
name: action[0],
|
||||
element: action[1]
|
||||
};
|
||||
}
|
||||
setAction(action) {
|
||||
if (!action) {
|
||||
unsetAction(this.eventInfo);
|
||||
return;
|
||||
}
|
||||
setAction(this.eventInfo, action.name, action.element);
|
||||
}
|
||||
getIsReplay() {
|
||||
return getIsReplay(this.eventInfo);
|
||||
}
|
||||
setIsReplay(replay) {
|
||||
setIsReplay(this.eventInfo, replay);
|
||||
}
|
||||
getResolved() {
|
||||
return getResolved(this.eventInfo);
|
||||
}
|
||||
setResolved(resolved) {
|
||||
setResolved(this.eventInfo, resolved);
|
||||
}
|
||||
clone() {
|
||||
return new EventInfoWrapper(cloneEventInfo(this.eventInfo));
|
||||
}
|
||||
}
|
||||
|
||||
const EMPTY_ACTION_MAP = {};
|
||||
const REGEXP_SEMICOLON = /\s*;\s*/;
|
||||
const DEFAULT_EVENT_TYPE = EventType.CLICK;
|
||||
class ActionResolver {
|
||||
a11yClickSupport = false;
|
||||
clickModSupport = true;
|
||||
syntheticMouseEventSupport;
|
||||
updateEventInfoForA11yClick = undefined;
|
||||
preventDefaultForA11yClick = undefined;
|
||||
populateClickOnlyAction = undefined;
|
||||
constructor({
|
||||
syntheticMouseEventSupport = false,
|
||||
clickModSupport = true
|
||||
} = {}) {
|
||||
this.syntheticMouseEventSupport = syntheticMouseEventSupport;
|
||||
this.clickModSupport = clickModSupport;
|
||||
}
|
||||
resolveEventType(eventInfo) {
|
||||
if (this.clickModSupport && getEventType(eventInfo) === EventType.CLICK && isModifiedClickEvent(getEvent(eventInfo))) {
|
||||
setEventType(eventInfo, EventType.CLICKMOD);
|
||||
} else if (this.a11yClickSupport) {
|
||||
this.updateEventInfoForA11yClick(eventInfo);
|
||||
}
|
||||
}
|
||||
resolveAction(eventInfo) {
|
||||
if (getResolved(eventInfo)) {
|
||||
return;
|
||||
}
|
||||
this.populateAction(eventInfo, getTargetElement(eventInfo));
|
||||
setResolved(eventInfo, true);
|
||||
}
|
||||
resolveParentAction(eventInfo) {
|
||||
const action = getAction(eventInfo);
|
||||
const actionElement = action && getActionElement(action);
|
||||
unsetAction(eventInfo);
|
||||
const parentNode = actionElement && this.getParentNode(actionElement);
|
||||
if (!parentNode) {
|
||||
return;
|
||||
}
|
||||
this.populateAction(eventInfo, parentNode);
|
||||
}
|
||||
populateAction(eventInfo, currentTarget) {
|
||||
let actionElement = currentTarget;
|
||||
while (actionElement && actionElement !== getContainer(eventInfo)) {
|
||||
if (actionElement.nodeType === Node.ELEMENT_NODE) {
|
||||
this.populateActionOnElement(actionElement, eventInfo);
|
||||
}
|
||||
if (getAction(eventInfo)) {
|
||||
break;
|
||||
}
|
||||
actionElement = this.getParentNode(actionElement);
|
||||
}
|
||||
const action = getAction(eventInfo);
|
||||
if (!action) {
|
||||
return;
|
||||
}
|
||||
if (this.a11yClickSupport) {
|
||||
this.preventDefaultForA11yClick(eventInfo);
|
||||
}
|
||||
if (this.syntheticMouseEventSupport) {
|
||||
if (getEventType(eventInfo) === EventType.MOUSEENTER || getEventType(eventInfo) === EventType.MOUSELEAVE || getEventType(eventInfo) === EventType.POINTERENTER || getEventType(eventInfo) === EventType.POINTERLEAVE) {
|
||||
if (isMouseSpecialEvent(getEvent(eventInfo), getEventType(eventInfo), getActionElement(action))) {
|
||||
const copiedEvent = createMouseSpecialEvent(getEvent(eventInfo), getActionElement(action));
|
||||
setEvent(eventInfo, copiedEvent);
|
||||
setTargetElement(eventInfo, getActionElement(action));
|
||||
} else {
|
||||
unsetAction(eventInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
getParentNode(element) {
|
||||
const owner = element[Property.OWNER];
|
||||
if (owner) {
|
||||
return owner;
|
||||
}
|
||||
const parentNode = element.parentNode;
|
||||
if (parentNode?.nodeName === '#document-fragment') {
|
||||
return parentNode?.host ?? null;
|
||||
}
|
||||
return parentNode;
|
||||
}
|
||||
populateActionOnElement(actionElement, eventInfo) {
|
||||
const actionMap = this.parseActions(actionElement);
|
||||
const actionName = actionMap[getEventType(eventInfo)];
|
||||
if (actionName !== undefined) {
|
||||
setAction(eventInfo, actionName, actionElement);
|
||||
}
|
||||
if (this.a11yClickSupport) {
|
||||
this.populateClickOnlyAction(actionElement, eventInfo, actionMap);
|
||||
}
|
||||
}
|
||||
parseActions(actionElement) {
|
||||
let actionMap = get(actionElement);
|
||||
if (!actionMap) {
|
||||
const jsactionAttribute = actionElement.getAttribute(Attribute.JSACTION);
|
||||
if (!jsactionAttribute) {
|
||||
actionMap = EMPTY_ACTION_MAP;
|
||||
set(actionElement, actionMap);
|
||||
} else {
|
||||
actionMap = getParsed(jsactionAttribute);
|
||||
if (!actionMap) {
|
||||
actionMap = {};
|
||||
const values = jsactionAttribute.split(REGEXP_SEMICOLON);
|
||||
for (let idx = 0; idx < values.length; idx++) {
|
||||
const value = values[idx];
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
const colon = value.indexOf(Char.EVENT_ACTION_SEPARATOR);
|
||||
const hasColon = colon !== -1;
|
||||
const type = hasColon ? value.substr(0, colon).trim() : DEFAULT_EVENT_TYPE;
|
||||
const action = hasColon ? value.substr(colon + 1).trim() : value;
|
||||
actionMap[type] = action;
|
||||
}
|
||||
setParsed(jsactionAttribute, actionMap);
|
||||
}
|
||||
set(actionElement, actionMap);
|
||||
}
|
||||
}
|
||||
return actionMap;
|
||||
}
|
||||
addA11yClickSupport(updateEventInfoForA11yClick, preventDefaultForA11yClick, populateClickOnlyAction) {
|
||||
this.a11yClickSupport = true;
|
||||
this.updateEventInfoForA11yClick = updateEventInfoForA11yClick;
|
||||
this.preventDefaultForA11yClick = preventDefaultForA11yClick;
|
||||
this.populateClickOnlyAction = populateClickOnlyAction;
|
||||
}
|
||||
}
|
||||
|
||||
var Restriction;
|
||||
(function (Restriction) {
|
||||
Restriction[Restriction["I_AM_THE_JSACTION_FRAMEWORK"] = 0] = "I_AM_THE_JSACTION_FRAMEWORK";
|
||||
})(Restriction || (Restriction = {}));
|
||||
|
||||
class Dispatcher {
|
||||
dispatchDelegate;
|
||||
actionResolver;
|
||||
eventReplayer;
|
||||
eventReplayScheduled = false;
|
||||
replayEventInfoWrappers = [];
|
||||
constructor(dispatchDelegate, {
|
||||
actionResolver,
|
||||
eventReplayer
|
||||
} = {}) {
|
||||
this.dispatchDelegate = dispatchDelegate;
|
||||
this.actionResolver = actionResolver;
|
||||
this.eventReplayer = eventReplayer;
|
||||
}
|
||||
dispatch(eventInfo) {
|
||||
const eventInfoWrapper = new EventInfoWrapper(eventInfo);
|
||||
this.actionResolver?.resolveEventType(eventInfo);
|
||||
this.actionResolver?.resolveAction(eventInfo);
|
||||
const action = eventInfoWrapper.getAction();
|
||||
if (action && shouldPreventDefaultBeforeDispatching(action.element, eventInfoWrapper)) {
|
||||
preventDefault(eventInfoWrapper.getEvent());
|
||||
}
|
||||
if (this.eventReplayer && eventInfoWrapper.getIsReplay()) {
|
||||
this.scheduleEventInfoWrapperReplay(eventInfoWrapper);
|
||||
return;
|
||||
}
|
||||
this.dispatchDelegate(eventInfoWrapper);
|
||||
}
|
||||
scheduleEventInfoWrapperReplay(eventInfoWrapper) {
|
||||
this.replayEventInfoWrappers.push(eventInfoWrapper);
|
||||
if (this.eventReplayScheduled) {
|
||||
return;
|
||||
}
|
||||
this.eventReplayScheduled = true;
|
||||
Promise.resolve().then(() => {
|
||||
this.eventReplayScheduled = false;
|
||||
this.eventReplayer(this.replayEventInfoWrappers);
|
||||
});
|
||||
}
|
||||
}
|
||||
function shouldPreventDefaultBeforeDispatching(actionElement, eventInfoWrapper) {
|
||||
return actionElement.tagName === 'A' && (eventInfoWrapper.getEventType() === EventType.CLICK || eventInfoWrapper.getEventType() === EventType.CLICKMOD);
|
||||
}
|
||||
|
||||
const PROPAGATION_STOPPED_SYMBOL = /* @__PURE__ */Symbol.for('propagationStopped');
|
||||
const EventPhase = {
|
||||
REPLAY: 101
|
||||
};
|
||||
const PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser dispatch, `preventDefault` would have no ' + 'effect. You can check whether an event is being replayed by accessing the event phase: ' + '`event.eventPhase === EventPhase.REPLAY`.';
|
||||
const PREVENT_DEFAULT_ERROR_MESSAGE = `\`preventDefault\` called during event replay.`;
|
||||
const COMPOSED_PATH_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser ' + 'dispatch, `composedPath()` will be empty. Iterate parent nodes from `event.target` or ' + '`event.currentTarget` if you need to check elements in the event path.';
|
||||
const COMPOSED_PATH_ERROR_MESSAGE = `\`composedPath\` called during event replay.`;
|
||||
class EventDispatcher {
|
||||
dispatchDelegate;
|
||||
clickModSupport;
|
||||
actionResolver;
|
||||
dispatcher;
|
||||
constructor(dispatchDelegate, clickModSupport = true) {
|
||||
this.dispatchDelegate = dispatchDelegate;
|
||||
this.clickModSupport = clickModSupport;
|
||||
this.actionResolver = new ActionResolver({
|
||||
clickModSupport
|
||||
});
|
||||
this.dispatcher = new Dispatcher(eventInfoWrapper => {
|
||||
this.dispatchToDelegate(eventInfoWrapper);
|
||||
}, {
|
||||
actionResolver: this.actionResolver
|
||||
});
|
||||
}
|
||||
dispatch(eventInfo) {
|
||||
this.dispatcher.dispatch(eventInfo);
|
||||
}
|
||||
dispatchToDelegate(eventInfoWrapper) {
|
||||
if (eventInfoWrapper.getIsReplay()) {
|
||||
prepareEventForReplay(eventInfoWrapper);
|
||||
}
|
||||
prepareEventForBubbling(eventInfoWrapper);
|
||||
while (eventInfoWrapper.getAction()) {
|
||||
prepareEventForDispatch(eventInfoWrapper);
|
||||
if (isCaptureEventType(eventInfoWrapper.getEventType()) && eventInfoWrapper.getAction().element !== eventInfoWrapper.getTargetElement()) {
|
||||
return;
|
||||
}
|
||||
this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction().name);
|
||||
if (propagationStopped(eventInfoWrapper)) {
|
||||
return;
|
||||
}
|
||||
this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
function prepareEventForBubbling(eventInfoWrapper) {
|
||||
const event = eventInfoWrapper.getEvent();
|
||||
const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event);
|
||||
const stopPropagation = () => {
|
||||
event[PROPAGATION_STOPPED_SYMBOL] = true;
|
||||
originalStopPropagation();
|
||||
};
|
||||
patchEventInstance(event, 'stopPropagation', stopPropagation);
|
||||
patchEventInstance(event, 'stopImmediatePropagation', stopPropagation);
|
||||
}
|
||||
function propagationStopped(eventInfoWrapper) {
|
||||
const event = eventInfoWrapper.getEvent();
|
||||
return !!event[PROPAGATION_STOPPED_SYMBOL];
|
||||
}
|
||||
function prepareEventForReplay(eventInfoWrapper) {
|
||||
const event = eventInfoWrapper.getEvent();
|
||||
const target = eventInfoWrapper.getTargetElement();
|
||||
const originalPreventDefault = event.preventDefault.bind(event);
|
||||
patchEventInstance(event, 'target', target);
|
||||
patchEventInstance(event, 'eventPhase', EventPhase.REPLAY);
|
||||
patchEventInstance(event, 'preventDefault', () => {
|
||||
originalPreventDefault();
|
||||
throw new Error(PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''));
|
||||
});
|
||||
patchEventInstance(event, 'composedPath', () => {
|
||||
throw new Error(COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''));
|
||||
});
|
||||
}
|
||||
function prepareEventForDispatch(eventInfoWrapper) {
|
||||
const event = eventInfoWrapper.getEvent();
|
||||
const currentTarget = eventInfoWrapper.getAction()?.element;
|
||||
if (currentTarget) {
|
||||
patchEventInstance(event, 'currentTarget', currentTarget, {
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
function patchEventInstance(event, property, value, {
|
||||
configurable = false
|
||||
} = {}) {
|
||||
Object.defineProperty(event, property, {
|
||||
value,
|
||||
configurable
|
||||
});
|
||||
}
|
||||
function registerDispatcher$1(eventContract, dispatcher) {
|
||||
eventContract.ecrd(eventInfo => {
|
||||
dispatcher.dispatch(eventInfo);
|
||||
}, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
|
||||
}
|
||||
|
||||
function createEarlyJsactionData(container) {
|
||||
const q = [];
|
||||
const d = eventInfo => {
|
||||
q.push(eventInfo);
|
||||
};
|
||||
const h = event => {
|
||||
d(createEventInfoFromParameters(event.type, event, event.target, container, Date.now()));
|
||||
};
|
||||
return {
|
||||
c: container,
|
||||
q,
|
||||
et: [],
|
||||
etc: [],
|
||||
d,
|
||||
h
|
||||
};
|
||||
}
|
||||
function addEvents(earlyJsactionData, types, capture) {
|
||||
for (let i = 0; i < types.length; i++) {
|
||||
const eventType = types[i];
|
||||
const eventTypes = capture ? earlyJsactionData.etc : earlyJsactionData.et;
|
||||
eventTypes.push(eventType);
|
||||
earlyJsactionData.c.addEventListener(eventType, earlyJsactionData.h, capture);
|
||||
}
|
||||
}
|
||||
function getQueuedEventInfos(earlyJsactionData) {
|
||||
return earlyJsactionData?.q ?? [];
|
||||
}
|
||||
function registerDispatcher(earlyJsactionData, dispatcher) {
|
||||
if (!earlyJsactionData) {
|
||||
return;
|
||||
}
|
||||
earlyJsactionData.d = dispatcher;
|
||||
}
|
||||
function removeAllEventListeners(earlyJsactionData) {
|
||||
if (!earlyJsactionData) {
|
||||
return;
|
||||
}
|
||||
removeEventListeners(earlyJsactionData.c, earlyJsactionData.et, earlyJsactionData.h);
|
||||
removeEventListeners(earlyJsactionData.c, earlyJsactionData.etc, earlyJsactionData.h, true);
|
||||
}
|
||||
function removeEventListeners(container, eventTypes, earlyEventHandler, capture) {
|
||||
for (let i = 0; i < eventTypes.length; i++) {
|
||||
container.removeEventListener(eventTypes[i], earlyEventHandler, capture);
|
||||
}
|
||||
}
|
||||
|
||||
const MOUSE_SPECIAL_SUPPORT = false;
|
||||
|
||||
class EventContract {
|
||||
static MOUSE_SPECIAL_SUPPORT = MOUSE_SPECIAL_SUPPORT;
|
||||
containerManager;
|
||||
eventHandlers = {};
|
||||
browserEventTypeToExtraEventTypes = {};
|
||||
dispatcher = null;
|
||||
queuedEventInfos = [];
|
||||
constructor(containerManager) {
|
||||
this.containerManager = containerManager;
|
||||
}
|
||||
handleEvent(eventType, event, container) {
|
||||
const eventInfo = createEventInfoFromParameters(eventType, event, event.target, container, Date.now());
|
||||
this.handleEventInfo(eventInfo);
|
||||
}
|
||||
handleEventInfo(eventInfo) {
|
||||
if (!this.dispatcher) {
|
||||
setIsReplay(eventInfo, true);
|
||||
this.queuedEventInfos?.push(eventInfo);
|
||||
return;
|
||||
}
|
||||
this.dispatcher(eventInfo);
|
||||
}
|
||||
addEvent(eventType, prefixedEventType, passive) {
|
||||
if (eventType in this.eventHandlers || !this.containerManager) {
|
||||
return;
|
||||
}
|
||||
if (!EventContract.MOUSE_SPECIAL_SUPPORT && MOUSE_SPECIAL_EVENT_TYPES.indexOf(eventType) >= 0) {
|
||||
return;
|
||||
}
|
||||
const eventHandler = (eventType, event, container) => {
|
||||
this.handleEvent(eventType, event, container);
|
||||
};
|
||||
this.eventHandlers[eventType] = eventHandler;
|
||||
const browserEventType = getBrowserEventType(prefixedEventType || eventType);
|
||||
if (browserEventType !== eventType) {
|
||||
const eventTypes = this.browserEventTypeToExtraEventTypes[browserEventType] || [];
|
||||
eventTypes.push(eventType);
|
||||
this.browserEventTypeToExtraEventTypes[browserEventType] = eventTypes;
|
||||
}
|
||||
this.containerManager.addEventListener(browserEventType, element => {
|
||||
return event => {
|
||||
eventHandler(eventType, event, element);
|
||||
};
|
||||
}, passive);
|
||||
}
|
||||
replayEarlyEvents(earlyJsactionData = window._ejsa) {
|
||||
if (!earlyJsactionData) {
|
||||
return;
|
||||
}
|
||||
this.replayEarlyEventInfos(earlyJsactionData.q);
|
||||
removeAllEventListeners(earlyJsactionData);
|
||||
delete window._ejsa;
|
||||
}
|
||||
replayEarlyEventInfos(earlyEventInfos) {
|
||||
for (let i = 0; i < earlyEventInfos.length; i++) {
|
||||
const earlyEventInfo = earlyEventInfos[i];
|
||||
const eventTypes = this.getEventTypesForBrowserEventType(earlyEventInfo.eventType);
|
||||
for (let j = 0; j < eventTypes.length; j++) {
|
||||
const eventInfo = cloneEventInfo(earlyEventInfo);
|
||||
setEventType(eventInfo, eventTypes[j]);
|
||||
this.handleEventInfo(eventInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
getEventTypesForBrowserEventType(browserEventType) {
|
||||
const eventTypes = [];
|
||||
if (this.eventHandlers[browserEventType]) {
|
||||
eventTypes.push(browserEventType);
|
||||
}
|
||||
if (this.browserEventTypeToExtraEventTypes[browserEventType]) {
|
||||
eventTypes.push(...this.browserEventTypeToExtraEventTypes[browserEventType]);
|
||||
}
|
||||
return eventTypes;
|
||||
}
|
||||
handler(eventType) {
|
||||
return this.eventHandlers[eventType];
|
||||
}
|
||||
cleanUp() {
|
||||
this.containerManager?.cleanUp();
|
||||
this.containerManager = null;
|
||||
this.eventHandlers = {};
|
||||
this.browserEventTypeToExtraEventTypes = {};
|
||||
this.dispatcher = null;
|
||||
this.queuedEventInfos = [];
|
||||
}
|
||||
registerDispatcher(dispatcher, restriction) {
|
||||
this.ecrd(dispatcher, restriction);
|
||||
}
|
||||
ecrd(dispatcher, restriction) {
|
||||
this.dispatcher = dispatcher;
|
||||
if (this.queuedEventInfos?.length) {
|
||||
for (let i = 0; i < this.queuedEventInfos.length; i++) {
|
||||
this.handleEventInfo(this.queuedEventInfos[i]);
|
||||
}
|
||||
this.queuedEventInfos = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bootstrapAppScopedEarlyEventContract(container, appId, bubbleEventTypes, captureEventTypes, dataContainer = window) {
|
||||
const earlyJsactionData = createEarlyJsactionData(container);
|
||||
if (!dataContainer._ejsas) {
|
||||
dataContainer._ejsas = {};
|
||||
}
|
||||
dataContainer._ejsas[appId] = earlyJsactionData;
|
||||
addEvents(earlyJsactionData, bubbleEventTypes);
|
||||
addEvents(earlyJsactionData, captureEventTypes, true);
|
||||
}
|
||||
function getAppScopedQueuedEventInfos(appId, dataContainer = window) {
|
||||
return getQueuedEventInfos(dataContainer._ejsas?.[appId]);
|
||||
}
|
||||
function registerAppScopedDispatcher(appId, dispatcher, dataContainer = window) {
|
||||
registerDispatcher(dataContainer._ejsas?.[appId], dispatcher);
|
||||
}
|
||||
function removeAllAppScopedEventListeners(appId, dataContainer = window) {
|
||||
removeAllEventListeners(dataContainer._ejsas?.[appId]);
|
||||
}
|
||||
function clearAppScopedEarlyEventContract(appId, dataContainer = window) {
|
||||
if (!dataContainer._ejsas) {
|
||||
return;
|
||||
}
|
||||
dataContainer._ejsas[appId] = undefined;
|
||||
}
|
||||
|
||||
export { Attribute, EventContract, EventContractContainer, EventDispatcher, EventInfoWrapper, EventPhase, bootstrapAppScopedEarlyEventContract, clearAppScopedEarlyEventContract, getDefaulted as getActionCache, getAppScopedQueuedEventInfos, isCaptureEventType, isEarlyEventType, registerAppScopedDispatcher, registerDispatcher$1 as registerDispatcher, removeAllAppScopedEventListeners };
|
||||
//# sourceMappingURL=primitives-event-dispatch.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+187
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { SIGNAL, consumerMarkDirty, REACTIVE_NODE, consumerDestroy, isInNotificationPhase, consumerPollProducersForChange, consumerBeforeComputation, consumerAfterComputation } from './_effect-chunk.mjs';
|
||||
export { BASE_EFFECT_NODE, SIGNAL_NODE, createComputed, createSignal, defaultEquals, finalizeConsumerAfterComputation, getActiveConsumer, isReactive, producerAccessed, producerIncrementEpoch, producerMarkClean, producerNotifyConsumers, producerUpdateValueVersion, producerUpdatesAllowed, resetConsumerBeforeComputation, runEffect, runPostProducerCreatedFn, runPostSignalSetFn, setActiveConsumer, setPostProducerCreatedFn, setPostSignalSetFn, setThrowInvalidWriteToSignalError, signalGetFn, signalSetFn, signalUpdateFn } from './_effect-chunk.mjs';
|
||||
export { createLinkedSignal, linkedSignalSetFn, linkedSignalUpdateFn, untracked } from './_untracked-chunk.mjs';
|
||||
export { setAlternateWeakRefImpl } from './_weak_ref-chunk.mjs';
|
||||
|
||||
const formatter = {
|
||||
header: (sig, config) => {
|
||||
if (!isSignal(sig) || config?.ngSkipFormatting) return null;
|
||||
let value;
|
||||
try {
|
||||
value = sig();
|
||||
} catch (e) {
|
||||
return ['span', `Signal(⚠️ Error)${e.message ? `: ${e.message}` : ''}`];
|
||||
}
|
||||
const kind = 'computation' in sig[SIGNAL] ? 'Computed' : 'Signal';
|
||||
const isPrimitive = value === null || !Array.isArray(value) && typeof value !== 'object';
|
||||
return ['span', {}, ['span', {}, `${kind}(`], (() => {
|
||||
if (isSignal(value)) {
|
||||
return formatter.header(value, config);
|
||||
} else if (isPrimitive && value !== undefined && typeof value !== 'function') {
|
||||
return ['object', {
|
||||
object: value
|
||||
}];
|
||||
} else {
|
||||
return prettifyPreview(value);
|
||||
}
|
||||
})(), ['span', {}, `)`]];
|
||||
},
|
||||
hasBody: (sig, config) => {
|
||||
if (!isSignal(sig)) return false;
|
||||
try {
|
||||
sig();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return !config?.ngSkipFormatting;
|
||||
},
|
||||
body: (sig, config) => {
|
||||
const color = 'var(--sys-color-primary)';
|
||||
return ['div', {
|
||||
style: `background: #FFFFFF10; padding-left: 4px; padding-top: 2px; padding-bottom: 2px;`
|
||||
}, ['div', {
|
||||
style: `color: ${color}`
|
||||
}, 'Signal value: '], ['div', {
|
||||
style: `padding-left: .5rem;`
|
||||
}, ['object', {
|
||||
object: sig(),
|
||||
config
|
||||
}]], ['div', {
|
||||
style: `color: ${color}`
|
||||
}, 'Signal function: '], ['div', {
|
||||
style: `padding-left: .5rem;`
|
||||
}, ['object', {
|
||||
object: sig,
|
||||
config: {
|
||||
...config,
|
||||
ngSkipFormatting: true
|
||||
}
|
||||
}]]];
|
||||
}
|
||||
};
|
||||
function prettifyPreview(value) {
|
||||
if (value === null) return 'null';
|
||||
if (Array.isArray(value)) return `Array(${value.length})`;
|
||||
if (value instanceof Element) return `<${value.tagName.toLowerCase()}>`;
|
||||
if (value instanceof URL) return `URL`;
|
||||
switch (typeof value) {
|
||||
case 'undefined':
|
||||
{
|
||||
return 'undefined';
|
||||
}
|
||||
case 'function':
|
||||
{
|
||||
if ('prototype' in value) {
|
||||
return 'class';
|
||||
} else {
|
||||
return '() => {…}';
|
||||
}
|
||||
}
|
||||
case 'object':
|
||||
{
|
||||
if (value.constructor.name === 'Object') {
|
||||
return '{…}';
|
||||
} else {
|
||||
return `${value.constructor.name} {}`;
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
return ['object', {
|
||||
object: value,
|
||||
config: {
|
||||
ngSkipFormatting: true
|
||||
}
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
function isSignal(value) {
|
||||
return value[SIGNAL] !== undefined;
|
||||
}
|
||||
function installDevToolsSignalFormatter() {
|
||||
globalThis.devtoolsFormatters ??= [];
|
||||
if (!globalThis.devtoolsFormatters.some(f => f === formatter)) {
|
||||
globalThis.devtoolsFormatters.push(formatter);
|
||||
}
|
||||
}
|
||||
|
||||
function createWatch(fn, schedule, allowSignalWrites) {
|
||||
const node = Object.create(WATCH_NODE);
|
||||
if (allowSignalWrites) {
|
||||
node.consumerAllowSignalWrites = true;
|
||||
}
|
||||
node.fn = fn;
|
||||
node.schedule = schedule;
|
||||
const registerOnCleanup = cleanupFn => {
|
||||
node.cleanupFn = cleanupFn;
|
||||
};
|
||||
function isWatchNodeDestroyed(node) {
|
||||
return node.fn === null && node.schedule === null;
|
||||
}
|
||||
function destroyWatchNode(node) {
|
||||
if (!isWatchNodeDestroyed(node)) {
|
||||
consumerDestroy(node);
|
||||
node.cleanupFn();
|
||||
node.fn = null;
|
||||
node.schedule = null;
|
||||
node.cleanupFn = NOOP_CLEANUP_FN;
|
||||
}
|
||||
}
|
||||
const run = () => {
|
||||
if (node.fn === null) {
|
||||
return;
|
||||
}
|
||||
if (isInNotificationPhase()) {
|
||||
throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? 'Schedulers cannot synchronously execute watches while scheduling.' : '');
|
||||
}
|
||||
node.dirty = false;
|
||||
if (node.version > 0 && !consumerPollProducersForChange(node)) {
|
||||
return;
|
||||
}
|
||||
node.version++;
|
||||
const prevConsumer = consumerBeforeComputation(node);
|
||||
try {
|
||||
node.cleanupFn();
|
||||
node.cleanupFn = NOOP_CLEANUP_FN;
|
||||
node.fn(registerOnCleanup);
|
||||
} finally {
|
||||
consumerAfterComputation(node, prevConsumer);
|
||||
}
|
||||
};
|
||||
node.ref = {
|
||||
notify: () => consumerMarkDirty(node),
|
||||
run,
|
||||
cleanup: () => node.cleanupFn(),
|
||||
destroy: () => destroyWatchNode(node),
|
||||
[SIGNAL]: node
|
||||
};
|
||||
return node.ref;
|
||||
}
|
||||
const NOOP_CLEANUP_FN = () => {};
|
||||
const WATCH_NODE = /* @__PURE__ */(() => {
|
||||
return {
|
||||
...REACTIVE_NODE,
|
||||
consumerIsAlwaysLive: true,
|
||||
consumerAllowSignalWrites: false,
|
||||
consumerMarkedDirty: node => {
|
||||
if (node.schedule !== null) {
|
||||
node.schedule(node.ref);
|
||||
}
|
||||
},
|
||||
cleanupFn: NOOP_CLEANUP_FN
|
||||
};
|
||||
})();
|
||||
|
||||
if (typeof ngDevMode === 'undefined' || ngDevMode) {
|
||||
installDevToolsSignalFormatter();
|
||||
}
|
||||
|
||||
export { REACTIVE_NODE, SIGNAL, consumerAfterComputation, consumerBeforeComputation, consumerDestroy, consumerMarkDirty, consumerPollProducersForChange, createWatch, installDevToolsSignalFormatter, isInNotificationPhase };
|
||||
//# sourceMappingURL=primitives-signals.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+260
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { Observable, ReplaySubject } from 'rxjs';
|
||||
import { takeUntil } from 'rxjs/operators';
|
||||
import { assertInInjectionContext, inject, DestroyRef, RuntimeError, Injector, effect, assertNotInReactiveContext, signal, PendingTasks } from './_effect-chunk2.mjs';
|
||||
import { getOutputDestroyRef, untracked, computed, resource, encapsulateResourceError } from './_resource-chunk.mjs';
|
||||
import './_effect-chunk.mjs';
|
||||
import './_not_found-chunk.mjs';
|
||||
import '@angular/core/primitives/signals';
|
||||
import '@angular/core/primitives/di';
|
||||
import './_untracked-chunk.mjs';
|
||||
|
||||
function takeUntilDestroyed(destroyRef) {
|
||||
if (!destroyRef) {
|
||||
ngDevMode && assertInInjectionContext(takeUntilDestroyed);
|
||||
destroyRef = inject(DestroyRef);
|
||||
}
|
||||
const destroyed$ = new Observable(subscriber => {
|
||||
if (destroyRef.destroyed) {
|
||||
subscriber.next();
|
||||
return;
|
||||
}
|
||||
const unregisterFn = destroyRef.onDestroy(subscriber.next.bind(subscriber));
|
||||
return unregisterFn;
|
||||
});
|
||||
return source => {
|
||||
return source.pipe(takeUntil(destroyed$));
|
||||
};
|
||||
}
|
||||
|
||||
class OutputFromObservableRef {
|
||||
source;
|
||||
destroyed = false;
|
||||
destroyRef = inject(DestroyRef);
|
||||
constructor(source) {
|
||||
this.source = source;
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.destroyed = true;
|
||||
});
|
||||
}
|
||||
subscribe(callbackFn) {
|
||||
if (this.destroyed) {
|
||||
throw new RuntimeError(953, ngDevMode && 'Unexpected subscription to destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');
|
||||
}
|
||||
const subscription = this.source.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
|
||||
next: value => callbackFn(value)
|
||||
});
|
||||
return {
|
||||
unsubscribe: () => subscription.unsubscribe()
|
||||
};
|
||||
}
|
||||
}
|
||||
function outputFromObservable(observable, opts) {
|
||||
ngDevMode && assertInInjectionContext(outputFromObservable);
|
||||
return new OutputFromObservableRef(observable);
|
||||
}
|
||||
|
||||
function outputToObservable(ref) {
|
||||
const destroyRef = getOutputDestroyRef(ref);
|
||||
return new Observable(observer => {
|
||||
const unregisterOnDestroy = destroyRef?.onDestroy(() => observer.complete());
|
||||
const subscription = ref.subscribe(v => observer.next(v));
|
||||
return () => {
|
||||
subscription.unsubscribe();
|
||||
unregisterOnDestroy?.();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function toObservable(source, options) {
|
||||
if (ngDevMode && !options?.injector) {
|
||||
assertInInjectionContext(toObservable);
|
||||
}
|
||||
const injector = options?.injector ?? inject(Injector);
|
||||
const subject = new ReplaySubject(1);
|
||||
const watcher = effect(() => {
|
||||
let value;
|
||||
try {
|
||||
value = source();
|
||||
} catch (err) {
|
||||
untracked(() => subject.error(err));
|
||||
return;
|
||||
}
|
||||
untracked(() => subject.next(value));
|
||||
}, {
|
||||
injector,
|
||||
manualCleanup: true
|
||||
});
|
||||
injector.get(DestroyRef).onDestroy(() => {
|
||||
watcher.destroy();
|
||||
subject.complete();
|
||||
});
|
||||
return subject.asObservable();
|
||||
}
|
||||
|
||||
function toSignal(source, options) {
|
||||
typeof ngDevMode !== 'undefined' && ngDevMode && assertNotInReactiveContext(toSignal, 'Invoking `toSignal` causes new subscriptions every time. ' + 'Consider moving `toSignal` outside of the reactive context and read the signal value where needed.');
|
||||
const requiresCleanup = !options?.manualCleanup;
|
||||
if (ngDevMode && requiresCleanup && !options?.injector) {
|
||||
assertInInjectionContext(toSignal);
|
||||
}
|
||||
const cleanupRef = requiresCleanup ? options?.injector?.get(DestroyRef) ?? inject(DestroyRef) : null;
|
||||
const equal = makeToSignalEqual(options?.equal);
|
||||
let state;
|
||||
if (options?.requireSync) {
|
||||
state = signal({
|
||||
kind: 0
|
||||
}, {
|
||||
equal,
|
||||
...(ngDevMode ? createDebugNameObject(options?.debugName, 'state') : undefined)
|
||||
});
|
||||
} else {
|
||||
state = signal({
|
||||
kind: 1,
|
||||
value: options?.initialValue
|
||||
}, {
|
||||
equal,
|
||||
...(ngDevMode ? createDebugNameObject(options?.debugName, 'state') : undefined)
|
||||
});
|
||||
}
|
||||
let destroyUnregisterFn;
|
||||
const sub = source.subscribe({
|
||||
next: value => state.set({
|
||||
kind: 1,
|
||||
value
|
||||
}),
|
||||
error: error => {
|
||||
state.set({
|
||||
kind: 2,
|
||||
error
|
||||
});
|
||||
destroyUnregisterFn?.();
|
||||
},
|
||||
complete: () => {
|
||||
destroyUnregisterFn?.();
|
||||
}
|
||||
});
|
||||
if (options?.requireSync && state().kind === 0) {
|
||||
throw new RuntimeError(601, (typeof ngDevMode === 'undefined' || ngDevMode) && '`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.');
|
||||
}
|
||||
destroyUnregisterFn = cleanupRef?.onDestroy(sub.unsubscribe.bind(sub));
|
||||
return computed(() => {
|
||||
const current = state();
|
||||
switch (current.kind) {
|
||||
case 1:
|
||||
return current.value;
|
||||
case 2:
|
||||
throw current.error;
|
||||
case 0:
|
||||
throw new RuntimeError(601, (typeof ngDevMode === 'undefined' || ngDevMode) && '`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.');
|
||||
}
|
||||
}, {
|
||||
equal: options?.equal,
|
||||
...(ngDevMode ? createDebugNameObject(options?.debugName, 'source') : undefined)
|
||||
});
|
||||
}
|
||||
function makeToSignalEqual(userEquality = Object.is) {
|
||||
return (a, b) => a.kind === 1 && b.kind === 1 && userEquality(a.value, b.value);
|
||||
}
|
||||
function createDebugNameObject(toSignalDebugName, internalSignalDebugName) {
|
||||
return {
|
||||
debugName: `toSignal${toSignalDebugName ? '#' + toSignalDebugName : ''}.${internalSignalDebugName}`
|
||||
};
|
||||
}
|
||||
|
||||
function pendingUntilEvent(injector) {
|
||||
if (injector === undefined) {
|
||||
ngDevMode && assertInInjectionContext(pendingUntilEvent);
|
||||
injector = inject(Injector);
|
||||
}
|
||||
const taskService = injector.get(PendingTasks);
|
||||
return sourceObservable => {
|
||||
return new Observable(originalSubscriber => {
|
||||
const removeTask = taskService.add();
|
||||
let cleanedUp = false;
|
||||
function cleanupTask() {
|
||||
if (cleanedUp) {
|
||||
return;
|
||||
}
|
||||
removeTask();
|
||||
cleanedUp = true;
|
||||
}
|
||||
const innerSubscription = sourceObservable.subscribe({
|
||||
next: v => {
|
||||
originalSubscriber.next(v);
|
||||
cleanupTask();
|
||||
},
|
||||
complete: () => {
|
||||
originalSubscriber.complete();
|
||||
cleanupTask();
|
||||
},
|
||||
error: e => {
|
||||
originalSubscriber.error(e);
|
||||
cleanupTask();
|
||||
}
|
||||
});
|
||||
innerSubscription.add(() => {
|
||||
originalSubscriber.unsubscribe();
|
||||
cleanupTask();
|
||||
});
|
||||
return innerSubscription;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function rxResource(opts) {
|
||||
if (ngDevMode && !opts?.injector) {
|
||||
assertInInjectionContext(rxResource);
|
||||
}
|
||||
return resource({
|
||||
...opts,
|
||||
loader: undefined,
|
||||
stream: params => {
|
||||
let sub;
|
||||
const onAbort = () => sub?.unsubscribe();
|
||||
params.abortSignal.addEventListener('abort', onAbort);
|
||||
const stream = signal({
|
||||
value: undefined
|
||||
});
|
||||
let resolve;
|
||||
const promise = new Promise(r => resolve = r);
|
||||
function send(value) {
|
||||
stream.set(value);
|
||||
resolve?.(stream);
|
||||
resolve = undefined;
|
||||
}
|
||||
const streamFn = opts.stream ?? opts.loader;
|
||||
if (streamFn === undefined) {
|
||||
throw new RuntimeError(990, ngDevMode && `Must provide \`stream\` option.`);
|
||||
}
|
||||
sub = streamFn(params).subscribe({
|
||||
next: value => send({
|
||||
value
|
||||
}),
|
||||
error: error => {
|
||||
send({
|
||||
error: encapsulateResourceError(error)
|
||||
});
|
||||
params.abortSignal.removeEventListener('abort', onAbort);
|
||||
},
|
||||
complete: () => {
|
||||
if (resolve) {
|
||||
send({
|
||||
error: new RuntimeError(991, ngDevMode && 'Resource completed before producing a value')
|
||||
});
|
||||
}
|
||||
params.abortSignal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export { outputFromObservable, outputToObservable, pendingUntilEvent, rxResource, takeUntilDestroyed, toObservable, toSignal };
|
||||
//# sourceMappingURL=rxjs-interop.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2509
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+98
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"name": "@angular/core",
|
||||
"version": "21.2.1",
|
||||
"description": "Angular - the core framework",
|
||||
"author": "angular",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
||||
},
|
||||
"exports": {
|
||||
"./schematics/*": {
|
||||
"default": "./schematics/*.js"
|
||||
},
|
||||
"./event-dispatch-contract.min.js": {
|
||||
"default": "./event-dispatch-contract.min.js"
|
||||
},
|
||||
"./package.json": {
|
||||
"default": "./package.json"
|
||||
},
|
||||
".": {
|
||||
"types": "./types/core.d.ts",
|
||||
"default": "./fesm2022/core.mjs"
|
||||
},
|
||||
"./primitives/di": {
|
||||
"types": "./types/primitives-di.d.ts",
|
||||
"default": "./fesm2022/primitives-di.mjs"
|
||||
},
|
||||
"./primitives/event-dispatch": {
|
||||
"types": "./types/primitives-event-dispatch.d.ts",
|
||||
"default": "./fesm2022/primitives-event-dispatch.mjs"
|
||||
},
|
||||
"./primitives/signals": {
|
||||
"types": "./types/primitives-signals.d.ts",
|
||||
"default": "./fesm2022/primitives-signals.mjs"
|
||||
},
|
||||
"./rxjs-interop": {
|
||||
"types": "./types/rxjs-interop.d.ts",
|
||||
"default": "./fesm2022/rxjs-interop.mjs"
|
||||
},
|
||||
"./testing": {
|
||||
"types": "./types/testing.d.ts",
|
||||
"default": "./fesm2022/testing.mjs"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/compiler": "21.2.1",
|
||||
"rxjs": "^6.5.3 || ^7.4.0",
|
||||
"zone.js": "~0.15.0 || ~0.16.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@angular/compiler": {
|
||||
"optional": true
|
||||
},
|
||||
"zone.js": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/angular/angular.git",
|
||||
"directory": "packages/core"
|
||||
},
|
||||
"ng-update": {
|
||||
"migrations": "./schematics/migrations.json",
|
||||
"packageGroup": [
|
||||
"@angular/core",
|
||||
"@angular/bazel",
|
||||
"@angular/common",
|
||||
"@angular/compiler",
|
||||
"@angular/compiler-cli",
|
||||
"@angular/animations",
|
||||
"@angular/elements",
|
||||
"@angular/platform-browser",
|
||||
"@angular/platform-browser-dynamic",
|
||||
"@angular/forms",
|
||||
"@angular/platform-server",
|
||||
"@angular/upgrade",
|
||||
"@angular/router",
|
||||
"@angular/language-service",
|
||||
"@angular/localize",
|
||||
"@angular/service-worker"
|
||||
]
|
||||
},
|
||||
"angular": {
|
||||
"bestPractices": {
|
||||
"format": "markdown",
|
||||
"path": "./resources/best-practices.md"
|
||||
}
|
||||
},
|
||||
"schematics": "./schematics/collection.json",
|
||||
"sideEffects": false,
|
||||
"module": "./fesm2022/core.mjs",
|
||||
"typings": "./types/core.d.ts",
|
||||
"type": "module"
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
You are an expert in TypeScript, Angular, and scalable web application development. You write functional, maintainable, performant, and accessible code following Angular and TypeScript best practices.
|
||||
|
||||
## TypeScript Best Practices
|
||||
|
||||
- Use strict type checking
|
||||
- Prefer type inference when the type is obvious
|
||||
- Avoid the `any` type; use `unknown` when type is uncertain
|
||||
|
||||
## Angular Best Practices
|
||||
|
||||
- Always use standalone components over NgModules
|
||||
- Must NOT set `standalone: true` inside Angular decorators. It's the default in Angular v20+.
|
||||
- Use signals for state management
|
||||
- Implement lazy loading for feature routes
|
||||
- Do NOT use the `@HostBinding` and `@HostListener` decorators. Put host bindings inside the `host` object of the `@Component` or `@Directive` decorator instead
|
||||
- Use `NgOptimizedImage` for all static images.
|
||||
- `NgOptimizedImage` does not work for inline base64 images.
|
||||
|
||||
## Accessibility Requirements
|
||||
|
||||
- It MUST pass all AXE checks.
|
||||
- It MUST follow all WCAG AA minimums, including focus management, color contrast, and ARIA attributes.
|
||||
|
||||
### Components
|
||||
|
||||
- Keep components small and focused on a single responsibility
|
||||
- Use `input()` and `output()` functions instead of decorators
|
||||
- Use `computed()` for derived state
|
||||
- Set `changeDetection: ChangeDetectionStrategy.OnPush` in `@Component` decorator
|
||||
- Prefer inline templates for small components
|
||||
- Prefer Reactive forms instead of Template-driven ones
|
||||
- Do NOT use `ngClass`, use `class` bindings instead
|
||||
- Do NOT use `ngStyle`, use `style` bindings instead
|
||||
- When using external templates/styles, use paths relative to the component TS file.
|
||||
|
||||
## State Management
|
||||
|
||||
- Use signals for local component state
|
||||
- Use `computed()` for derived state
|
||||
- Keep state transformations pure and predictable
|
||||
- Do NOT use `mutate` on signals, use `update` or `set` instead
|
||||
|
||||
## Templates
|
||||
|
||||
- Keep templates simple and avoid complex logic
|
||||
- Use native control flow (`@if`, `@for`, `@switch`) instead of `*ngIf`, `*ngFor`, `*ngSwitch`
|
||||
- Use the async pipe to handle observables
|
||||
- Do not assume globals like (`new Date()`) are available.
|
||||
|
||||
## Services
|
||||
|
||||
- Design services around a single responsibility
|
||||
- Use the `providedIn: 'root'` option for singleton services
|
||||
- Use the `inject()` function instead of constructor injection
|
||||
Generated
Vendored
+117
@@ -0,0 +1,117 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var ts = require('typescript');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
require('@angular/compiler-cli');
|
||||
require('node:path');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
function findArrowFunction(node) {
|
||||
let current = node;
|
||||
while (current) {
|
||||
if (ts.isArrowFunction(current)) {
|
||||
return current;
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
class AddBootstrapContextToServerMainMigration extends project_paths.TsurgeFunnelMigration {
|
||||
async analyze(info) {
|
||||
const replacements = [];
|
||||
let importManager = null;
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
if (!sourceFile.fileName.endsWith('main.server.ts')) {
|
||||
continue;
|
||||
}
|
||||
const bootstrapAppCalls = [];
|
||||
ts.forEachChild(sourceFile, function findCalls(node) {
|
||||
if (ts.isCallExpression(node) &&
|
||||
ts.isIdentifier(node.expression) &&
|
||||
node.expression.text === 'bootstrapApplication' &&
|
||||
node.arguments.length < 3) {
|
||||
bootstrapAppCalls.push(node);
|
||||
}
|
||||
ts.forEachChild(node, findCalls);
|
||||
});
|
||||
if (bootstrapAppCalls.length === 0) {
|
||||
continue;
|
||||
}
|
||||
for (const node of bootstrapAppCalls) {
|
||||
const end = node.arguments[node.arguments.length - 1].getEnd();
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), new project_paths.TextUpdate({
|
||||
position: end,
|
||||
end: end,
|
||||
toInsert: ', context',
|
||||
})));
|
||||
const arrowFunction = findArrowFunction(node);
|
||||
if (arrowFunction && arrowFunction.parameters.length === 0) {
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), new project_paths.TextUpdate({
|
||||
position: arrowFunction.parameters.end,
|
||||
end: arrowFunction.parameters.end,
|
||||
toInsert: 'context: BootstrapContext',
|
||||
})));
|
||||
}
|
||||
}
|
||||
importManager ??= new migrations.ImportManager({
|
||||
generateUniqueIdentifier: () => null,
|
||||
shouldUseSingleQuotes: () => true,
|
||||
});
|
||||
importManager.addImport({
|
||||
exportSymbolName: 'BootstrapContext',
|
||||
exportModuleSpecifier: '@angular/platform-browser',
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
}
|
||||
if (importManager !== null) {
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, info.sourceFiles, info);
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ replacements });
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return project_paths.confirmAsSerializable(globalData);
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const seen = new Set();
|
||||
const combined = [];
|
||||
[unitA.replacements, unitB.replacements].forEach((replacements) => {
|
||||
replacements.forEach((current) => {
|
||||
const { position, end, toInsert } = current.update.data;
|
||||
const key = current.projectFile.id + '/' + position + '/' + end + '/' + toInsert;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
combined.push(current);
|
||||
}
|
||||
});
|
||||
});
|
||||
return project_paths.confirmAsSerializable({ replacements: combined });
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats() {
|
||||
return project_paths.confirmAsSerializable({});
|
||||
}
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: () => new AddBootstrapContextToServerMainMigration(),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
require('@angular/compiler-cli');
|
||||
require('typescript');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
/** Migration that moves the import of `ApplicationConfig` from `platform-browser` to `core`. */
|
||||
class ApplicationConfigCoreMigration extends project_paths.TsurgeFunnelMigration {
|
||||
async analyze(info) {
|
||||
const replacements = [];
|
||||
let importManager = null;
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
const specifier = imports.getImportSpecifier(sourceFile, '@angular/platform-browser', 'ApplicationConfig');
|
||||
if (!specifier) {
|
||||
continue;
|
||||
}
|
||||
importManager ??= new migrations.ImportManager({
|
||||
// Prevent the manager from trying to generate a non-conflicting import.
|
||||
generateUniqueIdentifier: () => null,
|
||||
shouldUseSingleQuotes: () => true,
|
||||
});
|
||||
importManager.removeImport(sourceFile, 'ApplicationConfig', '@angular/platform-browser');
|
||||
importManager.addImport({
|
||||
exportSymbolName: 'ApplicationConfig',
|
||||
exportModuleSpecifier: '@angular/core',
|
||||
requestedFile: sourceFile,
|
||||
unsafeAliasOverride: specifier.propertyName ? specifier.name.text : undefined,
|
||||
});
|
||||
}
|
||||
if (importManager !== null) {
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, info.sourceFiles, info);
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ replacements });
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return project_paths.confirmAsSerializable(globalData);
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const seen = new Set();
|
||||
const combined = [];
|
||||
[unitA.replacements, unitB.replacements].forEach((replacements) => {
|
||||
replacements.forEach((current) => {
|
||||
const { position, end, toInsert } = current.update.data;
|
||||
const key = current.projectFile.id + '/' + position + '/' + end + '/' + toInsert;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
combined.push(current);
|
||||
}
|
||||
});
|
||||
});
|
||||
return project_paths.confirmAsSerializable({ replacements: combined });
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats() {
|
||||
return project_paths.confirmAsSerializable({});
|
||||
}
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: () => new ApplicationConfigCoreMigration(),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
var compilerCli = require('@angular/compiler-cli');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
|
||||
/**
|
||||
* Applies import manager changes, and writes them as replacements the
|
||||
* given result array.
|
||||
*/
|
||||
function applyImportManagerChanges(importManager, replacements, sourceFiles, info) {
|
||||
const { newImports, updatedImports, deletedImports } = importManager.finalize();
|
||||
const printer = ts.createPrinter({});
|
||||
const pathToFile = new Map(sourceFiles.map((s) => [s.fileName, s]));
|
||||
// Capture new imports
|
||||
newImports.forEach((newImports, fileName) => {
|
||||
newImports.forEach((newImport) => {
|
||||
const printedImport = printer.printNode(ts.EmitHint.Unspecified, newImport, pathToFile.get(fileName));
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(compilerCli.absoluteFrom(fileName), info), new project_paths.TextUpdate({ position: 0, end: 0, toInsert: `${printedImport}\n` })));
|
||||
});
|
||||
});
|
||||
// Capture updated imports
|
||||
for (const [oldBindings, newBindings] of updatedImports.entries()) {
|
||||
// The import will be generated as multi-line if it already is multi-line,
|
||||
// or if the number of elements significantly increased and it previously
|
||||
// consisted of very few specifiers.
|
||||
const isMultiline = oldBindings.getText().includes('\n') ||
|
||||
(newBindings.elements.length >= 6 && oldBindings.elements.length <= 3);
|
||||
const hasSpaceBetweenBraces = oldBindings.getText().startsWith('{ ');
|
||||
let formatFlags = ts.ListFormat.NamedImportsOrExportsElements |
|
||||
ts.ListFormat.Indented |
|
||||
ts.ListFormat.Braces |
|
||||
ts.ListFormat.PreserveLines |
|
||||
(isMultiline ? ts.ListFormat.MultiLine : ts.ListFormat.SingleLine);
|
||||
if (hasSpaceBetweenBraces) {
|
||||
formatFlags |= ts.ListFormat.SpaceBetweenBraces;
|
||||
}
|
||||
else {
|
||||
formatFlags &= ~ts.ListFormat.SpaceBetweenBraces;
|
||||
}
|
||||
const printedBindings = printer.printList(formatFlags, newBindings.elements, oldBindings.getSourceFile());
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(oldBindings.getSourceFile(), info), new project_paths.TextUpdate({
|
||||
position: oldBindings.getStart(),
|
||||
end: oldBindings.getEnd(),
|
||||
// TS uses four spaces as indent. We migrate to two spaces as we
|
||||
// assume this to be more common.
|
||||
toInsert: printedBindings.replace(/^ {4}/gm, ' '),
|
||||
})));
|
||||
}
|
||||
// Update removed imports
|
||||
for (const removedImport of deletedImports) {
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(removedImport.getSourceFile(), info), new project_paths.TextUpdate({
|
||||
position: removedImport.getStart(),
|
||||
end: removedImport.getEnd(),
|
||||
toInsert: '',
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
exports.applyImportManagerChanges = applyImportManagerChanges;
|
||||
+644
@@ -0,0 +1,644 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var ts = require('typescript');
|
||||
require('node:path');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
var property_name = require('./property_name-BCpALNpZ.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
var symbol = require('./symbol-DZeHSR-V.cjs');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
const CORE_PACKAGE = '@angular/core';
|
||||
const PROVIDE_ZONE_CHANGE_DETECTION = 'provideZoneChangeDetection';
|
||||
const ZONE_CD_PROVIDER = `${PROVIDE_ZONE_CHANGE_DETECTION}()`;
|
||||
const SAFE_TO_REMOVE_OPTIONS = [
|
||||
'ignoreChangesOutsideZone',
|
||||
'ngZoneRunCoalescing',
|
||||
'ngZoneEventCoalescing',
|
||||
];
|
||||
const BOOTSTRAP_OPTIONS = ['ngZone', ...SAFE_TO_REMOVE_OPTIONS];
|
||||
class BootstrapOptionsMigration extends project_paths.TsurgeFunnelMigration {
|
||||
async analyze(info) {
|
||||
let replacements = [];
|
||||
const importManager = new migrations.ImportManager();
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
// We need to migration either
|
||||
// * `bootstrapApplication(App)
|
||||
// * `platformBrowser().bootstrapModule(AppModule)`
|
||||
// * `platformBrowserDynamic().bootstrapModule(AppModule)`
|
||||
// * `TestBed.initTestEnvironment([AppModule], platformBrowserTesting())`
|
||||
// * `getTestBed.initTestEnvironment([AppModule], platformBrowserTesting())`
|
||||
const specifiers = getSpecifiers(sourceFile);
|
||||
// If none of the imports related to bootstraping are present, we can skip the file.
|
||||
if (specifiers === null)
|
||||
continue;
|
||||
const { bootstrapAppSpecifier, testBedSpecifier, createApplicationSpecifier, getTestBedSpecifier, } = specifiers;
|
||||
const typeChecker = info.program.getTypeChecker();
|
||||
const isCreateApplicationNode = (node) => {
|
||||
return (ts.isCallExpression(node) &&
|
||||
createApplicationSpecifier !== null &&
|
||||
symbol.isReferenceToImport(typeChecker, node.expression, createApplicationSpecifier));
|
||||
};
|
||||
const isBootstrapAppNode = (node) => {
|
||||
return (ts.isCallExpression(node) &&
|
||||
bootstrapAppSpecifier !== null &&
|
||||
symbol.isReferenceToImport(typeChecker, node.expression, bootstrapAppSpecifier));
|
||||
};
|
||||
const isBootstrapModuleNode = (node) => {
|
||||
return (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === 'bootstrapModule' &&
|
||||
node.arguments.length > 0);
|
||||
};
|
||||
const isTestBedInitEnvironmentNode = (node) => {
|
||||
return (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === 'initTestEnvironment' &&
|
||||
(symbol.isReferenceToImport(typeChecker, node.expression.expression, testBedSpecifier) ||
|
||||
symbol.isReferenceToImport(typeChecker, node.expression.expression, getTestBedSpecifier)));
|
||||
};
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const evaluator = new migrations.PartialEvaluator(reflector, typeChecker, null);
|
||||
const walk = (node) => {
|
||||
if (isBootstrapAppNode(node)) {
|
||||
this.analyzeBootstrapApplication(node, sourceFile, info, typeChecker, importManager, replacements);
|
||||
}
|
||||
else if (isCreateApplicationNode(node)) {
|
||||
this.analyzeCreateApplication(node, sourceFile, info, typeChecker, importManager, replacements);
|
||||
}
|
||||
else if (isBootstrapModuleNode(node)) {
|
||||
this.analyzeBootstrapModule(node, sourceFile, reflector, evaluator, info, typeChecker, importManager, replacements);
|
||||
}
|
||||
else if (isTestBedInitEnvironmentNode(node)) {
|
||||
this.analyzeTestBedInitEnvironment(node, sourceFile, info, typeChecker, importManager, replacements);
|
||||
}
|
||||
node.forEachChild(walk);
|
||||
};
|
||||
sourceFile.forEachChild(walk);
|
||||
}
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, info.sourceFiles, info);
|
||||
return project_paths.confirmAsSerializable({ replacements });
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const combined = [...unitA.replacements, ...unitB.replacements];
|
||||
return project_paths.confirmAsSerializable({ replacements: combined });
|
||||
}
|
||||
async globalMeta(data) {
|
||||
return project_paths.confirmAsSerializable(data);
|
||||
}
|
||||
async stats(data) {
|
||||
return project_paths.confirmAsSerializable({});
|
||||
}
|
||||
async migrate(data) {
|
||||
return { replacements: data.replacements };
|
||||
}
|
||||
analyzeBootstrapApplication(node, sourceFile, info, typeChecker, importManager, replacements) {
|
||||
const hasExistingChangeDetectionProvider = hasChangeDetectionProvider(node, typeChecker);
|
||||
if (hasExistingChangeDetectionProvider)
|
||||
return;
|
||||
const providerFn = 'provideZoneChangeDetection()';
|
||||
const optionsNode = node.arguments[1];
|
||||
const currentProjectFile = project_paths.projectFile(sourceFile, info);
|
||||
if (optionsNode) {
|
||||
let optionProjectFile = currentProjectFile;
|
||||
let optionLiteral;
|
||||
if (ts.isObjectLiteralExpression(optionsNode)) {
|
||||
optionLiteral = optionsNode;
|
||||
addProvidersToBootstrapOption(optionProjectFile, optionLiteral, providerFn, replacements);
|
||||
}
|
||||
else if (this.isServerConfigZoneless(optionsNode, typeChecker)) {
|
||||
// Nothing to migrate for the SSR bootstrap
|
||||
return;
|
||||
}
|
||||
else if (ts.isIdentifier(optionsNode)) {
|
||||
const text = `{...${optionsNode.getText()}, providers: [${providerFn}, ...${optionsNode.getText()}.providers]}`;
|
||||
replacements.push(new project_paths.Replacement(currentProjectFile, new project_paths.TextUpdate({
|
||||
position: optionsNode.getStart(),
|
||||
end: optionsNode.getEnd(),
|
||||
toInsert: text,
|
||||
})));
|
||||
}
|
||||
else {
|
||||
throw new Error('unsupported optionsNode: ' + optionsNode.getText());
|
||||
}
|
||||
}
|
||||
else {
|
||||
// No options object, add it.
|
||||
const text = `, {providers: [${providerFn}]}`;
|
||||
const component = node.arguments[0];
|
||||
replacements.push(new project_paths.Replacement(currentProjectFile, new project_paths.TextUpdate({ position: component.getEnd(), end: component.getEnd(), toInsert: text })));
|
||||
}
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: CORE_PACKAGE,
|
||||
exportSymbolName: 'provideZoneChangeDetection',
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* The optionsNode can be a appConfig built with mergeApplicationConfig
|
||||
* In this case we need to analyze if the base config uses provideZonelessChangeDetection
|
||||
*/
|
||||
isServerConfigZoneless(optionsNode, typeChecker) {
|
||||
// Check if optionsNode is a result of mergeApplicationConfig
|
||||
let symbol = typeChecker.getSymbolAtLocation(optionsNode);
|
||||
if (symbol && (symbol.flags & ts.SymbolFlags.Alias) !== 0) {
|
||||
symbol = typeChecker.getAliasedSymbol(symbol);
|
||||
}
|
||||
const optionDeclaration = symbol?.getDeclarations()?.[0];
|
||||
if (!optionDeclaration) {
|
||||
return false;
|
||||
}
|
||||
if (!ts.isVariableDeclaration(optionDeclaration) ||
|
||||
!optionDeclaration.initializer ||
|
||||
!ts.isCallExpression(optionDeclaration.initializer) ||
|
||||
!ts.isIdentifier(optionDeclaration.initializer.expression) ||
|
||||
optionDeclaration.initializer.expression.text !== 'mergeApplicationConfig') {
|
||||
// We didn't find a mergeApplicationConfig call, this isn't a server config
|
||||
return false;
|
||||
}
|
||||
let maybeAppConfig = optionDeclaration.initializer.arguments[0];
|
||||
if (ts.isIdentifier(maybeAppConfig)) {
|
||||
const resolved = getObjectLiteralFromIdentifier(maybeAppConfig, typeChecker);
|
||||
if (resolved) {
|
||||
maybeAppConfig = resolved;
|
||||
}
|
||||
}
|
||||
if (maybeAppConfig && ts.isObjectLiteralExpression(maybeAppConfig)) {
|
||||
for (const prop of maybeAppConfig.properties) {
|
||||
if (ts.isPropertyAssignment(prop) &&
|
||||
ts.isIdentifier(prop.name) &&
|
||||
prop.name.text === 'providers' &&
|
||||
ts.isArrayLiteralExpression(prop.initializer)) {
|
||||
for (const el of prop.initializer.elements) {
|
||||
if (ts.isCallExpression(el) &&
|
||||
ts.isIdentifier(el.expression) &&
|
||||
el.expression.text === 'provideZonelessChangeDetection') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
analyzeCreateApplication(node, sourceFile, info, typeChecker, importManager, replacements) {
|
||||
const hasExistingChangeDetectionProvider = hasChangeDetectionProvider(node, typeChecker);
|
||||
if (hasExistingChangeDetectionProvider)
|
||||
return;
|
||||
const providerFn = 'provideZoneChangeDetection()';
|
||||
const optionsNode = node.arguments[0];
|
||||
const currentProjectFile = project_paths.projectFile(sourceFile, info);
|
||||
if (optionsNode) {
|
||||
let optionProjectFile = currentProjectFile;
|
||||
let optionLiteral;
|
||||
if (ts.isObjectLiteralExpression(optionsNode)) {
|
||||
optionLiteral = optionsNode;
|
||||
addProvidersToBootstrapOption(optionProjectFile, optionLiteral, providerFn, replacements);
|
||||
}
|
||||
else if (ts.isIdentifier(optionsNode) ||
|
||||
ts.isCallExpression(optionsNode) ||
|
||||
ts.isPropertyAccessExpression(optionsNode)) {
|
||||
// This is tricky case to handle, in G3 we're might not be able to resolve the identifier's value
|
||||
// Our best alternative is to assume there is no CD providers set and add the ZoneChangeDetection provider
|
||||
// In the cases where it is, we'll just override the zone provider we just set by re-used inthe appConfig providers
|
||||
// TODO: Should we insert a TODO to clean this up ?
|
||||
const text = `{...${optionsNode.getText()}, providers: [${providerFn}, ...${optionsNode.getText()}.providers]}`;
|
||||
replacements.push(new project_paths.Replacement(currentProjectFile, new project_paths.TextUpdate({
|
||||
position: optionsNode.getStart(),
|
||||
end: optionsNode.getEnd(),
|
||||
toInsert: text,
|
||||
})));
|
||||
}
|
||||
else {
|
||||
throw new Error('unsupported optionsNode: ' + optionsNode.getText());
|
||||
}
|
||||
}
|
||||
else {
|
||||
// No options object, add it.
|
||||
const text = `{providers: [${providerFn}]}`;
|
||||
replacements.push(new project_paths.Replacement(currentProjectFile, new project_paths.TextUpdate({
|
||||
position: node.expression.getEnd() + 1,
|
||||
end: node.expression.getEnd() + 1,
|
||||
toInsert: text,
|
||||
})));
|
||||
}
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: CORE_PACKAGE,
|
||||
exportSymbolName: 'provideZoneChangeDetection',
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
}
|
||||
analyzeBootstrapModule(node, sourceFile, reflector, evaluator, info, typeChecker, importManager, replacements) {
|
||||
const moduleIdentifier = node.arguments[0];
|
||||
const moduleType = evaluator.evaluate(moduleIdentifier);
|
||||
if (!(moduleType instanceof migrations.Reference) || !ts.isClassDeclaration(moduleType.node)) {
|
||||
return;
|
||||
}
|
||||
const moduleClass = moduleType.node;
|
||||
const ngModule = findNgModule(moduleClass, reflector);
|
||||
if (!ngModule) {
|
||||
return;
|
||||
}
|
||||
const optionsNode = node.arguments[1];
|
||||
const file = project_paths.projectFile(sourceFile, info);
|
||||
replacements.push(new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: moduleIdentifier.getEnd(),
|
||||
end: node.getEnd() - 1,
|
||||
toInsert: '',
|
||||
})));
|
||||
const hasExistingChangeDetectionProvider = hasChangeDetectionProvider(ngModule, typeChecker);
|
||||
if (hasExistingChangeDetectionProvider) {
|
||||
return;
|
||||
}
|
||||
// Let's try to understand the bootstrap options.
|
||||
let options = optionsNode ? evaluator.evaluate(optionsNode) : null;
|
||||
let extraOptions = new Map();
|
||||
let zoneCdProvider = ZONE_CD_PROVIDER;
|
||||
let zoneInstanceProvider = null;
|
||||
if (Array.isArray(options)) {
|
||||
const mergedOptions = options.reduce((acc, item) => {
|
||||
if (item instanceof Map) {
|
||||
for (const [k, v] of item) {
|
||||
acc.set(k, v);
|
||||
if (!SAFE_TO_REMOVE_OPTIONS.includes(k)) {
|
||||
extraOptions.set(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, new Map());
|
||||
options = mergedOptions;
|
||||
}
|
||||
if (options instanceof Map) {
|
||||
[...options.entries()].forEach(([k, v]) => {
|
||||
if (!BOOTSTRAP_OPTIONS.includes(k) && typeof v !== 'string') {
|
||||
extraOptions.set(k, v);
|
||||
}
|
||||
});
|
||||
if (options.has('ngZoneRunCoalescing') || options.has('ngZoneEventCoalescing')) {
|
||||
const config = [];
|
||||
if (options.get('ngZoneRunCoalescing')) {
|
||||
config.push('runCoalescing: true');
|
||||
}
|
||||
if (options.get('ngZoneEventCoalescing')) {
|
||||
config.push('eventCoalescing: true');
|
||||
}
|
||||
zoneCdProvider = `${PROVIDE_ZONE_CHANGE_DETECTION}(${config.length > 0 ? `{ ${config.join(', ')} }` : ''})`;
|
||||
}
|
||||
const ngZoneOption = options.get('ngZone');
|
||||
if (ngZoneOption instanceof migrations.Reference) {
|
||||
const clazz = ngZoneOption.node;
|
||||
if (ts.isClassDeclaration(clazz) && clazz.name) {
|
||||
zoneInstanceProvider = `{provide: NgZone, useClass: ${clazz.name.text}}`;
|
||||
removePropertiesFromLiteral(file, optionsNode, ['ngZone'], replacements);
|
||||
}
|
||||
}
|
||||
else if (typeof ngZoneOption === 'string') {
|
||||
if (ngZoneOption === 'noop') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (ngZoneOption && typeof ngZoneOption !== 'string') {
|
||||
// This is a case where we're not able to migrate automatically
|
||||
// The migration fails gracefully, keeps the ngZone option and adds a TODO.
|
||||
let ngZoneValue;
|
||||
optionsNode.properties.forEach((p) => {
|
||||
if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === 'ngZone') {
|
||||
ngZoneValue = p.initializer.getText();
|
||||
}
|
||||
else if (ts.isShorthandPropertyAssignment(p) && p.name.text === 'ngZone') {
|
||||
ngZoneValue = p.name.text;
|
||||
}
|
||||
});
|
||||
if (ngZoneValue) {
|
||||
// We re-add the ngZone option
|
||||
extraOptions.set('ngZone', ngZoneValue);
|
||||
}
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), new project_paths.TextUpdate({
|
||||
position: node.getStart() - 1,
|
||||
end: node.getStart() - 1,
|
||||
toInsert: '// TODO: BootstrapOptions are deprecated & ignored. Configure NgZone in the providers array of the application module instead.',
|
||||
})));
|
||||
}
|
||||
}
|
||||
const providers = [zoneCdProvider];
|
||||
if (zoneInstanceProvider) {
|
||||
providers.push(zoneInstanceProvider);
|
||||
}
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: CORE_PACKAGE,
|
||||
exportSymbolName: PROVIDE_ZONE_CHANGE_DETECTION,
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
// if we only use the key, we use the a shorthand asignment
|
||||
const extraOptionsStr = [...extraOptions.entries()]
|
||||
.map(([k, v]) => (k != v ? `${k}: ${v},` : `${k},`))
|
||||
.join(', ');
|
||||
replacements.push(new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: moduleIdentifier.end,
|
||||
end: moduleIdentifier.end,
|
||||
toInsert: `, { applicationProviders: [${providers.join(', ')}], ${extraOptionsStr}}`,
|
||||
})));
|
||||
}
|
||||
analyzeTestBedInitEnvironment(callExpr, sourceFile, info, typeChecker, importManager, replacements) {
|
||||
const hasExistingChangeDetectionProvider = hasChangeDetectionProvider(callExpr, typeChecker);
|
||||
if (hasExistingChangeDetectionProvider)
|
||||
return;
|
||||
const ngModules = callExpr.arguments[0];
|
||||
const moduleProjectFile = project_paths.projectFile(sourceFile, info);
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: CORE_PACKAGE,
|
||||
exportSymbolName: PROVIDE_ZONE_CHANGE_DETECTION,
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
let tmpNode = callExpr;
|
||||
let insertPosition = 0;
|
||||
while (tmpNode.parent.kind !== ts.SyntaxKind.SourceFile) {
|
||||
insertPosition = tmpNode.parent.getStart(sourceFile, true) - 1;
|
||||
tmpNode = tmpNode.parent;
|
||||
}
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: CORE_PACKAGE,
|
||||
exportSymbolName: 'NgModule',
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
addZoneCDModule(ZONE_CD_PROVIDER, moduleProjectFile, insertPosition, replacements);
|
||||
insertZoneCDModule(ngModules, moduleProjectFile, replacements, 'ZoneChangeDetectionModule');
|
||||
}
|
||||
}
|
||||
function addZoneCDModule(providersText, projectFile, location, replacements) {
|
||||
const newModuleText = `\n@NgModule({ providers: [ ${providersText} ] })
|
||||
export class ZoneChangeDetectionModule {}\n\n`;
|
||||
if (replacementsHaveZoneCdModule(projectFile.rootRelativePath, replacements, newModuleText)) {
|
||||
return;
|
||||
}
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: location,
|
||||
end: location,
|
||||
toInsert: newModuleText,
|
||||
})));
|
||||
}
|
||||
function insertZoneCDModule(node, projectFile, replacements, importedModule) {
|
||||
if (ts.isArrayLiteralExpression(node)) {
|
||||
const literal = node;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: literal.elements[0]?.getStart() ?? literal.getEnd() - 1,
|
||||
end: literal.elements[0]?.getStart() ?? literal.getEnd() - 1,
|
||||
toInsert: importedModule + ',',
|
||||
})));
|
||||
}
|
||||
else if (ts.isIdentifier(node)) {
|
||||
// This should be a good enough heuristic to determine if the identifier is not array
|
||||
let isArray = !node.text.endsWith('Module');
|
||||
// Because if it's an array, we need to spread it
|
||||
const newImports = `[${importedModule}, ${isArray ? '...' : ''}${node.text}]`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: node.getStart(),
|
||||
end: node.getEnd(),
|
||||
toInsert: newImports,
|
||||
})));
|
||||
}
|
||||
else {
|
||||
throw new Error('unsupported importsNode: ' + node.getText());
|
||||
}
|
||||
}
|
||||
function addProvidersToBootstrapOption(projectFile, optionsNode, providersText, replacements) {
|
||||
const providersProp = property_name.findLiteralProperty(optionsNode, 'providers');
|
||||
if (providersProp && ts.isPropertyAssignment(providersProp)) {
|
||||
// Can be bootstrap(App, {providers: [...]}), bootstrap(App, {providers}), bootstrap(App, {...appConfig, providers}) etc.
|
||||
if (ts.isArrayLiteralExpression(providersProp.initializer)) {
|
||||
const initializer = providersProp.initializer;
|
||||
const text = `${providersText},`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: initializer.elements[0]?.getStart() ?? initializer.getEnd() - 1,
|
||||
end: initializer.elements[0]?.getStart() ?? initializer.getEnd() - 1,
|
||||
toInsert: text,
|
||||
})));
|
||||
}
|
||||
else if (ts.isIdentifier(providersProp.initializer)) {
|
||||
const newProviders = `[${providersText}, ...${providersProp.initializer.text}]`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: providersProp.initializer.getStart(),
|
||||
end: providersProp.initializer.getEnd(),
|
||||
toInsert: newProviders,
|
||||
})));
|
||||
}
|
||||
else {
|
||||
const newProviders = `[${providersText}, ...`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: providersProp.initializer.getStart(),
|
||||
end: providersProp.initializer.getStart(),
|
||||
toInsert: newProviders,
|
||||
})));
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: providersProp.initializer.getEnd(),
|
||||
end: providersProp.initializer.getEnd(),
|
||||
toInsert: ']',
|
||||
})));
|
||||
}
|
||||
}
|
||||
else if (providersProp && ts.isShorthandPropertyAssignment(providersProp)) {
|
||||
const newProviders = `providers: [${providersText}, ...${providersProp.name.text}]`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: providersProp.getStart(),
|
||||
end: providersProp.getEnd(),
|
||||
toInsert: newProviders,
|
||||
})));
|
||||
}
|
||||
else if (optionsNode.properties.length === 1 &&
|
||||
ts.isSpreadAssignment(optionsNode.properties[0])) {
|
||||
const spread = optionsNode.properties[0];
|
||||
const newProviders = `, providers: [${providersText}, ...${spread.expression.getText()}.providers]`;
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position: spread.getEnd(),
|
||||
end: spread.getEnd(),
|
||||
toInsert: newProviders,
|
||||
})));
|
||||
}
|
||||
else {
|
||||
const text = `providers: [${providersText}]`;
|
||||
let toInsert;
|
||||
let position;
|
||||
if (optionsNode.properties.length > 0) {
|
||||
const lastProperty = optionsNode.properties[optionsNode.properties.length - 1];
|
||||
toInsert = `,\n ${text}`;
|
||||
position = lastProperty.getEnd();
|
||||
}
|
||||
else {
|
||||
toInsert = `\n ${text}\n`;
|
||||
position = optionsNode.getStart() + 1;
|
||||
}
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({
|
||||
position,
|
||||
end: position,
|
||||
toInsert,
|
||||
})));
|
||||
}
|
||||
}
|
||||
function findNgModule(node, reflector) {
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(node);
|
||||
if (decorators) {
|
||||
const ngModuleDecorator = migrations.getAngularDecorators(decorators, ['NgModule'], true)[0];
|
||||
if (ngModuleDecorator &&
|
||||
ngModuleDecorator.args &&
|
||||
ngModuleDecorator.args.length > 0 &&
|
||||
ts.isObjectLiteralExpression(ngModuleDecorator.args[0])) {
|
||||
return ngModuleDecorator.args[0];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function hasChangeDetectionProvider(expression, // either the bootstrapApplication or platformBrowserDynamic().bootstrapModule()
|
||||
typeChecker) {
|
||||
let literal;
|
||||
if (ts.isCallExpression(expression)) {
|
||||
let optionsNode = expression.arguments[1];
|
||||
if (!optionsNode &&
|
||||
symbol.isReferenceToImport(typeChecker, expression.expression, imports.getImportSpecifier(expression.getSourceFile(), '@angular/core', 'createApplication'))) {
|
||||
optionsNode = expression.arguments[0];
|
||||
}
|
||||
if (!optionsNode)
|
||||
return false;
|
||||
if (ts.isIdentifier(optionsNode)) {
|
||||
literal = getObjectLiteralFromIdentifier(optionsNode, typeChecker);
|
||||
}
|
||||
else {
|
||||
literal = optionsNode;
|
||||
}
|
||||
}
|
||||
else {
|
||||
literal = expression;
|
||||
}
|
||||
if (!literal) {
|
||||
return false;
|
||||
}
|
||||
const provideZoneCdSpecifier = imports.getImportSpecifier(literal.getSourceFile(), '@angular/core', 'provideZoneChangeDetection');
|
||||
const provideZonelessCdSpecifier = imports.getImportSpecifier(literal.getSourceFile(), '@angular/core', 'provideZonelessChangeDetection');
|
||||
if (provideZoneCdSpecifier === null && provideZonelessCdSpecifier === null) {
|
||||
return false;
|
||||
}
|
||||
const found = ts.forEachChild(literal, function walk(node) {
|
||||
if (ts.isCallExpression(node)) {
|
||||
if (provideZonelessCdSpecifier &&
|
||||
node.getText().includes(provideZonelessCdSpecifier.getText())) {
|
||||
return true;
|
||||
}
|
||||
if (provideZoneCdSpecifier && node.getText().includes(provideZoneCdSpecifier.getText())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return ts.forEachChild(node, walk);
|
||||
});
|
||||
return !!found;
|
||||
}
|
||||
function getObjectLiteralFromIdentifier(identifier, typeChecker) {
|
||||
let symbol = typeChecker.getSymbolAtLocation(identifier);
|
||||
if (!symbol)
|
||||
return;
|
||||
// Follow aliases (for imported symbols)
|
||||
if ((symbol.flags & ts.SymbolFlags.Alias) !== 0) {
|
||||
symbol = typeChecker.getAliasedSymbol(symbol);
|
||||
}
|
||||
const declarations = symbol.getDeclarations();
|
||||
if (!declarations)
|
||||
return;
|
||||
for (const decl of declarations) {
|
||||
if (ts.isVariableDeclaration(decl) &&
|
||||
decl.initializer &&
|
||||
ts.isObjectLiteralExpression(decl.initializer)) {
|
||||
return decl.initializer;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Extracts the import specifiers related to bootstraping from the source file.
|
||||
* Returns null if no relevant specifiers are found.
|
||||
*/
|
||||
function getSpecifiers(sourceFile) {
|
||||
const createApplicationSpecifier = imports.getImportSpecifier(sourceFile, '@angular/core', 'createApplication');
|
||||
const bootstrapAppSpecifier = imports.getImportSpecifier(sourceFile, '@angular/platform-browser', 'bootstrapApplication');
|
||||
const platformBrowserDynamicSpecifier = imports.getImportSpecifier(sourceFile, '@angular/platform-browser-dynamic', 'platformBrowserDynamic');
|
||||
const platformBrowserSpecifier = imports.getImportSpecifier(sourceFile, '@angular/platform-browser', 'platformBrowser');
|
||||
const testBedSpecifier = imports.getImportSpecifier(sourceFile, '@angular/core/testing', 'TestBed');
|
||||
const getTestBedSpecifier = imports.getImportSpecifier(sourceFile, '@angular/core/testing', 'getTestBed');
|
||||
const ngModuleSpecifier = imports.getImportSpecifier(sourceFile, '@angular/core', 'NgModule');
|
||||
if (!createApplicationSpecifier &&
|
||||
!bootstrapAppSpecifier &&
|
||||
!platformBrowserSpecifier &&
|
||||
!platformBrowserDynamicSpecifier &&
|
||||
!testBedSpecifier &&
|
||||
!ngModuleSpecifier &&
|
||||
!getTestBedSpecifier) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
createApplicationSpecifier,
|
||||
bootstrapAppSpecifier,
|
||||
platformBrowserDynamicSpecifier,
|
||||
platformBrowserSpecifier,
|
||||
testBedSpecifier,
|
||||
ngModuleSpecifier,
|
||||
getTestBedSpecifier,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* In the case we're looking to insert a new ZoneChangeDetectionModule, we need to check if we already inserted one.
|
||||
*
|
||||
* This function also checks if the existing one has fewer options (shorter text length), which means the previous migration strategy inserted one
|
||||
* but the following one is more complete and we should still add it (the dedup function will take care of the cleanup).
|
||||
*/
|
||||
function replacementsHaveZoneCdModule(rootRelativePath, replacements, text) {
|
||||
return replacements.some((replacement) => {
|
||||
const exisitingText = replacement.update.data.toInsert;
|
||||
const isSameFile = replacement.projectFile.rootRelativePath === rootRelativePath;
|
||||
return (isSameFile &&
|
||||
text.includes('ZoneChangeDetectionModule') &&
|
||||
exisitingText.length >= text.length);
|
||||
});
|
||||
}
|
||||
function removePropertiesFromLiteral(projectFile, literal, propertyNames, replacements) {
|
||||
const syntaxList = literal.getChildren().find((ch) => ch.kind === ts.SyntaxKind.SyntaxList);
|
||||
const optionsElements = syntaxList.getChildren();
|
||||
const optionsToRemove = [];
|
||||
optionsElements.forEach((node, i, children) => {
|
||||
if (ts.isPropertyAssignment(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
propertyNames.includes(node.name.text)) {
|
||||
// Look ahead for comma
|
||||
const next = children[i + 1];
|
||||
if (next && next.kind === ts.SyntaxKind.CommaToken) {
|
||||
optionsToRemove.push({ start: node.getStart(), end: next.getEnd() });
|
||||
}
|
||||
else {
|
||||
optionsToRemove.push({ start: node.getStart(), end: node.getEnd() });
|
||||
}
|
||||
}
|
||||
});
|
||||
optionsToRemove.forEach((toRemove) => {
|
||||
replacements.push(new project_paths.Replacement(projectFile, new project_paths.TextUpdate({ position: toRemove.start, end: toRemove.end, toInsert: '' })));
|
||||
});
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: () => new BootstrapOptionsMigration(),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var ts = require('typescript');
|
||||
var compilerCli = require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
/** Migration that cleans up unused imports from a project. */
|
||||
class UnusedImportsMigration extends project_paths.TsurgeFunnelMigration {
|
||||
printer = ts.createPrinter();
|
||||
createProgram(tsconfigAbsPath, fs) {
|
||||
return super.createProgram(tsconfigAbsPath, fs, {
|
||||
extendedDiagnostics: {
|
||||
checks: {
|
||||
// Ensure that the diagnostic is enabled.
|
||||
unusedStandaloneImports: migrations.DiagnosticCategoryLabel.Warning,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
async analyze(info) {
|
||||
const nodePositions = new Map();
|
||||
const replacements = [];
|
||||
let removedImports = 0;
|
||||
let changedFiles = 0;
|
||||
info.ngCompiler?.getDiagnostics().forEach((diag) => {
|
||||
if (diag.file !== undefined &&
|
||||
diag.start !== undefined &&
|
||||
diag.length !== undefined &&
|
||||
diag.code === compilerCli.ngErrorCode(compilerCli.ErrorCode.UNUSED_STANDALONE_IMPORTS)) {
|
||||
// Skip files that aren't owned by this compilation unit.
|
||||
if (!info.sourceFiles.includes(diag.file)) {
|
||||
return;
|
||||
}
|
||||
if (!nodePositions.has(diag.file)) {
|
||||
nodePositions.set(diag.file, new Set());
|
||||
}
|
||||
nodePositions.get(diag.file).add(this.getNodeKey(diag.start, diag.length));
|
||||
}
|
||||
});
|
||||
nodePositions.forEach((locations, sourceFile) => {
|
||||
const resolvedLocations = this.resolveRemovalLocations(sourceFile, locations);
|
||||
const usageAnalysis = this.analyzeUsages(sourceFile, resolvedLocations);
|
||||
if (resolvedLocations.allRemovedIdentifiers.size > 0) {
|
||||
removedImports += resolvedLocations.allRemovedIdentifiers.size;
|
||||
changedFiles++;
|
||||
}
|
||||
this.generateReplacements(sourceFile, resolvedLocations, usageAnalysis, info, replacements);
|
||||
});
|
||||
return project_paths.confirmAsSerializable({ replacements, removedImports, changedFiles });
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return project_paths.confirmAsSerializable(globalData);
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
return project_paths.confirmAsSerializable({
|
||||
replacements: [...unitA.replacements, ...unitB.replacements],
|
||||
removedImports: unitA.removedImports + unitB.removedImports,
|
||||
changedFiles: unitA.changedFiles + unitB.changedFiles,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
return project_paths.confirmAsSerializable({
|
||||
removedImports: globalMetadata.removedImports,
|
||||
changedFiles: globalMetadata.changedFiles,
|
||||
});
|
||||
}
|
||||
/** Gets a key that can be used to look up a node based on its location. */
|
||||
getNodeKey(start, length) {
|
||||
return `${start}/${length}`;
|
||||
}
|
||||
/**
|
||||
* Resolves a set of node locations to the actual AST nodes that need to be migrated.
|
||||
* @param sourceFile File in which to resolve the locations.
|
||||
* @param locations Location keys that should be resolved.
|
||||
*/
|
||||
resolveRemovalLocations(sourceFile, locations) {
|
||||
const result = {
|
||||
fullRemovals: new Set(),
|
||||
partialRemovals: new Map(),
|
||||
allRemovedIdentifiers: new Set(),
|
||||
};
|
||||
const walk = (node) => {
|
||||
if (!ts.isIdentifier(node)) {
|
||||
node.forEachChild(walk);
|
||||
return;
|
||||
}
|
||||
// The TS typings don't reflect that the parent can be undefined.
|
||||
const parent = node.parent;
|
||||
if (!parent) {
|
||||
return;
|
||||
}
|
||||
if (locations.has(this.getNodeKey(node.getStart(), node.getWidth()))) {
|
||||
// When the entire array needs to be cleared, the diagnostic is
|
||||
// reported on the property assignment, rather than an array element.
|
||||
if (ts.isPropertyAssignment(parent) &&
|
||||
parent.name === node &&
|
||||
ts.isArrayLiteralExpression(parent.initializer)) {
|
||||
result.fullRemovals.add(parent.initializer);
|
||||
parent.initializer.elements.forEach((element) => {
|
||||
if (ts.isIdentifier(element)) {
|
||||
result.allRemovedIdentifiers.add(element.text);
|
||||
}
|
||||
});
|
||||
}
|
||||
else if (ts.isArrayLiteralExpression(parent)) {
|
||||
if (!result.partialRemovals.has(parent)) {
|
||||
result.partialRemovals.set(parent, new Set());
|
||||
}
|
||||
result.partialRemovals.get(parent).add(node);
|
||||
result.allRemovedIdentifiers.add(node.text);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(sourceFile);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Analyzes how identifiers are used across a file.
|
||||
* @param sourceFile File to be analyzed.
|
||||
* @param locations Locations that will be changed as a part of this migration.
|
||||
*/
|
||||
analyzeUsages(sourceFile, locations) {
|
||||
const { partialRemovals, fullRemovals } = locations;
|
||||
const result = {
|
||||
importedSymbols: new Map(),
|
||||
identifierCounts: new Map(),
|
||||
};
|
||||
const walk = (node) => {
|
||||
if (ts.isIdentifier(node) &&
|
||||
node.parent &&
|
||||
// Don't track individual identifiers marked for removal.
|
||||
(!ts.isArrayLiteralExpression(node.parent) ||
|
||||
!partialRemovals.has(node.parent) ||
|
||||
!partialRemovals.get(node.parent).has(node))) {
|
||||
result.identifierCounts.set(node.text, (result.identifierCounts.get(node.text) ?? 0) + 1);
|
||||
}
|
||||
// Don't track identifiers in array literals that are about to be removed.
|
||||
if (ts.isArrayLiteralExpression(node) && fullRemovals.has(node)) {
|
||||
return;
|
||||
}
|
||||
if (ts.isImportDeclaration(node)) {
|
||||
const namedBindings = node.importClause?.namedBindings;
|
||||
const moduleName = ts.isStringLiteral(node.moduleSpecifier)
|
||||
? node.moduleSpecifier.text
|
||||
: null;
|
||||
if (namedBindings && ts.isNamedImports(namedBindings) && moduleName !== null) {
|
||||
namedBindings.elements.forEach((imp) => {
|
||||
if (!result.importedSymbols.has(moduleName)) {
|
||||
result.importedSymbols.set(moduleName, new Map());
|
||||
}
|
||||
const symbolName = (imp.propertyName || imp.name).text;
|
||||
const localName = imp.name.text;
|
||||
result.importedSymbols.get(moduleName).set(localName, symbolName);
|
||||
});
|
||||
}
|
||||
// Don't track identifiers in imports.
|
||||
return;
|
||||
}
|
||||
// Track identifiers in all other node kinds.
|
||||
node.forEachChild(walk);
|
||||
};
|
||||
walk(sourceFile);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Generates text replacements based on the data produced by the migration.
|
||||
* @param sourceFile File being migrated.
|
||||
* @param removalLocations Data about nodes being removed.
|
||||
* @param usages Data about identifier usage.
|
||||
* @param info Information about the current program.
|
||||
* @param replacements Array tracking all text replacements.
|
||||
*/
|
||||
generateReplacements(sourceFile, removalLocations, usages, info, replacements) {
|
||||
const { fullRemovals, partialRemovals, allRemovedIdentifiers } = removalLocations;
|
||||
const { importedSymbols, identifierCounts } = usages;
|
||||
const importManager = new migrations.ImportManager();
|
||||
const sourceText = sourceFile.getFullText();
|
||||
// Replace full arrays with empty ones. This allows preserves more of the user's formatting.
|
||||
fullRemovals.forEach((node) => {
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), new project_paths.TextUpdate({
|
||||
position: node.getStart(),
|
||||
end: node.getEnd(),
|
||||
toInsert: '[]',
|
||||
})));
|
||||
});
|
||||
// Filter out the unused identifiers from an array.
|
||||
partialRemovals.forEach((toRemove, parent) => {
|
||||
toRemove.forEach((node) => {
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), getArrayElementRemovalUpdate(node, sourceText)));
|
||||
});
|
||||
stripTrailingSameLineCommas(parent, toRemove, sourceText)?.forEach((update) => {
|
||||
replacements.push(new project_paths.Replacement(project_paths.projectFile(sourceFile, info), update));
|
||||
});
|
||||
});
|
||||
// Attempt to clean up unused import declarations. Note that this isn't foolproof, because we
|
||||
// do the matching based on identifier text, rather than going through the type checker which
|
||||
// can be expensive. This should be enough for the vast majority of cases in this schematic
|
||||
// since we're dealing exclusively with directive/pipe class names which tend to be very
|
||||
// specific. In the worst case we may end up not removing an import declaration which would
|
||||
// still be valid code that the user can clean up themselves.
|
||||
importedSymbols.forEach((names, moduleName) => {
|
||||
names.forEach((symbolName, localName) => {
|
||||
// Note that in the `identifierCounts` lookup both zero and undefined
|
||||
// are valid and mean that the identifiers isn't being used anymore.
|
||||
if (allRemovedIdentifiers.has(localName) && !identifierCounts.get(localName)) {
|
||||
importManager.removeImport(sourceFile, symbolName, moduleName);
|
||||
}
|
||||
});
|
||||
});
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, [sourceFile], info);
|
||||
}
|
||||
}
|
||||
/** Generates a `TextUpdate` for the removal of an array element. */
|
||||
function getArrayElementRemovalUpdate(node, sourceText) {
|
||||
let position = node.getStart();
|
||||
let end = node.getEnd();
|
||||
let toInsert = '';
|
||||
const whitespaceOrLineFeed = /\s/;
|
||||
// Usually the way we'd remove the nodes would be to recreate the `parent` while excluding
|
||||
// the nodes that should be removed. The problem with this is that it'll strip out comments
|
||||
// inside the array which can have special meaning internally. We work around it by removing
|
||||
// only the node's own offsets. This comes with another problem in that it won't remove the commas
|
||||
// that separate array elements which in turn can look weird if left in place (e.g.
|
||||
// `[One, Two, Three, Four]` can turn into `[One,,Four]`). To account for them, we start with the
|
||||
// node's end offset and then expand it to include trailing commas, whitespace and line breaks.
|
||||
for (let i = end; i < sourceText.length; i++) {
|
||||
if (sourceText[i] === ',' || whitespaceOrLineFeed.test(sourceText[i])) {
|
||||
end++;
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new project_paths.TextUpdate({ position, end, toInsert });
|
||||
}
|
||||
/** Returns `TextUpdate`s that will remove any leftover trailing commas on the same line. */
|
||||
function stripTrailingSameLineCommas(node, toRemove, sourceText) {
|
||||
let updates = null;
|
||||
for (let i = 0; i < node.elements.length; i++) {
|
||||
// Skip over elements that are being removed already.
|
||||
if (toRemove.has(node.elements[i])) {
|
||||
continue;
|
||||
}
|
||||
// An element might have a trailing comma if all elements after it have been removed.
|
||||
const mightHaveTrailingComma = node.elements.slice(i + 1).every((e) => toRemove.has(e));
|
||||
if (!mightHaveTrailingComma) {
|
||||
continue;
|
||||
}
|
||||
const position = node.elements[i].getEnd();
|
||||
let end = position;
|
||||
// If the item might have a trailing comma, start looking after it until we hit a line break.
|
||||
for (let charIndex = position; charIndex < node.getEnd(); charIndex++) {
|
||||
const char = sourceText[charIndex];
|
||||
if (char === ',' || char === ' ') {
|
||||
end++;
|
||||
}
|
||||
else {
|
||||
if (char !== '\n' && position !== end) {
|
||||
updates ??= [];
|
||||
updates.push(new project_paths.TextUpdate({ position, end, toInsert: '' }));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
getMigration: () => new UnusedImportsMigration(),
|
||||
tree,
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for unused imports using ${tsconfigPath}`);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Schematic failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: ({ removedImports, changedFiles }) => {
|
||||
let statsMessage;
|
||||
if (removedImports === 0) {
|
||||
statsMessage = 'Schematic could not find unused imports in the project';
|
||||
}
|
||||
else {
|
||||
statsMessage =
|
||||
`Removed ${removedImports} import${removedImports !== 1 ? 's' : ''} ` +
|
||||
`in ${changedFiles} file${changedFiles !== 1 ? 's' : ''}`;
|
||||
}
|
||||
context.logger.info('');
|
||||
context.logger.info(statsMessage);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var ng_component_template = require('./ng_component_template-BOuKAnQd.cjs');
|
||||
var ng_decorators = require('./ng_decorators-DYy6II6x.cjs');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
require('./property_name-BCpALNpZ.cjs');
|
||||
|
||||
const commonModuleStr = 'CommonModule';
|
||||
const angularCommonStr = '@angular/common';
|
||||
const PATTERN_IMPORTS = [
|
||||
// Structural directives
|
||||
{ pattern: /\*ngIf\b/g, imports: ['NgIf'] },
|
||||
{ pattern: /\*ngFor\b/g, imports: ['NgFor'] },
|
||||
{ pattern: /\[ngForOf]\b/g, imports: ['NgForOf'] },
|
||||
{ pattern: /\[ngPlural\]/g, imports: ['NgPlural'] },
|
||||
// Match ngPluralCase as structural (*ngPluralCase) or attribute (ngPluralCase="value")
|
||||
{ pattern: /(\*ngPluralCase\b|\s+ngPluralCase\s*=)/g, imports: ['NgPluralCase'] },
|
||||
// Match ngSwitchCase as structural (*ngSwitchCase) or attribute (ngSwitchCase="value")
|
||||
{ pattern: /(\*ngSwitchCase\b|\s+ngSwitchCase\s*=)/g, imports: ['NgSwitchCase'] },
|
||||
// Match ngSwitchDefault as structural (*ngSwitchDefault) or standalone attribute (ngSwitchDefault>)
|
||||
{ pattern: /(\*ngSwitchDefault\b|\s+ngSwitchDefault(?=\s*>))/g, imports: ['NgSwitchDefault'] },
|
||||
{ pattern: /\[ngClass\]/g, imports: ['NgClass'] },
|
||||
{ pattern: /\[ngStyle\]/g, imports: ['NgStyle'] },
|
||||
// Match ngSwitch as property binding [ngSwitch] or attribute ngSwitch="value"
|
||||
{ pattern: /(\[ngSwitch\]|\s+ngSwitch\s*=)/g, imports: ['NgSwitch'] },
|
||||
// Match ngTemplateOutlet as structural (*ngTemplateOutlet) or property binding [ngTemplateOutlet]
|
||||
{ pattern: /(\*ngTemplateOutlet\b|\[ngTemplateOutlet\])/g, imports: ['NgTemplateOutlet'] },
|
||||
// Match ngComponentOutlet as structural (*ngComponentOutlet) or property binding [ngComponentOutlet]
|
||||
{ pattern: /(\*ngComponentOutlet\b|\[ngComponentOutlet\])/g, imports: ['NgComponentOutlet'] },
|
||||
// Common pipes
|
||||
{ pattern: /\|\s*async\b/g, imports: ['AsyncPipe'] },
|
||||
{ pattern: /\|\s*json\b/g, imports: ['JsonPipe'] },
|
||||
{ pattern: /\|\s*date\b/g, imports: ['DatePipe'] },
|
||||
{ pattern: /\|\s*currency\b/g, imports: ['CurrencyPipe'] },
|
||||
{ pattern: /\|\s*number\b/g, imports: ['DecimalPipe'] },
|
||||
{ pattern: /\|\s*percent\b/g, imports: ['PercentPipe'] },
|
||||
{ pattern: /\|\s*lowercase\b/g, imports: ['LowerCasePipe'] },
|
||||
{ pattern: /\|\s*uppercase\b/g, imports: ['UpperCasePipe'] },
|
||||
{ pattern: /\|\s*titlecase\b/g, imports: ['TitleCasePipe'] },
|
||||
{ pattern: /\|\s*slice\b/g, imports: ['SlicePipe'] },
|
||||
{ pattern: /\|\s*keyvalue\b/g, imports: ['KeyValuePipe'] },
|
||||
{ pattern: /\|\s*i18nPlural\b/g, imports: ['I18nPluralPipe'] },
|
||||
{ pattern: /\|\s*i18nSelect\b/g, imports: ['I18nSelectPipe'] },
|
||||
];
|
||||
function analyzeTemplateWithRegex(template, neededImports) {
|
||||
PATTERN_IMPORTS.forEach(({ pattern, imports }) => {
|
||||
// Reset regex lastIndex to avoid state issues with global flag
|
||||
pattern.lastIndex = 0;
|
||||
if (pattern.test(template)) {
|
||||
imports.forEach((imp) => neededImports.add(imp));
|
||||
}
|
||||
});
|
||||
}
|
||||
function migrateCommonModuleUsage(template, componentNode, typeChecker) {
|
||||
const analysis = analyzeTemplateContent(template);
|
||||
const hasCommonModule = hasCommonModuleInImports(componentNode, typeChecker);
|
||||
return {
|
||||
migrated: template,
|
||||
changed: hasCommonModule,
|
||||
replacementCount: hasCommonModule ? 1 : 0,
|
||||
canRemoveCommonModule: hasCommonModule,
|
||||
neededImports: Array.from(analysis.neededImports),
|
||||
};
|
||||
}
|
||||
function createCommonModuleImportsArrayRemoval(classNode, file, typeChecker, neededImports) {
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(classNode);
|
||||
if (!decorators) {
|
||||
return null;
|
||||
}
|
||||
const decorator = decorators.find((decorator) => decorator.name === 'Component');
|
||||
if (!decorator?.node) {
|
||||
return null;
|
||||
}
|
||||
const decoratorNode = decorator.node;
|
||||
if (!ts.isDecorator(decoratorNode) ||
|
||||
!ts.isCallExpression(decoratorNode.expression) ||
|
||||
decoratorNode.expression.arguments.length === 0 ||
|
||||
!ts.isObjectLiteralExpression(decoratorNode.expression.arguments[0])) {
|
||||
return null;
|
||||
}
|
||||
const metadata = decoratorNode.expression.arguments[0];
|
||||
const importsProperty = metadata.properties.find((p) => ts.isPropertyAssignment(p) && p.name?.getText() === 'imports');
|
||||
if (!importsProperty || !ts.isArrayLiteralExpression(importsProperty.initializer)) {
|
||||
return null;
|
||||
}
|
||||
const importsArray = importsProperty.initializer;
|
||||
const originalElements = importsArray.elements;
|
||||
const filteredElements = originalElements.filter((el) => {
|
||||
if (!ts.isIdentifier(el))
|
||||
return true;
|
||||
return !isCommonModuleFromAngularCommon(typeChecker, el);
|
||||
});
|
||||
// Get existing import names to avoid duplicates
|
||||
const existingImportNames = new Set(filteredElements.filter((el) => ts.isIdentifier(el)).map((el) => el.getText()));
|
||||
// Only add imports that don't already exist
|
||||
const importsToAdd = neededImports
|
||||
.filter((imp) => !existingImportNames.has(imp))
|
||||
.sort()
|
||||
.map((imp) => ts.factory.createIdentifier(imp));
|
||||
const newElements = [...filteredElements, ...importsToAdd];
|
||||
if (newElements.length === originalElements.length && neededImports.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (newElements.length === 0) {
|
||||
// For standalone components, keep imports: [] instead of removing the property entirely
|
||||
const printer = ts.createPrinter();
|
||||
const emptyArray = ts.factory.createArrayLiteralExpression([]);
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, emptyArray, classNode.getSourceFile());
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: importsArray.getStart(),
|
||||
end: importsArray.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
const printer = ts.createPrinter();
|
||||
const newArray = ts.factory.updateArrayLiteralExpression(importsArray, newElements);
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, newArray, classNode.getSourceFile());
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: importsArray.getStart(),
|
||||
end: importsArray.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
function analyzeTemplateContent(templateContent) {
|
||||
const neededImports = new Set();
|
||||
const errors = [];
|
||||
try {
|
||||
analyzeTemplateWithRegex(templateContent, neededImports);
|
||||
}
|
||||
catch (error) {
|
||||
errors.push(`Failed to analyze template: ${error}`);
|
||||
}
|
||||
return { neededImports, errors };
|
||||
}
|
||||
function hasCommonModuleInImports(componentNode, typeChecker) {
|
||||
// First check if there's a CommonModule in the imports array
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(componentNode);
|
||||
if (!decorators) {
|
||||
return false;
|
||||
}
|
||||
const decorator = decorators.find((decorator) => decorator.name === 'Component');
|
||||
if (!decorator?.node) {
|
||||
return false;
|
||||
}
|
||||
const decoratorNode = decorator.node;
|
||||
if (!ts.isDecorator(decoratorNode) ||
|
||||
!ts.isCallExpression(decoratorNode.expression) ||
|
||||
decoratorNode.expression.arguments.length === 0 ||
|
||||
!ts.isObjectLiteralExpression(decoratorNode.expression.arguments[0])) {
|
||||
return false;
|
||||
}
|
||||
const metadata = decoratorNode.expression.arguments[0];
|
||||
const importsProperty = metadata.properties.find((p) => ts.isPropertyAssignment(p) && p.name?.getText() === 'imports');
|
||||
if (!importsProperty || !ts.isArrayLiteralExpression(importsProperty.initializer)) {
|
||||
return false;
|
||||
}
|
||||
const importsArray = importsProperty.initializer;
|
||||
return importsArray.elements.some((el) => {
|
||||
if (!ts.isIdentifier(el))
|
||||
return false;
|
||||
return isCommonModuleFromAngularCommon(typeChecker, el);
|
||||
});
|
||||
}
|
||||
function isCommonModuleFromAngularCommon(typeChecker, identifier) {
|
||||
const importInfo = imports.getImportOfIdentifier(typeChecker, identifier);
|
||||
return (importInfo !== null &&
|
||||
importInfo.name === commonModuleStr &&
|
||||
importInfo.importModule === angularCommonStr);
|
||||
}
|
||||
function processResolvedTemplate(template, componentNode, info, typeChecker, replacements, filesWithNeededImports) {
|
||||
const result = migrateCommonModuleUsage(template.content, componentNode, typeChecker);
|
||||
if (result.changed) {
|
||||
const sourceFile = componentNode.getSourceFile();
|
||||
const file = project_paths.projectFile(sourceFile, info);
|
||||
filesWithNeededImports.set(sourceFile.fileName, result.neededImports);
|
||||
const replacement = createCommonModuleImportsArrayRemoval(componentNode, file, typeChecker, result.neededImports);
|
||||
if (replacement) {
|
||||
replacements.push(replacement);
|
||||
}
|
||||
const importManager = new migrations.ImportManager({
|
||||
shouldUseSingleQuotes: () => true,
|
||||
});
|
||||
// Always remove 'CommonModule' regardless of whether it's aliased or not
|
||||
// ImportManager handles removing the correct import specifier
|
||||
importManager.removeImport(sourceFile, commonModuleStr, angularCommonStr);
|
||||
if (result.neededImports.length > 0) {
|
||||
result.neededImports.forEach((importName) => {
|
||||
importManager.addImport({
|
||||
exportSymbolName: importName,
|
||||
exportModuleSpecifier: angularCommonStr,
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
});
|
||||
}
|
||||
const importReplacements = [];
|
||||
apply_import_manager.applyImportManagerChanges(importManager, importReplacements, [sourceFile], info);
|
||||
replacements.push(...importReplacements);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Angular Common to Standalone migration.
|
||||
*
|
||||
* This migration converts standalone components and Angular modules from using
|
||||
* CommonModule to importing individual directives and pipes.
|
||||
*/
|
||||
class CommonToStandaloneMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
async analyze(info) {
|
||||
const fileReplacements = [];
|
||||
const references = [];
|
||||
const filesWithNeededImports = new Map();
|
||||
for (const sf of info.sourceFiles) {
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
if (this.config.shouldMigrate && !this.config.shouldMigrate(file)) {
|
||||
continue;
|
||||
}
|
||||
this.visitSourceFile(sf, info, fileReplacements, references, filesWithNeededImports);
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
replacements: fileReplacements,
|
||||
references,
|
||||
filesWithNeededImports,
|
||||
});
|
||||
}
|
||||
visitSourceFile(sourceFile, info, replacements, references, filesWithNeededImports) {
|
||||
const typeChecker = info.program.getTypeChecker();
|
||||
const visit = (node) => {
|
||||
const hasNode = ts.isClassDeclaration(node) && node.name;
|
||||
if (!hasNode) {
|
||||
ts.forEachChild(node, visit);
|
||||
return;
|
||||
}
|
||||
const nodeDecorators = ts.getDecorators(node);
|
||||
if (!nodeDecorators) {
|
||||
ts.forEachChild(node, visit);
|
||||
return;
|
||||
}
|
||||
const decorators = ng_decorators.getAngularDecorators(typeChecker, nodeDecorators);
|
||||
const hasComponentDecorator = decorators.some((d) => d.name === 'Component');
|
||||
if (!hasComponentDecorator) {
|
||||
return;
|
||||
}
|
||||
const ref = this.analyzeClass(node, typeChecker);
|
||||
if (!ref) {
|
||||
return;
|
||||
}
|
||||
references.push(ref);
|
||||
const templateVisitor = new ng_component_template.NgComponentTemplateVisitor(typeChecker);
|
||||
templateVisitor.visitNode(node);
|
||||
for (const template of templateVisitor.resolvedTemplates) {
|
||||
processResolvedTemplate(template, node, info, typeChecker, replacements, filesWithNeededImports);
|
||||
}
|
||||
// Component has CommonModule in imports but no template content to analyze
|
||||
// We still need to process these cases to remove unused CommonModule imports
|
||||
if (templateVisitor.resolvedTemplates.length === 0) {
|
||||
processResolvedTemplate({ content: ''}, node, info, typeChecker, replacements, filesWithNeededImports);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sourceFile);
|
||||
}
|
||||
analyzeClass(node, typeChecker) {
|
||||
const nodeDecorators = ts.getDecorators(node);
|
||||
if (!nodeDecorators)
|
||||
return null;
|
||||
const decorators = ng_decorators.getAngularDecorators(typeChecker, nodeDecorators);
|
||||
// Only process Component decorators, not Directive or other Angular decorators
|
||||
for (const decorator of decorators) {
|
||||
if (decorator.name === 'Component') {
|
||||
return this.analyzeComponentDecorator(node, decorator, typeChecker);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
analyzeComponentDecorator(node, decorator, typeChecker) {
|
||||
const decoratorNode = decorator.node;
|
||||
if (!ts.isCallExpression(decoratorNode.expression)) {
|
||||
return null;
|
||||
}
|
||||
const config = decoratorNode.expression.arguments[0];
|
||||
if (!ts.isObjectLiteralExpression(config)) {
|
||||
return null;
|
||||
}
|
||||
if (hasCommonModuleInImports(node, typeChecker)) {
|
||||
return { node };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const combinedFilesWithNeededImports = new Map(unitA.filesWithNeededImports);
|
||||
for (const [fileName, imports] of unitB.filesWithNeededImports) {
|
||||
if (combinedFilesWithNeededImports.has(fileName)) {
|
||||
const existingImports = combinedFilesWithNeededImports.get(fileName) || [];
|
||||
const mergedImports = Array.from(new Set([...existingImports, ...imports]));
|
||||
combinedFilesWithNeededImports.set(fileName, mergedImports);
|
||||
}
|
||||
else {
|
||||
combinedFilesWithNeededImports.set(fileName, imports);
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
replacements: [...unitA.replacements, ...unitB.replacements],
|
||||
references: [...unitA.references, ...unitB.references],
|
||||
filesWithNeededImports: combinedFilesWithNeededImports,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const stats = {
|
||||
counters: {
|
||||
replacements: globalMetadata.replacements.length,
|
||||
references: globalMetadata.references.length,
|
||||
},
|
||||
};
|
||||
return stats;
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return {
|
||||
replacements: globalData.replacements,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new CommonToStandaloneMigration({
|
||||
shouldMigrate: (file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for CommonModule usage: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: (stats) => {
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated CommonModule to standalone imports 🎉`);
|
||||
context.logger.info(` -> Migrated ${stats.counters.replacements} CommonModule references affecting ${stats.counters.references} components.`);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var path = require('path');
|
||||
|
||||
function _interopNamespaceDefault(e) {
|
||||
var n = Object.create(null);
|
||||
if (e) {
|
||||
Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default') {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
n.default = e;
|
||||
return Object.freeze(n);
|
||||
}
|
||||
|
||||
var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
|
||||
|
||||
/** Tracks changes that have to be made for specific files. */
|
||||
class ChangeTracker {
|
||||
_printer;
|
||||
_importRemapper;
|
||||
_changes = new Map();
|
||||
_importManager;
|
||||
_quotesCache = new WeakMap();
|
||||
constructor(_printer, _importRemapper) {
|
||||
this._printer = _printer;
|
||||
this._importRemapper = _importRemapper;
|
||||
this._importManager = new migrations.ImportManager({
|
||||
shouldUseSingleQuotes: (file) => this._getQuoteKind(file) === 0 /* QuoteKind.SINGLE */,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Tracks the insertion of some text.
|
||||
* @param sourceFile File in which the text is being inserted.
|
||||
* @param start Index at which the text is insert.
|
||||
* @param text Text to be inserted.
|
||||
*/
|
||||
insertText(sourceFile, index, text) {
|
||||
this._trackChange(sourceFile, { start: index, text });
|
||||
}
|
||||
/**
|
||||
* Replaces text within a file.
|
||||
* @param sourceFile File in which to replace the text.
|
||||
* @param start Index from which to replace the text.
|
||||
* @param removeLength Length of the text being replaced.
|
||||
* @param text Text to be inserted instead of the old one.
|
||||
*/
|
||||
replaceText(sourceFile, start, removeLength, text) {
|
||||
this._trackChange(sourceFile, { start, removeLength, text });
|
||||
}
|
||||
/**
|
||||
* Replaces the text of an AST node with a new one.
|
||||
* @param oldNode Node to be replaced.
|
||||
* @param newNode New node to be inserted.
|
||||
* @param emitHint Hint when formatting the text of the new node.
|
||||
* @param sourceFileWhenPrinting File to use when printing out the new node. This is important
|
||||
* when copying nodes from one file to another, because TypeScript might not output literal nodes
|
||||
* without it.
|
||||
*/
|
||||
replaceNode(oldNode, newNode, emitHint = ts.EmitHint.Unspecified, sourceFileWhenPrinting) {
|
||||
const sourceFile = oldNode.getSourceFile();
|
||||
this.replaceText(sourceFile, oldNode.getStart(), oldNode.getWidth(), this._printer.printNode(emitHint, newNode, sourceFileWhenPrinting || sourceFile));
|
||||
}
|
||||
/**
|
||||
* Removes the text of an AST node from a file.
|
||||
* @param node Node whose text should be removed.
|
||||
* @param useFullOffsets Whether to remove the node using its full offset (e.g. `getFullStart`
|
||||
* rather than `fullStart`). This has the advantage of removing any comments that may be tied
|
||||
* to the node, but can lead to too much code being deleted.
|
||||
*/
|
||||
removeNode(node, useFullOffsets = false) {
|
||||
this._trackChange(node.getSourceFile(), {
|
||||
start: useFullOffsets ? node.getFullStart() : node.getStart(),
|
||||
removeLength: useFullOffsets ? node.getFullWidth() : node.getWidth(),
|
||||
text: '',
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Adds an import to a file.
|
||||
* @param sourceFile File to which to add the import.
|
||||
* @param symbolName Symbol being imported.
|
||||
* @param moduleName Module from which the symbol is imported.
|
||||
* @param alias Alias to use for the import.
|
||||
*/
|
||||
addImport(sourceFile, symbolName, moduleName, alias) {
|
||||
if (this._importRemapper) {
|
||||
moduleName = this._importRemapper(moduleName, sourceFile.fileName);
|
||||
}
|
||||
// It's common for paths to be manipulated with Node's `path` utilties which
|
||||
// can yield a path with back slashes. Normalize them since outputting such
|
||||
// paths will also cause TS to escape the forward slashes.
|
||||
moduleName = normalizePath(moduleName);
|
||||
if (!this._changes.has(sourceFile)) {
|
||||
this._changes.set(sourceFile, []);
|
||||
}
|
||||
return this._importManager.addImport({
|
||||
requestedFile: sourceFile,
|
||||
exportSymbolName: symbolName,
|
||||
exportModuleSpecifier: moduleName,
|
||||
unsafeAliasOverride: alias,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Removes an import from a file.
|
||||
* @param sourceFile File from which to remove the import.
|
||||
* @param symbolName Original name of the symbol to be removed. Used even if the import is aliased.
|
||||
* @param moduleName Module from which the symbol is imported.
|
||||
*/
|
||||
removeImport(sourceFile, symbolName, moduleName) {
|
||||
// It's common for paths to be manipulated with Node's `path` utilties which
|
||||
// can yield a path with back slashes. Normalize them since outputting such
|
||||
// paths will also cause TS to escape the forward slashes.
|
||||
moduleName = normalizePath(moduleName);
|
||||
if (!this._changes.has(sourceFile)) {
|
||||
this._changes.set(sourceFile, []);
|
||||
}
|
||||
this._importManager.removeImport(sourceFile, symbolName, moduleName);
|
||||
}
|
||||
/**
|
||||
* Gets the changes that should be applied to all the files in the migration.
|
||||
* The changes are sorted in the order in which they should be applied.
|
||||
*/
|
||||
recordChanges() {
|
||||
this._recordImports();
|
||||
return this._changes;
|
||||
}
|
||||
/**
|
||||
* Clear the tracked changes
|
||||
*/
|
||||
clearChanges() {
|
||||
this._changes.clear();
|
||||
}
|
||||
/**
|
||||
* Adds a change to a `ChangesByFile` map.
|
||||
* @param file File that the change is associated with.
|
||||
* @param change Change to be added.
|
||||
*/
|
||||
_trackChange(file, change) {
|
||||
const changes = this._changes.get(file);
|
||||
if (changes) {
|
||||
// Insert the changes in reverse so that they're applied in reverse order.
|
||||
// This ensures that the offsets of subsequent changes aren't affected by
|
||||
// previous changes changing the file's text.
|
||||
const insertIndex = changes.findIndex((current) => current.start <= change.start);
|
||||
if (insertIndex === -1) {
|
||||
changes.push(change);
|
||||
}
|
||||
else {
|
||||
changes.splice(insertIndex, 0, change);
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._changes.set(file, [change]);
|
||||
}
|
||||
}
|
||||
/** Determines what kind of quotes to use for a specific file. */
|
||||
_getQuoteKind(sourceFile) {
|
||||
if (this._quotesCache.has(sourceFile)) {
|
||||
return this._quotesCache.get(sourceFile);
|
||||
}
|
||||
let kind = 0 /* QuoteKind.SINGLE */;
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
|
||||
kind = statement.moduleSpecifier.getText()[0] === '"' ? 1 /* QuoteKind.DOUBLE */ : 0 /* QuoteKind.SINGLE */;
|
||||
this._quotesCache.set(sourceFile, kind);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return kind;
|
||||
}
|
||||
/** Records the pending import changes from the import manager. */
|
||||
_recordImports() {
|
||||
const { newImports, updatedImports, deletedImports } = this._importManager.finalize();
|
||||
for (const [original, replacement] of updatedImports) {
|
||||
this.replaceNode(original, replacement);
|
||||
}
|
||||
for (const node of deletedImports) {
|
||||
this.removeNode(node);
|
||||
}
|
||||
for (const [sourceFile] of this._changes) {
|
||||
const importsToAdd = newImports.get(sourceFile.fileName);
|
||||
if (!importsToAdd) {
|
||||
continue;
|
||||
}
|
||||
const importLines = [];
|
||||
let lastImport = null;
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (ts.isImportDeclaration(statement)) {
|
||||
lastImport = statement;
|
||||
}
|
||||
}
|
||||
for (const decl of importsToAdd) {
|
||||
importLines.push(this._printer.printNode(ts.EmitHint.Unspecified, decl, sourceFile));
|
||||
}
|
||||
this.insertText(sourceFile, lastImport ? lastImport.getEnd() : 0, (lastImport ? '\n' : '') + importLines.join('\n'));
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Normalizes a path to use posix separators. */
|
||||
function normalizePath(path) {
|
||||
return path.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
function parseTsconfigFile(tsconfigPath, basePath) {
|
||||
const { config } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
|
||||
const parseConfigHost = {
|
||||
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
|
||||
fileExists: ts.sys.fileExists,
|
||||
readDirectory: ts.sys.readDirectory,
|
||||
readFile: ts.sys.readFile,
|
||||
};
|
||||
// Throw if incorrect arguments are passed to this function. Passing relative base paths
|
||||
// results in root directories not being resolved and in later type checking runtime errors.
|
||||
// More details can be found here: https://github.com/microsoft/TypeScript/issues/37731.
|
||||
if (!path__namespace.isAbsolute(basePath)) {
|
||||
throw Error('Unexpected relative base path has been specified.');
|
||||
}
|
||||
return ts.parseJsonConfigFileContent(config, parseConfigHost, basePath, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a TypeScript program instance for a TypeScript project within
|
||||
* the virtual file system tree.
|
||||
* @param tree Virtual file system tree that contains the source files.
|
||||
* @param tsconfigPath Virtual file system path that resolves to the TypeScript project.
|
||||
* @param basePath Base path for the virtual file system tree.
|
||||
* @param fakeFileRead Optional file reader function. Can be used to overwrite files in
|
||||
* the TypeScript program, or to add in-memory files (e.g. to add global types).
|
||||
* @param additionalFiles Additional file paths that should be added to the program.
|
||||
*/
|
||||
function createMigrationProgram(tree, tsconfigPath, basePath, fakeFileRead, additionalFiles) {
|
||||
const { rootNames, options, host } = createProgramOptions(tree, tsconfigPath, basePath, fakeFileRead);
|
||||
return ts.createProgram(rootNames, options, host);
|
||||
}
|
||||
/**
|
||||
* Creates the options necessary to instantiate a TypeScript program.
|
||||
* @param tree Virtual file system tree that contains the source files.
|
||||
* @param tsconfigPath Virtual file system path that resolves to the TypeScript project.
|
||||
* @param basePath Base path for the virtual file system tree.
|
||||
* @param fakeFileRead Optional file reader function. Can be used to overwrite files in
|
||||
* the TypeScript program, or to add in-memory files (e.g. to add global types).
|
||||
* @param additionalFiles Additional file paths that should be added to the program.
|
||||
* @param optionOverrides Overrides of the parsed compiler options.
|
||||
*/
|
||||
function createProgramOptions(tree, tsconfigPath, basePath, fakeFileRead, additionalFiles, optionOverrides) {
|
||||
// Resolve the tsconfig path to an absolute path. This is needed as TypeScript otherwise
|
||||
// is not able to resolve root directories in the given tsconfig. More details can be found
|
||||
// in the following issue: https://github.com/microsoft/TypeScript/issues/37731.
|
||||
tsconfigPath = path.resolve(basePath, tsconfigPath);
|
||||
const parsed = parseTsconfigFile(tsconfigPath, path.dirname(tsconfigPath));
|
||||
const options = optionOverrides ? { ...parsed.options, ...optionOverrides } : parsed.options;
|
||||
const host = createMigrationCompilerHost(tree, options, basePath, fakeFileRead);
|
||||
return { rootNames: parsed.fileNames.concat([]), options, host };
|
||||
}
|
||||
function createMigrationCompilerHost(tree, options, basePath, fakeRead) {
|
||||
const host = ts.createCompilerHost(options, true);
|
||||
const defaultReadFile = host.readFile;
|
||||
// We need to overwrite the host "readFile" method, as we want the TypeScript
|
||||
// program to be based on the file contents in the virtual file tree. Otherwise
|
||||
// if we run multiple migrations we might have intersecting changes and
|
||||
// source files.
|
||||
host.readFile = (fileName) => {
|
||||
const treeRelativePath = path.relative(basePath, fileName);
|
||||
let result = fakeRead?.(treeRelativePath);
|
||||
if (typeof result !== 'string') {
|
||||
// If the relative path resolved to somewhere outside of the tree, fall back to
|
||||
// TypeScript's default file reading function since the `tree` will throw an error.
|
||||
result = treeRelativePath.startsWith('..')
|
||||
? defaultReadFile.call(host, fileName)
|
||||
: tree.read(treeRelativePath)?.toString();
|
||||
}
|
||||
// Strip BOM as otherwise TSC methods (Ex: getWidth) will return an offset,
|
||||
// which breaks the CLI UpdateRecorder.
|
||||
// See: https://github.com/angular/angular/pull/30719
|
||||
return typeof result === 'string' ? result.replace(/^\uFEFF/, '') : undefined;
|
||||
};
|
||||
return host;
|
||||
}
|
||||
/**
|
||||
* Checks whether a file can be migrate by our automated migrations.
|
||||
* @param basePath Absolute path to the project.
|
||||
* @param sourceFile File being checked.
|
||||
* @param program Program that includes the source file.
|
||||
*/
|
||||
function canMigrateFile(basePath, sourceFile, program) {
|
||||
// We shouldn't migrate .d.ts files, files from an external library or type checking files.
|
||||
if (sourceFile.fileName.endsWith('.ngtypecheck.ts') ||
|
||||
sourceFile.isDeclarationFile ||
|
||||
program.isSourceFileFromExternalLibrary(sourceFile)) {
|
||||
return false;
|
||||
}
|
||||
// Our migrations are set up to create a `Program` from the project's tsconfig and to migrate all
|
||||
// the files within the program. This can include files that are outside of the Angular CLI
|
||||
// project. We can't migrate files outside of the project, because our file system interactions
|
||||
// go through the CLI's `Tree` which assumes that all files are within the project. See:
|
||||
// https://github.com/angular/angular-cli/blob/0b0961c9c233a825b6e4bb59ab7f0790f9b14676/packages/angular_devkit/schematics/src/tree/host-tree.ts#L131
|
||||
return !path.relative(basePath, sourceFile.fileName).startsWith('..');
|
||||
}
|
||||
|
||||
exports.ChangeTracker = ChangeTracker;
|
||||
exports.canMigrateFile = canMigrateFile;
|
||||
exports.createMigrationProgram = createMigrationProgram;
|
||||
exports.createProgramOptions = createProgramOptions;
|
||||
exports.normalizePath = normalizePath;
|
||||
+1930
File diff suppressed because it is too large
Load Diff
+110
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
|
||||
/** Gets import information about the specified identifier by using the Type checker. */
|
||||
function getImportOfIdentifier(typeChecker, node) {
|
||||
const symbol = typeChecker.getSymbolAtLocation(node);
|
||||
if (!symbol || symbol.declarations === undefined || !symbol.declarations.length) {
|
||||
return null;
|
||||
}
|
||||
const decl = symbol.declarations[0];
|
||||
if (!ts.isImportSpecifier(decl)) {
|
||||
return null;
|
||||
}
|
||||
const importDecl = decl.parent.parent.parent;
|
||||
if (!ts.isImportDeclaration(importDecl) || !ts.isStringLiteral(importDecl.moduleSpecifier)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
// Handles aliased imports: e.g. "import {Component as myComp} from ...";
|
||||
name: decl.propertyName ? decl.propertyName.text : decl.name.text,
|
||||
importModule: importDecl.moduleSpecifier.text,
|
||||
node: importDecl,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Gets a top-level import specifier with a specific name that is imported from a particular module.
|
||||
* E.g. given a file that looks like:
|
||||
*
|
||||
* ```ts
|
||||
* import { Component, Directive } from '@angular/core';
|
||||
* import { Foo } from './foo';
|
||||
* ```
|
||||
*
|
||||
* Calling `getImportSpecifier(sourceFile, '@angular/core', 'Directive')` will yield the node
|
||||
* referring to `Directive` in the top import.
|
||||
*
|
||||
* @param sourceFile File in which to look for imports.
|
||||
* @param moduleName Name of the import's module.
|
||||
* @param specifierName Original name of the specifier to look for. Aliases will be resolved to
|
||||
* their original name.
|
||||
*/
|
||||
function getImportSpecifier(sourceFile, moduleName, specifierName) {
|
||||
return getImportSpecifiers(sourceFile, moduleName, specifierName)[0] ?? null;
|
||||
}
|
||||
/**
|
||||
* Note: returns only matching imports specifiers,
|
||||
* Unmatched imports will be ignored (you won't get undefined), but a shorter array.
|
||||
*/
|
||||
function getImportSpecifiers(sourceFile, moduleName, specifierOrSpecifiers) {
|
||||
const matches = [];
|
||||
for (const node of sourceFile.statements) {
|
||||
if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) {
|
||||
continue;
|
||||
}
|
||||
const namedBindings = node.importClause?.namedBindings;
|
||||
const isMatch = typeof moduleName === 'string'
|
||||
? node.moduleSpecifier.text === moduleName
|
||||
: moduleName.test(node.moduleSpecifier.text);
|
||||
if (!isMatch || !namedBindings || !ts.isNamedImports(namedBindings)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof specifierOrSpecifiers === 'string') {
|
||||
const match = findImportSpecifier(namedBindings.elements, specifierOrSpecifiers);
|
||||
if (match) {
|
||||
matches.push(match);
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (const specifierName of specifierOrSpecifiers) {
|
||||
const match = findImportSpecifier(namedBindings.elements, specifierName);
|
||||
if (match) {
|
||||
matches.push(match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
function getNamedImports(sourceFile, moduleName) {
|
||||
for (const node of sourceFile.statements) {
|
||||
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
||||
const isMatch = node.moduleSpecifier.text === moduleName
|
||||
;
|
||||
const namedBindings = node.importClause?.namedBindings;
|
||||
if (isMatch && namedBindings && ts.isNamedImports(namedBindings)) {
|
||||
return namedBindings;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Finds an import specifier with a particular name. */
|
||||
function findImportSpecifier(nodes, specifierName) {
|
||||
return nodes.find((element) => {
|
||||
const { name, propertyName } = element;
|
||||
return propertyName ? propertyName.text === specifierName : name.text === specifierName;
|
||||
});
|
||||
}
|
||||
|
||||
exports.getImportOfIdentifier = getImportOfIdentifier;
|
||||
exports.getImportSpecifier = getImportSpecifier;
|
||||
exports.getImportSpecifiers = getImportSpecifiers;
|
||||
exports.getNamedImports = getNamedImports;
|
||||
+998
@@ -0,0 +1,998 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
var compilerCli = require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var compiler = require('@angular/compiler');
|
||||
|
||||
function getMemberName(member) {
|
||||
if (member.name === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (ts.isIdentifier(member.name) || ts.isStringLiteralLike(member.name)) {
|
||||
return member.name.text;
|
||||
}
|
||||
if (ts.isPrivateIdentifier(member.name)) {
|
||||
return `#${member.name.text}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Checks whether the given node can be an `@Input()` declaration node. */
|
||||
function isInputContainerNode(node) {
|
||||
return (((ts.isAccessor(node) && ts.isClassDeclaration(node.parent)) ||
|
||||
ts.isPropertyDeclaration(node)) &&
|
||||
getMemberName(node) !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects `query(By.directive(T)).componentInstance` patterns and enhances
|
||||
* them with information of `T`. This is important because `.componentInstance`
|
||||
* is currently typed as `any` and may cause runtime test failures after input
|
||||
* migrations then.
|
||||
*
|
||||
* The reference resolution pass leverages information from this pattern
|
||||
* recognizer.
|
||||
*/
|
||||
class DebugElementComponentInstance {
|
||||
checker;
|
||||
cache = new WeakMap();
|
||||
constructor(checker) {
|
||||
this.checker = checker;
|
||||
}
|
||||
detect(node) {
|
||||
if (this.cache.has(node)) {
|
||||
return this.cache.get(node);
|
||||
}
|
||||
if (!ts.isPropertyAccessExpression(node)) {
|
||||
return null;
|
||||
}
|
||||
// Check for `<>.componentInstance`.
|
||||
if (!ts.isIdentifier(node.name) || node.name.text !== 'componentInstance') {
|
||||
return null;
|
||||
}
|
||||
// Check for `<>.query(..).<>`.
|
||||
if (!ts.isCallExpression(node.expression) ||
|
||||
!ts.isPropertyAccessExpression(node.expression.expression) ||
|
||||
!ts.isIdentifier(node.expression.expression.name) ||
|
||||
node.expression.expression.name.text !== 'query') {
|
||||
return null;
|
||||
}
|
||||
const queryCall = node.expression;
|
||||
if (queryCall.arguments.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
const queryArg = queryCall.arguments[0];
|
||||
let typeExpr;
|
||||
if (ts.isCallExpression(queryArg) &&
|
||||
queryArg.arguments.length === 1 &&
|
||||
ts.isIdentifier(queryArg.arguments[0])) {
|
||||
// Detect references, like: `query(By.directive(T))`.
|
||||
typeExpr = queryArg.arguments[0];
|
||||
}
|
||||
else if (ts.isIdentifier(queryArg)) {
|
||||
// Detect references, like: `harness.query(T)`.
|
||||
typeExpr = queryArg;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
const symbol = this.checker.getSymbolAtLocation(typeExpr);
|
||||
if (symbol?.valueDeclaration === undefined ||
|
||||
!ts.isClassDeclaration(symbol?.valueDeclaration)) {
|
||||
// Cache this as we use the expensive type checker.
|
||||
this.cache.set(node, null);
|
||||
return null;
|
||||
}
|
||||
const type = this.checker.getTypeAtLocation(symbol.valueDeclaration);
|
||||
this.cache.set(node, type);
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognizes `Partial<T>` instances in Catalyst tests. Those type queries
|
||||
* are likely used for typing property initialization values for the given class `T`
|
||||
* and we have a few scenarios:
|
||||
*
|
||||
* 1. The API does not unwrap signal inputs. In which case, the values are likely no
|
||||
* longer assignable to an `InputSignal`.
|
||||
* 2. The API does unwrap signal inputs, in which case we need to unwrap the `Partial`
|
||||
* because the values are raw initial values, like they were before.
|
||||
*
|
||||
* We can enable this heuristic when we detect Catalyst as we know it supports unwrapping.
|
||||
*/
|
||||
class PartialDirectiveTypeInCatalystTests {
|
||||
checker;
|
||||
knownFields;
|
||||
constructor(checker, knownFields) {
|
||||
this.checker = checker;
|
||||
this.knownFields = knownFields;
|
||||
}
|
||||
detect(node) {
|
||||
// Detect `Partial<...>`
|
||||
if (!ts.isTypeReferenceNode(node) ||
|
||||
!ts.isIdentifier(node.typeName) ||
|
||||
node.typeName.text !== 'Partial') {
|
||||
return null;
|
||||
}
|
||||
// Ignore if the source file doesn't reference Catalyst.
|
||||
if (!node.getSourceFile().text.includes('angular2/testing/catalyst')) {
|
||||
return null;
|
||||
}
|
||||
// Extract T of `Partial<T>`.
|
||||
const cmpTypeArg = node.typeArguments?.[0];
|
||||
if (!cmpTypeArg ||
|
||||
!ts.isTypeReferenceNode(cmpTypeArg) ||
|
||||
!ts.isIdentifier(cmpTypeArg.typeName)) {
|
||||
return null;
|
||||
}
|
||||
const cmpType = cmpTypeArg.typeName;
|
||||
const symbol = this.checker.getSymbolAtLocation(cmpType);
|
||||
// Note: Technically the class might be derived of an input-containing class,
|
||||
// but this is out of scope for now. We can expand if we see it's a common case.
|
||||
if (symbol?.valueDeclaration === undefined ||
|
||||
!ts.isClassDeclaration(symbol.valueDeclaration) ||
|
||||
!this.knownFields.shouldTrackClassReference(symbol.valueDeclaration)) {
|
||||
return null;
|
||||
}
|
||||
return { referenceNode: node, targetClass: symbol.valueDeclaration };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to look up the given property access chain using
|
||||
* the type checker.
|
||||
*
|
||||
* Notably this is not as safe as using the type checker directly to
|
||||
* retrieve symbols of a given identifier, but in some cases this is
|
||||
* a necessary approach to compensate e.g. for a lack of TCB information
|
||||
* when processing Angular templates.
|
||||
*
|
||||
* The path is a list of properties to be accessed sequentially on the
|
||||
* given type.
|
||||
*/
|
||||
function lookupPropertyAccess(checker, type, path, options = {}) {
|
||||
let symbol = null;
|
||||
for (const propName of path) {
|
||||
// Note: We support assuming `NonNullable` for the pathl This is necessary
|
||||
// in some situations as otherwise the lookups would fail to resolve the target
|
||||
// symbol just because of e.g. a ternary. This is used in the signal input migration
|
||||
// for host bindings.
|
||||
type = options.ignoreNullability ? type.getNonNullableType() : type;
|
||||
const propSymbol = type.getProperty(propName);
|
||||
if (propSymbol === undefined) {
|
||||
return null;
|
||||
}
|
||||
symbol = propSymbol;
|
||||
type = checker.getTypeOfSymbol(propSymbol);
|
||||
}
|
||||
if (symbol === null) {
|
||||
return null;
|
||||
}
|
||||
return { symbol, type };
|
||||
}
|
||||
|
||||
/**
|
||||
* AST visitor that iterates through a template and finds all
|
||||
* input references.
|
||||
*
|
||||
* This resolution is important to be able to migrate references to inputs
|
||||
* that will be migrated to signal inputs.
|
||||
*/
|
||||
class TemplateReferenceVisitor extends compiler.TmplAstRecursiveVisitor {
|
||||
result = [];
|
||||
/**
|
||||
* Whether we are currently descending into HTML AST nodes
|
||||
* where all bound attributes are considered potentially narrowing.
|
||||
*
|
||||
* Keeps track of all referenced inputs in such attribute expressions.
|
||||
*/
|
||||
templateAttributeReferencedFields = null;
|
||||
expressionVisitor;
|
||||
seenKnownFieldsCount = new Map();
|
||||
constructor(typeChecker, templateTypeChecker, componentClass, knownFields, fieldNamesToConsiderForReferenceLookup) {
|
||||
super();
|
||||
this.expressionVisitor = new TemplateExpressionReferenceVisitor(typeChecker, templateTypeChecker, componentClass, knownFields, fieldNamesToConsiderForReferenceLookup);
|
||||
}
|
||||
checkExpressionForReferencedFields(activeNode, expressionNode) {
|
||||
const referencedFields = this.expressionVisitor.checkTemplateExpression(activeNode, expressionNode);
|
||||
// Add all references to the overall visitor result.
|
||||
this.result.push(...referencedFields);
|
||||
// Count usages of seen input references. We'll use this to make decisions
|
||||
// based on whether inputs are potentially narrowed or not.
|
||||
for (const input of referencedFields) {
|
||||
this.seenKnownFieldsCount.set(input.targetField.key, (this.seenKnownFieldsCount.get(input.targetField.key) ?? 0) + 1);
|
||||
}
|
||||
return referencedFields;
|
||||
}
|
||||
descendAndCheckForNarrowedSimilarReferences(potentiallyNarrowedInputs, descend) {
|
||||
const inputs = potentiallyNarrowedInputs.map((i) => ({
|
||||
ref: i,
|
||||
key: i.targetField.key,
|
||||
pastCount: this.seenKnownFieldsCount.get(i.targetField.key) ?? 0,
|
||||
}));
|
||||
descend();
|
||||
for (const input of inputs) {
|
||||
// Input was referenced inside a narrowable spot, and is used in child nodes.
|
||||
// This is a sign for the input to be narrowed. Mark it as such.
|
||||
if ((this.seenKnownFieldsCount.get(input.key) ?? 0) > input.pastCount) {
|
||||
input.ref.isLikelyNarrowed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
visitTemplate(template) {
|
||||
// Note: We assume all bound expressions for templates may be subject
|
||||
// to TCB narrowing. This is relevant for now until we support narrowing
|
||||
// of signal calls in templates.
|
||||
// TODO: Remove with: https://github.com/angular/angular/pull/55456.
|
||||
this.templateAttributeReferencedFields = [];
|
||||
compiler.tmplAstVisitAll(this, template.attributes);
|
||||
compiler.tmplAstVisitAll(this, template.templateAttrs);
|
||||
// If we are dealing with a microsyntax template, do not check
|
||||
// inputs and outputs as those are already passed to the children.
|
||||
// Template attributes may contain relevant expressions though.
|
||||
if (template.tagName === 'ng-template') {
|
||||
compiler.tmplAstVisitAll(this, template.inputs);
|
||||
compiler.tmplAstVisitAll(this, template.outputs);
|
||||
}
|
||||
const referencedInputs = this.templateAttributeReferencedFields;
|
||||
this.templateAttributeReferencedFields = null;
|
||||
this.descendAndCheckForNarrowedSimilarReferences(referencedInputs, () => {
|
||||
compiler.tmplAstVisitAll(this, template.children);
|
||||
compiler.tmplAstVisitAll(this, template.references);
|
||||
compiler.tmplAstVisitAll(this, template.variables);
|
||||
});
|
||||
}
|
||||
visitIfBlockBranch(block) {
|
||||
if (block.expression) {
|
||||
const referencedFields = this.checkExpressionForReferencedFields(block, block.expression);
|
||||
this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => {
|
||||
super.visitIfBlockBranch(block);
|
||||
});
|
||||
}
|
||||
else {
|
||||
super.visitIfBlockBranch(block);
|
||||
}
|
||||
}
|
||||
visitForLoopBlock(block) {
|
||||
this.checkExpressionForReferencedFields(block, block.expression);
|
||||
this.checkExpressionForReferencedFields(block, block.trackBy);
|
||||
super.visitForLoopBlock(block);
|
||||
}
|
||||
visitSwitchBlock(block) {
|
||||
const referencedFields = this.checkExpressionForReferencedFields(block, block.expression);
|
||||
this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => {
|
||||
super.visitSwitchBlock(block);
|
||||
});
|
||||
}
|
||||
visitSwitchBlockCase(block) {
|
||||
if (block.expression) {
|
||||
const referencedFields = this.checkExpressionForReferencedFields(block, block.expression);
|
||||
this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => {
|
||||
super.visitSwitchBlockCase(block);
|
||||
});
|
||||
}
|
||||
else {
|
||||
super.visitSwitchBlockCase(block);
|
||||
}
|
||||
}
|
||||
visitDeferredBlock(deferred) {
|
||||
if (deferred.triggers.when) {
|
||||
this.checkExpressionForReferencedFields(deferred, deferred.triggers.when.value);
|
||||
}
|
||||
if (deferred.prefetchTriggers.when) {
|
||||
this.checkExpressionForReferencedFields(deferred, deferred.prefetchTriggers.when.value);
|
||||
}
|
||||
super.visitDeferredBlock(deferred);
|
||||
}
|
||||
visitBoundText(text) {
|
||||
this.checkExpressionForReferencedFields(text, text.value);
|
||||
}
|
||||
visitBoundEvent(attribute) {
|
||||
this.checkExpressionForReferencedFields(attribute, attribute.handler);
|
||||
}
|
||||
visitBoundAttribute(attribute) {
|
||||
const referencedFields = this.checkExpressionForReferencedFields(attribute, attribute.value);
|
||||
// Attributes inside templates are potentially "narrowed" and hence we
|
||||
// keep track of all referenced inputs to see if they actually are.
|
||||
if (this.templateAttributeReferencedFields !== null) {
|
||||
this.templateAttributeReferencedFields.push(...referencedFields);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Expression AST visitor that checks whether a given expression references
|
||||
* a known `@Input()`.
|
||||
*
|
||||
* This resolution is important to be able to migrate references to inputs
|
||||
* that will be migrated to signal inputs.
|
||||
*/
|
||||
class TemplateExpressionReferenceVisitor extends compiler.RecursiveAstVisitor {
|
||||
typeChecker;
|
||||
templateTypeChecker;
|
||||
componentClass;
|
||||
knownFields;
|
||||
fieldNamesToConsiderForReferenceLookup;
|
||||
activeTmplAstNode = null;
|
||||
detectedInputReferences = [];
|
||||
isInsideObjectShorthandExpression = false;
|
||||
insideConditionalExpressionsWithReads = [];
|
||||
constructor(typeChecker, templateTypeChecker, componentClass, knownFields, fieldNamesToConsiderForReferenceLookup) {
|
||||
super();
|
||||
this.typeChecker = typeChecker;
|
||||
this.templateTypeChecker = templateTypeChecker;
|
||||
this.componentClass = componentClass;
|
||||
this.knownFields = knownFields;
|
||||
this.fieldNamesToConsiderForReferenceLookup = fieldNamesToConsiderForReferenceLookup;
|
||||
}
|
||||
/** Checks the given AST expression. */
|
||||
checkTemplateExpression(activeNode, expressionNode) {
|
||||
this.detectedInputReferences = [];
|
||||
this.activeTmplAstNode = activeNode;
|
||||
expressionNode.visit(this, []);
|
||||
return this.detectedInputReferences;
|
||||
}
|
||||
visit(ast, context) {
|
||||
super.visit(ast, [...context, ast]);
|
||||
}
|
||||
// Keep track when we are inside an object shorthand expression. This is
|
||||
// necessary as we need to expand the shorthand to invoke a potential new signal.
|
||||
// E.g. `{bla}` may be transformed to `{bla: bla()}`.
|
||||
visitLiteralMap(ast, context) {
|
||||
for (const [idx, key] of ast.keys.entries()) {
|
||||
this.isInsideObjectShorthandExpression =
|
||||
key.kind === 'property' && !!key.isShorthandInitialized;
|
||||
ast.values[idx].visit(this, context);
|
||||
this.isInsideObjectShorthandExpression = false;
|
||||
}
|
||||
}
|
||||
visitPropertyRead(ast, context) {
|
||||
this._inspectPropertyAccess(ast, false, context);
|
||||
super.visitPropertyRead(ast, context);
|
||||
}
|
||||
visitSafePropertyRead(ast, context) {
|
||||
this._inspectPropertyAccess(ast, false, context);
|
||||
super.visitPropertyRead(ast, context);
|
||||
}
|
||||
visitBinary(ast, context) {
|
||||
if (ast.operation === '=' && ast.left instanceof compiler.PropertyRead) {
|
||||
this._inspectPropertyAccess(ast.left, true, [...context, ast, ast.left]);
|
||||
}
|
||||
else {
|
||||
super.visitBinary(ast, context);
|
||||
}
|
||||
}
|
||||
visitConditional(ast, context) {
|
||||
this.visit(ast.condition, context);
|
||||
this.insideConditionalExpressionsWithReads.push(ast.condition);
|
||||
this.visit(ast.trueExp, context);
|
||||
this.visit(ast.falseExp, context);
|
||||
this.insideConditionalExpressionsWithReads.pop();
|
||||
}
|
||||
/**
|
||||
* Inspects the property access and attempts to resolve whether they access
|
||||
* a known field. If so, the result is captured.
|
||||
*/
|
||||
_inspectPropertyAccess(ast, isAssignment, astPath) {
|
||||
if (this.fieldNamesToConsiderForReferenceLookup !== null &&
|
||||
!this.fieldNamesToConsiderForReferenceLookup.has(ast.name)) {
|
||||
return;
|
||||
}
|
||||
const isWrite = !!(isAssignment ||
|
||||
(this.activeTmplAstNode && isTwoWayBindingNode(this.activeTmplAstNode)));
|
||||
this._checkAccessViaTemplateTypeCheckBlock(ast, isWrite, astPath) ||
|
||||
this._checkAccessViaOwningComponentClassType(ast, isWrite, astPath);
|
||||
}
|
||||
/**
|
||||
* Checks whether the node refers to an input using the TCB information.
|
||||
* Type check block may not exist for e.g. test components, so this can return `null`.
|
||||
*/
|
||||
_checkAccessViaTemplateTypeCheckBlock(ast, isWrite, astPath) {
|
||||
// There might be no template type checker. E.g. if we check host bindings.
|
||||
if (this.templateTypeChecker === null) {
|
||||
return false;
|
||||
}
|
||||
const symbol = this.templateTypeChecker.getSymbolOfNode(ast, this.componentClass);
|
||||
if (symbol?.kind !== migrations.SymbolKind.Expression || symbol.tsSymbol === null) {
|
||||
return false;
|
||||
}
|
||||
// Dangerous: Type checking symbol retrieval is a totally different `ts.Program`,
|
||||
// than the one where we analyzed `knownInputs`.
|
||||
// --> Find the input via its input id.
|
||||
const targetInput = this.knownFields.attemptRetrieveDescriptorFromSymbol(symbol.tsSymbol);
|
||||
if (targetInput === null) {
|
||||
return false;
|
||||
}
|
||||
this.detectedInputReferences.push({
|
||||
targetNode: targetInput.node,
|
||||
targetField: targetInput,
|
||||
read: ast,
|
||||
readAstPath: astPath,
|
||||
context: this.activeTmplAstNode,
|
||||
isLikelyNarrowed: this._isPartOfNarrowingTernary(ast),
|
||||
isObjectShorthandExpression: this.isInsideObjectShorthandExpression,
|
||||
isWrite,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Simple resolution checking whether the given AST refers to a known input.
|
||||
* This is a fallback for when there is no type checking information (e.g. in host bindings).
|
||||
*
|
||||
* It attempts to resolve references by traversing accesses of the "component class" type.
|
||||
* e.g. `this.bla` is resolved via `CompType#bla` and further.
|
||||
*/
|
||||
_checkAccessViaOwningComponentClassType(ast, isWrite, astPath) {
|
||||
// We might check host bindings, which can never point to template variables or local refs.
|
||||
const expressionTemplateTarget = this.templateTypeChecker === null
|
||||
? null
|
||||
: this.templateTypeChecker.getExpressionTarget(ast, this.componentClass);
|
||||
// Skip checking if:
|
||||
// - the reference resolves to a template variable or local ref. No way to resolve without TCB.
|
||||
// - the owning component does not have a name (should not happen technically).
|
||||
if (expressionTemplateTarget !== null || this.componentClass.name === undefined) {
|
||||
return;
|
||||
}
|
||||
const property = traverseReceiverAndLookupSymbol(ast, this.componentClass, this.typeChecker);
|
||||
if (property === null) {
|
||||
return;
|
||||
}
|
||||
const matchingTarget = this.knownFields.attemptRetrieveDescriptorFromSymbol(property);
|
||||
if (matchingTarget === null) {
|
||||
return;
|
||||
}
|
||||
this.detectedInputReferences.push({
|
||||
targetNode: matchingTarget.node,
|
||||
targetField: matchingTarget,
|
||||
read: ast,
|
||||
readAstPath: astPath,
|
||||
context: this.activeTmplAstNode,
|
||||
isLikelyNarrowed: this._isPartOfNarrowingTernary(ast),
|
||||
isObjectShorthandExpression: this.isInsideObjectShorthandExpression,
|
||||
isWrite,
|
||||
});
|
||||
}
|
||||
_isPartOfNarrowingTernary(read) {
|
||||
// Note: We do not safe check that the reads are fully matching 1:1. This is acceptable
|
||||
// as worst case we just skip an input from being migrated. This is very unlikely too.
|
||||
return this.insideConditionalExpressionsWithReads.some((r) => (r instanceof compiler.PropertyRead || r instanceof compiler.SafePropertyRead) && r.name === read.name);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Emulates an access to a given field using the TypeScript `ts.Type`
|
||||
* of the given class. The resolved symbol of the access is returned.
|
||||
*/
|
||||
function traverseReceiverAndLookupSymbol(readOrWrite, componentClass, checker) {
|
||||
const path = [readOrWrite.name];
|
||||
let node = readOrWrite;
|
||||
while (node.receiver instanceof compiler.PropertyRead) {
|
||||
node = node.receiver;
|
||||
path.unshift(node.name);
|
||||
}
|
||||
if (!(node.receiver instanceof compiler.ImplicitReceiver)) {
|
||||
return null;
|
||||
}
|
||||
const classType = checker.getTypeAtLocation(componentClass.name);
|
||||
return (lookupPropertyAccess(checker, classType, path, {
|
||||
// Necessary to avoid breaking the resolution if there is
|
||||
// some narrowing involved. E.g. `myClass ? myClass.input`.
|
||||
ignoreNullability: true,
|
||||
})?.symbol ?? null);
|
||||
}
|
||||
/** Whether the given node refers to a two-way binding AST node. */
|
||||
function isTwoWayBindingNode(node) {
|
||||
return ((node instanceof compiler.TmplAstBoundAttribute && node.type === compiler.BindingType.TwoWay) ||
|
||||
(node instanceof compiler.TmplAstBoundEvent && node.type === compiler.ParsedEventType.TwoWay));
|
||||
}
|
||||
|
||||
/** Possible types of references to known fields detected. */
|
||||
exports.ReferenceKind = void 0;
|
||||
(function (ReferenceKind) {
|
||||
ReferenceKind[ReferenceKind["InTemplate"] = 0] = "InTemplate";
|
||||
ReferenceKind[ReferenceKind["InHostBinding"] = 1] = "InHostBinding";
|
||||
ReferenceKind[ReferenceKind["TsReference"] = 2] = "TsReference";
|
||||
ReferenceKind[ReferenceKind["TsClassTypeReference"] = 3] = "TsClassTypeReference";
|
||||
})(exports.ReferenceKind || (exports.ReferenceKind = {}));
|
||||
/** Whether the given reference is a TypeScript reference. */
|
||||
function isTsReference(ref) {
|
||||
return ref.kind === exports.ReferenceKind.TsReference;
|
||||
}
|
||||
/** Whether the given reference is a template reference. */
|
||||
function isTemplateReference(ref) {
|
||||
return ref.kind === exports.ReferenceKind.InTemplate;
|
||||
}
|
||||
/** Whether the given reference is a host binding reference. */
|
||||
function isHostBindingReference(ref) {
|
||||
return ref.kind === exports.ReferenceKind.InHostBinding;
|
||||
}
|
||||
/**
|
||||
* Whether the given reference is a TypeScript `ts.Type` reference
|
||||
* to a class containing known fields.
|
||||
*/
|
||||
function isTsClassTypeReference(ref) {
|
||||
return ref.kind === exports.ReferenceKind.TsClassTypeReference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks host bindings of the given class and tracks all
|
||||
* references to inputs within bindings.
|
||||
*/
|
||||
function identifyHostBindingReferences(node, programInfo, checker, reflector, result, knownFields, fieldNamesToConsiderForReferenceLookup) {
|
||||
if (node.name === undefined) {
|
||||
return;
|
||||
}
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(node);
|
||||
if (decorators === null) {
|
||||
return;
|
||||
}
|
||||
const angularDecorators = migrations.getAngularDecorators(decorators, ['Directive', 'Component'],
|
||||
/* isAngularCore */ false);
|
||||
if (angularDecorators.length === 0) {
|
||||
return;
|
||||
}
|
||||
// Assume only one Angular decorator per class.
|
||||
const ngDecorator = angularDecorators[0];
|
||||
if (ngDecorator.args?.length !== 1) {
|
||||
return;
|
||||
}
|
||||
const metadataNode = migrations.unwrapExpression(ngDecorator.args[0]);
|
||||
if (!ts.isObjectLiteralExpression(metadataNode)) {
|
||||
return;
|
||||
}
|
||||
const metadata = migrations.reflectObjectLiteral(metadataNode);
|
||||
if (!metadata.has('host')) {
|
||||
return;
|
||||
}
|
||||
let hostField = migrations.unwrapExpression(metadata.get('host'));
|
||||
// Special-case in case host bindings are shared via a variable.
|
||||
// e.g. Material button shares host bindings as a constant in the same target.
|
||||
if (ts.isIdentifier(hostField)) {
|
||||
let symbol = checker.getSymbolAtLocation(hostField);
|
||||
// Plain identifier references can point to alias symbols (e.g. imports).
|
||||
if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias) {
|
||||
symbol = checker.getAliasedSymbol(symbol);
|
||||
}
|
||||
if (symbol !== undefined &&
|
||||
symbol.valueDeclaration !== undefined &&
|
||||
ts.isVariableDeclaration(symbol.valueDeclaration)) {
|
||||
hostField = symbol?.valueDeclaration.initializer;
|
||||
}
|
||||
}
|
||||
if (hostField === undefined || !ts.isObjectLiteralExpression(hostField)) {
|
||||
return;
|
||||
}
|
||||
const hostMap = migrations.reflectObjectLiteral(hostField);
|
||||
const expressionResult = [];
|
||||
const expressionVisitor = new TemplateExpressionReferenceVisitor(checker, null, node, knownFields, fieldNamesToConsiderForReferenceLookup);
|
||||
for (const [rawName, expression] of hostMap.entries()) {
|
||||
if (!ts.isStringLiteralLike(expression)) {
|
||||
continue;
|
||||
}
|
||||
const isEventBinding = rawName.startsWith('(');
|
||||
const isPropertyBinding = rawName.startsWith('[');
|
||||
// Only migrate property or event bindings.
|
||||
if (!isPropertyBinding && !isEventBinding) {
|
||||
continue;
|
||||
}
|
||||
const parser = compiler.makeBindingParser();
|
||||
const sourceSpan = new compiler.ParseSourceSpan(
|
||||
// Fake source span to keep parsing offsets zero-based.
|
||||
// We then later combine these with the expression TS node offsets.
|
||||
new compiler.ParseLocation({ content: '', url: '' }, 0, 0, 0), new compiler.ParseLocation({ content: '', url: '' }, 0, 0, 0));
|
||||
const name = rawName.substring(1, rawName.length - 1);
|
||||
let parsed = undefined;
|
||||
if (isEventBinding) {
|
||||
const result = [];
|
||||
parser.parseEvent(name.substring(1, name.length - 1), expression.text, false, sourceSpan, sourceSpan, [], result, sourceSpan);
|
||||
parsed = result[0].handler;
|
||||
}
|
||||
else {
|
||||
const result = [];
|
||||
parser.parsePropertyBinding(name, expression.text, true,
|
||||
/* isTwoWayBinding */ false, sourceSpan, 0, sourceSpan, [], result, sourceSpan);
|
||||
parsed = result[0].expression;
|
||||
}
|
||||
if (parsed != null) {
|
||||
expressionResult.push(...expressionVisitor.checkTemplateExpression(expression, parsed));
|
||||
}
|
||||
}
|
||||
for (const ref of expressionResult) {
|
||||
result.references.push({
|
||||
kind: exports.ReferenceKind.InHostBinding,
|
||||
from: {
|
||||
read: ref.read,
|
||||
readAstPath: ref.readAstPath,
|
||||
isObjectShorthandExpression: ref.isObjectShorthandExpression,
|
||||
isWrite: ref.isWrite,
|
||||
file: project_paths.projectFile(ref.context.getSourceFile(), programInfo),
|
||||
hostPropertyNode: ref.context,
|
||||
},
|
||||
target: ref.targetField,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to extract the `TemplateDefinition` for the given
|
||||
* class, if possible.
|
||||
*
|
||||
* The definition can then be used with the Angular compiler to
|
||||
* load/parse the given template.
|
||||
*/
|
||||
function attemptExtractTemplateDefinition(node, checker, reflector, resourceLoader) {
|
||||
const classDecorators = reflector.getDecoratorsOfDeclaration(node);
|
||||
const evaluator = new migrations.PartialEvaluator(reflector, checker, null);
|
||||
const ngDecorators = classDecorators !== null
|
||||
? migrations.getAngularDecorators(classDecorators, ['Component'], /* isAngularCore */ false)
|
||||
: [];
|
||||
if (ngDecorators.length === 0 ||
|
||||
ngDecorators[0].args === null ||
|
||||
ngDecorators[0].args.length === 0 ||
|
||||
!ts.isObjectLiteralExpression(ngDecorators[0].args[0])) {
|
||||
return null;
|
||||
}
|
||||
const properties = migrations.reflectObjectLiteral(ngDecorators[0].args[0]);
|
||||
const templateProp = properties.get('template');
|
||||
const templateUrlProp = properties.get('templateUrl');
|
||||
const containingFile = node.getSourceFile().fileName;
|
||||
// inline template.
|
||||
if (templateProp !== undefined) {
|
||||
const templateStr = evaluator.evaluate(templateProp);
|
||||
if (typeof templateStr === 'string') {
|
||||
return {
|
||||
isInline: true,
|
||||
expression: templateProp,
|
||||
preserveWhitespaces: false,
|
||||
resolvedTemplateUrl: containingFile,
|
||||
templateUrl: containingFile,
|
||||
};
|
||||
}
|
||||
}
|
||||
try {
|
||||
// external template.
|
||||
if (templateUrlProp !== undefined) {
|
||||
const templateUrl = evaluator.evaluate(templateUrlProp);
|
||||
if (typeof templateUrl === 'string') {
|
||||
return {
|
||||
isInline: false,
|
||||
preserveWhitespaces: false,
|
||||
templateUrlExpression: templateUrlProp,
|
||||
templateUrl,
|
||||
resolvedTemplateUrl: resourceLoader.resolve(templateUrl, containingFile),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`Could not parse external template: ${e}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given class has an Angular template, and resolves
|
||||
* all of the references to inputs.
|
||||
*/
|
||||
function identifyTemplateReferences(programInfo, node, reflector, checker, evaluator, templateTypeChecker, resourceLoader, options, result, knownFields, fieldNamesToConsiderForReferenceLookup) {
|
||||
const template = templateTypeChecker.getTemplate(node, compilerCli.OptimizeFor.WholeProgram) ??
|
||||
// If there is no template registered in the TCB or compiler, the template may
|
||||
// be skipped due to an explicit `jit: true` setting. We try to detect this case
|
||||
// and parse the template manually.
|
||||
extractTemplateWithoutCompilerAnalysis(node, checker, reflector, resourceLoader, evaluator, options);
|
||||
if (template !== null) {
|
||||
const visitor = new TemplateReferenceVisitor(checker, templateTypeChecker, node, knownFields, fieldNamesToConsiderForReferenceLookup);
|
||||
template.forEach((node) => node.visit(visitor));
|
||||
for (const res of visitor.result) {
|
||||
const templateFilePath = res.context.sourceSpan.start.file.url;
|
||||
// Templates without an URL are non-mappable artifacts of e.g.
|
||||
// string concatenated templates. See the `indirect` template
|
||||
// source mapping concept in the compiler. We skip such references
|
||||
// as those cannot be migrated, but print an error for now.
|
||||
if (templateFilePath === '') {
|
||||
// TODO: Incorporate a TODO potentially.
|
||||
console.error(`Found reference to field ${res.targetField.key} that cannot be ` +
|
||||
`migrated because the template cannot be parsed with source map information ` +
|
||||
`(in file: ${node.getSourceFile().fileName}).`);
|
||||
continue;
|
||||
}
|
||||
result.references.push({
|
||||
kind: exports.ReferenceKind.InTemplate,
|
||||
from: {
|
||||
read: res.read,
|
||||
readAstPath: res.readAstPath,
|
||||
node: res.context,
|
||||
isObjectShorthandExpression: res.isObjectShorthandExpression,
|
||||
originatingTsFile: project_paths.projectFile(node.getSourceFile(), programInfo),
|
||||
templateFile: project_paths.projectFile(compilerCli.absoluteFrom(templateFilePath), programInfo),
|
||||
isLikelyPartOfNarrowing: res.isLikelyNarrowed,
|
||||
isWrite: res.isWrite,
|
||||
},
|
||||
target: res.targetField,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Attempts to extract a `@Component` template from the given class,
|
||||
* without relying on the `NgCompiler` program analysis.
|
||||
*
|
||||
* This is useful for JIT components using `jit: true` which were not
|
||||
* processed by the Angular compiler, but may still have templates that
|
||||
* contain references to inputs that we can resolve via the fallback
|
||||
* reference resolutions (that does not use the type check block).
|
||||
*/
|
||||
function extractTemplateWithoutCompilerAnalysis(node, checker, reflector, resourceLoader, evaluator, options) {
|
||||
if (node.name === undefined) {
|
||||
return null;
|
||||
}
|
||||
const tmplDef = attemptExtractTemplateDefinition(node, checker, reflector, resourceLoader);
|
||||
if (tmplDef === null) {
|
||||
return null;
|
||||
}
|
||||
return migrations.extractTemplate(node, tmplDef, evaluator, null, resourceLoader, {
|
||||
enableBlockSyntax: true,
|
||||
enableLetSyntax: true,
|
||||
usePoisonedData: true,
|
||||
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat !== false,
|
||||
i18nNormalizeLineEndingsInICUs: options.i18nNormalizeLineEndingsInICUs === true,
|
||||
enableSelectorless: false,
|
||||
}, migrations.CompilationMode.FULL).nodes;
|
||||
}
|
||||
|
||||
/** Gets the pattern and property name for a given binding element. */
|
||||
function resolveBindingElement(node) {
|
||||
const name = node.propertyName ?? node.name;
|
||||
// If we are discovering a non-analyzable element in the path, abort.
|
||||
if (!ts.isStringLiteralLike(name) && !ts.isIdentifier(name)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
pattern: node.parent,
|
||||
propertyName: name.text,
|
||||
};
|
||||
}
|
||||
/** Gets the declaration node of the given binding element. */
|
||||
function getBindingElementDeclaration(node) {
|
||||
while (true) {
|
||||
if (ts.isBindingElement(node.parent.parent)) {
|
||||
node = node.parent.parent;
|
||||
}
|
||||
else {
|
||||
return node.parent.parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands the given reference to its containing expression, capturing
|
||||
* the full context.
|
||||
*
|
||||
* E.g. `traverseAccess(ref<`bla`>)` may return `this.bla`
|
||||
* or `traverseAccess(ref<`bla`>)` may return `this.someObj.a.b.c.bla`.
|
||||
*
|
||||
* This helper is useful as we will replace the full access with a temporary
|
||||
* variable for narrowing. Replacing just the identifier is wrong.
|
||||
*/
|
||||
function traverseAccess(access) {
|
||||
if (ts.isPropertyAccessExpression(access.parent) && access.parent.name === access) {
|
||||
return access.parent;
|
||||
}
|
||||
else if (ts.isElementAccessExpression(access.parent) &&
|
||||
access.parent.argumentExpression === access) {
|
||||
return access.parent;
|
||||
}
|
||||
return access;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps the parent of the given node, if it's a
|
||||
* parenthesized expression or `as` expression.
|
||||
*/
|
||||
function unwrapParent(node) {
|
||||
if (ts.isParenthesizedExpression(node.parent)) {
|
||||
return unwrapParent(node.parent);
|
||||
}
|
||||
else if (ts.isAsExpression(node.parent)) {
|
||||
return unwrapParent(node.parent);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* List of binary operators that indicate a write operation.
|
||||
*
|
||||
* Useful for figuring out whether an expression assigns to
|
||||
* something or not.
|
||||
*/
|
||||
const writeBinaryOperators = [
|
||||
ts.SyntaxKind.EqualsToken,
|
||||
ts.SyntaxKind.BarBarEqualsToken,
|
||||
ts.SyntaxKind.BarEqualsToken,
|
||||
ts.SyntaxKind.AmpersandEqualsToken,
|
||||
ts.SyntaxKind.AmpersandAmpersandEqualsToken,
|
||||
ts.SyntaxKind.SlashEqualsToken,
|
||||
ts.SyntaxKind.MinusEqualsToken,
|
||||
ts.SyntaxKind.PlusEqualsToken,
|
||||
ts.SyntaxKind.CaretEqualsToken,
|
||||
ts.SyntaxKind.PercentEqualsToken,
|
||||
ts.SyntaxKind.AsteriskEqualsToken,
|
||||
ts.SyntaxKind.ExclamationEqualsToken,
|
||||
];
|
||||
|
||||
/**
|
||||
* Checks whether given TypeScript reference refers to an Angular input, and captures
|
||||
* the reference if possible.
|
||||
*
|
||||
* @param fieldNamesToConsiderForReferenceLookup List of field names that should be
|
||||
* respected when expensively looking up references to known fields.
|
||||
* May be null if all identifiers should be inspected.
|
||||
*/
|
||||
function identifyPotentialTypeScriptReference(node, programInfo, checker, knownFields, result, fieldNamesToConsiderForReferenceLookup, advisors) {
|
||||
// Skip all identifiers that never can point to a migrated field.
|
||||
// TODO: Capture these assumptions and performance optimizations in the design doc.
|
||||
if (fieldNamesToConsiderForReferenceLookup !== null &&
|
||||
!fieldNamesToConsiderForReferenceLookup.has(node.text)) {
|
||||
return;
|
||||
}
|
||||
let target = undefined;
|
||||
try {
|
||||
// Resolve binding elements to their declaration symbol.
|
||||
// Commonly inputs are accessed via object expansion. e.g. `const {input} = this;`.
|
||||
if (ts.isBindingElement(node.parent)) {
|
||||
// Skip binding elements that are using spread.
|
||||
if (node.parent.dotDotDotToken !== undefined) {
|
||||
return;
|
||||
}
|
||||
const bindingInfo = resolveBindingElement(node.parent);
|
||||
if (bindingInfo === null) {
|
||||
// The declaration could not be resolved. Skip analyzing this.
|
||||
return;
|
||||
}
|
||||
const bindingType = checker.getTypeAtLocation(bindingInfo.pattern);
|
||||
const resolved = lookupPropertyAccess(checker, bindingType, [bindingInfo.propertyName]);
|
||||
target = resolved?.symbol;
|
||||
}
|
||||
else {
|
||||
target = checker.getSymbolAtLocation(node);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error('Unexpected error while trying to resolve identifier reference:');
|
||||
console.error(e);
|
||||
// Gracefully skip analyzing. This can happen when e.g. a reference is named similar
|
||||
// to an input, but is dependant on `.d.ts` that is not necessarily available (clutz dts).
|
||||
return;
|
||||
}
|
||||
noTargetSymbolCheck: if (target === undefined) {
|
||||
if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) {
|
||||
const propAccessSymbol = checker.getSymbolAtLocation(node.parent.expression);
|
||||
if (propAccessSymbol !== undefined &&
|
||||
propAccessSymbol.valueDeclaration !== undefined &&
|
||||
ts.isVariableDeclaration(propAccessSymbol.valueDeclaration) &&
|
||||
propAccessSymbol.valueDeclaration.initializer !== undefined) {
|
||||
target = advisors.debugElComponentInstanceTracker
|
||||
.detect(propAccessSymbol.valueDeclaration.initializer)
|
||||
?.getProperty(node.text);
|
||||
// We found a target in the fallback path. Break out.
|
||||
if (target !== undefined) {
|
||||
break noTargetSymbolCheck;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let targetInput = knownFields.attemptRetrieveDescriptorFromSymbol(target);
|
||||
if (targetInput === null) {
|
||||
return;
|
||||
}
|
||||
const access = unwrapParent(traverseAccess(node));
|
||||
const accessParent = access.parent;
|
||||
const isWriteReference = ts.isBinaryExpression(accessParent) &&
|
||||
accessParent.left === access &&
|
||||
writeBinaryOperators.includes(accessParent.operatorToken.kind);
|
||||
// track accesses from source files to known fields.
|
||||
result.references.push({
|
||||
kind: exports.ReferenceKind.TsReference,
|
||||
from: {
|
||||
node,
|
||||
file: project_paths.projectFile(node.getSourceFile(), programInfo),
|
||||
isWrite: isWriteReference,
|
||||
isPartOfElementBinding: ts.isBindingElement(node.parent),
|
||||
},
|
||||
target: targetInput,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase where we iterate through all source file references and
|
||||
* detect references to known fields (e.g. commonly inputs).
|
||||
*
|
||||
* This is useful, for example in the signal input migration whe
|
||||
* references need to be migrated to unwrap signals, given that
|
||||
* their target properties is no longer holding a raw value, but
|
||||
* instead an `InputSignal`.
|
||||
*
|
||||
* This phase detects references in all types of locations:
|
||||
* - TS source files
|
||||
* - Angular templates (inline or external)
|
||||
* - Host binding expressions.
|
||||
*/
|
||||
function createFindAllSourceFileReferencesVisitor(programInfo, checker, reflector, resourceLoader, evaluator, templateTypeChecker, knownFields, fieldNamesToConsiderForReferenceLookup, result) {
|
||||
const debugElComponentInstanceTracker = new DebugElementComponentInstance(checker);
|
||||
const partialDirectiveCatalystTracker = new PartialDirectiveTypeInCatalystTests(checker, knownFields);
|
||||
const perfCounters = {
|
||||
template: 0,
|
||||
hostBindings: 0,
|
||||
tsReferences: 0,
|
||||
tsTypes: 0,
|
||||
};
|
||||
// Schematic NodeJS execution may not have `global.performance` defined.
|
||||
const currentTimeInMs = () => typeof global.performance !== 'undefined' ? global.performance.now() : Date.now();
|
||||
const visitor = (node) => {
|
||||
let lastTime = currentTimeInMs();
|
||||
// Note: If there is no template type checker and resource loader, we aren't processing
|
||||
// an Angular program, and can skip template detection.
|
||||
if (ts.isClassDeclaration(node) && templateTypeChecker !== null && resourceLoader !== null) {
|
||||
identifyTemplateReferences(programInfo, node, reflector, checker, evaluator, templateTypeChecker, resourceLoader, programInfo.userOptions, result, knownFields, fieldNamesToConsiderForReferenceLookup);
|
||||
perfCounters.template += (currentTimeInMs() - lastTime) / 1000;
|
||||
lastTime = currentTimeInMs();
|
||||
identifyHostBindingReferences(node, programInfo, checker, reflector, result, knownFields, fieldNamesToConsiderForReferenceLookup);
|
||||
perfCounters.hostBindings += (currentTimeInMs() - lastTime) / 1000;
|
||||
lastTime = currentTimeInMs();
|
||||
}
|
||||
lastTime = currentTimeInMs();
|
||||
// find references, but do not capture input declarations itself.
|
||||
if (ts.isIdentifier(node) &&
|
||||
!(isInputContainerNode(node.parent) && node.parent.name === node)) {
|
||||
identifyPotentialTypeScriptReference(node, programInfo, checker, knownFields, result, fieldNamesToConsiderForReferenceLookup, {
|
||||
debugElComponentInstanceTracker,
|
||||
});
|
||||
}
|
||||
perfCounters.tsReferences += (currentTimeInMs() - lastTime) / 1000;
|
||||
lastTime = currentTimeInMs();
|
||||
// Detect `Partial<T>` references.
|
||||
// Those are relevant to be tracked as they may be updated in Catalyst to
|
||||
// unwrap signal inputs. Commonly people use `Partial` in Catalyst to type
|
||||
// some "component initial values".
|
||||
const partialDirectiveInCatalyst = partialDirectiveCatalystTracker.detect(node);
|
||||
if (partialDirectiveInCatalyst !== null) {
|
||||
result.references.push({
|
||||
kind: exports.ReferenceKind.TsClassTypeReference,
|
||||
from: {
|
||||
file: project_paths.projectFile(partialDirectiveInCatalyst.referenceNode.getSourceFile(), programInfo),
|
||||
node: partialDirectiveInCatalyst.referenceNode,
|
||||
},
|
||||
isPartialReference: true,
|
||||
isPartOfCatalystFile: true,
|
||||
target: partialDirectiveInCatalyst.targetClass,
|
||||
});
|
||||
}
|
||||
perfCounters.tsTypes += (currentTimeInMs() - lastTime) / 1000;
|
||||
};
|
||||
return {
|
||||
visitor,
|
||||
debugPrintMetrics: () => {
|
||||
console.info('Source file analysis performance', perfCounters);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
exports.createFindAllSourceFileReferencesVisitor = createFindAllSourceFileReferencesVisitor;
|
||||
exports.getBindingElementDeclaration = getBindingElementDeclaration;
|
||||
exports.getMemberName = getMemberName;
|
||||
exports.isHostBindingReference = isHostBindingReference;
|
||||
exports.isInputContainerNode = isInputContainerNode;
|
||||
exports.isTemplateReference = isTemplateReference;
|
||||
exports.isTsClassTypeReference = isTsClassTypeReference;
|
||||
exports.isTsReference = isTsReference;
|
||||
exports.traverseAccess = traverseAccess;
|
||||
exports.unwrapParent = unwrapParent;
|
||||
+1364
File diff suppressed because it is too large
Load Diff
+30
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Gets the leading line whitespace of a given node.
|
||||
*
|
||||
* Useful for inserting e.g. TODOs without breaking indentation.
|
||||
*/
|
||||
function getLeadingLineWhitespaceOfNode(node) {
|
||||
const fullText = node.getFullText().substring(0, node.getStart() - node.getFullStart());
|
||||
let result = '';
|
||||
for (let i = fullText.length - 1; i > -1; i--) {
|
||||
// Note: LF line endings are `\n` while CRLF are `\r\n`. This logic should cover both, because
|
||||
// we start from the beginning of the node and go backwards so will always hit `\n` first.
|
||||
if (fullText[i] !== '\n') {
|
||||
result = fullText[i] + result;
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
exports.getLeadingLineWhitespaceOfNode = getLeadingLineWhitespaceOfNode;
|
||||
Generated
Vendored
+1971
File diff suppressed because it is too large
Load Diff
+185
@@ -0,0 +1,185 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
var compilerCli = require('@angular/compiler-cli');
|
||||
var ng_decorators = require('./ng_decorators-DYy6II6x.cjs');
|
||||
var property_name = require('./property_name-BCpALNpZ.cjs');
|
||||
|
||||
/**
|
||||
* Unwraps a given expression TypeScript node. Expressions can be wrapped within multiple
|
||||
* parentheses or as expression. e.g. "(((({exp}))))()". The function should return the
|
||||
* TypeScript node referring to the inner expression. e.g "exp".
|
||||
*/
|
||||
function unwrapExpression(node) {
|
||||
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)) {
|
||||
return unwrapExpression(node.expression);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
/** Extracts `@Directive` or `@Component` metadata from the given class. */
|
||||
function extractAngularClassMetadata(typeChecker, node) {
|
||||
const decorators = ts.getDecorators(node);
|
||||
if (!decorators || !decorators.length) {
|
||||
return null;
|
||||
}
|
||||
const ngDecorators = ng_decorators.getAngularDecorators(typeChecker, decorators);
|
||||
const componentDecorator = ngDecorators.find((dec) => dec.name === 'Component');
|
||||
const directiveDecorator = ngDecorators.find((dec) => dec.name === 'Directive');
|
||||
const decorator = componentDecorator ?? directiveDecorator;
|
||||
// In case no decorator could be found on the current class, skip.
|
||||
if (!decorator) {
|
||||
return null;
|
||||
}
|
||||
const decoratorCall = decorator.node.expression;
|
||||
// In case the decorator call is not valid, skip this class declaration.
|
||||
if (decoratorCall.arguments.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
const metadata = unwrapExpression(decoratorCall.arguments[0]);
|
||||
// Ensure that the metadata is an object literal expression.
|
||||
if (!ts.isObjectLiteralExpression(metadata)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: componentDecorator ? 'component' : 'directive',
|
||||
node: metadata,
|
||||
};
|
||||
}
|
||||
|
||||
const LF_CHAR = 10;
|
||||
const CR_CHAR = 13;
|
||||
const LINE_SEP_CHAR = 8232;
|
||||
const PARAGRAPH_CHAR = 8233;
|
||||
/** Gets the line and character for the given position from the line starts map. */
|
||||
function getLineAndCharacterFromPosition(lineStartsMap, position) {
|
||||
const lineIndex = findClosestLineStartPosition(lineStartsMap, position);
|
||||
return { character: position - lineStartsMap[lineIndex], line: lineIndex };
|
||||
}
|
||||
/**
|
||||
* Computes the line start map of the given text. This can be used in order to
|
||||
* retrieve the line and character of a given text position index.
|
||||
*/
|
||||
function computeLineStartsMap(text) {
|
||||
const result = [0];
|
||||
let pos = 0;
|
||||
while (pos < text.length) {
|
||||
const char = text.charCodeAt(pos++);
|
||||
// Handles the "CRLF" line break. In that case we peek the character
|
||||
// after the "CR" and check if it is a line feed.
|
||||
if (char === CR_CHAR) {
|
||||
if (text.charCodeAt(pos) === LF_CHAR) {
|
||||
pos++;
|
||||
}
|
||||
result.push(pos);
|
||||
}
|
||||
else if (char === LF_CHAR || char === LINE_SEP_CHAR || char === PARAGRAPH_CHAR) {
|
||||
result.push(pos);
|
||||
}
|
||||
}
|
||||
result.push(pos);
|
||||
return result;
|
||||
}
|
||||
/** Finds the closest line start for the given position. */
|
||||
function findClosestLineStartPosition(linesMap, position, low = 0, high = linesMap.length - 1) {
|
||||
while (low <= high) {
|
||||
const pivotIdx = Math.floor((low + high) / 2);
|
||||
const pivotEl = linesMap[pivotIdx];
|
||||
if (pivotEl === position) {
|
||||
return pivotIdx;
|
||||
}
|
||||
else if (position > pivotEl) {
|
||||
low = pivotIdx + 1;
|
||||
}
|
||||
else {
|
||||
high = pivotIdx - 1;
|
||||
}
|
||||
}
|
||||
// In case there was no exact match, return the closest "lower" line index. We also
|
||||
// subtract the index by one because want the index of the previous line start.
|
||||
return low - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visitor that can be used to determine Angular templates referenced within given
|
||||
* TypeScript source files (inline templates or external referenced templates)
|
||||
*/
|
||||
class NgComponentTemplateVisitor {
|
||||
typeChecker;
|
||||
resolvedTemplates = [];
|
||||
fs = compilerCli.getFileSystem();
|
||||
constructor(typeChecker) {
|
||||
this.typeChecker = typeChecker;
|
||||
}
|
||||
visitNode(node) {
|
||||
if (node.kind === ts.SyntaxKind.ClassDeclaration) {
|
||||
this.visitClassDeclaration(node);
|
||||
}
|
||||
ts.forEachChild(node, (n) => this.visitNode(n));
|
||||
}
|
||||
visitClassDeclaration(node) {
|
||||
const metadata = extractAngularClassMetadata(this.typeChecker, node);
|
||||
if (metadata === null || metadata.type !== 'component') {
|
||||
return;
|
||||
}
|
||||
const sourceFile = node.getSourceFile();
|
||||
const sourceFileName = sourceFile.fileName;
|
||||
// Walk through all component metadata properties and determine the referenced
|
||||
// HTML templates (either external or inline)
|
||||
metadata.node.properties.forEach((property) => {
|
||||
if (!ts.isPropertyAssignment(property)) {
|
||||
return;
|
||||
}
|
||||
const propertyName = property_name.getPropertyNameText(property.name);
|
||||
// In case there is an inline template specified, ensure that the value is statically
|
||||
// analyzable by checking if the initializer is a string literal-like node.
|
||||
if (propertyName === 'template' && ts.isStringLiteralLike(property.initializer)) {
|
||||
// Need to add an offset of one to the start because the template quotes are
|
||||
// not part of the template content.
|
||||
// The `getText()` method gives us the original raw text.
|
||||
// We could have used the `text` property, but if the template is defined as a backtick
|
||||
// string then the `text` property contains a "cooked" version of the string. Such cooked
|
||||
// strings will have converted CRLF characters to only LF. This messes up string
|
||||
// replacements in template migrations.
|
||||
// The raw text returned by `getText()` includes the enclosing quotes so we change the
|
||||
// `content` and `start` values accordingly.
|
||||
const content = property.initializer.getText().slice(1, -1);
|
||||
const start = property.initializer.getStart() + 1;
|
||||
this.resolvedTemplates.push({
|
||||
filePath: sourceFileName,
|
||||
container: node,
|
||||
content,
|
||||
inline: true,
|
||||
start: start,
|
||||
getCharacterAndLineOfPosition: (pos) => ts.getLineAndCharacterOfPosition(sourceFile, pos + start),
|
||||
});
|
||||
}
|
||||
if (propertyName === 'templateUrl' && ts.isStringLiteralLike(property.initializer)) {
|
||||
const absolutePath = this.fs.resolve(this.fs.dirname(sourceFileName), property.initializer.text);
|
||||
if (!this.fs.exists(absolutePath)) {
|
||||
return;
|
||||
}
|
||||
const fileContent = this.fs.readFile(absolutePath);
|
||||
const lineStartsMap = computeLineStartsMap(fileContent);
|
||||
this.resolvedTemplates.push({
|
||||
filePath: absolutePath,
|
||||
container: node,
|
||||
content: fileContent,
|
||||
inline: false,
|
||||
start: 0,
|
||||
getCharacterAndLineOfPosition: (pos) => getLineAndCharacterFromPosition(lineStartsMap, pos),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
exports.NgComponentTemplateVisitor = NgComponentTemplateVisitor;
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
|
||||
function getCallDecoratorImport(typeChecker, decorator) {
|
||||
// Note that this does not cover the edge case where decorators are called from
|
||||
// a namespace import: e.g. "@core.Component()". This is not handled by Ngtsc either.
|
||||
if (!ts.isCallExpression(decorator.expression) ||
|
||||
!ts.isIdentifier(decorator.expression.expression)) {
|
||||
return null;
|
||||
}
|
||||
const identifier = decorator.expression.expression;
|
||||
return imports.getImportOfIdentifier(typeChecker, identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
|
||||
* from a list of decorators.
|
||||
*/
|
||||
function getAngularDecorators(typeChecker, decorators) {
|
||||
return decorators
|
||||
.map((node) => ({ node, importData: getCallDecoratorImport(typeChecker, node) }))
|
||||
.filter(({ importData }) => importData && importData.importModule.startsWith('@angular/'))
|
||||
.map(({ node, importData }) => ({
|
||||
node: node,
|
||||
name: importData.name,
|
||||
moduleName: importData.importModule,
|
||||
importNode: importData.node,
|
||||
}));
|
||||
}
|
||||
|
||||
exports.getAngularDecorators = getAngularDecorators;
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var compiler = require('@angular/compiler');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
var parse_html = require('./parse_html-C8eKA9px.cjs');
|
||||
var ng_component_template = require('./ng_component_template-BOuKAnQd.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
require('./ng_decorators-DYy6II6x.cjs');
|
||||
require('./property_name-BCpALNpZ.cjs');
|
||||
|
||||
const ngClassStr = 'NgClass';
|
||||
const commonModuleStr = '@angular/common';
|
||||
const commonModuleImportsStr = 'CommonModule';
|
||||
function migrateNgClassBindings(template, config, componentNode, typeChecker) {
|
||||
const parsed = parse_html.parseTemplate(template);
|
||||
if (!parsed.tree || !parsed.tree.rootNodes.length) {
|
||||
return { migrated: template, changed: false, replacementCount: 0, canRemoveCommonModule: false };
|
||||
}
|
||||
const visitor = new NgClassCollector(template, componentNode, typeChecker);
|
||||
compiler.visitAll(visitor, parsed.tree.rootNodes, config);
|
||||
let newTemplate = template;
|
||||
let changedOffset = 0;
|
||||
let replacementCount = 0;
|
||||
for (const { start, end, replacement } of visitor.replacements) {
|
||||
const currentLength = newTemplate.length;
|
||||
newTemplate = replaceTemplate(newTemplate, replacement, start, end, changedOffset);
|
||||
changedOffset += newTemplate.length - currentLength;
|
||||
replacementCount++;
|
||||
}
|
||||
const changed = newTemplate !== template;
|
||||
return {
|
||||
migrated: newTemplate,
|
||||
changed,
|
||||
replacementCount,
|
||||
canRemoveCommonModule: changed ? parse_html.canRemoveCommonModule(newTemplate) : false,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Creates a Replacement to remove `NgClass` from a component's `imports` array.
|
||||
* Uses ReflectionHost + PartialEvaluator for robust AST analysis.
|
||||
*/
|
||||
function createNgClassImportsArrayRemoval(classNode, file, typeChecker, removeCommonModule) {
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const evaluator = new migrations.PartialEvaluator(reflector, typeChecker, null);
|
||||
// Use ReflectionHost to get decorators instead of manual AST traversal
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(classNode);
|
||||
if (!decorators) {
|
||||
return null;
|
||||
}
|
||||
// Find @Component decorator using ReflectionHost
|
||||
const componentDecorator = decorators.find((decorator) => decorator.name === 'Component');
|
||||
if (!componentDecorator || !componentDecorator.args || componentDecorator.args.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// Use PartialEvaluator to evaluate the decorator metadata
|
||||
const decoratorMetadata = evaluator.evaluate(componentDecorator.args[0]);
|
||||
if (!decoratorMetadata || typeof decoratorMetadata !== 'object') {
|
||||
return null;
|
||||
}
|
||||
// Get the actual AST node for the imports property
|
||||
const componentDecoratorNode = componentDecorator.node;
|
||||
if (!ts.isDecorator(componentDecoratorNode) ||
|
||||
!ts.isCallExpression(componentDecoratorNode.expression) ||
|
||||
!ts.isObjectLiteralExpression(componentDecoratorNode.expression.arguments[0])) {
|
||||
return null;
|
||||
}
|
||||
const objLiteral = componentDecoratorNode.expression.arguments[0];
|
||||
const importsProperty = objLiteral.properties.find((p) => ts.isPropertyAssignment(p) &&
|
||||
p.name.getText() === 'imports' &&
|
||||
ts.isArrayLiteralExpression(p.initializer));
|
||||
if (!importsProperty || !ts.isArrayLiteralExpression(importsProperty.initializer)) {
|
||||
return null;
|
||||
}
|
||||
const importsArray = importsProperty.initializer;
|
||||
const elementsToRemove = new Set([ngClassStr]);
|
||||
if (removeCommonModule) {
|
||||
elementsToRemove.add(commonModuleImportsStr);
|
||||
}
|
||||
const originalElements = importsArray.elements;
|
||||
const filteredElements = originalElements.filter((el) => !ts.isIdentifier(el) || !elementsToRemove.has(el.text));
|
||||
if (filteredElements.length === originalElements.length) {
|
||||
return null; // No changes needed.
|
||||
}
|
||||
// If the array becomes empty, remove the entire `imports` property.
|
||||
if (filteredElements.length === 0) {
|
||||
const removalRange = getPropertyRemovalRange(importsProperty);
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: removalRange.start,
|
||||
end: removalRange.end,
|
||||
toInsert: '',
|
||||
}));
|
||||
}
|
||||
const printer = ts.createPrinter();
|
||||
const newArray = ts.factory.updateArrayLiteralExpression(importsArray, filteredElements);
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, newArray, classNode.getSourceFile());
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: importsArray.getStart(),
|
||||
end: importsArray.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
function getPropertyRemovalRange(property) {
|
||||
const parent = property.parent;
|
||||
if (!ts.isObjectLiteralExpression(parent)) {
|
||||
return { start: property.getStart(), end: property.getEnd() };
|
||||
}
|
||||
const properties = parent.properties;
|
||||
const propertyIndex = properties.indexOf(property);
|
||||
const end = property.getEnd();
|
||||
if (propertyIndex < properties.length - 1) {
|
||||
const nextProperty = properties[propertyIndex + 1];
|
||||
return { start: property.getStart(), end: nextProperty.getStart() };
|
||||
}
|
||||
return { start: property.getStart(), end };
|
||||
}
|
||||
function calculateImportReplacements(info, sourceFiles, filesToRemoveCommonModule) {
|
||||
const importReplacements = {};
|
||||
const importManager = new migrations.ImportManager();
|
||||
for (const sf of sourceFiles) {
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
// Always remove NgClass if it's imported directly.
|
||||
importManager.removeImport(sf, ngClassStr, commonModuleStr);
|
||||
// Conditionally remove CommonModule if it's no longer needed.
|
||||
if (filesToRemoveCommonModule.has(file.id)) {
|
||||
importManager.removeImport(sf, commonModuleImportsStr, commonModuleStr);
|
||||
}
|
||||
const addRemove = [];
|
||||
apply_import_manager.applyImportManagerChanges(importManager, addRemove, [sf], info);
|
||||
if (addRemove.length > 0) {
|
||||
importReplacements[file.id] = {
|
||||
add: [],
|
||||
addAndRemove: addRemove,
|
||||
};
|
||||
}
|
||||
}
|
||||
return importReplacements;
|
||||
}
|
||||
function replaceTemplate(template, replaceValue, start, end, offset) {
|
||||
return template.slice(0, start + offset) + replaceValue + template.slice(end + offset);
|
||||
}
|
||||
/**
|
||||
* Visitor class that scans Angular templates and collects replacements
|
||||
* for [ngClass] bindings that use static object literals.
|
||||
*/
|
||||
class NgClassCollector extends compiler.RecursiveVisitor {
|
||||
componentNode;
|
||||
typeChecker;
|
||||
replacements = [];
|
||||
originalTemplate;
|
||||
isNgClassImported = true; // Default to true (permissive)
|
||||
constructor(template, componentNode, typeChecker) {
|
||||
super();
|
||||
this.componentNode = componentNode;
|
||||
this.typeChecker = typeChecker;
|
||||
this.originalTemplate = template;
|
||||
// If we have enough information, check if NgClass is actually imported.
|
||||
// If not, we can confidently disable the migration for this component.
|
||||
if (componentNode && typeChecker) {
|
||||
const imports$1 = imports.getImportSpecifiers(componentNode.getSourceFile(), commonModuleStr, [
|
||||
ngClassStr,
|
||||
commonModuleImportsStr,
|
||||
]);
|
||||
if (imports$1.length === 0) {
|
||||
this.isNgClassImported = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
visitElement(element, config) {
|
||||
// If NgClass is not imported, do not attempt to migrate.
|
||||
if (!this.isNgClassImported) {
|
||||
return;
|
||||
}
|
||||
for (const attr of element.attrs) {
|
||||
if (attr.name === '[ngClass]' && attr.valueSpan) {
|
||||
const expr = this.originalTemplate.slice(attr.valueSpan.start.offset, attr.valueSpan.end.offset);
|
||||
const staticMatch = tryParseStaticObjectLiteral(expr);
|
||||
if (staticMatch === null) {
|
||||
continue;
|
||||
}
|
||||
let replacement;
|
||||
if (staticMatch.length === 0) {
|
||||
replacement = '[class]=""';
|
||||
}
|
||||
else if (staticMatch.length === 1) {
|
||||
const { key, value } = staticMatch[0];
|
||||
// Special case: If the key is an empty string, use [class]=""
|
||||
if (key === '') {
|
||||
replacement = '[class]=""';
|
||||
}
|
||||
else {
|
||||
// Normal single condition: use [class.className]="condition"
|
||||
replacement = `[class.${key}]="${value}"`;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Check if all entries have the same value (condition)
|
||||
const allSameValue = staticMatch.every((entry) => entry.value === staticMatch[0].value);
|
||||
if (allSameValue &&
|
||||
staticMatch.length > 1 &&
|
||||
// Check if this was originally a single key with multiple classes
|
||||
expr.includes('{') &&
|
||||
expr.includes('}') &&
|
||||
expr.split(':').length === 2) {
|
||||
// Multiple classes with the same condition: use [class.class1]="condition" [class.class2]="condition"
|
||||
if (config.migrateSpaceSeparatedKey) {
|
||||
replacement = staticMatch
|
||||
.map(({ key, value }) => `[class.${key}]="${value}"`)
|
||||
.join(' ');
|
||||
}
|
||||
else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Multiple conditions with different values: use [class]="{'class1': condition1, 'class2': condition2}"
|
||||
replacement = `[class]="${expr}"`;
|
||||
}
|
||||
}
|
||||
this.replacements.push({
|
||||
start: attr.sourceSpan.start.offset,
|
||||
end: attr.sourceSpan.end.offset,
|
||||
replacement,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (attr.name === 'ngClass' && attr.value) {
|
||||
this.replacements.push({
|
||||
start: attr.sourceSpan.start.offset,
|
||||
end: attr.sourceSpan.end.offset,
|
||||
replacement: `class="${attr.value}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return super.visitElement(element, config);
|
||||
}
|
||||
}
|
||||
function tryParseStaticObjectLiteral(expr) {
|
||||
const trimmedExpr = expr.trim();
|
||||
if (trimmedExpr === '{}' || trimmedExpr === '[]') {
|
||||
return [];
|
||||
}
|
||||
if (!isObjectLiteralSyntax(trimmedExpr)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const objectLiteral = parseAsObjectLiteral(trimmedExpr);
|
||||
if (!objectLiteral) {
|
||||
return null;
|
||||
}
|
||||
return extractClassBindings(objectLiteral);
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates basic object literal syntax
|
||||
*/
|
||||
function isObjectLiteralSyntax(expr) {
|
||||
return expr.startsWith('{') && expr.endsWith('}');
|
||||
}
|
||||
/**
|
||||
* Parses expression as TypeScript object literal
|
||||
*/
|
||||
function parseAsObjectLiteral(expr) {
|
||||
try {
|
||||
const sourceFile = ts.createSourceFile('temp.ts', `const obj = ${expr}`, ts.ScriptTarget.Latest, true);
|
||||
const variableStatement = sourceFile.statements[0];
|
||||
if (!ts.isVariableStatement(variableStatement)) {
|
||||
return null;
|
||||
}
|
||||
const declaration = variableStatement.declarationList.declarations[0];
|
||||
if (!declaration.initializer || !ts.isObjectLiteralExpression(declaration.initializer)) {
|
||||
return null;
|
||||
}
|
||||
// Manage invalid syntax ngClass="{class1 class2}"
|
||||
const content = expr.slice(1, -1).trim();
|
||||
if (content && !content.includes(':') && content.includes(' ') && !content.includes(',')) {
|
||||
return null;
|
||||
}
|
||||
return declaration.initializer;
|
||||
}
|
||||
catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Extracts class bindings from object literal properties
|
||||
*/
|
||||
function extractClassBindings(objectLiteral) {
|
||||
const result = [];
|
||||
for (const property of objectLiteral.properties) {
|
||||
if (ts.isShorthandPropertyAssignment(property)) {
|
||||
const key = property.name.getText();
|
||||
if (key.includes(' ')) {
|
||||
return null;
|
||||
}
|
||||
result.push({ key, value: key });
|
||||
}
|
||||
else if (ts.isPropertyAssignment(property)) {
|
||||
const keyText = extractPropertyKey(property.name);
|
||||
const valueText = extractPropertyValue(property.initializer);
|
||||
if (keyText === '' && valueText) {
|
||||
result.push({ key: '', value: valueText });
|
||||
}
|
||||
else {
|
||||
if (!keyText || !valueText) {
|
||||
return null;
|
||||
}
|
||||
// Handle multiple CSS classes in single key (e.g., 'class1 class2': condition)
|
||||
const classNames = keyText.split(/\s+/).filter(Boolean);
|
||||
for (const className of classNames) {
|
||||
result.push({ key: className, value: valueText });
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Extracts text from property key (name)
|
||||
*/
|
||||
function extractPropertyKey(name) {
|
||||
if (ts.isIdentifier(name)) {
|
||||
return name.text;
|
||||
}
|
||||
if (ts.isStringLiteral(name)) {
|
||||
return name.text;
|
||||
}
|
||||
if (ts.isNumericLiteral(name)) {
|
||||
return name.text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Extracts text from property value
|
||||
*/
|
||||
function extractPropertyValue(initializer) {
|
||||
// String literals: 'value' or "value"
|
||||
if (ts.isStringLiteral(initializer)) {
|
||||
return `'${initializer.text}'`;
|
||||
}
|
||||
// Numeric literals: 42, 3.14
|
||||
if (ts.isNumericLiteral(initializer)) {
|
||||
return initializer.text;
|
||||
}
|
||||
// Boolean and null keywords
|
||||
if (initializer.kind === ts.SyntaxKind.TrueKeyword) {
|
||||
return 'true';
|
||||
}
|
||||
if (initializer.kind === ts.SyntaxKind.FalseKeyword) {
|
||||
return 'false';
|
||||
}
|
||||
if (initializer.kind === ts.SyntaxKind.NullKeyword) {
|
||||
return 'null';
|
||||
}
|
||||
// Identifiers: isActive, condition, etc.
|
||||
if (ts.isIdentifier(initializer)) {
|
||||
return initializer.text;
|
||||
}
|
||||
return initializer.getText();
|
||||
}
|
||||
|
||||
class NgClassMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
processTemplate(template, node, file, info, typeChecker) {
|
||||
const { migrated, changed, replacementCount, canRemoveCommonModule } = migrateNgClassBindings(template.content, this.config, node, typeChecker);
|
||||
if (!changed) {
|
||||
return null;
|
||||
}
|
||||
const fileToMigrate = template.inline
|
||||
? file
|
||||
: project_paths.projectFile(template.filePath, info);
|
||||
const end = template.start + template.content.length;
|
||||
return {
|
||||
replacements: [prepareTextReplacement(fileToMigrate, migrated, template.start, end)],
|
||||
replacementCount,
|
||||
canRemoveCommonModule,
|
||||
};
|
||||
}
|
||||
async analyze(info) {
|
||||
const { sourceFiles, program } = info;
|
||||
const typeChecker = program.getTypeChecker();
|
||||
const ngClassReplacements = [];
|
||||
const filesWithNgClassDeclarations = new Set();
|
||||
const filesToRemoveCommonModule = new Set();
|
||||
for (const sf of sourceFiles) {
|
||||
ts.forEachChild(sf, (node) => {
|
||||
if (!ts.isClassDeclaration(node)) {
|
||||
return;
|
||||
}
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
if (this.config.shouldMigrate && !this.config.shouldMigrate(file)) {
|
||||
return;
|
||||
}
|
||||
const templateVisitor = new ng_component_template.NgComponentTemplateVisitor(typeChecker);
|
||||
templateVisitor.visitNode(node);
|
||||
const replacementsForClass = [];
|
||||
let replacementCountForClass = 0;
|
||||
let canRemoveCommonModuleForFile = true;
|
||||
for (const template of templateVisitor.resolvedTemplates) {
|
||||
const result = this.processTemplate(template, node, file, info, typeChecker);
|
||||
if (result) {
|
||||
replacementsForClass.push(...result.replacements);
|
||||
replacementCountForClass += result.replacementCount;
|
||||
if (!result.canRemoveCommonModule) {
|
||||
canRemoveCommonModuleForFile = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replacementsForClass.length > 0) {
|
||||
if (canRemoveCommonModuleForFile) {
|
||||
filesToRemoveCommonModule.add(file.id);
|
||||
}
|
||||
// Handle the `@Component({ imports: [...] })` array.
|
||||
const importsRemoval = createNgClassImportsArrayRemoval(node, file, typeChecker, canRemoveCommonModuleForFile);
|
||||
if (importsRemoval) {
|
||||
replacementsForClass.push(importsRemoval);
|
||||
}
|
||||
ngClassReplacements.push({
|
||||
file,
|
||||
replacementCount: replacementCountForClass,
|
||||
replacements: replacementsForClass,
|
||||
});
|
||||
filesWithNgClassDeclarations.add(sf);
|
||||
}
|
||||
});
|
||||
}
|
||||
const importReplacements = calculateImportReplacements(info, filesWithNgClassDeclarations, filesToRemoveCommonModule);
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngClassReplacements,
|
||||
importReplacements,
|
||||
});
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const importReplacements = {};
|
||||
for (const unit of [unitA, unitB]) {
|
||||
for (const fileIDStr of Object.keys(unit.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
importReplacements[fileID] = unit.importReplacements[fileID];
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngClassReplacements: [...unitA.ngClassReplacements, ...unitB.ngClassReplacements],
|
||||
importReplacements,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngClassReplacements: combinedData.ngClassReplacements,
|
||||
importReplacements: combinedData.importReplacements,
|
||||
});
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const touchedFilesCount = globalMetadata.ngClassReplacements.length;
|
||||
const replacementCount = globalMetadata.ngClassReplacements.reduce((acc, cur) => acc + cur.replacementCount, 0);
|
||||
return project_paths.confirmAsSerializable({
|
||||
touchedFilesCount,
|
||||
replacementCount,
|
||||
});
|
||||
}
|
||||
async migrate(globalData) {
|
||||
const replacements = [];
|
||||
replacements.push(...globalData.ngClassReplacements.flatMap(({ replacements }) => replacements));
|
||||
for (const fileIDStr of Object.keys(globalData.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
const importReplacements = globalData.importReplacements[fileID];
|
||||
replacements.push(...importReplacements.addAndRemove);
|
||||
}
|
||||
return { replacements };
|
||||
}
|
||||
}
|
||||
function prepareTextReplacement(file, replacement, start, end) {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: start,
|
||||
end: end,
|
||||
toInsert: replacement,
|
||||
}));
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new NgClassMigration({
|
||||
migrateSpaceSeparatedKey: options.migrateSpaceSeparatedKey,
|
||||
shouldMigrate: (file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for ngClass bindings: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: ({ touchedFilesCount, replacementCount, }) => {
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated to class from ngClass 🎉`);
|
||||
context.logger.info(` -> Migrated ${replacementCount} ngClass to class in ${touchedFilesCount} files.`);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var compiler = require('@angular/compiler');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
var parse_html = require('./parse_html-C8eKA9px.cjs');
|
||||
var ng_component_template = require('./ng_component_template-BOuKAnQd.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
require('./ng_decorators-DYy6II6x.cjs');
|
||||
require('./property_name-BCpALNpZ.cjs');
|
||||
|
||||
const ngStyleStr = 'NgStyle';
|
||||
const commonModuleStr = '@angular/common';
|
||||
const commonModuleImportsStr = 'CommonModule';
|
||||
function migrateNgStyleBindings(template, config, componentNode, typeChecker) {
|
||||
const parsed = parse_html.parseTemplate(template);
|
||||
if (!parsed.tree || !parsed.tree.rootNodes.length) {
|
||||
return { migrated: template, changed: false, replacementCount: 0, canRemoveCommonModule: false };
|
||||
}
|
||||
const visitor = new NgStyleCollector(template, componentNode, typeChecker);
|
||||
compiler.visitAll(visitor, parsed.tree.rootNodes, config);
|
||||
let newTemplate = template;
|
||||
let changedOffset = 0;
|
||||
let replacementCount = 0;
|
||||
for (const { start, end, replacement } of visitor.replacements) {
|
||||
const currentLength = newTemplate.length;
|
||||
newTemplate = replaceTemplate(newTemplate, replacement, start, end, changedOffset);
|
||||
changedOffset += newTemplate.length - currentLength;
|
||||
replacementCount++;
|
||||
}
|
||||
const changed = newTemplate !== template;
|
||||
return {
|
||||
migrated: newTemplate,
|
||||
changed,
|
||||
replacementCount,
|
||||
canRemoveCommonModule: changed ? parse_html.canRemoveCommonModule(newTemplate) : false,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Creates a Replacement to remove `NgStyle` from a component's `imports` array.
|
||||
* Uses ReflectionHost + PartialEvaluator for robust AST analysis.
|
||||
*/
|
||||
function createNgStyleImportsArrayRemoval(classNode, file, typeChecker, removeCommonModule) {
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(classNode);
|
||||
if (!decorators) {
|
||||
return null;
|
||||
}
|
||||
const componentDecorator = decorators.find((decorator) => decorator.name === 'Component');
|
||||
if (!componentDecorator?.node) {
|
||||
return null;
|
||||
}
|
||||
const decoratorNode = componentDecorator.node;
|
||||
if (!ts.isDecorator(decoratorNode) ||
|
||||
!ts.isCallExpression(decoratorNode.expression) ||
|
||||
decoratorNode.expression.arguments.length === 0 ||
|
||||
!ts.isObjectLiteralExpression(decoratorNode.expression.arguments[0])) {
|
||||
return null;
|
||||
}
|
||||
const metadata = decoratorNode.expression.arguments[0];
|
||||
const importsProperty = metadata.properties.find((p) => ts.isPropertyAssignment(p) && p.name?.getText() === 'imports');
|
||||
if (!importsProperty || !ts.isArrayLiteralExpression(importsProperty.initializer)) {
|
||||
return null;
|
||||
}
|
||||
const importsArray = importsProperty.initializer;
|
||||
const elementsToRemove = new Set([ngStyleStr]);
|
||||
if (removeCommonModule) {
|
||||
elementsToRemove.add(commonModuleImportsStr);
|
||||
}
|
||||
const originalElements = importsArray.elements;
|
||||
const filteredElements = originalElements.filter((el) => !ts.isIdentifier(el) || !elementsToRemove.has(el.text));
|
||||
if (filteredElements.length === originalElements.length) {
|
||||
return null; // No changes needed.
|
||||
}
|
||||
// If the array becomes empty, remove the entire `imports` property.
|
||||
if (filteredElements.length === 0) {
|
||||
const removalRange = getPropertyRemovalRange(importsProperty);
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: removalRange.start,
|
||||
end: removalRange.end,
|
||||
toInsert: '',
|
||||
}));
|
||||
}
|
||||
const printer = ts.createPrinter();
|
||||
const newArray = ts.factory.updateArrayLiteralExpression(importsArray, filteredElements);
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, newArray, classNode.getSourceFile());
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: importsArray.getStart(),
|
||||
end: importsArray.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Calculates the removal range for a property in an object literal,
|
||||
* including the trailing comma if it's not the last property.
|
||||
*/
|
||||
function getPropertyRemovalRange(property) {
|
||||
const parent = property.parent;
|
||||
if (!ts.isObjectLiteralExpression(parent)) {
|
||||
return { start: property.getStart(), end: property.getEnd() };
|
||||
}
|
||||
const properties = parent.properties;
|
||||
const propertyIndex = properties.indexOf(property);
|
||||
const end = property.getEnd();
|
||||
if (propertyIndex < properties.length - 1) {
|
||||
const nextProperty = properties[propertyIndex + 1];
|
||||
return { start: property.getStart(), end: nextProperty.getStart() };
|
||||
}
|
||||
return { start: property.getStart(), end };
|
||||
}
|
||||
function calculateImportReplacements(info, sourceFiles, filesToRemoveCommonModule) {
|
||||
const importReplacements = {};
|
||||
const importManager = new migrations.ImportManager();
|
||||
for (const sf of sourceFiles) {
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
// Always remove NgStyle if it's imported directly.
|
||||
importManager.removeImport(sf, ngStyleStr, commonModuleStr);
|
||||
// Conditionally remove CommonModule if it's no longer needed.
|
||||
if (filesToRemoveCommonModule.has(file.id)) {
|
||||
importManager.removeImport(sf, commonModuleImportsStr, commonModuleStr);
|
||||
}
|
||||
const addRemove = [];
|
||||
apply_import_manager.applyImportManagerChanges(importManager, addRemove, [sf], info);
|
||||
if (addRemove.length > 0) {
|
||||
importReplacements[file.id] = {
|
||||
add: [],
|
||||
addAndRemove: addRemove,
|
||||
};
|
||||
}
|
||||
}
|
||||
return importReplacements;
|
||||
}
|
||||
function replaceTemplate(template, replaceValue, start, end, offset) {
|
||||
return template.slice(0, start + offset) + replaceValue + template.slice(end + offset);
|
||||
}
|
||||
/**
|
||||
* Visitor class that scans Angular templates and collects replacements
|
||||
* for [ngStyle] bindings that use static object literals.
|
||||
*/
|
||||
class NgStyleCollector extends compiler.RecursiveVisitor {
|
||||
originalTemplate;
|
||||
replacements = [];
|
||||
isNgStyleImported = true; // Default to true (permissive)
|
||||
constructor(originalTemplate, componentNode, typeChecker) {
|
||||
super();
|
||||
this.originalTemplate = originalTemplate;
|
||||
// If we have enough information, check if NgStyle is actually imported.
|
||||
// If not, we can confidently disable the migration for this component.
|
||||
if (componentNode && typeChecker) {
|
||||
const imports$1 = imports.getImportSpecifiers(componentNode.getSourceFile(), commonModuleStr, [
|
||||
ngStyleStr,
|
||||
commonModuleImportsStr,
|
||||
]);
|
||||
if (imports$1.length === 0) {
|
||||
this.isNgStyleImported = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
visitElement(element, config) {
|
||||
// If NgStyle is not imported, do not attempt to migrate.
|
||||
if (!this.isNgStyleImported) {
|
||||
return;
|
||||
}
|
||||
for (const attr of element.attrs) {
|
||||
if (attr.name !== '[ngStyle]' && attr.name !== 'ngStyle') {
|
||||
continue;
|
||||
}
|
||||
if (attr.name === '[ngStyle]' && attr.valueSpan) {
|
||||
const expr = this.originalTemplate.slice(attr.valueSpan.start.offset, attr.valueSpan.end.offset);
|
||||
const staticMatch = parseStaticObjectLiteral(expr);
|
||||
if (staticMatch === null) {
|
||||
if (config.bestEffortMode && !isObjectLiteralSyntax(expr.trim())) {
|
||||
const keyReplacement = this.originalTemplate
|
||||
.slice(attr.sourceSpan.start.offset, attr.valueSpan.start.offset)
|
||||
.replace('[ngStyle]', '[style]');
|
||||
this.replacements.push({
|
||||
start: attr.sourceSpan.start.offset,
|
||||
end: attr.valueSpan.start.offset,
|
||||
replacement: keyReplacement,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let replacement;
|
||||
if (staticMatch.length === 0) {
|
||||
replacement = '';
|
||||
}
|
||||
else if (staticMatch.length === 1) {
|
||||
const { key, value } = staticMatch[0];
|
||||
// Special case: If the key is an empty string, use [style]=""
|
||||
if (key === '') {
|
||||
replacement = '';
|
||||
}
|
||||
else {
|
||||
// Normal single condition: use [style.styleName]="condition"
|
||||
replacement = `[style.${key}]="${value}"`;
|
||||
}
|
||||
}
|
||||
else {
|
||||
replacement = `[style]="${expr}"`;
|
||||
}
|
||||
this.replacements.push({
|
||||
start: attr.sourceSpan.start.offset,
|
||||
end: attr.sourceSpan.end.offset,
|
||||
replacement,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (attr.name === 'ngStyle' && attr.value) {
|
||||
this.replacements.push({
|
||||
start: attr.sourceSpan.start.offset,
|
||||
end: attr.sourceSpan.end.offset,
|
||||
replacement: `style="${attr.value}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return super.visitElement(element, config);
|
||||
}
|
||||
}
|
||||
function parseStaticObjectLiteral(expr) {
|
||||
const trimmedExpr = expr.trim();
|
||||
if (trimmedExpr === '{}' || trimmedExpr === '[]') {
|
||||
return [];
|
||||
}
|
||||
if (!isObjectLiteralSyntax(trimmedExpr)) {
|
||||
return null;
|
||||
}
|
||||
const objectLiteral = parseAsObjectLiteral(trimmedExpr);
|
||||
if (!objectLiteral) {
|
||||
return null;
|
||||
}
|
||||
return extractStyleBindings(objectLiteral);
|
||||
}
|
||||
/**
|
||||
* Validates basic object literal syntax
|
||||
*/
|
||||
function isObjectLiteralSyntax(expr) {
|
||||
return expr.startsWith('{') && expr.endsWith('}');
|
||||
}
|
||||
/**
|
||||
* Parses expression as TypeScript object literal
|
||||
*/
|
||||
function parseAsObjectLiteral(expr) {
|
||||
const sourceFile = ts.createSourceFile('temp.ts', `const obj = ${expr}`, ts.ScriptTarget.Latest, true);
|
||||
const variableStatement = sourceFile.statements[0];
|
||||
if (!ts.isVariableStatement(variableStatement)) {
|
||||
return null;
|
||||
}
|
||||
const declaration = variableStatement.declarationList.declarations[0];
|
||||
if (!declaration.initializer || !ts.isObjectLiteralExpression(declaration.initializer)) {
|
||||
return null;
|
||||
}
|
||||
return declaration.initializer;
|
||||
}
|
||||
function extractStyleBindings(objectLiteral) {
|
||||
const result = [];
|
||||
for (const property of objectLiteral.properties) {
|
||||
if (ts.isShorthandPropertyAssignment(property)) {
|
||||
return null;
|
||||
}
|
||||
else if (ts.isPropertyAssignment(property)) {
|
||||
const keyText = extractPropertyKey(property.name);
|
||||
const valueText = extractPropertyValue(property.initializer);
|
||||
if (keyText === '' && valueText) {
|
||||
result.push({ key: '', value: valueText });
|
||||
continue;
|
||||
}
|
||||
if (!keyText || !valueText) {
|
||||
return null;
|
||||
}
|
||||
result.push({ key: keyText, value: valueText });
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Extracts text from property key (name)
|
||||
*/
|
||||
function extractPropertyKey(name) {
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
|
||||
return name.text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Extracts text from property value
|
||||
*/
|
||||
function extractPropertyValue(initializer) {
|
||||
// String literals: 'value' or "value"
|
||||
if (ts.isStringLiteral(initializer)) {
|
||||
return `'${initializer.text}'`;
|
||||
}
|
||||
// Numeric literals: 42, 3.14
|
||||
if (ts.isNumericLiteral(initializer) || ts.isIdentifier(initializer)) {
|
||||
return initializer.text;
|
||||
}
|
||||
// Boolean and null keywords
|
||||
if (initializer.kind === ts.SyntaxKind.TrueKeyword) {
|
||||
return 'true';
|
||||
}
|
||||
if (initializer.kind === ts.SyntaxKind.FalseKeyword) {
|
||||
return 'false';
|
||||
}
|
||||
if (initializer.kind === ts.SyntaxKind.NullKeyword) {
|
||||
return 'null';
|
||||
}
|
||||
return initializer.getText();
|
||||
}
|
||||
|
||||
class NgStyleMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
processTemplate(template, node, file, info, typeChecker) {
|
||||
const { migrated, changed, replacementCount, canRemoveCommonModule } = migrateNgStyleBindings(template.content, this.config, node, typeChecker);
|
||||
if (!changed) {
|
||||
return null;
|
||||
}
|
||||
const fileToMigrate = template.inline
|
||||
? file
|
||||
: project_paths.projectFile(template.filePath, info);
|
||||
const end = template.start + template.content.length;
|
||||
return {
|
||||
replacements: [prepareTextReplacement(fileToMigrate, migrated, template.start, end)],
|
||||
replacementCount,
|
||||
canRemoveCommonModule,
|
||||
};
|
||||
}
|
||||
async analyze(info) {
|
||||
const { sourceFiles, program } = info;
|
||||
const typeChecker = program.getTypeChecker();
|
||||
const ngStyleReplacements = [];
|
||||
const filesWithNgStyleDeclarations = new Set();
|
||||
const filesToRemoveCommonModule = new Set();
|
||||
for (const sf of sourceFiles) {
|
||||
ts.forEachChild(sf, (node) => {
|
||||
if (!ts.isClassDeclaration(node)) {
|
||||
return;
|
||||
}
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
if (this.config.shouldMigrate && !this.config.shouldMigrate(file)) {
|
||||
return;
|
||||
}
|
||||
const templateVisitor = new ng_component_template.NgComponentTemplateVisitor(typeChecker);
|
||||
templateVisitor.visitNode(node);
|
||||
const replacementsForStyle = [];
|
||||
let replacementCountForStyle = 0;
|
||||
let canRemoveCommonModuleForFile = true;
|
||||
for (const template of templateVisitor.resolvedTemplates) {
|
||||
const result = this.processTemplate(template, node, file, info, typeChecker);
|
||||
if (result) {
|
||||
replacementsForStyle.push(...result.replacements);
|
||||
replacementCountForStyle += result.replacementCount;
|
||||
if (!result.canRemoveCommonModule) {
|
||||
canRemoveCommonModuleForFile = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replacementsForStyle.length > 0) {
|
||||
if (canRemoveCommonModuleForFile) {
|
||||
filesToRemoveCommonModule.add(file.id);
|
||||
}
|
||||
// Handle the `@Component({ imports: [...] })` array.
|
||||
const importsRemoval = createNgStyleImportsArrayRemoval(node, file, typeChecker, canRemoveCommonModuleForFile);
|
||||
if (importsRemoval) {
|
||||
replacementsForStyle.push(importsRemoval);
|
||||
}
|
||||
ngStyleReplacements.push({
|
||||
file,
|
||||
replacementCount: replacementCountForStyle,
|
||||
replacements: replacementsForStyle,
|
||||
});
|
||||
filesWithNgStyleDeclarations.add(sf);
|
||||
}
|
||||
});
|
||||
}
|
||||
const importReplacements = calculateImportReplacements(info, filesWithNgStyleDeclarations, filesToRemoveCommonModule);
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngStyleReplacements,
|
||||
importReplacements,
|
||||
});
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const importReplacements = {};
|
||||
for (const unit of [unitA, unitB]) {
|
||||
for (const fileIDStr of Object.keys(unit.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
importReplacements[fileID] = unit.importReplacements[fileID];
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngStyleReplacements: [...unitA.ngStyleReplacements, ...unitB.ngStyleReplacements],
|
||||
importReplacements,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable({
|
||||
ngStyleReplacements: combinedData.ngStyleReplacements,
|
||||
importReplacements: combinedData.importReplacements,
|
||||
});
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const touchedFilesCount = globalMetadata.ngStyleReplacements.length;
|
||||
const replacementCount = globalMetadata.ngStyleReplacements.reduce((acc, cur) => acc + cur.replacementCount, 0);
|
||||
return project_paths.confirmAsSerializable({
|
||||
touchedFilesCount,
|
||||
replacementCount,
|
||||
});
|
||||
}
|
||||
async migrate(globalData) {
|
||||
const replacements = [];
|
||||
replacements.push(...globalData.ngStyleReplacements.flatMap(({ replacements }) => replacements));
|
||||
for (const fileIDStr of Object.keys(globalData.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
const importReplacements = globalData.importReplacements[fileID];
|
||||
replacements.push(...importReplacements.addAndRemove);
|
||||
}
|
||||
return { replacements };
|
||||
}
|
||||
}
|
||||
function prepareTextReplacement(file, replacement, start, end) {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: start,
|
||||
end: end,
|
||||
toInsert: replacement,
|
||||
}));
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new NgStyleMigration({
|
||||
bestEffortMode: options.bestEffortMode,
|
||||
shouldMigrate: (file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for component tags: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: ({ touchedFilesCount, replacementCount, }) => {
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated to style bindings from ngStyle 🎉`);
|
||||
context.logger.info(` -> Migrated ${replacementCount} ngStyle to style bindings in ${touchedFilesCount} files.`);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
|
||||
/** Find the closest parent node of a particular kind. */
|
||||
function closestNode(node, predicate) {
|
||||
let current = node.parent;
|
||||
while (current && !ts.isSourceFile(current)) {
|
||||
if (predicate(current)) {
|
||||
return current;
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
exports.closestNode = closestNode;
|
||||
+602
@@ -0,0 +1,602 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var compiler = require('@angular/compiler');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
var index = require('./index-BtLcQH8g.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
function isOutputDeclarationEligibleForMigration(node) {
|
||||
return (node.initializer !== undefined &&
|
||||
ts.isNewExpression(node.initializer) &&
|
||||
ts.isIdentifier(node.initializer.expression) &&
|
||||
node.initializer.expression.text === 'EventEmitter');
|
||||
}
|
||||
function isPotentialOutputCallUsage(node, name) {
|
||||
if (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
ts.isIdentifier(node.expression.name)) {
|
||||
return node.expression?.name.text === name;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function isPotentialPipeCallUsage(node) {
|
||||
return isPotentialOutputCallUsage(node, 'pipe');
|
||||
}
|
||||
function isPotentialNextCallUsage(node) {
|
||||
return isPotentialOutputCallUsage(node, 'next');
|
||||
}
|
||||
function isPotentialCompleteCallUsage(node) {
|
||||
return isPotentialOutputCallUsage(node, 'complete');
|
||||
}
|
||||
function isTargetOutputDeclaration(node, checker, reflector, dtsReader) {
|
||||
const targetSymbol = checker.getSymbolAtLocation(node);
|
||||
if (targetSymbol !== undefined) {
|
||||
const propertyDeclaration = getTargetPropertyDeclaration(targetSymbol);
|
||||
if (propertyDeclaration !== null &&
|
||||
isOutputDeclaration(propertyDeclaration, reflector, dtsReader)) {
|
||||
return propertyDeclaration;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Gets whether the given property is an Angular `@Output`. */
|
||||
function isOutputDeclaration(node, reflector, dtsReader) {
|
||||
// `.d.ts` file, so we check the `static ecmp` metadata on the `declare class`.
|
||||
if (node.getSourceFile().isDeclarationFile) {
|
||||
if (!ts.isIdentifier(node.name) ||
|
||||
!ts.isClassDeclaration(node.parent) ||
|
||||
node.parent.name === undefined) {
|
||||
return false;
|
||||
}
|
||||
const ref = new migrations.Reference(node.parent);
|
||||
const directiveMeta = dtsReader.getDirectiveMetadata(ref);
|
||||
return !!directiveMeta?.outputs.getByClassPropertyName(node.name.text);
|
||||
}
|
||||
// `.ts` file, so we check for the `@Output()` decorator.
|
||||
return getOutputDecorator(node, reflector) !== null;
|
||||
}
|
||||
function getTargetPropertyDeclaration(targetSymbol) {
|
||||
const valDeclaration = targetSymbol.valueDeclaration;
|
||||
if (valDeclaration !== undefined && ts.isPropertyDeclaration(valDeclaration)) {
|
||||
return valDeclaration;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Returns Angular `@Output` decorator or null when a given property declaration is not an @Output */
|
||||
function getOutputDecorator(node, reflector) {
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(node);
|
||||
const ngDecorators = decorators !== null ? migrations.getAngularDecorators(decorators, ['Output'], /* isCore */ false) : [];
|
||||
return ngDecorators.length > 0 ? ngDecorators[0] : null;
|
||||
}
|
||||
// THINK: this utility + type is not specific to @Output, really, maybe move it to tsurge?
|
||||
/** Computes an unique ID for a given Angular `@Output` property. */
|
||||
function getUniqueIdForProperty(info, prop) {
|
||||
const { id } = project_paths.projectFile(prop.getSourceFile(), info);
|
||||
id.replace(/\.d\.ts$/, '.ts');
|
||||
return `${id}@@${prop.parent.name ?? 'unknown-class'}@@${prop.name.getText()}`;
|
||||
}
|
||||
function isTestRunnerImport(node) {
|
||||
if (ts.isImportDeclaration(node)) {
|
||||
const moduleSpecifier = node.moduleSpecifier.getText();
|
||||
return moduleSpecifier.includes('jasmine') || moduleSpecifier.includes('catalyst');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// TODO: code duplication with signals migration - sort it out
|
||||
/**
|
||||
* Gets whether the given read is used to access
|
||||
* the specified field.
|
||||
*
|
||||
* E.g. whether `<my-read>.toArray` is detected.
|
||||
*/
|
||||
function checkNonTsReferenceAccessesField(ref, fieldName) {
|
||||
const readFromPath = ref.from.readAstPath.at(-1);
|
||||
const parentRead = ref.from.readAstPath.at(-2);
|
||||
if (ref.from.read !== readFromPath) {
|
||||
return null;
|
||||
}
|
||||
if (!(parentRead instanceof compiler.PropertyRead) || parentRead.name !== fieldName) {
|
||||
return null;
|
||||
}
|
||||
return parentRead;
|
||||
}
|
||||
/**
|
||||
* Gets whether the given reference is accessed to call the
|
||||
* specified function on it.
|
||||
*
|
||||
* E.g. whether `<my-read>.toArray()` is detected.
|
||||
*/
|
||||
function checkNonTsReferenceCallsField(ref, fieldName) {
|
||||
const propertyAccess = checkNonTsReferenceAccessesField(ref, fieldName);
|
||||
if (propertyAccess === null) {
|
||||
return null;
|
||||
}
|
||||
const accessIdx = ref.from.readAstPath.indexOf(propertyAccess);
|
||||
if (accessIdx === -1) {
|
||||
return null;
|
||||
}
|
||||
const potentialRead = ref.from.readAstPath[accessIdx];
|
||||
if (potentialRead === undefined) {
|
||||
return null;
|
||||
}
|
||||
return potentialRead;
|
||||
}
|
||||
|
||||
const printer = ts.createPrinter();
|
||||
function calculateDeclarationReplacement(info, node, aliasParam) {
|
||||
const sf = node.getSourceFile();
|
||||
let payloadTypes;
|
||||
if (node.initializer && ts.isNewExpression(node.initializer) && node.initializer.typeArguments) {
|
||||
payloadTypes = node.initializer.typeArguments;
|
||||
}
|
||||
else if (node.type && ts.isTypeReferenceNode(node.type) && node.type.typeArguments) {
|
||||
payloadTypes = ts.factory.createNodeArray(node.type.typeArguments);
|
||||
}
|
||||
const outputCall = ts.factory.createCallExpression(ts.factory.createIdentifier('output'), payloadTypes, aliasParam !== undefined
|
||||
? [
|
||||
ts.factory.createObjectLiteralExpression([
|
||||
ts.factory.createPropertyAssignment('alias', ts.factory.createStringLiteral(aliasParam, true)),
|
||||
], false),
|
||||
]
|
||||
: []);
|
||||
const existingModifiers = (node.modifiers ?? []).filter((modifier) => !ts.isDecorator(modifier) && modifier.kind !== ts.SyntaxKind.ReadonlyKeyword);
|
||||
const updatedOutputDeclaration = ts.factory.createPropertyDeclaration(
|
||||
// Think: this logic of dealing with modifiers is applicable to all signal-based migrations
|
||||
ts.factory.createNodeArray([
|
||||
...existingModifiers,
|
||||
ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword),
|
||||
]), node.name, undefined, undefined, outputCall);
|
||||
return prepareTextReplacementForNode(info, node, printer.printNode(ts.EmitHint.Unspecified, updatedOutputDeclaration, sf));
|
||||
}
|
||||
function calculateImportReplacements(info, sourceFiles) {
|
||||
const importReplacements = {};
|
||||
for (const sf of sourceFiles) {
|
||||
const importManager = new migrations.ImportManager();
|
||||
const addOnly = [];
|
||||
const addRemove = [];
|
||||
const file = project_paths.projectFile(sf, info);
|
||||
importManager.addImport({
|
||||
requestedFile: sf,
|
||||
exportModuleSpecifier: '@angular/core',
|
||||
exportSymbolName: 'output',
|
||||
});
|
||||
apply_import_manager.applyImportManagerChanges(importManager, addOnly, [sf], info);
|
||||
importManager.removeImport(sf, 'Output', '@angular/core');
|
||||
importManager.removeImport(sf, 'EventEmitter', '@angular/core');
|
||||
apply_import_manager.applyImportManagerChanges(importManager, addRemove, [sf], info);
|
||||
importReplacements[file.id] = {
|
||||
add: addOnly,
|
||||
addAndRemove: addRemove,
|
||||
};
|
||||
}
|
||||
return importReplacements;
|
||||
}
|
||||
function calculateNextFnReplacement(info, node) {
|
||||
return prepareTextReplacementForNode(info, node, 'emit');
|
||||
}
|
||||
function calculateNextFnReplacementInTemplate(file, span) {
|
||||
return prepareTextReplacement(file, 'emit', span.start, span.end);
|
||||
}
|
||||
function calculateNextFnReplacementInHostBinding(file, offset, span) {
|
||||
return prepareTextReplacement(file, 'emit', offset + span.start, offset + span.end);
|
||||
}
|
||||
function calculateCompleteCallReplacement(info, node) {
|
||||
return prepareTextReplacementForNode(info, node, '', node.getFullStart());
|
||||
}
|
||||
function calculatePipeCallReplacement(info, node) {
|
||||
if (ts.isPropertyAccessExpression(node.expression)) {
|
||||
const sf = node.getSourceFile();
|
||||
const importManager = new migrations.ImportManager();
|
||||
const outputToObservableIdent = importManager.addImport({
|
||||
requestedFile: sf,
|
||||
exportModuleSpecifier: '@angular/core/rxjs-interop',
|
||||
exportSymbolName: 'outputToObservable',
|
||||
});
|
||||
const toObsCallExp = ts.factory.createCallExpression(outputToObservableIdent, undefined, [
|
||||
node.expression.expression,
|
||||
]);
|
||||
const pipePropAccessExp = ts.factory.updatePropertyAccessExpression(node.expression, toObsCallExp, node.expression.name);
|
||||
const pipeCallExp = ts.factory.updateCallExpression(node, pipePropAccessExp, [], node.arguments);
|
||||
const replacements = [
|
||||
prepareTextReplacementForNode(info, node, printer.printNode(ts.EmitHint.Unspecified, pipeCallExp, sf)),
|
||||
];
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, [sf], info);
|
||||
return replacements;
|
||||
}
|
||||
else {
|
||||
// TODO: assert instead?
|
||||
throw new Error(`Unexpected call expression for .pipe - expected a property access but got "${node.getText()}"`);
|
||||
}
|
||||
}
|
||||
function prepareTextReplacementForNode(info, node, replacement, start) {
|
||||
const sf = node.getSourceFile();
|
||||
return new project_paths.Replacement(project_paths.projectFile(sf, info), new project_paths.TextUpdate({
|
||||
position: start ?? node.getStart(),
|
||||
end: node.getEnd(),
|
||||
toInsert: replacement,
|
||||
}));
|
||||
}
|
||||
function prepareTextReplacement(file, replacement, start, end) {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: start,
|
||||
end: end,
|
||||
toInsert: replacement,
|
||||
}));
|
||||
}
|
||||
|
||||
class OutputMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
async analyze(info) {
|
||||
const { sourceFiles, program } = info;
|
||||
const outputFieldReplacements = {};
|
||||
const problematicUsages = {};
|
||||
let problematicDeclarationCount = 0;
|
||||
const filesWithOutputDeclarations = new Set();
|
||||
const checker = program.getTypeChecker();
|
||||
const reflector = new migrations.TypeScriptReflectionHost(checker);
|
||||
const dtsReader = new migrations.DtsMetadataReader(checker, reflector);
|
||||
const evaluator = new migrations.PartialEvaluator(reflector, checker, null);
|
||||
const resourceLoader = info.ngCompiler?.['resourceManager'] ?? null;
|
||||
// Pre-analyze the program and get access to the template type checker.
|
||||
// If we are processing a non-Angular target, there is no template info.
|
||||
const { templateTypeChecker } = info.ngCompiler?.['ensureAnalyzed']() ?? {
|
||||
templateTypeChecker: null,
|
||||
};
|
||||
const knownFields = {
|
||||
// Note: We don't support cross-target migration of `Partial<T>` usages.
|
||||
// This is an acceptable limitation for performance reasons.
|
||||
shouldTrackClassReference: () => false,
|
||||
attemptRetrieveDescriptorFromSymbol: (s) => {
|
||||
const propDeclaration = getTargetPropertyDeclaration(s);
|
||||
if (propDeclaration !== null) {
|
||||
const classFieldID = getUniqueIdForProperty(info, propDeclaration);
|
||||
if (classFieldID !== null) {
|
||||
return {
|
||||
node: propDeclaration,
|
||||
key: classFieldID,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
let isTestFile = false;
|
||||
const outputMigrationVisitor = (node) => {
|
||||
// detect output declarations
|
||||
if (ts.isPropertyDeclaration(node)) {
|
||||
const outputDecorator = getOutputDecorator(node, reflector);
|
||||
if (outputDecorator !== null) {
|
||||
if (isOutputDeclarationEligibleForMigration(node)) {
|
||||
const outputDef = {
|
||||
id: getUniqueIdForProperty(info, node),
|
||||
aliasParam: outputDecorator.args?.at(0),
|
||||
};
|
||||
const outputFile = project_paths.projectFile(node.getSourceFile(), info);
|
||||
if (this.config.shouldMigrate === undefined ||
|
||||
this.config.shouldMigrate({
|
||||
key: outputDef.id,
|
||||
node: node,
|
||||
}, outputFile)) {
|
||||
const aliasParam = outputDef.aliasParam;
|
||||
const aliasOptionValue = aliasParam ? evaluator.evaluate(aliasParam) : undefined;
|
||||
if (aliasOptionValue == undefined || typeof aliasOptionValue === 'string') {
|
||||
filesWithOutputDeclarations.add(node.getSourceFile());
|
||||
addOutputReplacement(outputFieldReplacements, outputDef.id, outputFile, calculateDeclarationReplacement(info, node, aliasOptionValue?.toString()));
|
||||
}
|
||||
else {
|
||||
problematicUsages[outputDef.id] = true;
|
||||
problematicDeclarationCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
problematicDeclarationCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
// detect .next usages that should be migrated to .emit
|
||||
if (isPotentialNextCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
|
||||
const propertyDeclaration = isTargetOutputDeclaration(node.expression.expression, checker, reflector, dtsReader);
|
||||
if (propertyDeclaration !== null) {
|
||||
const id = getUniqueIdForProperty(info, propertyDeclaration);
|
||||
const outputFile = project_paths.projectFile(node.getSourceFile(), info);
|
||||
addOutputReplacement(outputFieldReplacements, id, outputFile, calculateNextFnReplacement(info, node.expression.name));
|
||||
}
|
||||
}
|
||||
// detect .complete usages that should be removed
|
||||
if (isPotentialCompleteCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
|
||||
const propertyDeclaration = isTargetOutputDeclaration(node.expression.expression, checker, reflector, dtsReader);
|
||||
if (propertyDeclaration !== null) {
|
||||
const id = getUniqueIdForProperty(info, propertyDeclaration);
|
||||
const outputFile = project_paths.projectFile(node.getSourceFile(), info);
|
||||
if (ts.isExpressionStatement(node.parent)) {
|
||||
addOutputReplacement(outputFieldReplacements, id, outputFile, calculateCompleteCallReplacement(info, node.parent));
|
||||
}
|
||||
else {
|
||||
problematicUsages[id] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
addCommentForEmptyEmit(node, info, checker, reflector, dtsReader, outputFieldReplacements);
|
||||
// detect imports of test runners
|
||||
if (isTestRunnerImport(node)) {
|
||||
isTestFile = true;
|
||||
}
|
||||
// detect unsafe access of the output property
|
||||
if (isPotentialPipeCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
|
||||
const propertyDeclaration = isTargetOutputDeclaration(node.expression.expression, checker, reflector, dtsReader);
|
||||
if (propertyDeclaration !== null) {
|
||||
const id = getUniqueIdForProperty(info, propertyDeclaration);
|
||||
if (isTestFile) {
|
||||
const outputFile = project_paths.projectFile(node.getSourceFile(), info);
|
||||
addOutputReplacement(outputFieldReplacements, id, outputFile, ...calculatePipeCallReplacement(info, node));
|
||||
}
|
||||
else {
|
||||
problematicUsages[id] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, outputMigrationVisitor);
|
||||
};
|
||||
// calculate output migration replacements
|
||||
for (const sf of sourceFiles) {
|
||||
isTestFile = false;
|
||||
ts.forEachChild(sf, outputMigrationVisitor);
|
||||
}
|
||||
// take care of the references in templates and host bindings
|
||||
const referenceResult = { references: [] };
|
||||
const { visitor: templateHostRefVisitor } = index.createFindAllSourceFileReferencesVisitor(info, checker, reflector, resourceLoader, evaluator, templateTypeChecker, knownFields, null, // TODO: capture known output names as an optimization
|
||||
referenceResult);
|
||||
// calculate template / host binding replacements
|
||||
for (const sf of sourceFiles) {
|
||||
ts.forEachChild(sf, templateHostRefVisitor);
|
||||
}
|
||||
for (const ref of referenceResult.references) {
|
||||
// detect .next usages that should be migrated to .emit in template and host binding expressions
|
||||
if (ref.kind === index.ReferenceKind.InTemplate) {
|
||||
const callExpr = checkNonTsReferenceCallsField(ref, 'next');
|
||||
// TODO: here and below for host bindings, we should ideally filter in the global meta stage
|
||||
// (instead of using the `outputFieldReplacements` map)
|
||||
// as technically, the call expression could refer to an output
|
||||
// from a whole different compilation unit (e.g. tsconfig.json).
|
||||
if (callExpr !== null && outputFieldReplacements[ref.target.key] !== undefined) {
|
||||
addOutputReplacement(outputFieldReplacements, ref.target.key, ref.from.templateFile, calculateNextFnReplacementInTemplate(ref.from.templateFile, callExpr.nameSpan));
|
||||
}
|
||||
}
|
||||
else if (ref.kind === index.ReferenceKind.InHostBinding) {
|
||||
const callExpr = checkNonTsReferenceCallsField(ref, 'next');
|
||||
if (callExpr !== null && outputFieldReplacements[ref.target.key] !== undefined) {
|
||||
addOutputReplacement(outputFieldReplacements, ref.target.key, ref.from.file, calculateNextFnReplacementInHostBinding(ref.from.file, ref.from.hostPropertyNode.getStart() + 1, callExpr.nameSpan));
|
||||
}
|
||||
}
|
||||
}
|
||||
// calculate import replacements but do so only for files that have output declarations
|
||||
const importReplacements = calculateImportReplacements(info, filesWithOutputDeclarations);
|
||||
return project_paths.confirmAsSerializable({
|
||||
problematicDeclarationCount,
|
||||
outputFields: outputFieldReplacements,
|
||||
importReplacements,
|
||||
problematicUsages,
|
||||
});
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const outputFields = {};
|
||||
const importReplacements = {};
|
||||
const problematicUsages = {};
|
||||
let problematicDeclarationCount = 0;
|
||||
for (const unit of [unitA, unitB]) {
|
||||
for (const declIdStr of Object.keys(unit.outputFields)) {
|
||||
const declId = declIdStr;
|
||||
// THINK: detect clash? Should we have an utility to merge data based on unique IDs?
|
||||
outputFields[declId] = unit.outputFields[declId];
|
||||
}
|
||||
for (const fileIDStr of Object.keys(unit.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
importReplacements[fileID] = unit.importReplacements[fileID];
|
||||
}
|
||||
problematicDeclarationCount += unit.problematicDeclarationCount;
|
||||
}
|
||||
for (const unit of [unitA, unitB]) {
|
||||
for (const declIdStr of Object.keys(unit.problematicUsages)) {
|
||||
const declId = declIdStr;
|
||||
problematicUsages[declId] = unit.problematicUsages[declId];
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
problematicDeclarationCount,
|
||||
outputFields,
|
||||
importReplacements,
|
||||
problematicUsages,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
const globalMeta = {
|
||||
importReplacements: combinedData.importReplacements,
|
||||
outputFields: combinedData.outputFields,
|
||||
problematicDeclarationCount: combinedData.problematicDeclarationCount,
|
||||
problematicUsages: {},
|
||||
};
|
||||
for (const keyStr of Object.keys(combinedData.problematicUsages)) {
|
||||
const key = keyStr;
|
||||
// it might happen that a problematic usage is detected but we didn't see the declaration - skipping those
|
||||
if (globalMeta.outputFields[key] !== undefined) {
|
||||
globalMeta.problematicUsages[key] = true;
|
||||
}
|
||||
}
|
||||
// Noop here as we don't have any form of special global metadata.
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const detectedOutputs = new Set(Object.keys(globalMetadata.outputFields)).size +
|
||||
globalMetadata.problematicDeclarationCount;
|
||||
const problematicOutputs = new Set(Object.keys(globalMetadata.problematicUsages)).size +
|
||||
globalMetadata.problematicDeclarationCount;
|
||||
const successRate = detectedOutputs > 0 ? (detectedOutputs - problematicOutputs) / detectedOutputs : 1;
|
||||
return project_paths.confirmAsSerializable({
|
||||
detectedOutputs,
|
||||
problematicOutputs,
|
||||
successRate,
|
||||
});
|
||||
}
|
||||
async migrate(globalData) {
|
||||
const migratedFiles = new Set();
|
||||
const problematicFiles = new Set();
|
||||
const replacements = [];
|
||||
for (const declIdStr of Object.keys(globalData.outputFields)) {
|
||||
const declId = declIdStr;
|
||||
const outputField = globalData.outputFields[declId];
|
||||
if (!globalData.problematicUsages[declId]) {
|
||||
replacements.push(...outputField.replacements);
|
||||
migratedFiles.add(outputField.file.id);
|
||||
}
|
||||
else {
|
||||
problematicFiles.add(outputField.file.id);
|
||||
}
|
||||
}
|
||||
for (const fileIDStr of Object.keys(globalData.importReplacements)) {
|
||||
const fileID = fileIDStr;
|
||||
if (migratedFiles.has(fileID)) {
|
||||
const importReplacements = globalData.importReplacements[fileID];
|
||||
if (problematicFiles.has(fileID)) {
|
||||
replacements.push(...importReplacements.add);
|
||||
}
|
||||
else {
|
||||
replacements.push(...importReplacements.addAndRemove);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { replacements };
|
||||
}
|
||||
}
|
||||
function addOutputReplacement(outputFieldReplacements, outputId, file, ...replacements) {
|
||||
let existingReplacements = outputFieldReplacements[outputId];
|
||||
if (existingReplacements === undefined) {
|
||||
outputFieldReplacements[outputId] = existingReplacements = {
|
||||
file: file,
|
||||
replacements: [],
|
||||
};
|
||||
}
|
||||
existingReplacements.replacements.push(...replacements);
|
||||
}
|
||||
function addCommentForEmptyEmit(node, info, checker, reflector, dtsReader, outputFieldReplacements) {
|
||||
if (!isEmptyEmitCall(node))
|
||||
return;
|
||||
const propertyAccess = getPropertyAccess(node);
|
||||
if (!propertyAccess)
|
||||
return;
|
||||
const symbol = checker.getSymbolAtLocation(propertyAccess.name);
|
||||
if (!symbol || !symbol.declarations?.length)
|
||||
return;
|
||||
const propertyDeclaration = isTargetOutputDeclaration(propertyAccess, checker, reflector, dtsReader);
|
||||
if (!propertyDeclaration)
|
||||
return;
|
||||
const eventEmitterType = getEventEmitterArgumentType(propertyDeclaration);
|
||||
if (!eventEmitterType)
|
||||
return;
|
||||
const id = getUniqueIdForProperty(info, propertyDeclaration);
|
||||
const file = project_paths.projectFile(node.getSourceFile(), info);
|
||||
const formatter = getFormatterText(node);
|
||||
const todoReplacement = new project_paths.TextUpdate({
|
||||
toInsert: `${formatter.indent}// TODO: The 'emit' function requires a mandatory ${eventEmitterType} argument\n`,
|
||||
end: formatter.lineStartPos,
|
||||
position: formatter.lineStartPos,
|
||||
});
|
||||
addOutputReplacement(outputFieldReplacements, id, file, new project_paths.Replacement(file, todoReplacement));
|
||||
}
|
||||
function isEmptyEmitCall(node) {
|
||||
return (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === 'emit' &&
|
||||
node.arguments.length === 0);
|
||||
}
|
||||
function getPropertyAccess(node) {
|
||||
const propertyAccessExpression = node.expression.expression;
|
||||
return ts.isPropertyAccessExpression(propertyAccessExpression) ? propertyAccessExpression : null;
|
||||
}
|
||||
function getEventEmitterArgumentType(propertyDeclaration) {
|
||||
const initializer = propertyDeclaration.initializer;
|
||||
if (!initializer || !ts.isNewExpression(initializer))
|
||||
return null;
|
||||
const isEventEmitter = ts.isIdentifier(initializer.expression) && initializer.expression.getText() === 'EventEmitter';
|
||||
if (!isEventEmitter)
|
||||
return null;
|
||||
const [typeArg] = initializer.typeArguments ?? [];
|
||||
return typeArg ? typeArg.getText() : null;
|
||||
}
|
||||
function getFormatterText(node) {
|
||||
const sourceFile = node.getSourceFile();
|
||||
const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
||||
const lineStartPos = sourceFile.getPositionOfLineAndCharacter(line, 0);
|
||||
const indent = sourceFile.text.slice(lineStartPos, node.getStart());
|
||||
return { indent, lineStartPos };
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new OutputMigration({
|
||||
shouldMigrate: (_, file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
afterProgramCreation: (info, fs) => {
|
||||
const analysisPath = fs.resolve(options.analysisDir);
|
||||
// Support restricting the analysis to subfolders for larger projects.
|
||||
if (analysisPath !== '/') {
|
||||
info.sourceFiles = info.sourceFiles.filter((sf) => sf.fileName.startsWith(analysisPath));
|
||||
info.fullProgramSourceFiles = info.fullProgramSourceFiles.filter((sf) => sf.fileName.startsWith(analysisPath));
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for outputs: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: ({ detectedOutputs, problematicOutputs, successRate }) => {
|
||||
const migratedOutputs = detectedOutputs - problematicOutputs;
|
||||
const successRatePercent = (successRate * 100).toFixed(2);
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated to outputs as functions 🎉`);
|
||||
context.logger.info(` -> Migrated ${migratedOutputs} out of ${detectedOutputs} detected outputs (${successRatePercent} %).`);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var compiler = require('@angular/compiler');
|
||||
|
||||
/**
|
||||
* parses the template string into the Html AST
|
||||
*/
|
||||
function parseTemplate(template) {
|
||||
let parsed;
|
||||
try {
|
||||
// Note: we use the HtmlParser here, instead of the `parseTemplate` function, because the
|
||||
// latter returns an Ivy AST, not an HTML AST. The HTML AST has the advantage of preserving
|
||||
// interpolated text as text nodes containing a mixture of interpolation tokens and text tokens,
|
||||
// rather than turning them into `BoundText` nodes like the Ivy AST does. This allows us to
|
||||
// easily get the text-only ranges without having to reconstruct the original text.
|
||||
parsed = new compiler.HtmlParser().parse(template, '', {
|
||||
// Allows for ICUs to be parsed.
|
||||
tokenizeExpansionForms: true,
|
||||
// Explicitly disable blocks so that their characters are treated as plain text.
|
||||
tokenizeBlocks: true,
|
||||
preserveLineEndings: true,
|
||||
});
|
||||
// Don't migrate invalid templates.
|
||||
if (parsed.errors && parsed.errors.length > 0) {
|
||||
const errors = parsed.errors.map((e) => ({ type: 'parse', error: e }));
|
||||
return { tree: undefined, errors };
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
return { tree: undefined, errors: [{ type: 'parse', error: e }] };
|
||||
}
|
||||
return { tree: parsed, errors: [] };
|
||||
}
|
||||
function pipeMatchRegExpFor(name) {
|
||||
return new RegExp(`\\|\\s*${name}`);
|
||||
}
|
||||
const commonModulePipes = [
|
||||
'date',
|
||||
'async',
|
||||
'currency',
|
||||
'number',
|
||||
'i18nPlural',
|
||||
'i18nSelect',
|
||||
'json',
|
||||
'keyvalue',
|
||||
'slice',
|
||||
'lowercase',
|
||||
'uppercase',
|
||||
'titlecase',
|
||||
'percent',
|
||||
].map((name) => pipeMatchRegExpFor(name));
|
||||
function allFormsOf(selector) {
|
||||
return [selector, `*${selector}`, `[${selector}]`];
|
||||
}
|
||||
const commonModuleDirectives = new Set([
|
||||
...allFormsOf('ngComponentOutlet'),
|
||||
...allFormsOf('ngTemplateOutlet'),
|
||||
...allFormsOf('ngClass'),
|
||||
...allFormsOf('ngPlural'),
|
||||
...allFormsOf('ngPluralCase'),
|
||||
...allFormsOf('ngStyle'),
|
||||
...allFormsOf('ngTemplateOutlet'),
|
||||
...allFormsOf('ngComponentOutlet'),
|
||||
'[NgForOf]',
|
||||
'[NgForTrackBy]',
|
||||
'[ngIfElse]',
|
||||
'[ngIfThenElse]',
|
||||
'*ngIf',
|
||||
'*ngSwitch',
|
||||
'*ngFor',
|
||||
]);
|
||||
/**
|
||||
* determines if the CommonModule can be safely removed from imports
|
||||
*/
|
||||
function canRemoveCommonModule(template) {
|
||||
const parsed = parseTemplate(template);
|
||||
let removeCommonModule = false;
|
||||
if (parsed.tree !== undefined) {
|
||||
const visitor = new CommonCollector();
|
||||
compiler.visitAll(visitor, parsed.tree.rootNodes);
|
||||
removeCommonModule = visitor.count === 0;
|
||||
}
|
||||
return removeCommonModule;
|
||||
}
|
||||
/** Finds all non-control flow elements from common module. */
|
||||
class CommonCollector extends compiler.RecursiveVisitor {
|
||||
count = 0;
|
||||
visitElement(el) {
|
||||
if (el.attrs.length > 0) {
|
||||
for (const attr of el.attrs) {
|
||||
if (this.hasDirectives(attr.name) || this.hasPipes(attr.value)) {
|
||||
this.count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
super.visitElement(el, null);
|
||||
}
|
||||
visitBlock(ast) {
|
||||
for (const blockParam of ast.parameters) {
|
||||
if (this.hasPipes(blockParam.expression)) {
|
||||
this.count++;
|
||||
}
|
||||
}
|
||||
super.visitBlock(ast, null);
|
||||
}
|
||||
visitText(ast) {
|
||||
if (this.hasPipes(ast.value)) {
|
||||
this.count++;
|
||||
}
|
||||
}
|
||||
visitLetDeclaration(decl) {
|
||||
if (this.hasPipes(decl.value)) {
|
||||
this.count++;
|
||||
}
|
||||
super.visitLetDeclaration(decl, null);
|
||||
}
|
||||
hasDirectives(input) {
|
||||
return commonModuleDirectives.has(input);
|
||||
}
|
||||
hasPipes(input) {
|
||||
return commonModulePipes.some((regexp) => regexp.test(input));
|
||||
}
|
||||
}
|
||||
|
||||
exports.canRemoveCommonModule = canRemoveCommonModule;
|
||||
exports.parseTemplate = parseTemplate;
|
||||
+586
@@ -0,0 +1,586 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var compilerCli = require('@angular/compiler-cli');
|
||||
var schematics = require('@angular-devkit/schematics');
|
||||
var core = require('@angular-devkit/core');
|
||||
var posixPath = require('node:path/posix');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var ts = require('typescript');
|
||||
var path = require('node:path');
|
||||
var project_tsconfig_paths = require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
function _interopNamespaceDefault(e) {
|
||||
var n = Object.create(null);
|
||||
if (e) {
|
||||
Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default') {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
n.default = e;
|
||||
return Object.freeze(n);
|
||||
}
|
||||
|
||||
var posixPath__namespace = /*#__PURE__*/_interopNamespaceDefault(posixPath);
|
||||
var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
|
||||
|
||||
/**
|
||||
* Angular compiler file system implementation that leverages an
|
||||
* CLI schematic virtual file tree.
|
||||
*/
|
||||
class DevkitMigrationFilesystem {
|
||||
tree;
|
||||
constructor(tree) {
|
||||
this.tree = tree;
|
||||
}
|
||||
extname(path) {
|
||||
return core.extname(path);
|
||||
}
|
||||
isRoot(path) {
|
||||
return path === core.normalize('/');
|
||||
}
|
||||
isRooted(path) {
|
||||
return this.normalize(path).startsWith('/');
|
||||
}
|
||||
dirname(file) {
|
||||
return this.normalize(core.dirname(file));
|
||||
}
|
||||
join(basePath, ...paths) {
|
||||
return this.normalize(core.join(basePath, ...paths));
|
||||
}
|
||||
relative(from, to) {
|
||||
return this.normalize(core.relative(from, to));
|
||||
}
|
||||
basename(filePath, extension) {
|
||||
return posixPath__namespace.basename(filePath, extension);
|
||||
}
|
||||
normalize(path) {
|
||||
return core.normalize(path);
|
||||
}
|
||||
resolve(...paths) {
|
||||
const normalizedPaths = paths.map((p) => core.normalize(p));
|
||||
// In dev-kit, the NodeJS working directory should never be
|
||||
// considered, so `/` is the last resort over `cwd`.
|
||||
return this.normalize(posixPath__namespace.resolve(core.normalize('/'), ...normalizedPaths));
|
||||
}
|
||||
pwd() {
|
||||
return '/';
|
||||
}
|
||||
isCaseSensitive() {
|
||||
return true;
|
||||
}
|
||||
exists(path) {
|
||||
return statPath(this.tree, path) !== null;
|
||||
}
|
||||
readFile(path) {
|
||||
return this.tree.readText(path);
|
||||
}
|
||||
readFileBuffer(path) {
|
||||
const buffer = this.tree.read(path);
|
||||
if (buffer === null) {
|
||||
throw new Error(`File does not exist: ${path}`);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
readdir(path) {
|
||||
const dir = this.tree.getDir(path);
|
||||
return [
|
||||
...dir.subdirs,
|
||||
...dir.subfiles,
|
||||
];
|
||||
}
|
||||
lstat(path) {
|
||||
const stat = statPath(this.tree, path);
|
||||
if (stat === null) {
|
||||
throw new Error(`File does not exist for "lstat": ${path}`);
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
stat(path) {
|
||||
const stat = statPath(this.tree, path);
|
||||
if (stat === null) {
|
||||
throw new Error(`File does not exist for "stat": ${path}`);
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
realpath(filePath) {
|
||||
return filePath;
|
||||
}
|
||||
getDefaultLibLocation() {
|
||||
return 'node_modules/typescript/lib';
|
||||
}
|
||||
ensureDir(path) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#ensureDir is not supported.');
|
||||
}
|
||||
writeFile(path, data) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#writeFile is not supported.');
|
||||
}
|
||||
removeFile(path) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#removeFile is not supported.');
|
||||
}
|
||||
copyFile(from, to) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#copyFile is not supported.');
|
||||
}
|
||||
moveFile(from, to) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#moveFile is not supported.');
|
||||
}
|
||||
removeDeep(path) {
|
||||
// Migrations should compute replacements and not write directly.
|
||||
throw new Error('DevkitFilesystem#removeDeep is not supported.');
|
||||
}
|
||||
chdir(_path) {
|
||||
throw new Error('FileSystem#chdir is not supported.');
|
||||
}
|
||||
symlink() {
|
||||
throw new Error('FileSystem#symlink is not supported.');
|
||||
}
|
||||
}
|
||||
/** Stats the given path in the virtual tree. */
|
||||
function statPath(tree, path) {
|
||||
let fileInfo = null;
|
||||
let dirInfo = null;
|
||||
try {
|
||||
fileInfo = tree.get(path);
|
||||
}
|
||||
catch (e) {
|
||||
if (e.constructor.name === 'PathIsDirectoryException') {
|
||||
dirInfo = tree.getDir(path);
|
||||
}
|
||||
else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
if (fileInfo !== null || dirInfo !== null) {
|
||||
return {
|
||||
isDirectory: () => dirInfo !== null,
|
||||
isFile: () => fileInfo !== null,
|
||||
isSymbolicLink: () => false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups the given replacements per project relative
|
||||
* file path.
|
||||
*
|
||||
* This allows for simple execution of the replacements
|
||||
* against a given file. E.g. via {@link applyTextUpdates}.
|
||||
*/
|
||||
function groupReplacementsByFile(replacements) {
|
||||
const result = new Map();
|
||||
for (const { projectFile, update } of replacements) {
|
||||
if (!result.has(projectFile.rootRelativePath)) {
|
||||
result.set(projectFile.rootRelativePath, []);
|
||||
}
|
||||
result.get(projectFile.rootRelativePath).push(update);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously combines unit data for the given migration.
|
||||
*
|
||||
* Note: This helper is useful for testing and execution of
|
||||
* Tsurge migrations in non-batchable environments. In general,
|
||||
* prefer parallel execution of combining via e.g. Beam combiners.
|
||||
*/
|
||||
async function synchronouslyCombineUnitData(migration, unitDatas) {
|
||||
if (unitDatas.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (unitDatas.length === 1) {
|
||||
return unitDatas[0];
|
||||
}
|
||||
let combined = unitDatas[0];
|
||||
for (let i = 1; i < unitDatas.length; i++) {
|
||||
const other = unitDatas[i];
|
||||
combined = await migration.combine(combined, other);
|
||||
}
|
||||
return combined;
|
||||
}
|
||||
|
||||
/** Whether we are executing inside Google */
|
||||
function isGoogle3() {
|
||||
return process.env['GOOGLE3_TSURGE'] === '1';
|
||||
}
|
||||
/**
|
||||
* By default, Tsurge will always create an Angular compiler program
|
||||
* for projects analyzed and migrated. This works perfectly fine in
|
||||
* third-party where Tsurge migrations run in Angular CLI projects.
|
||||
*
|
||||
* In first party, when running against full Google3, creating an Angular
|
||||
* program for e.g. plain `ts_library` targets is overly expensive and
|
||||
* can result in out of memory issues for large TS targets. In 1P we can
|
||||
* reliably distinguish between TS and Angular targets via the `angularCompilerOptions`.
|
||||
*/
|
||||
function google3UsePlainTsProgramIfNoKnownAngularOption() {
|
||||
return process.env['GOOGLE3_TSURGE'] === '1';
|
||||
}
|
||||
|
||||
/** Options that are good defaults for Tsurge migrations. */
|
||||
const defaultMigrationTsOptions = {
|
||||
// Avoid checking libraries to speed up migrations.
|
||||
skipLibCheck: true,
|
||||
skipDefaultLibCheck: true,
|
||||
noEmit: true,
|
||||
// Does not apply to g3 and externally is enforced when the app is built by the compiler.
|
||||
disableTypeScriptVersionCheck: true,
|
||||
};
|
||||
/**
|
||||
* Creates an instance of a TypeScript program for the given project.
|
||||
*/
|
||||
function createPlainTsProgram(tsHost, tsconfig, optionOverrides) {
|
||||
const program = ts.createProgram({
|
||||
rootNames: tsconfig.rootNames,
|
||||
options: {
|
||||
...tsconfig.options,
|
||||
...defaultMigrationTsOptions,
|
||||
...optionOverrides,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ngCompiler: null,
|
||||
program,
|
||||
userOptions: tsconfig.options,
|
||||
__programAbsoluteRootFileNames: tsconfig.rootNames,
|
||||
host: tsHost,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the configuration of the given TypeScript project and creates
|
||||
* an instance of the Angular compiler for the project.
|
||||
*/
|
||||
function createNgtscProgram(tsHost, tsconfig, optionOverrides) {
|
||||
const ngtscProgram = new compilerCli.NgtscProgram(tsconfig.rootNames, {
|
||||
...tsconfig.options,
|
||||
...defaultMigrationTsOptions,
|
||||
...optionOverrides,
|
||||
}, tsHost);
|
||||
// Expose an easy way to debug-print ng semantic diagnostics.
|
||||
if (process.env['DEBUG_NG_SEMANTIC_DIAGNOSTICS'] === '1') {
|
||||
console.error(ts.formatDiagnosticsWithColorAndContext(ngtscProgram.getNgSemanticDiagnostics(), tsHost));
|
||||
}
|
||||
return {
|
||||
ngCompiler: ngtscProgram.compiler,
|
||||
program: ngtscProgram.getTsProgram(),
|
||||
userOptions: tsconfig.options,
|
||||
__programAbsoluteRootFileNames: tsconfig.rootNames,
|
||||
host: tsHost,
|
||||
};
|
||||
}
|
||||
|
||||
/** Code of the error raised by TypeScript when a tsconfig doesn't match any files. */
|
||||
const NO_INPUTS_ERROR_CODE = 18003;
|
||||
/** Parses the given tsconfig file, supporting Angular compiler options. */
|
||||
function parseTsconfigOrDie(absoluteTsconfigPath, fs) {
|
||||
const tsconfig = compilerCli.readConfiguration(absoluteTsconfigPath, {}, fs);
|
||||
// Skip the "No inputs found..." error since we don't want to interrupt the migration if a
|
||||
// tsconfig doesn't match a file. This will result in an empty `Program` which is still valid.
|
||||
const errors = tsconfig.errors.filter((diag) => diag.code !== NO_INPUTS_ERROR_CODE);
|
||||
if (errors.length) {
|
||||
throw new Error(`Tsconfig could not be parsed or is invalid:\n\n` + `${errors.map((e) => e.messageText)}`);
|
||||
}
|
||||
return tsconfig;
|
||||
}
|
||||
|
||||
// Note: Try to keep mostly in sync with
|
||||
// //depot/google3/javascript/angular2/tools/ngc_wrapped/tsc_plugin.ts
|
||||
// TODO: Consider moving this logic into the 1P launcher.
|
||||
const EXT = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
|
||||
function fileNameToModuleNameFactory(rootDirs, workspaceName) {
|
||||
return (importedFilePath) => {
|
||||
let relativePath = '';
|
||||
for (const rootDir of rootDirs) {
|
||||
const rel = path__namespace.posix.relative(rootDir, importedFilePath);
|
||||
if (!rel.startsWith('.')) {
|
||||
relativePath = rel;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (relativePath) {
|
||||
return `${workspaceName}/${relativePath.replace(EXT, '')}`;
|
||||
}
|
||||
else {
|
||||
return importedFilePath.replace(EXT, '');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Creates the base program info for the given tsconfig path. */
|
||||
function createBaseProgramInfo(absoluteTsconfigPath, fs, optionOverrides = {}) {
|
||||
// Make sure the FS becomes globally available. Some code paths
|
||||
// of the Angular compiler, or tsconfig parsing aren't leveraging
|
||||
// the specified file system.
|
||||
compilerCli.setFileSystem(fs);
|
||||
const tsconfig = parseTsconfigOrDie(absoluteTsconfigPath, fs);
|
||||
const tsHost = new compilerCli.NgtscCompilerHost(fs, tsconfig.options);
|
||||
// When enabled, use a plain TS program if we are sure it's not
|
||||
// an Angular project based on the `tsconfig.json`.
|
||||
if (google3UsePlainTsProgramIfNoKnownAngularOption() &&
|
||||
tsconfig.options['_useHostForImportGeneration'] === undefined) {
|
||||
return createPlainTsProgram(tsHost, tsconfig, optionOverrides);
|
||||
}
|
||||
// The Angular program may try to emit references during analysis or migration.
|
||||
// To replicate the Google3 import emission here, ensure the unified module resolution
|
||||
// can be enabled by the compiler.
|
||||
if (isGoogle3() && tsconfig.options.rootDirs) {
|
||||
tsHost.fileNameToModuleName = fileNameToModuleNameFactory(tsconfig.options.rootDirs,
|
||||
/* workspaceName*/ 'google3');
|
||||
}
|
||||
return createNgtscProgram(tsHost, tsconfig, optionOverrides);
|
||||
}
|
||||
/**
|
||||
* Creates the {@link ProgramInfo} from the given base information.
|
||||
*
|
||||
* This function purely exists to support custom programs that are
|
||||
* intended to be injected into Tsurge migrations. e.g. for language
|
||||
* service refactorings.
|
||||
*/
|
||||
function getProgramInfoFromBaseInfo(baseInfo) {
|
||||
const fullProgramSourceFiles = [...baseInfo.program.getSourceFiles()];
|
||||
const sourceFiles = fullProgramSourceFiles.filter((f) => !f.isDeclarationFile &&
|
||||
// Note `isShim` will work for the initial program, but for TCB programs, the shims are no longer annotated.
|
||||
!migrations.isShim(f) &&
|
||||
!f.fileName.endsWith('.ngtypecheck.ts'));
|
||||
// Sort it by length in reverse order (longest first). This speeds up lookups,
|
||||
// since there's no need to keep going through the array once a match is found.
|
||||
const sortedRootDirs = migrations.getRootDirs(baseInfo.host, baseInfo.userOptions).sort((a, b) => b.length - a.length);
|
||||
// TODO: Consider also following TS's logic here, finding the common source root.
|
||||
// See: Program#getCommonSourceDirectory.
|
||||
const primaryRoot = compilerCli.absoluteFrom(baseInfo.userOptions.rootDir ?? sortedRootDirs.at(-1) ?? baseInfo.program.getCurrentDirectory());
|
||||
return {
|
||||
...baseInfo,
|
||||
sourceFiles,
|
||||
fullProgramSourceFiles,
|
||||
sortedRootDirs,
|
||||
projectRoot: primaryRoot,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*
|
||||
* Base class for the possible Tsurge migration variants.
|
||||
*
|
||||
* For example, this class exposes methods to conveniently create
|
||||
* TypeScript programs, while also allowing migration authors to override.
|
||||
*/
|
||||
class TsurgeBaseMigration {
|
||||
/**
|
||||
* Creates the TypeScript program for a given compilation unit.
|
||||
*
|
||||
* By default:
|
||||
* - In 3P: Ngtsc programs are being created.
|
||||
* - In 1P: Ngtsc or TS programs are created based on the Blaze target.
|
||||
*/
|
||||
createProgram(tsconfigAbsPath, fs, optionsOverride) {
|
||||
return getProgramInfoFromBaseInfo(createBaseProgramInfo(tsconfigAbsPath, fs, optionsOverride));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A simpler variant of a {@link TsurgeComplexMigration} that does not
|
||||
* fan-out into multiple workers per compilation unit to compute
|
||||
* the final migration replacements.
|
||||
*
|
||||
* This is faster and less resource intensive as workers and TS programs
|
||||
* are only ever created once.
|
||||
*
|
||||
* This is commonly the case when migrations are refactored to eagerly
|
||||
* compute replacements in the analyze stage, and then leverage the
|
||||
* global unit data to filter replacements that turned out to be "invalid".
|
||||
*/
|
||||
class TsurgeFunnelMigration extends TsurgeBaseMigration {
|
||||
}
|
||||
/**
|
||||
* Complex variant of a `Tsurge` migration.
|
||||
*
|
||||
* For example, every analyze worker may contribute to a list of TS
|
||||
* references that are later combined. The migrate phase can then compute actual
|
||||
* file updates for all individual compilation units, leveraging the global metadata
|
||||
* to e.g. see if there are any references from other compilation units that may be
|
||||
* problematic and prevent migration of a given file.
|
||||
*/
|
||||
class TsurgeComplexMigration extends TsurgeBaseMigration {
|
||||
}
|
||||
|
||||
exports.MigrationStage = void 0;
|
||||
(function (MigrationStage) {
|
||||
/** The migration is analyzing an entrypoint */
|
||||
MigrationStage[MigrationStage["Analysis"] = 0] = "Analysis";
|
||||
/** The migration is about to migrate an entrypoint */
|
||||
MigrationStage[MigrationStage["Migrate"] = 1] = "Migrate";
|
||||
})(exports.MigrationStage || (exports.MigrationStage = {}));
|
||||
/** Runs a Tsurge within an Angular Devkit context. */
|
||||
async function runMigrationInDevkit(config) {
|
||||
const { buildPaths, testPaths } = await project_tsconfig_paths.getProjectTsConfigPaths(config.tree);
|
||||
if (!buildPaths.length && !testPaths.length) {
|
||||
throw new schematics.SchematicsException('Could not find any tsconfig file. Cannot run the migration.');
|
||||
}
|
||||
const tsconfigPaths = [...buildPaths, ...testPaths];
|
||||
const fs = new DevkitMigrationFilesystem(config.tree);
|
||||
compilerCli.setFileSystem(fs);
|
||||
const migration = config.getMigration(fs);
|
||||
const unitResults = [];
|
||||
const isFunnelMigration = migration instanceof TsurgeFunnelMigration;
|
||||
const compilationUnitAssignments = new Map();
|
||||
for (const tsconfigPath of tsconfigPaths) {
|
||||
config.beforeProgramCreation?.(tsconfigPath, exports.MigrationStage.Analysis);
|
||||
const info = migration.createProgram(tsconfigPath, fs);
|
||||
modifyProgramInfoToEnsureNonOverlappingFiles(tsconfigPath, info, compilationUnitAssignments);
|
||||
config.afterProgramCreation?.(info, fs, exports.MigrationStage.Analysis);
|
||||
config.beforeUnitAnalysis?.(tsconfigPath);
|
||||
unitResults.push(await migration.analyze(info));
|
||||
}
|
||||
config.afterAllAnalyzed?.();
|
||||
const combined = await synchronouslyCombineUnitData(migration, unitResults);
|
||||
if (combined === null) {
|
||||
config.afterAnalysisFailure?.();
|
||||
return;
|
||||
}
|
||||
const globalMeta = await migration.globalMeta(combined);
|
||||
let replacements;
|
||||
if (isFunnelMigration) {
|
||||
replacements = (await migration.migrate(globalMeta)).replacements;
|
||||
}
|
||||
else {
|
||||
replacements = [];
|
||||
for (const tsconfigPath of tsconfigPaths) {
|
||||
config.beforeProgramCreation?.(tsconfigPath, exports.MigrationStage.Migrate);
|
||||
const info = migration.createProgram(tsconfigPath, fs);
|
||||
modifyProgramInfoToEnsureNonOverlappingFiles(tsconfigPath, info, compilationUnitAssignments);
|
||||
config.afterProgramCreation?.(info, fs, exports.MigrationStage.Migrate);
|
||||
const result = await migration.migrate(globalMeta, info);
|
||||
replacements.push(...result.replacements);
|
||||
}
|
||||
}
|
||||
const replacementsPerFile = new Map();
|
||||
const changesPerFile = groupReplacementsByFile(replacements);
|
||||
for (const [file, changes] of changesPerFile) {
|
||||
if (!replacementsPerFile.has(file)) {
|
||||
replacementsPerFile.set(file, changes);
|
||||
}
|
||||
}
|
||||
for (const [file, changes] of replacementsPerFile) {
|
||||
const recorder = config.tree.beginUpdate(file);
|
||||
for (const c of changes) {
|
||||
recorder
|
||||
.remove(c.data.position, c.data.end - c.data.position)
|
||||
.insertRight(c.data.position, c.data.toInsert);
|
||||
}
|
||||
config.tree.commitUpdate(recorder);
|
||||
}
|
||||
config.whenDone?.(await migration.stats(globalMeta));
|
||||
}
|
||||
/**
|
||||
* Special logic for devkit migrations. In the Angular CLI, or in 3P precisely,
|
||||
* projects can have tsconfigs with overlapping source files. i.e. two tsconfigs
|
||||
* like e.g. build or test include the same `ts.SourceFile` (`.ts`). Migrations
|
||||
* should never have 2+ compilation units with overlapping source files as this
|
||||
* can result in duplicated replacements or analysis— hence we only ever assign a
|
||||
* source file to a compilation unit *once*.
|
||||
*
|
||||
* Note that this is fine as we expect Tsurge migrations to work together as
|
||||
* isolated compilation units— so it shouldn't matter if worst case a `.ts`
|
||||
* file ends up in the e.g. test program.
|
||||
*/
|
||||
function modifyProgramInfoToEnsureNonOverlappingFiles(tsconfigPath, info, compilationUnitAssignments) {
|
||||
const sourceFiles = [];
|
||||
for (const sf of info.sourceFiles) {
|
||||
const assignment = compilationUnitAssignments.get(sf.fileName);
|
||||
// File is already assigned to a different compilation unit.
|
||||
if (assignment !== undefined && assignment !== tsconfigPath) {
|
||||
continue;
|
||||
}
|
||||
compilationUnitAssignments.set(sf.fileName, tsconfigPath);
|
||||
sourceFiles.push(sf);
|
||||
}
|
||||
info.sourceFiles = sourceFiles;
|
||||
}
|
||||
|
||||
/** A text replacement for the given file. */
|
||||
class Replacement {
|
||||
projectFile;
|
||||
update;
|
||||
constructor(projectFile, update) {
|
||||
this.projectFile = projectFile;
|
||||
this.update = update;
|
||||
}
|
||||
}
|
||||
/** An isolated text update that may be applied to a file. */
|
||||
class TextUpdate {
|
||||
data;
|
||||
constructor(data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
/** Confirms that the given data `T` is serializable. */
|
||||
function confirmAsSerializable(data) {
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a project file instance for the given file.
|
||||
*
|
||||
* Use this helper for dealing with project paths throughout your
|
||||
* migration. The return type is serializable.
|
||||
*
|
||||
* See {@link ProjectFile}.
|
||||
*/
|
||||
function projectFile(file, { sortedRootDirs, projectRoot }) {
|
||||
const fs = compilerCli.getFileSystem();
|
||||
const filePath = fs.resolve(typeof file === 'string' ? file : file.fileName);
|
||||
// Sorted root directories are sorted longest to shortest. First match
|
||||
// is the appropriate root directory for ID computation.
|
||||
for (const rootDir of sortedRootDirs) {
|
||||
if (!isWithinBasePath(fs, rootDir, filePath)) {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
id: fs.relative(rootDir, filePath),
|
||||
rootRelativePath: fs.relative(projectRoot, filePath),
|
||||
};
|
||||
}
|
||||
// E.g. project directory may be `src/`, but files may be looked up
|
||||
// from `node_modules/`. This is fine, but in those cases, no root
|
||||
// directory matches.
|
||||
const rootRelativePath = fs.relative(projectRoot, filePath);
|
||||
return {
|
||||
id: rootRelativePath,
|
||||
rootRelativePath: rootRelativePath,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Whether `path` is a descendant of the `base`?
|
||||
* E.g. `a/b/c` is within `a/b` but not within `a/x`.
|
||||
*/
|
||||
function isWithinBasePath(fs, base, path) {
|
||||
return compilerCli.isLocalRelativePath(fs.relative(base, path));
|
||||
}
|
||||
|
||||
exports.Replacement = Replacement;
|
||||
exports.TextUpdate = TextUpdate;
|
||||
exports.TsurgeComplexMigration = TsurgeComplexMigration;
|
||||
exports.TsurgeFunnelMigration = TsurgeFunnelMigration;
|
||||
exports.confirmAsSerializable = confirmAsSerializable;
|
||||
exports.projectFile = projectFile;
|
||||
exports.runMigrationInDevkit = runMigrationInDevkit;
|
||||
Generated
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var core = require('@angular-devkit/core');
|
||||
|
||||
/**
|
||||
* Gets all tsconfig paths from a CLI project by reading the workspace configuration
|
||||
* and looking for common tsconfig locations.
|
||||
*/
|
||||
async function getProjectTsConfigPaths(tree) {
|
||||
// Start with some tsconfig paths that are generally used within CLI projects. Note
|
||||
// that we are not interested in IDE-specific tsconfig files (e.g. /tsconfig.json)
|
||||
const buildPaths = new Set();
|
||||
const testPaths = new Set();
|
||||
const workspace = await getWorkspace(tree);
|
||||
for (const [, project] of workspace.projects) {
|
||||
for (const [name, target] of project.targets) {
|
||||
if (name !== 'build' && name !== 'test') {
|
||||
continue;
|
||||
}
|
||||
for (const [, options] of allTargetOptions(target)) {
|
||||
const tsConfig = options['tsConfig'];
|
||||
// Filter out tsconfig files that don't exist in the CLI project.
|
||||
if (typeof tsConfig !== 'string' || !tree.exists(tsConfig)) {
|
||||
continue;
|
||||
}
|
||||
if (name === 'build') {
|
||||
buildPaths.add(core.normalize(tsConfig));
|
||||
}
|
||||
else {
|
||||
testPaths.add(core.normalize(tsConfig));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
buildPaths: [...buildPaths],
|
||||
testPaths: [...testPaths],
|
||||
};
|
||||
}
|
||||
/** Get options for all configurations for the passed builder target. */
|
||||
function* allTargetOptions(target) {
|
||||
if (target.options) {
|
||||
yield [undefined, target.options];
|
||||
}
|
||||
if (!target.configurations) {
|
||||
return;
|
||||
}
|
||||
for (const [name, options] of Object.entries(target.configurations)) {
|
||||
if (options) {
|
||||
yield [name, options];
|
||||
}
|
||||
}
|
||||
}
|
||||
function createHost(tree) {
|
||||
return {
|
||||
async readFile(path) {
|
||||
const data = tree.read(path);
|
||||
if (!data) {
|
||||
throw new Error('File not found.');
|
||||
}
|
||||
return core.virtualFs.fileBufferToString(data);
|
||||
},
|
||||
async writeFile(path, data) {
|
||||
return tree.overwrite(path, data);
|
||||
},
|
||||
async isDirectory(path) {
|
||||
// Approximate a directory check.
|
||||
// We don't need to consider empty directories and hence this is a good enough approach.
|
||||
// This is also per documentation, see:
|
||||
// https://angular.dev/tools/cli/schematics-for-libraries#get-the-project-configuration
|
||||
return !tree.exists(path) && tree.getDir(path).subfiles.length > 0;
|
||||
},
|
||||
async isFile(path) {
|
||||
return tree.exists(path);
|
||||
},
|
||||
};
|
||||
}
|
||||
async function getWorkspace(tree) {
|
||||
const host = createHost(tree);
|
||||
const { workspace } = await core.workspaces.readWorkspace('/', host);
|
||||
return workspace;
|
||||
}
|
||||
|
||||
exports.getProjectTsConfigPaths = getProjectTsConfigPaths;
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
|
||||
/**
|
||||
* Gets the text of the given property name. Returns null if the property
|
||||
* name couldn't be determined statically.
|
||||
*/
|
||||
function getPropertyNameText(node) {
|
||||
if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) {
|
||||
return node.text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Finds a property with a specific name in an object literal expression. */
|
||||
function findLiteralProperty(literal, name) {
|
||||
return literal.properties.find((prop) => prop.name && ts.isIdentifier(prop.name) && prop.name.text === name);
|
||||
}
|
||||
|
||||
exports.findLiteralProperty = findLiteralProperty;
|
||||
exports.getPropertyNameText = getPropertyNameText;
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var schematics = require('@angular-devkit/schematics');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var compiler_host = require('./compiler_host-CY14HvaP.cjs');
|
||||
var project_tsconfig_paths = require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
var ts = require('typescript');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var property_name = require('./property_name-BCpALNpZ.cjs');
|
||||
require('@angular-devkit/core');
|
||||
|
||||
/**
|
||||
* Finds the class declaration that is being referred to by a node.
|
||||
* @param reference Node referring to a class declaration.
|
||||
* @param typeChecker
|
||||
*/
|
||||
function findClassDeclaration(reference, typeChecker) {
|
||||
return (typeChecker
|
||||
.getTypeAtLocation(reference)
|
||||
.getSymbol()
|
||||
?.declarations?.find(ts.isClassDeclaration) || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a component is standalone.
|
||||
* @param node Class being checked.
|
||||
* @param reflector The reflection host to use.
|
||||
*/
|
||||
function isStandaloneComponent(node, reflector) {
|
||||
const decorators = reflector.getDecoratorsOfDeclaration(node);
|
||||
if (decorators === null) {
|
||||
return false;
|
||||
}
|
||||
const decorator = migrations.findAngularDecorator(decorators, 'Component', false);
|
||||
if (decorator === undefined || decorator.args === null || decorator.args.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
const arg = decorator.args[0];
|
||||
if (ts.isObjectLiteralExpression(arg)) {
|
||||
const property = property_name.findLiteralProperty(arg, 'standalone');
|
||||
if (property) {
|
||||
return property.initializer.getText() === 'true';
|
||||
}
|
||||
else {
|
||||
return true; // standalone is true by default in v19
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Checks whether a node is variable declaration of type Routes or Route[] and comes from @angular/router
|
||||
* @param node Variable declaration being checked.
|
||||
* @param typeChecker
|
||||
*/
|
||||
function isAngularRoutesArray(node, typeChecker) {
|
||||
if (ts.isVariableDeclaration(node)) {
|
||||
const type = typeChecker.getTypeAtLocation(node);
|
||||
if (type && typeChecker.isArrayType(type)) {
|
||||
// Route[] is an array type
|
||||
const typeArguments = typeChecker.getTypeArguments(type);
|
||||
const symbol = typeArguments[0]?.getSymbol();
|
||||
return (symbol?.name === 'Route' &&
|
||||
symbol?.declarations?.some((decl) => {
|
||||
return decl.getSourceFile().fileName.includes('@angular/router');
|
||||
}));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Checks whether a node is a call expression to a router module method.
|
||||
* Examples:
|
||||
* - RouterModule.forRoot(routes)
|
||||
* - RouterModule.forChild(routes)
|
||||
*/
|
||||
function isRouterModuleCallExpression(node, typeChecker) {
|
||||
if (ts.isPropertyAccessExpression(node.expression)) {
|
||||
const propAccess = node.expression;
|
||||
const moduleSymbol = typeChecker.getSymbolAtLocation(propAccess.expression);
|
||||
return (moduleSymbol?.name === 'RouterModule' &&
|
||||
(propAccess.name.text === 'forRoot' || propAccess.name.text === 'forChild'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Checks whether a node is a call expression to a router method.
|
||||
* Example: this.router.resetConfig(routes)
|
||||
*/
|
||||
function isRouterCallExpression(node, typeChecker) {
|
||||
if (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === 'resetConfig') {
|
||||
const calleeExpression = node.expression.expression;
|
||||
const symbol = typeChecker.getSymbolAtLocation(calleeExpression);
|
||||
if (symbol) {
|
||||
const type = typeChecker.getTypeOfSymbolAtLocation(symbol, calleeExpression);
|
||||
// if type of router is Router, then it is a router call expression
|
||||
return type.aliasSymbol?.escapedName === 'Router';
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Checks whether a node is a call expression to router provide function.
|
||||
* Example: provideRoutes(routes)
|
||||
*/
|
||||
function isRouterProviderCallExpression(node, typeChecker) {
|
||||
if (ts.isIdentifier(node.expression)) {
|
||||
const moduleSymbol = typeChecker.getSymbolAtLocation(node.expression);
|
||||
return moduleSymbol && moduleSymbol.name === 'provideRoutes';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Checks whether a node is a call expression to provideRouter function.
|
||||
* Example: provideRouter(routes)
|
||||
*/
|
||||
function isProvideRoutesCallExpression(node, typeChecker) {
|
||||
if (ts.isIdentifier(node.expression)) {
|
||||
const moduleSymbol = typeChecker.getSymbolAtLocation(node.expression);
|
||||
return moduleSymbol && moduleSymbol.name === 'provideRouter';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all application routes that are using standalone components to be lazy loaded.
|
||||
* @param sourceFile File that should be migrated.
|
||||
* @param program
|
||||
*/
|
||||
function migrateFileToLazyRoutes(sourceFile, program) {
|
||||
const typeChecker = program.getTypeChecker();
|
||||
const reflector = new migrations.TypeScriptReflectionHost(typeChecker);
|
||||
const printer = ts.createPrinter();
|
||||
const tracker = new compiler_host.ChangeTracker(printer);
|
||||
const routeArraysToMigrate = findRoutesArrayToMigrate(sourceFile, typeChecker);
|
||||
if (routeArraysToMigrate.length === 0) {
|
||||
return { pendingChanges: [], skippedRoutes: [], migratedRoutes: [] };
|
||||
}
|
||||
const { skippedRoutes, migratedRoutes } = migrateRoutesArray(routeArraysToMigrate, typeChecker, reflector, tracker);
|
||||
return {
|
||||
pendingChanges: tracker.recordChanges().get(sourceFile) || [],
|
||||
skippedRoutes,
|
||||
migratedRoutes,
|
||||
};
|
||||
}
|
||||
/** Finds route object that can be migrated */
|
||||
function findRoutesArrayToMigrate(sourceFile, typeChecker) {
|
||||
const routesArrays = [];
|
||||
sourceFile.forEachChild(function walk(node) {
|
||||
if (ts.isCallExpression(node)) {
|
||||
if (isRouterModuleCallExpression(node, typeChecker) ||
|
||||
isRouterProviderCallExpression(node, typeChecker) ||
|
||||
isRouterCallExpression(node, typeChecker) ||
|
||||
isProvideRoutesCallExpression(node, typeChecker)) {
|
||||
const arg = node.arguments[0]; // ex: RouterModule.forRoot(routes) or provideRouter(routes)
|
||||
const routeFileImports = sourceFile.statements.filter(ts.isImportDeclaration);
|
||||
if (ts.isArrayLiteralExpression(arg) && arg.elements.length > 0) {
|
||||
// ex: inline routes array: RouterModule.forRoot([{ path: 'test', component: TestComponent }])
|
||||
routesArrays.push({
|
||||
routeFilePath: sourceFile.fileName,
|
||||
array: arg,
|
||||
routeFileImports,
|
||||
});
|
||||
}
|
||||
else if (ts.isIdentifier(arg)) {
|
||||
// ex: reference to routes array: RouterModule.forRoot(routes)
|
||||
// RouterModule.forRoot(routes), provideRouter(routes), provideRoutes(routes)
|
||||
const symbol = typeChecker.getSymbolAtLocation(arg);
|
||||
if (!symbol?.declarations)
|
||||
return;
|
||||
for (const declaration of symbol.declarations) {
|
||||
if (ts.isVariableDeclaration(declaration)) {
|
||||
const initializer = declaration.initializer;
|
||||
if (initializer && ts.isArrayLiteralExpression(initializer)) {
|
||||
// ex: const routes = [{ path: 'test', component: TestComponent }];
|
||||
routesArrays.push({
|
||||
routeFilePath: sourceFile.fileName,
|
||||
array: initializer,
|
||||
routeFileImports,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ts.isVariableDeclaration(node)) {
|
||||
if (isAngularRoutesArray(node, typeChecker)) {
|
||||
const initializer = node.initializer;
|
||||
if (initializer &&
|
||||
ts.isArrayLiteralExpression(initializer) &&
|
||||
initializer.elements.length > 0) {
|
||||
// ex: const routes: Routes = [{ path: 'test', component: TestComponent }];
|
||||
if (routesArrays.find((x) => x.array === initializer)) {
|
||||
// already exists
|
||||
return;
|
||||
}
|
||||
routesArrays.push({
|
||||
routeFilePath: sourceFile.fileName,
|
||||
array: initializer,
|
||||
routeFileImports: sourceFile.statements.filter(ts.isImportDeclaration),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ts.isExportAssignment(node)) {
|
||||
// Handles `export default routes`, `export default [...]` and `export default [...] as Routes`
|
||||
let expression = node.expression;
|
||||
if (ts.isAsExpression(expression)) {
|
||||
expression = expression.expression;
|
||||
}
|
||||
if (ts.isArrayLiteralExpression(expression)) {
|
||||
routesArrays.push({
|
||||
routeFilePath: sourceFile.fileName,
|
||||
array: expression,
|
||||
routeFileImports: sourceFile.statements.filter(ts.isImportDeclaration),
|
||||
});
|
||||
}
|
||||
else if (ts.isIdentifier(expression)) {
|
||||
manageRoutesExportedByDefault(routesArrays, typeChecker, expression, sourceFile);
|
||||
}
|
||||
}
|
||||
else if (ts.isExportDeclaration(node)) {
|
||||
// Handles cases like `export { routes as default }`
|
||||
if (node.exportClause && ts.isNamedExports(node.exportClause)) {
|
||||
for (const specifier of node.exportClause.elements) {
|
||||
if (specifier.name.text === 'default') {
|
||||
manageRoutesExportedByDefault(routesArrays, typeChecker, specifier.propertyName ?? specifier.name, sourceFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
node.forEachChild(walk);
|
||||
});
|
||||
return routesArrays;
|
||||
}
|
||||
/** Migrate a routes object standalone components to be lazy loaded. */
|
||||
function migrateRoutesArray(routesArray, typeChecker, reflector, tracker) {
|
||||
const migratedRoutes = [];
|
||||
const skippedRoutes = [];
|
||||
const importsToRemove = [];
|
||||
for (const route of routesArray) {
|
||||
route.array.elements.forEach((element) => {
|
||||
if (ts.isObjectLiteralExpression(element)) {
|
||||
const { migratedRoutes: migrated, skippedRoutes: toBeSkipped, importsToRemove: toBeRemoved, } = migrateRoute(element, route, typeChecker, reflector, tracker);
|
||||
migratedRoutes.push(...migrated);
|
||||
skippedRoutes.push(...toBeSkipped);
|
||||
importsToRemove.push(...toBeRemoved);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (const importToRemove of importsToRemove) {
|
||||
tracker.removeNode(importToRemove);
|
||||
}
|
||||
return { migratedRoutes, skippedRoutes };
|
||||
}
|
||||
/**
|
||||
* Migrates a single route object and returns the results of the migration
|
||||
* It recursively migrates the children routes if they exist
|
||||
*/
|
||||
function migrateRoute(element, route, typeChecker, reflector, tracker) {
|
||||
const skippedRoutes = [];
|
||||
const migratedRoutes = [];
|
||||
const importsToRemove = [];
|
||||
const component = property_name.findLiteralProperty(element, 'component');
|
||||
// this can be empty string or a variable that is not a string, or not present at all
|
||||
const routePath = property_name.findLiteralProperty(element, 'path')?.getText() ?? '';
|
||||
const children = property_name.findLiteralProperty(element, 'children');
|
||||
// recursively migrate children routes first if they exist
|
||||
if (children && ts.isArrayLiteralExpression(children.initializer)) {
|
||||
for (const childRoute of children.initializer.elements) {
|
||||
if (ts.isObjectLiteralExpression(childRoute)) {
|
||||
const { migratedRoutes: migrated, skippedRoutes: toBeSkipped, importsToRemove: toBeRemoved, } = migrateRoute(childRoute, route, typeChecker, reflector, tracker);
|
||||
migratedRoutes.push(...migrated);
|
||||
skippedRoutes.push(...toBeSkipped);
|
||||
importsToRemove.push(...toBeRemoved);
|
||||
}
|
||||
}
|
||||
}
|
||||
const routeMigrationResults = { migratedRoutes, skippedRoutes, importsToRemove };
|
||||
if (!component) {
|
||||
return routeMigrationResults;
|
||||
}
|
||||
const componentDeclaration = findClassDeclaration(component, typeChecker);
|
||||
if (!componentDeclaration) {
|
||||
return routeMigrationResults;
|
||||
}
|
||||
// if component is not a standalone component, skip it
|
||||
if (!isStandaloneComponent(componentDeclaration, reflector)) {
|
||||
skippedRoutes.push({ path: routePath, file: route.routeFilePath });
|
||||
return routeMigrationResults;
|
||||
}
|
||||
const componentClassName = componentDeclaration.name && ts.isIdentifier(componentDeclaration.name)
|
||||
? componentDeclaration.name.text
|
||||
: null;
|
||||
if (!componentClassName) {
|
||||
return routeMigrationResults;
|
||||
}
|
||||
// if component is in the same file as the routes array, skip it
|
||||
if (componentDeclaration.getSourceFile().fileName === route.routeFilePath) {
|
||||
return routeMigrationResults;
|
||||
}
|
||||
const componentImport = route.routeFileImports.find((importDecl) => importDecl.importClause?.getText().includes(componentClassName));
|
||||
// remove single and double quotes from the import path
|
||||
let componentImportPath = ts.isStringLiteral(componentImport?.moduleSpecifier)
|
||||
? componentImport.moduleSpecifier.text
|
||||
: null;
|
||||
// if the import path is not a string literal, skip it
|
||||
if (!componentImportPath) {
|
||||
skippedRoutes.push({ path: routePath, file: route.routeFilePath });
|
||||
return routeMigrationResults;
|
||||
}
|
||||
const isDefaultExport = componentDeclaration.modifiers?.some((x) => x.kind === ts.SyntaxKind.DefaultKeyword) ?? false;
|
||||
const loadComponent = createLoadComponentPropertyAssignment(componentImportPath, componentClassName, isDefaultExport);
|
||||
tracker.replaceNode(component, loadComponent);
|
||||
// Add the import statement for the standalone component
|
||||
if (!importsToRemove.includes(componentImport)) {
|
||||
importsToRemove.push(componentImport);
|
||||
}
|
||||
migratedRoutes.push({ path: routePath, file: route.routeFilePath });
|
||||
// the component was migrated, so we return the results
|
||||
return routeMigrationResults;
|
||||
}
|
||||
/**
|
||||
* Generates the loadComponent property assignment for a given component.
|
||||
*
|
||||
* Example:
|
||||
* loadComponent: () => import('./path').then(m => m.componentName)
|
||||
* or
|
||||
* loadComponent: () => import('./path') // when isDefaultExport is true
|
||||
*/
|
||||
function createLoadComponentPropertyAssignment(componentImportPath, componentDeclarationName, isDefaultExport) {
|
||||
return ts.factory.createPropertyAssignment('loadComponent', ts.factory.createArrowFunction(undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), isDefaultExport
|
||||
? createImportCallExpression(componentImportPath) // will generate import('./path) and will skip the then() call
|
||||
: ts.factory.createCallExpression(
|
||||
// will generate import('./path).then(m => m.componentName)
|
||||
ts.factory.createPropertyAccessExpression(createImportCallExpression(componentImportPath), 'then'), undefined, [createImportThenCallExpression(componentDeclarationName)])));
|
||||
}
|
||||
const manageRoutesExportedByDefault = (routesArrays, typeChecker, expression, sourceFile) => {
|
||||
const symbol = typeChecker.getSymbolAtLocation(expression);
|
||||
if (!symbol?.declarations) {
|
||||
return;
|
||||
}
|
||||
for (const declaration of symbol.declarations) {
|
||||
if (ts.isVariableDeclaration(declaration) &&
|
||||
declaration.initializer &&
|
||||
ts.isArrayLiteralExpression(declaration.initializer)) {
|
||||
routesArrays.push({
|
||||
routeFilePath: sourceFile.fileName,
|
||||
array: declaration.initializer,
|
||||
routeFileImports: sourceFile.statements.filter(ts.isImportDeclaration),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
// import('./path)
|
||||
const createImportCallExpression = (componentImportPath) => ts.factory.createCallExpression(ts.factory.createIdentifier('import'), undefined, [
|
||||
ts.factory.createStringLiteral(componentImportPath, true),
|
||||
]);
|
||||
// m => m.componentName
|
||||
const createImportThenCallExpression = (componentDeclarationName) => ts.factory.createArrowFunction(undefined, undefined, [ts.factory.createParameterDeclaration(undefined, undefined, 'm', undefined, undefined)], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('m'), componentDeclarationName));
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
const { buildPaths } = await project_tsconfig_paths.getProjectTsConfigPaths(tree);
|
||||
const basePath = process.cwd();
|
||||
// TS and Schematic use paths in POSIX format even on Windows. This is needed as otherwise
|
||||
// string matching such as `sourceFile.fileName.startsWith(pathToMigrate)` might not work.
|
||||
const pathToMigrate = compiler_host.normalizePath(path.join(basePath, options.path));
|
||||
if (!buildPaths.length) {
|
||||
throw new schematics.SchematicsException('Could not find any tsconfig file. Cannot run the route lazy loading migration.');
|
||||
}
|
||||
let migratedRoutes = [];
|
||||
let skippedRoutes = [];
|
||||
for (const tsconfigPath of buildPaths) {
|
||||
const { migratedRoutes: migrated, skippedRoutes: skipped } = standaloneRoutesMigration(tree, tsconfigPath, basePath, pathToMigrate, options);
|
||||
migratedRoutes.push(...migrated);
|
||||
skippedRoutes.push(...skipped);
|
||||
}
|
||||
if (migratedRoutes.length === 0 && skippedRoutes.length === 0) {
|
||||
throw new schematics.SchematicsException(`Could not find any files to migrate under the path ${pathToMigrate}.`);
|
||||
}
|
||||
context.logger.info('🎉 Automated migration step has finished! 🎉');
|
||||
context.logger.info(`Number of updated routes: ${migratedRoutes.length}`);
|
||||
context.logger.info(`Number of skipped routes: ${skippedRoutes.length}`);
|
||||
if (skippedRoutes.length > 0) {
|
||||
context.logger.info(`Note: this migration was unable to optimize the following routes, since they use components declared in NgModules:`);
|
||||
for (const route of skippedRoutes) {
|
||||
context.logger.info(`- \`${route.path}\` path at \`${route.file}\``);
|
||||
}
|
||||
context.logger.info(`Consider making those components standalone and run this migration again. More information about standalone migration can be found at https://angular.dev/reference/migrations/standalone`);
|
||||
}
|
||||
context.logger.info('IMPORTANT! Please verify manually that your application builds and behaves as expected.');
|
||||
context.logger.info(`See https://angular.dev/reference/migrations/route-lazy-loading for more information.`);
|
||||
};
|
||||
}
|
||||
function standaloneRoutesMigration(tree, tsconfigPath, basePath, pathToMigrate, schematicOptions) {
|
||||
if (schematicOptions.path.startsWith('..')) {
|
||||
throw new schematics.SchematicsException('Cannot run route lazy loading migration outside of the current project.');
|
||||
}
|
||||
if (fs.existsSync(pathToMigrate) && !fs.statSync(pathToMigrate).isDirectory()) {
|
||||
throw new schematics.SchematicsException(`Migration path ${pathToMigrate} has to be a directory. Cannot run the route lazy loading migration.`);
|
||||
}
|
||||
const program = compiler_host.createMigrationProgram(tree, tsconfigPath, basePath);
|
||||
const sourceFiles = program
|
||||
.getSourceFiles()
|
||||
.filter((sourceFile) => sourceFile.fileName.startsWith(pathToMigrate) &&
|
||||
compiler_host.canMigrateFile(basePath, sourceFile, program));
|
||||
const migratedRoutes = [];
|
||||
const skippedRoutes = [];
|
||||
if (sourceFiles.length === 0) {
|
||||
return { migratedRoutes, skippedRoutes };
|
||||
}
|
||||
for (const sourceFile of sourceFiles) {
|
||||
const { pendingChanges, skippedRoutes: skipped, migratedRoutes: migrated, } = migrateFileToLazyRoutes(sourceFile, program);
|
||||
skippedRoutes.push(...skipped);
|
||||
migratedRoutes.push(...migrated);
|
||||
const update = tree.beginUpdate(path.relative(basePath, sourceFile.fileName));
|
||||
pendingChanges.forEach((change) => {
|
||||
if (change.removeLength != null) {
|
||||
update.remove(change.start, change.removeLength);
|
||||
}
|
||||
update.insertRight(change.start, change.text);
|
||||
});
|
||||
tree.commitUpdate(update);
|
||||
}
|
||||
return { migratedRoutes, skippedRoutes };
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
var symbol = require('./symbol-DZeHSR-V.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
/** Name of the method being replaced. */
|
||||
const METHOD_NAME = 'getCurrentNavigation';
|
||||
/** Migration that replaces `Router.getCurrentNavigation` usages with `Router.currentNavigation()`. */
|
||||
class RouterCurrentNavigationMigration extends project_paths.TsurgeFunnelMigration {
|
||||
async analyze(info) {
|
||||
const locations = [];
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
const routerSpecifier = imports.getImportSpecifier(sourceFile, '@angular/router', 'Router');
|
||||
if (routerSpecifier === null) {
|
||||
continue;
|
||||
}
|
||||
const typeChecker = info.program.getTypeChecker();
|
||||
sourceFile.forEachChild(function walk(node) {
|
||||
if (ts.isPropertyAccessExpression(node) &&
|
||||
node.name.text === METHOD_NAME &&
|
||||
isRouterType(typeChecker, node.expression, routerSpecifier)) {
|
||||
locations.push({ file: project_paths.projectFile(sourceFile, info), position: node.name.getStart() });
|
||||
}
|
||||
else {
|
||||
node.forEachChild(walk);
|
||||
}
|
||||
});
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ locations });
|
||||
}
|
||||
async migrate(globalData) {
|
||||
const replacements = globalData.locations.map(({ file, position }) => {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: position,
|
||||
end: position + METHOD_NAME.length,
|
||||
toInsert: 'currentNavigation',
|
||||
}));
|
||||
});
|
||||
return project_paths.confirmAsSerializable({ replacements });
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const seen = new Set();
|
||||
const locations = [];
|
||||
const combined = [...unitA.locations, ...unitB.locations];
|
||||
for (const location of combined) {
|
||||
const key = `${location.file.id}#${location.position}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
locations.push(location);
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ locations });
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats() {
|
||||
return project_paths.confirmAsSerializable({});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if the given symbol represents a Router type.
|
||||
*/
|
||||
function isRouterType(typeChecker, expression, routerSpecifier) {
|
||||
const expressionType = typeChecker.getTypeAtLocation(expression);
|
||||
const expressionSymbol = expressionType.getSymbol();
|
||||
if (!expressionSymbol) {
|
||||
return false;
|
||||
}
|
||||
const declarations = expressionSymbol.getDeclarations() ?? [];
|
||||
for (const declaration of declarations) {
|
||||
if (symbol.isReferenceToImport(typeChecker, declaration, routerSpecifier)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return declarations.some((decl) => decl === routerSpecifier);
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: () => new RouterCurrentNavigationMigration(),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
Generated
Vendored
+103
@@ -0,0 +1,103 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var imports = require('./imports-CVmcbVA9.cjs');
|
||||
var symbol = require('./symbol-DZeHSR-V.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
/** Name of the method being replaced. */
|
||||
const METHOD_NAME = 'lastSuccessfulNavigation';
|
||||
/** Migration that replaces `Router.lastSuccessfulNavigation` usages with `Router.lastSuccessfulNavigation()`. */
|
||||
class RouterLastSuccessfulNavigationMigration extends project_paths.TsurgeFunnelMigration {
|
||||
async analyze(info) {
|
||||
const locations = [];
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
const routerSpecifier = imports.getImportSpecifier(sourceFile, '@angular/router', 'Router');
|
||||
if (routerSpecifier === null) {
|
||||
continue;
|
||||
}
|
||||
const typeChecker = info.program.getTypeChecker();
|
||||
sourceFile.forEachChild(function walk(node) {
|
||||
if (ts.isPropertyAccessExpression(node) &&
|
||||
node.name.text === METHOD_NAME &&
|
||||
isRouterType(typeChecker, node.expression, routerSpecifier)) {
|
||||
locations.push({ file: project_paths.projectFile(sourceFile, info), position: node.name.getStart() });
|
||||
}
|
||||
else {
|
||||
node.forEachChild(walk);
|
||||
}
|
||||
});
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ locations });
|
||||
}
|
||||
async migrate(globalData) {
|
||||
const replacements = globalData.locations.map(({ file, position }) => {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: position,
|
||||
end: position + METHOD_NAME.length,
|
||||
toInsert: 'lastSuccessfulNavigation()',
|
||||
}));
|
||||
});
|
||||
return project_paths.confirmAsSerializable({ replacements });
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const seen = new Set();
|
||||
const locations = [];
|
||||
const combined = [...unitA.locations, ...unitB.locations];
|
||||
for (const location of combined) {
|
||||
const key = `${location.file.id}#${location.position}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
locations.push(location);
|
||||
}
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ locations });
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats() {
|
||||
return project_paths.confirmAsSerializable({});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if the given symbol represents a Router type.
|
||||
*/
|
||||
function isRouterType(typeChecker, expression, routerSpecifier) {
|
||||
const expressionType = typeChecker.getTypeAtLocation(expression);
|
||||
const expressionSymbol = expressionType.getSymbol();
|
||||
if (!expressionSymbol) {
|
||||
return false;
|
||||
}
|
||||
const declarations = expressionSymbol.getDeclarations() ?? [];
|
||||
for (const declaration of declarations) {
|
||||
if (symbol.isReferenceToImport(typeChecker, declaration, routerSpecifier)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return declarations.some((decl) => decl === routerSpecifier);
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
return async (tree) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: () => new RouterLastSuccessfulNavigationMigration(),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
Generated
Vendored
+502
@@ -0,0 +1,502 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
require('@angular/compiler-cli');
|
||||
var migrations = require('@angular/compiler-cli/private/migrations');
|
||||
var ts = require('typescript');
|
||||
require('node:path');
|
||||
var apply_import_manager = require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
|
||||
const ROUTER_TESTING_MODULE = 'RouterTestingModule';
|
||||
const SPY_LOCATION = 'SpyLocation';
|
||||
const ROUTER_MODULE = 'RouterModule';
|
||||
const PROVIDE_LOCATION_MOCKS = 'provideLocationMocks';
|
||||
const ANGULAR_ROUTER_TESTING = '@angular/router/testing';
|
||||
const ANGULAR_ROUTER = '@angular/router';
|
||||
const ANGULAR_COMMON_TESTING = '@angular/common/testing';
|
||||
const IMPORTS_PROPERTY = 'imports';
|
||||
const PROVIDERS_PROPERTY = 'providers';
|
||||
const WITH_ROUTES_STATIC_METHOD = 'withRoutes';
|
||||
const TESTBED_IDENTIFIER = 'TestBed';
|
||||
const CONFIGURE_TESTING_MODULE = 'configureTestingModule';
|
||||
function hasImportFromModule(sourceFile, modulePath, ...symbolNames) {
|
||||
const symbolSet = new Set(symbolNames);
|
||||
let hasImport = false;
|
||||
ts.forEachChild(sourceFile, (node) => {
|
||||
if (ts.isImportDeclaration(node) &&
|
||||
ts.isStringLiteral(node.moduleSpecifier) &&
|
||||
node.moduleSpecifier.text === modulePath &&
|
||||
node.importClause?.namedBindings &&
|
||||
ts.isNamedImports(node.importClause.namedBindings)) {
|
||||
for (const element of node.importClause.namedBindings.elements) {
|
||||
if (symbolSet.has(element.name.text)) {
|
||||
hasImport = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return hasImport;
|
||||
}
|
||||
function detectSpyLocationUrlChangesUsage(sourceFile) {
|
||||
const hasSpyLocationImport = hasImportFromModule(sourceFile, ANGULAR_COMMON_TESTING, SPY_LOCATION);
|
||||
let usesUrlChangesFeature = false;
|
||||
function walk(node) {
|
||||
if (usesUrlChangesFeature) {
|
||||
return;
|
||||
}
|
||||
if (ts.isPropertyAccessExpression(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
node.name.text === 'urlChanges') {
|
||||
usesUrlChangesFeature = true;
|
||||
return;
|
||||
}
|
||||
node.forEachChild(walk);
|
||||
}
|
||||
walk(sourceFile);
|
||||
return hasSpyLocationImport && usesUrlChangesFeature;
|
||||
}
|
||||
function createArrayLiteralReplacement(file, arrayLiteral, newElements, sourceFile) {
|
||||
const elementNodes = newElements.map((element) => {
|
||||
if (typeof element === 'string') {
|
||||
return parseStringToExpression(element);
|
||||
}
|
||||
return element;
|
||||
});
|
||||
const newArray = ts.factory.updateArrayLiteralExpression(arrayLiteral, elementNodes);
|
||||
const printer = ts.createPrinter({
|
||||
newLine: ts.NewLineKind.LineFeed,
|
||||
});
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, newArray, sourceFile);
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: arrayLiteral.getStart(),
|
||||
end: arrayLiteral.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
function createImportRemovalReplacement(file, importDeclaration, namedBindings, symbolToRemove, sourceFile) {
|
||||
const otherImports = namedBindings.elements.filter((el) => el.name.text !== symbolToRemove);
|
||||
if (otherImports.length === 0) {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: importDeclaration.getStart(),
|
||||
end: importDeclaration.getEnd() + 1,
|
||||
toInsert: '',
|
||||
}));
|
||||
}
|
||||
else {
|
||||
const newNamedBindings = ts.factory.updateNamedImports(namedBindings, otherImports);
|
||||
const printer = ts.createPrinter();
|
||||
const newText = printer.printNode(ts.EmitHint.Unspecified, newNamedBindings, sourceFile);
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: namedBindings.getStart(),
|
||||
end: namedBindings.getEnd(),
|
||||
toInsert: newText,
|
||||
}));
|
||||
}
|
||||
}
|
||||
function isEmptyArrayExpression(expression) {
|
||||
return ts.isArrayLiteralExpression(expression) && expression.elements.length === 0;
|
||||
}
|
||||
function getRoutesArgumentForMigration(routesNode, optionsNode) {
|
||||
if (!routesNode) {
|
||||
return undefined;
|
||||
}
|
||||
if (!isEmptyArrayExpression(routesNode)) {
|
||||
return routesNode;
|
||||
}
|
||||
return optionsNode ? routesNode : undefined;
|
||||
}
|
||||
function createRouterModuleExpression(routesArg, optionsArg) {
|
||||
const routerModuleIdentifier = ts.factory.createIdentifier(ROUTER_MODULE);
|
||||
if (routesArg) {
|
||||
// Build args list and include options if present
|
||||
const args = [routesArg];
|
||||
if (optionsArg) {
|
||||
args.push(optionsArg);
|
||||
}
|
||||
// Create RouterModule.forRoot(routes, options?) expression
|
||||
return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(routerModuleIdentifier, ts.factory.createIdentifier('forRoot')), undefined, args);
|
||||
}
|
||||
return routerModuleIdentifier;
|
||||
}
|
||||
function createProviderCallExpression(functionName, argument) {
|
||||
return ts.factory.createCallExpression(ts.factory.createIdentifier(functionName), undefined, []);
|
||||
}
|
||||
function createArrayLiteralFromExpressions(expressions) {
|
||||
return ts.factory.createArrayLiteralExpression(Array.from(expressions), true);
|
||||
}
|
||||
function parseStringToExpression(text) {
|
||||
const wrapped = `(${text})`;
|
||||
const sourceFile = ts.createSourceFile('temp.ts', wrapped, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
||||
if (sourceFile.statements.length === 1) {
|
||||
const statement = sourceFile.statements[0];
|
||||
if (ts.isExpressionStatement(statement) && ts.isParenthesizedExpression(statement.expression)) {
|
||||
return statement.expression.expression;
|
||||
}
|
||||
}
|
||||
return parseExpressionWithPatternRecognition(text);
|
||||
}
|
||||
function parseExpressionWithPatternRecognition(text) {
|
||||
const callPattern = analyzeCallPattern(text);
|
||||
if (callPattern) {
|
||||
return ts.factory.createCallExpression(callPattern.expression, undefined, Array.from(callPattern.arguments));
|
||||
}
|
||||
const arrayPattern = analyzeArrayPattern(text);
|
||||
if (arrayPattern) {
|
||||
return ts.factory.createArrayLiteralExpression(Array.from(arrayPattern.elements), true);
|
||||
}
|
||||
const literalPattern = analyzeLiteralPattern(text);
|
||||
if (literalPattern) {
|
||||
return literalPattern.expression;
|
||||
}
|
||||
return ts.factory.createIdentifier(text);
|
||||
}
|
||||
function analyzeCallPattern(text) {
|
||||
const testExpression = `(${text})`;
|
||||
const sourceFile = ts.createSourceFile('temp.ts', testExpression, ts.ScriptTarget.Latest, true);
|
||||
if (sourceFile.statements.length === 1) {
|
||||
const statement = sourceFile.statements[0];
|
||||
if (ts.isExpressionStatement(statement) &&
|
||||
ts.isParenthesizedExpression(statement.expression) &&
|
||||
ts.isCallExpression(statement.expression.expression)) {
|
||||
const callExpr = statement.expression.expression;
|
||||
return {
|
||||
type: 'call',
|
||||
expression: callExpr.expression,
|
||||
arguments: callExpr.arguments,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function analyzeArrayPattern(text) {
|
||||
const sourceFile = ts.createSourceFile('temp.ts', text, ts.ScriptTarget.Latest, true);
|
||||
if (sourceFile.statements.length === 1) {
|
||||
const statement = sourceFile.statements[0];
|
||||
if (ts.isExpressionStatement(statement) && ts.isArrayLiteralExpression(statement.expression)) {
|
||||
return {
|
||||
type: 'array',
|
||||
elements: statement.expression.elements,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function analyzeLiteralPattern(text) {
|
||||
const sourceFile = ts.createSourceFile('temp.ts', text, ts.ScriptTarget.Latest, true);
|
||||
if (sourceFile.statements.length === 1) {
|
||||
const statement = sourceFile.statements[0];
|
||||
if (ts.isExpressionStatement(statement)) {
|
||||
const expr = statement.expression;
|
||||
if (ts.isStringLiteral(expr) || ts.isNumericLiteral(expr) || ts.isLiteralExpression(expr)) {
|
||||
return {
|
||||
type: 'literal',
|
||||
expression: expr,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function removeRouterTestingModuleImport(sourceFile, file, replacements) {
|
||||
ts.forEachChild(sourceFile, (node) => {
|
||||
if (ts.isImportDeclaration(node) &&
|
||||
ts.isStringLiteral(node.moduleSpecifier) &&
|
||||
node.moduleSpecifier.text === ANGULAR_ROUTER_TESTING &&
|
||||
node.importClause?.namedBindings &&
|
||||
ts.isNamedImports(node.importClause.namedBindings)) {
|
||||
const namedBindings = node.importClause.namedBindings;
|
||||
replacements.push(createImportRemovalReplacement(file, node, namedBindings, ROUTER_TESTING_MODULE, sourceFile));
|
||||
}
|
||||
});
|
||||
}
|
||||
function migrateToRouterModule(usage, file, routesNode, optionsNode, replacements) {
|
||||
const neededImportsExpressions = new Set();
|
||||
const neededProvidersExpressions = new Set();
|
||||
const optionsExpression = optionsNode ? optionsNode : undefined;
|
||||
const routesExpression = getRoutesArgumentForMigration(routesNode, optionsNode);
|
||||
const routerModuleExpression = createRouterModuleExpression(routesExpression, optionsExpression);
|
||||
neededImportsExpressions.add(routerModuleExpression);
|
||||
if (usage.usesSpyLocationUrlChanges) {
|
||||
const provideLocationMocksExpression = createProviderCallExpression(PROVIDE_LOCATION_MOCKS);
|
||||
neededProvidersExpressions.add(provideLocationMocksExpression);
|
||||
}
|
||||
if (usage.importsProperty && ts.isArrayLiteralExpression(usage.importsProperty.initializer)) {
|
||||
const importsArray = usage.importsProperty.initializer;
|
||||
const otherImportExpressions = usage.importsArrayElements.filter((el) => el !== usage.routerTestingModuleElement);
|
||||
const allImportExpressions = [
|
||||
...otherImportExpressions,
|
||||
...Array.from(neededImportsExpressions),
|
||||
];
|
||||
replacements.push(createArrayLiteralReplacement(file, importsArray, allImportExpressions, usage.sourceFile));
|
||||
}
|
||||
if (neededProvidersExpressions.size > 0) {
|
||||
if (usage.providersProperty &&
|
||||
ts.isArrayLiteralExpression(usage.providersProperty.initializer)) {
|
||||
const existingProvidersArray = usage.providersProperty.initializer;
|
||||
const allProviderExpressions = [
|
||||
...existingProvidersArray.elements,
|
||||
...Array.from(neededProvidersExpressions),
|
||||
];
|
||||
replacements.push(createArrayLiteralReplacement(file, existingProvidersArray, allProviderExpressions, usage.sourceFile));
|
||||
}
|
||||
else {
|
||||
const providersArray = createArrayLiteralFromExpressions(neededProvidersExpressions);
|
||||
const printer = ts.createPrinter();
|
||||
const providersText = printer.printNode(ts.EmitHint.Unspecified, providersArray, usage.sourceFile);
|
||||
const insertPosition = usage.importsProperty.getEnd();
|
||||
replacements.push(new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: insertPosition,
|
||||
end: insertPosition,
|
||||
toInsert: `,\n ${PROVIDERS_PROPERTY}: ${providersText}`,
|
||||
})));
|
||||
}
|
||||
}
|
||||
}
|
||||
function analyzeRouterTestingModuleUsage(usage) {
|
||||
const neededProviders = new Set();
|
||||
const neededImports = new Set();
|
||||
let hasLocationMocks = false;
|
||||
const optionsExpression = usage.optionsNode ? usage.optionsNode : undefined;
|
||||
const routesExpression = getRoutesArgumentForMigration(usage.routesNode, usage.optionsNode);
|
||||
// Add RouterModule to imports (preserve options when present)
|
||||
const routerModuleExpression = createRouterModuleExpression(routesExpression, optionsExpression);
|
||||
neededImports.add(routerModuleExpression);
|
||||
// Add location mocks ONLY if:
|
||||
// 1. SpyLocation is imported from @angular/common/testing, AND
|
||||
// 2. urlChanges property is accessed in the test
|
||||
// 3. provideLocationMocks() is not already present
|
||||
if (usage.usesSpyLocationUrlChanges) {
|
||||
const provideLocationMocksExpression = createProviderCallExpression(PROVIDE_LOCATION_MOCKS);
|
||||
neededProviders.add(provideLocationMocksExpression);
|
||||
hasLocationMocks = true;
|
||||
}
|
||||
return {
|
||||
neededProviders,
|
||||
neededImports,
|
||||
canRemoveRouterTestingModule: true,
|
||||
replacementCount: 1,
|
||||
hasLocationMocks,
|
||||
};
|
||||
}
|
||||
function findRouterTestingModuleUsages(sourceFile) {
|
||||
const usages = [];
|
||||
const hasRouterTestingModule = hasImportFromModule(sourceFile, ANGULAR_ROUTER_TESTING, ROUTER_TESTING_MODULE);
|
||||
const usesSpyLocationUrlChanges = detectSpyLocationUrlChangesUsage(sourceFile);
|
||||
if (!hasRouterTestingModule) {
|
||||
return usages;
|
||||
}
|
||||
function walk(node) {
|
||||
if (ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === CONFIGURE_TESTING_MODULE &&
|
||||
ts.isIdentifier(node.expression.expression) &&
|
||||
node.expression.expression.text === TESTBED_IDENTIFIER &&
|
||||
node.arguments.length > 0 &&
|
||||
ts.isObjectLiteralExpression(node.arguments[0])) {
|
||||
const config = node.arguments[0];
|
||||
let importsProperty = null;
|
||||
let providersProperty = null;
|
||||
for (const prop of config.properties) {
|
||||
if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
||||
if (prop.name.text === IMPORTS_PROPERTY) {
|
||||
importsProperty = prop;
|
||||
}
|
||||
else if (prop.name.text === PROVIDERS_PROPERTY) {
|
||||
providersProperty = prop;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!importsProperty || !ts.isArrayLiteralExpression(importsProperty.initializer)) {
|
||||
node.forEachChild(walk);
|
||||
return;
|
||||
}
|
||||
const importsArray = importsProperty.initializer;
|
||||
let routerTestingModuleElement = null;
|
||||
let routesNode = null;
|
||||
let optionsNode = null;
|
||||
for (const element of importsArray.elements) {
|
||||
if (ts.isIdentifier(element) && element.text === ROUTER_TESTING_MODULE) {
|
||||
routerTestingModuleElement = element;
|
||||
break;
|
||||
}
|
||||
else if (ts.isCallExpression(element) &&
|
||||
ts.isPropertyAccessExpression(element.expression) &&
|
||||
ts.isIdentifier(element.expression.expression) &&
|
||||
element.expression.expression.text === ROUTER_TESTING_MODULE &&
|
||||
element.expression.name.text === WITH_ROUTES_STATIC_METHOD) {
|
||||
routerTestingModuleElement = element;
|
||||
if (element.arguments.length > 0) {
|
||||
routesNode = element.arguments[0];
|
||||
}
|
||||
if (element.arguments.length > 1) {
|
||||
optionsNode = element.arguments[1];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (routerTestingModuleElement) {
|
||||
usages.push({
|
||||
sourceFile,
|
||||
configObject: config,
|
||||
importsProperty,
|
||||
providersProperty,
|
||||
routerTestingModuleElement,
|
||||
routesNode,
|
||||
optionsNode,
|
||||
importsArrayElements: Array.from(importsArray.elements),
|
||||
usesSpyLocationUrlChanges,
|
||||
});
|
||||
}
|
||||
}
|
||||
node.forEachChild(walk);
|
||||
}
|
||||
walk(sourceFile);
|
||||
return usages;
|
||||
}
|
||||
function processRouterTestingModuleUsage(usage, sourceFile, info, importManager, replacements) {
|
||||
const file = project_paths.projectFile(sourceFile, info);
|
||||
const routesNode = usage.routesNode;
|
||||
const optionsNode = usage.optionsNode;
|
||||
const analysis = analyzeRouterTestingModuleUsage(usage);
|
||||
migrateToRouterModule(usage, file, routesNode, optionsNode, replacements);
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: ANGULAR_ROUTER,
|
||||
exportSymbolName: ROUTER_MODULE,
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
if (analysis.hasLocationMocks) {
|
||||
importManager.addImport({
|
||||
exportModuleSpecifier: ANGULAR_COMMON_TESTING,
|
||||
exportSymbolName: PROVIDE_LOCATION_MOCKS,
|
||||
requestedFile: sourceFile,
|
||||
});
|
||||
}
|
||||
removeRouterTestingModuleImport(sourceFile, file, replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration that converts RouterTestingModule usages to the recommended API:
|
||||
* - Replace RouterTestingModule with RouterModule for all tests (respecting existing imports)
|
||||
* - Adds provideLocationMocks only when needed and not conflicting
|
||||
*/
|
||||
class RouterTestingModuleMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
async analyze(info) {
|
||||
const replacements = [];
|
||||
const migratedUsages = [];
|
||||
const filesWithLocationMocks = new Map();
|
||||
const importManager = new migrations.ImportManager({
|
||||
shouldUseSingleQuotes: () => true,
|
||||
});
|
||||
for (const sourceFile of info.sourceFiles) {
|
||||
const file = project_paths.projectFile(sourceFile, info);
|
||||
if (this.config.shouldMigrate && !this.config.shouldMigrate(file)) {
|
||||
continue;
|
||||
}
|
||||
const usages = findRouterTestingModuleUsages(sourceFile);
|
||||
for (const usage of usages) {
|
||||
processRouterTestingModuleUsage(usage, sourceFile, info, importManager, replacements);
|
||||
migratedUsages.push(usage);
|
||||
if (usage.usesSpyLocationUrlChanges) {
|
||||
filesWithLocationMocks.set(sourceFile.fileName, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
apply_import_manager.applyImportManagerChanges(importManager, replacements, info.sourceFiles, info);
|
||||
return project_paths.confirmAsSerializable({
|
||||
replacements,
|
||||
migratedUsages,
|
||||
filesWithLocationMocks,
|
||||
});
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return {
|
||||
replacements: globalData.replacements,
|
||||
};
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
const combinedFilesWithLocationMocks = new Map(unitA.filesWithLocationMocks);
|
||||
for (const [fileName, hasLocationMocks] of unitB.filesWithLocationMocks) {
|
||||
combinedFilesWithLocationMocks.set(fileName, hasLocationMocks || combinedFilesWithLocationMocks.get(fileName) || false);
|
||||
}
|
||||
return project_paths.confirmAsSerializable({
|
||||
replacements: [...unitA.replacements, ...unitB.replacements],
|
||||
migratedUsages: [...unitA.migratedUsages, ...unitB.migratedUsages],
|
||||
filesWithLocationMocks: combinedFilesWithLocationMocks,
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
return project_paths.confirmAsSerializable(combinedData);
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const stats = {
|
||||
counters: {
|
||||
replacements: globalMetadata.replacements.length,
|
||||
migratedUsages: globalMetadata.migratedUsages.length,
|
||||
filesWithLocationMocks: globalMetadata.filesWithLocationMocks.size,
|
||||
totalFiles: new Set(globalMetadata.migratedUsages.map((usage) => usage.sourceFile.fileName))
|
||||
.size,
|
||||
},
|
||||
};
|
||||
return stats;
|
||||
}
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new RouterTestingModuleMigration({
|
||||
shouldMigrate: (file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath) &&
|
||||
/\.spec\.ts$/.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for RouterTestingModule usage: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: (stats) => {
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated RouterTestingModule to RouterModule 🎉`);
|
||||
context.logger.info(` -> Migrated ${stats.counters.migratedUsages} RouterTestingModule usages in ${stats.counters.totalFiles} test files.`);
|
||||
if (stats.counters.filesWithLocationMocks > 0) {
|
||||
context.logger.info(` -> Added provideLocationMocks() to ${stats.counters.filesWithLocationMocks} files with SpyLocation.urlChanges usage.`);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
require('@angular/compiler-cli/private/migrations');
|
||||
require('node:path');
|
||||
var project_paths = require('./project_paths-D2V-Uh2L.cjs');
|
||||
var ng_component_template = require('./ng_component_template-BOuKAnQd.cjs');
|
||||
var compiler = require('@angular/compiler');
|
||||
var parse_html = require('./parse_html-C8eKA9px.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('@angular-devkit/schematics');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
require('./ng_decorators-DYy6II6x.cjs');
|
||||
require('./imports-CVmcbVA9.cjs');
|
||||
require('./property_name-BCpALNpZ.cjs');
|
||||
|
||||
function migrateTemplateToSelfClosingTags(template) {
|
||||
let parsed = parse_html.parseTemplate(template);
|
||||
if (parsed.tree === undefined) {
|
||||
return { migrated: template, changed: false, replacementCount: 0 };
|
||||
}
|
||||
const visitor = new AngularElementCollector();
|
||||
compiler.visitAll(visitor, parsed.tree.rootNodes);
|
||||
let newTemplate = template;
|
||||
let changedOffset = 0;
|
||||
let replacementCount = 0;
|
||||
for (let element of visitor.elements) {
|
||||
const { start, end, tagName } = element;
|
||||
const currentLength = newTemplate.length;
|
||||
const templatePart = newTemplate.slice(start + changedOffset, end + changedOffset);
|
||||
const convertedTemplate = replaceWithSelfClosingTag(templatePart, tagName);
|
||||
// if the template has changed, replace the original template with the new one
|
||||
if (convertedTemplate.length !== templatePart.length) {
|
||||
newTemplate = replaceTemplate(newTemplate, convertedTemplate, start, end, changedOffset);
|
||||
changedOffset += newTemplate.length - currentLength;
|
||||
replacementCount++;
|
||||
}
|
||||
}
|
||||
return { migrated: newTemplate, changed: changedOffset !== 0, replacementCount };
|
||||
}
|
||||
function replaceWithSelfClosingTag(html, tagName) {
|
||||
const pattern = new RegExp(`<\\s*${tagName}\\s*([^>]*?(?:"[^"]*"|'[^']*'|[^'">])*)\\s*>([\\s\\S]*?)<\\s*/\\s*${tagName}\\s*>`, 'gi');
|
||||
return html.replace(pattern, (_, content) => `<${tagName}${content ? ` ${content}` : ''} />`);
|
||||
}
|
||||
/**
|
||||
* Replace the value in the template with the new value based on the start and end position + offset
|
||||
*/
|
||||
function replaceTemplate(template, replaceValue, start, end, offset) {
|
||||
return template.slice(0, start + offset) + replaceValue + template.slice(end + offset);
|
||||
}
|
||||
const ALL_HTML_TAGS = new compiler.DomElementSchemaRegistry().allKnownElementNames();
|
||||
class AngularElementCollector extends compiler.RecursiveVisitor {
|
||||
elements = [];
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
visitElement(element) {
|
||||
if (!element.isSelfClosing &&
|
||||
!ALL_HTML_TAGS.includes(element.name) &&
|
||||
this.elementHasNoContent(element)) {
|
||||
this.elements.push({
|
||||
tagName: element.name,
|
||||
start: element.sourceSpan.start.offset,
|
||||
end: element.sourceSpan.end.offset,
|
||||
});
|
||||
}
|
||||
return super.visitElement(element, null);
|
||||
}
|
||||
elementHasNoContent(element) {
|
||||
if (!element.children?.length) {
|
||||
return true;
|
||||
}
|
||||
if (element.children.length === 1) {
|
||||
const child = element.children[0];
|
||||
return child instanceof compiler.Text && /^\s*$/.test(child.value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class SelfClosingTagsMigration extends project_paths.TsurgeFunnelMigration {
|
||||
config;
|
||||
constructor(config = {}) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
async analyze(info) {
|
||||
const { sourceFiles, program } = info;
|
||||
const typeChecker = program.getTypeChecker();
|
||||
const tagReplacements = [];
|
||||
for (const sf of sourceFiles) {
|
||||
ts.forEachChild(sf, (node) => {
|
||||
// Skipping any non component declarations
|
||||
if (!ts.isClassDeclaration(node)) {
|
||||
return;
|
||||
}
|
||||
const file = project_paths.projectFile(node.getSourceFile(), info);
|
||||
if (this.config.shouldMigrate && this.config.shouldMigrate(file) === false) {
|
||||
return;
|
||||
}
|
||||
const templateVisitor = new ng_component_template.NgComponentTemplateVisitor(typeChecker);
|
||||
templateVisitor.visitNode(node);
|
||||
templateVisitor.resolvedTemplates.forEach((template) => {
|
||||
const { migrated, changed, replacementCount } = migrateTemplateToSelfClosingTags(template.content);
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
const fileToMigrate = template.inline
|
||||
? file
|
||||
: project_paths.projectFile(template.filePath, info);
|
||||
const end = template.start + template.content.length;
|
||||
const replacements = [
|
||||
prepareTextReplacement(fileToMigrate, migrated, template.start, end),
|
||||
];
|
||||
const fileReplacements = tagReplacements.find((tagReplacement) => tagReplacement.file === file);
|
||||
if (fileReplacements) {
|
||||
fileReplacements.replacements.push(...replacements);
|
||||
fileReplacements.replacementCount += replacementCount;
|
||||
}
|
||||
else {
|
||||
tagReplacements.push({ file, replacements, replacementCount });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
return project_paths.confirmAsSerializable({ tagReplacements });
|
||||
}
|
||||
async combine(unitA, unitB) {
|
||||
return project_paths.confirmAsSerializable({
|
||||
tagReplacements: [...unitA.tagReplacements, ...unitB.tagReplacements],
|
||||
});
|
||||
}
|
||||
async globalMeta(combinedData) {
|
||||
const globalMeta = {
|
||||
tagReplacements: combinedData.tagReplacements,
|
||||
};
|
||||
return project_paths.confirmAsSerializable(globalMeta);
|
||||
}
|
||||
async stats(globalMetadata) {
|
||||
const touchedFilesCount = globalMetadata.tagReplacements.length;
|
||||
const replacementCount = globalMetadata.tagReplacements.reduce((acc, cur) => acc + cur.replacementCount, 0);
|
||||
return project_paths.confirmAsSerializable({
|
||||
touchedFilesCount,
|
||||
replacementCount,
|
||||
});
|
||||
}
|
||||
async migrate(globalData) {
|
||||
return { replacements: globalData.tagReplacements.flatMap(({ replacements }) => replacements) };
|
||||
}
|
||||
}
|
||||
function prepareTextReplacement(file, replacement, start, end) {
|
||||
return new project_paths.Replacement(file, new project_paths.TextUpdate({
|
||||
position: start,
|
||||
end: end,
|
||||
toInsert: replacement,
|
||||
}));
|
||||
}
|
||||
|
||||
function migrate(options) {
|
||||
return async (tree, context) => {
|
||||
await project_paths.runMigrationInDevkit({
|
||||
tree,
|
||||
getMigration: (fs) => new SelfClosingTagsMigration({
|
||||
shouldMigrate: (file) => {
|
||||
return (file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
|
||||
!/(^|\/)node_modules\//.test(file.rootRelativePath));
|
||||
},
|
||||
}),
|
||||
beforeProgramCreation: (tsconfigPath, stage) => {
|
||||
if (stage === project_paths.MigrationStage.Analysis) {
|
||||
context.logger.info(`Preparing analysis for: ${tsconfigPath}...`);
|
||||
}
|
||||
else {
|
||||
context.logger.info(`Running migration for: ${tsconfigPath}...`);
|
||||
}
|
||||
},
|
||||
beforeUnitAnalysis: (tsconfigPath) => {
|
||||
context.logger.info(`Scanning for component tags: ${tsconfigPath}...`);
|
||||
},
|
||||
afterAllAnalyzed: () => {
|
||||
context.logger.info(``);
|
||||
context.logger.info(`Processing analysis data between targets...`);
|
||||
context.logger.info(``);
|
||||
},
|
||||
afterAnalysisFailure: () => {
|
||||
context.logger.error('Migration failed unexpectedly with no analysis data');
|
||||
},
|
||||
whenDone: ({ touchedFilesCount, replacementCount }) => {
|
||||
context.logger.info('');
|
||||
context.logger.info(`Successfully migrated to self-closing tags 🎉`);
|
||||
context.logger.info(` -> Migrated ${replacementCount} components to self-closing tags in ${touchedFilesCount} component files.`);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+1573
File diff suppressed because it is too large
Load Diff
+1173
File diff suppressed because it is too large
Load Diff
+51
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var schematics = require('@angular-devkit/schematics');
|
||||
var signalQueriesMigration = require('./signal-queries-migration.cjs');
|
||||
var signalInputMigration = require('./signal-input-migration.cjs');
|
||||
var outputMigration = require('./output-migration.cjs');
|
||||
require('@angular/compiler-cli/private/migrations');
|
||||
require('typescript');
|
||||
require('@angular/compiler-cli');
|
||||
require('node:path');
|
||||
require('./project_paths-D2V-Uh2L.cjs');
|
||||
require('@angular-devkit/core');
|
||||
require('node:path/posix');
|
||||
require('./project_tsconfig_paths-DkkMibv-.cjs');
|
||||
require('./apply_import_manager-CxA_YYgB.cjs');
|
||||
require('./migrate_ts_type_references-MWoZx-Cb.cjs');
|
||||
require('assert');
|
||||
require('./index-BtLcQH8g.cjs');
|
||||
require('@angular/compiler');
|
||||
require('./leading_space-BTPRV0wu.cjs');
|
||||
|
||||
function migrate(options) {
|
||||
// The migrations are independent so we can run them in any order, but we sort them here
|
||||
// alphabetically so we get a consistent execution order in case of issue reports.
|
||||
const migrations = options.migrations.slice().sort();
|
||||
const rules = [];
|
||||
for (const migration of migrations) {
|
||||
switch (migration) {
|
||||
case "inputs" /* SupportedMigrations.inputs */:
|
||||
rules.push(signalInputMigration.migrate(options));
|
||||
break;
|
||||
case "outputs" /* SupportedMigrations.outputs */:
|
||||
rules.push(outputMigration.migrate(options));
|
||||
break;
|
||||
case "queries" /* SupportedMigrations.queries */:
|
||||
rules.push(signalQueriesMigration.migrate(options));
|
||||
break;
|
||||
default:
|
||||
throw new schematics.SchematicsException(`Unsupported migration "${migration}"`);
|
||||
}
|
||||
}
|
||||
return schematics.chain(rules);
|
||||
}
|
||||
|
||||
exports.migrate = migrate;
|
||||
+2105
File diff suppressed because it is too large
Load Diff
+26
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ts = require('typescript');
|
||||
|
||||
/** Checks whether a node is referring to a specific import specifier. */
|
||||
function isReferenceToImport(typeChecker, node, importSpecifier) {
|
||||
// If this function is called on an identifier (should be most cases), we can quickly rule out
|
||||
// non-matches by comparing the identifier's string and the local name of the import specifier
|
||||
// which saves us some calls to the type checker.
|
||||
if (importSpecifier === null ||
|
||||
(ts.isIdentifier(node) && node.text !== importSpecifier.name.text)) {
|
||||
return false;
|
||||
}
|
||||
const nodeSymbol = typeChecker.getTypeAtLocation(node).getSymbol();
|
||||
const importSymbol = typeChecker.getTypeAtLocation(importSpecifier).getSymbol();
|
||||
return (!!(nodeSymbol?.declarations?.[0] && importSymbol?.declarations?.[0]) &&
|
||||
nodeSymbol.declarations[0] === importSymbol.declarations[0]);
|
||||
}
|
||||
|
||||
exports.isReferenceToImport = isReferenceToImport;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"schematics": {
|
||||
"standalone-migration": {
|
||||
"description": "Converts the entire application or a part of it to standalone",
|
||||
"factory": "./bundles/standalone-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/standalone-migration/schema.json",
|
||||
"aliases": ["standalone"]
|
||||
},
|
||||
"inject-migration": {
|
||||
"description": "Converts usages of constructor-based injection to the inject() function",
|
||||
"factory": "./bundles/inject-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/inject-migration/schema.json",
|
||||
"aliases": ["inject"]
|
||||
},
|
||||
"route-lazy-loading-migration": {
|
||||
"description": "Updates route definitions to use lazy-loading of components instead of eagerly referencing them",
|
||||
"factory": "./bundles/route-lazy-loading.cjs#migrate",
|
||||
"schema": "./ng-generate/route-lazy-loading/schema.json",
|
||||
"aliases": ["route-lazy-loading"]
|
||||
},
|
||||
"signal-input-migration": {
|
||||
"description": "Updates `@Input` declarations to signal inputs, while also migrating all relevant references.",
|
||||
"factory": "./bundles/signal-input-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/signal-input-migration/schema.json",
|
||||
"aliases": ["signal-inputs", "signal-input"]
|
||||
},
|
||||
"signal-queries-migration": {
|
||||
"description": "Updates query declarations to signal queries, while also migrating all relevant references.",
|
||||
"factory": "./bundles/signal-queries-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/signal-queries-migration/schema.json",
|
||||
"aliases": ["signal-queries", "signal-query", "signal-query-migration"]
|
||||
},
|
||||
"output-migration": {
|
||||
"description": "Updates @output declarations to the functional equivalent, while also migrating all relevant references.",
|
||||
"factory": "./bundles/output-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/output-migration/schema.json",
|
||||
"aliases": ["outputs"]
|
||||
},
|
||||
"signals": {
|
||||
"description": "Combines all signals-related migrations into a single migration",
|
||||
"factory": "./bundles/signals.cjs#migrate",
|
||||
"schema": "./ng-generate/signals/schema.json"
|
||||
},
|
||||
"cleanup-unused-imports": {
|
||||
"description": "Removes unused imports from standalone components.",
|
||||
"factory": "./bundles/cleanup-unused-imports.cjs#migrate",
|
||||
"schema": "./ng-generate/cleanup-unused-imports/schema.json"
|
||||
},
|
||||
"self-closing-tags-migration": {
|
||||
"description": "Updates the components templates to use self-closing tags where possible",
|
||||
"factory": "./bundles/self-closing-tags-migration.cjs#migrate",
|
||||
"schema": "./ng-generate/self-closing-tags-migration/schema.json",
|
||||
"aliases": ["self-closing-tag"]
|
||||
},
|
||||
"common-to-standalone-migration": {
|
||||
"description": "Replaces CommonModule with individual imports from @angular/common",
|
||||
"factory": "./bundles/common-to-standalone-migration.cjs#migrate",
|
||||
"schema": "./migrations/common-to-standalone-migration/schema.json",
|
||||
"aliases": ["common-to-standalone"]
|
||||
},
|
||||
"control-flow-migration": {
|
||||
"description": "Converts the entire application to block control flow syntax",
|
||||
"factory": "./bundles/control-flow-migration.cjs#migrate",
|
||||
"schema": "./migrations/control-flow-migration/schema.json",
|
||||
"aliases": ["control-flow"]
|
||||
},
|
||||
"ngclass-to-class-migration": {
|
||||
"description": "Updates usages of `ngClass` directives to the `class` bindings where possible",
|
||||
"factory": "./bundles/ngclass-to-class-migration.cjs#migrate",
|
||||
"schema": "./migrations/ngclass-to-class-migration/schema.json",
|
||||
"aliases": ["ngclass-to-class"]
|
||||
},
|
||||
"ngstyle-to-style-migration": {
|
||||
"description": "Updates usages of `ngStyle` directives to the `style` bindings where possible",
|
||||
"factory": "./bundles/ngstyle-to-style-migration.cjs#migrate",
|
||||
"schema": "./migrations/ngstyle-to-style-migration/schema.json",
|
||||
"aliases": ["ngstyle-to-style"]
|
||||
},
|
||||
"router-testing-module-migration": {
|
||||
"description": "Replaces deprecated RouterTestingModule with provideRouter() as recommended in the deprecation note",
|
||||
"factory": "./bundles/router-testing-module-migration.cjs#migrate",
|
||||
"schema": "./migrations/router-testing-module-migration/schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"schematics": {
|
||||
"control-flow-migration": {
|
||||
"version": "21.0.0",
|
||||
"description": "Converts the entire application to block control flow syntax",
|
||||
"factory": "./bundles/control-flow-migration.cjs#migrate"
|
||||
},
|
||||
"router-current-navigation": {
|
||||
"version": "21.0.0",
|
||||
"description": "Replaces usages of the deprecated Router.getCurrentNavigation method with the Router.currentNavigation signal",
|
||||
"factory": "./bundles/router-current-navigation.cjs#migrate",
|
||||
"optional": true
|
||||
},
|
||||
"router-last-successful-navigation": {
|
||||
"version": "21.0.0",
|
||||
"description": "Ensures that the Router.lastSuccessfulNavigation signal is now invoked",
|
||||
"factory": "./bundles/router-last-successful-navigation.cjs#migrate"
|
||||
},
|
||||
"application-config-core": {
|
||||
"version": "21.0.0",
|
||||
"description": "Moves imports of `ApplicationConfig` from `@angular/platform-browser` to `@angular/core`",
|
||||
"factory": "./bundles/application-config-core.cjs#migrate"
|
||||
},
|
||||
"add-bootstrap-context-to-server-main": {
|
||||
"version": "21.0.0",
|
||||
"description": "Adds `BootstrapContext` to `bootstrapApplication` calls in `main.server.ts` to support server rendering.",
|
||||
"factory": "./bundles/add-bootstrap-context-to-server-main.cjs#migrate"
|
||||
},
|
||||
"bootstrap-options-migration": {
|
||||
"version": "21.0.0",
|
||||
"description": "Migrates deprecated bootstrap options to providers.",
|
||||
"factory": "./bundles/bootstrap-options-migration.cjs#migrate"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularCommonToStandaloneMigration",
|
||||
"title": "Angular Common to Standalone Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all components and modules should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularControlFlowMigration",
|
||||
"title": "Angular Control Flow Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path relative to the project root which should be migrated",
|
||||
"x-prompt": "Which path in your project should be migrated?",
|
||||
"default": "./"
|
||||
},
|
||||
"format": {
|
||||
"type": "boolean",
|
||||
"description": "Enables reformatting of your templates",
|
||||
"x-prompt": "Should the migration reformat your templates?",
|
||||
"default": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularNgclassToClassMigration",
|
||||
"title": "Angular ngClass to class Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all templates should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"migrateSpaceSeparatedKey": {
|
||||
"type": "boolean",
|
||||
"description": "Enables the migration of object literals with space-separated keys",
|
||||
"x-prompt": "Should the migration also migrate space-separated keys?",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularNgStyleToStyleMigration",
|
||||
"title": "Angular ngStyle to style Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all templates should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"bestEffortMode": {
|
||||
"type": "boolean",
|
||||
"description": "Enables the migration of object references",
|
||||
"x-prompt": "Should the migration also migrate object references?",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularRouterTestingToProvideRouterMigration",
|
||||
"title": "Angular RouterTestingModule to provideRouter Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all tests should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularCleanupUnusedImportsMigration",
|
||||
"title": "Angular Cleanup Unused Imports Schema",
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularInjectMigration",
|
||||
"title": "Angular Inject Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path relative to the project root which should be migrated",
|
||||
"x-prompt": "Which path in your project should be migrated?",
|
||||
"default": "./"
|
||||
},
|
||||
"migrateAbstractClasses": {
|
||||
"type": "boolean",
|
||||
"description": "Whether abstract classes should be migrated",
|
||||
"x-prompt": "Do you want to migrate abstract classes? Abstract classes are not migrated by default, because their parameters aren't guaranteed to be injectable",
|
||||
"default": false
|
||||
},
|
||||
"backwardsCompatibleConstructors": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to clean up constructors or keep their signatures backwards compatible",
|
||||
"x-prompt": "Do you want to clean up all constructors or keep them backwards compatible? Enabling this option will include an additional signature of `constructor(...args: unknown[]);` that will avoid errors for sub-classes, but will increase the amount of generated code by the migration",
|
||||
"default": false
|
||||
},
|
||||
"nonNullableOptional": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to cast the optional inject sites to be non-nullable",
|
||||
"x-prompt": "Do you want optional inject calls to be non-nullable? Enable this option if you want the return type to be identical to @Optional(), at the expense of worse type safety",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularOutputMigration",
|
||||
"title": "Angular Output migration",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all outputs should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"analysisDir": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory that should be analyzed. References to migrated outputs are migrated based on this folder. Useful for larger projects if the analysis takes too long and the analysis scope can be narrowed.",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularStandaloneRoutesMigration",
|
||||
"title": "Angular Standalone Routes Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path relative to the project root which should be migrated",
|
||||
"x-prompt": "Which path in your project should be migrated?",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularSelfClosingTagMigration",
|
||||
"title": "Angular Self Closing Tag Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all templates should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularSignalInputMigration",
|
||||
"title": "Angular Signal Input migration",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all inputs should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"analysisDir": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory that should be analyzed. References to migrated inputs are migrated based on this folder. Useful for larger projects if the analysis takes too long and the analysis scope can be narrowed.",
|
||||
"default": "./"
|
||||
},
|
||||
"bestEffortMode": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to eagerly migrate as much as possible, ignoring problematic patterns that would otherwise prevent migration.",
|
||||
"x-prompt": "Do you want to migrate as much as possible, even if it may break your build?",
|
||||
"default": false
|
||||
},
|
||||
"insertTodos": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the migration should add TODOs for inputs that could not be migrated",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularSignalQueriesMigration",
|
||||
"title": "Angular Signal Queries migration",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory where all queries should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"analysisDir": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory that should be analyzed. References to migrated queries are migrated based on this folder. Useful for larger projects if the analysis takes too long and the analysis scope can be narrowed.",
|
||||
"default": "./"
|
||||
},
|
||||
"bestEffortMode": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to eagerly migrate as much as possible, ignoring problematic patterns that would otherwise prevent migration.",
|
||||
"x-prompt": "Do you want to migrate as much as possible, even if it may break your build?",
|
||||
"default": false
|
||||
},
|
||||
"insertTodos": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the migration should add TODOs for queries that could not be migrated",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularSignalMigration",
|
||||
"title": "Angular Signals migration",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"migrations": {
|
||||
"type": "array",
|
||||
"default": [
|
||||
"inputs",
|
||||
"outputs",
|
||||
"queries"
|
||||
],
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"inputs",
|
||||
"outputs",
|
||||
"queries"
|
||||
]
|
||||
},
|
||||
"description": "Signals-related migrations that should be run",
|
||||
"x-prompt": {
|
||||
"message": "Which migrations do you want to run?",
|
||||
"type": "list",
|
||||
"multiselect": true,
|
||||
"items": [
|
||||
{
|
||||
"value": "inputs",
|
||||
"label": "Convert `@Input` to the signal-based `input`"
|
||||
},
|
||||
{
|
||||
"value": "outputs",
|
||||
"label": "Convert `@Output` to the new `output` function"
|
||||
},
|
||||
{
|
||||
"value": "queries",
|
||||
"label": "Convert `@ViewChild`/`@ViewChildren` and `@ContentChild`/`@ContentChildren` to the signal-based `viewChild`/`viewChildren` and `contentChild`/`contentChildren`"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory that should be migrated.",
|
||||
"x-prompt": "Which directory do you want to migrate?",
|
||||
"default": "./"
|
||||
},
|
||||
"analysisDir": {
|
||||
"type": "string",
|
||||
"description": "Path to the directory that should be analyzed. Useful for larger projects if the analysis takes too long and the analysis scope can be narrowed.",
|
||||
"default": "./"
|
||||
},
|
||||
"bestEffortMode": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to eagerly migrate as much as possible, ignoring problematic patterns that would otherwise prevent migration.",
|
||||
"x-prompt": "Do you want to migrate as much as possible, even if it may break your build?",
|
||||
"default": false
|
||||
},
|
||||
"insertTodos": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the migration should add TODOs for code that could not be migrated",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "AngularStandaloneMigration",
|
||||
"title": "Angular Standalone Migration Schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"description": "Operation that should be performed by the migrator",
|
||||
"type": "string",
|
||||
"enum": ["convert-to-standalone", "prune-ng-modules", "standalone-bootstrap"],
|
||||
"default": "convert-to-standalone",
|
||||
"x-prompt": {
|
||||
"message": "Choose the type of migration:",
|
||||
"type": "list",
|
||||
"items": [
|
||||
{
|
||||
"value": "convert-to-standalone",
|
||||
"label": "Convert all components, directives and pipes to standalone"
|
||||
},
|
||||
{
|
||||
"value": "prune-ng-modules",
|
||||
"label": "Remove unnecessary NgModule classes"
|
||||
},
|
||||
{
|
||||
"value": "standalone-bootstrap",
|
||||
"label": "Bootstrap the application using standalone APIs"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path relative to the project root which should be migrated",
|
||||
"x-prompt": "Which path in your project should be migrated?",
|
||||
"default": "./"
|
||||
}
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { OutputRef, OutputRefSubscription, DestroyRef, Signal, WritableSignal, ValueEqualityFn, Injector } from './_chrome_dev_tools_performance-chunk.js';
|
||||
|
||||
/**
|
||||
* An `OutputEmitterRef` is created by the `output()` function and can be
|
||||
* used to emit values to consumers of your directive or component.
|
||||
*
|
||||
* Consumers of your directive/component can bind to the output and
|
||||
* subscribe to changes via the bound event syntax. For example:
|
||||
*
|
||||
* ```html
|
||||
* <my-comp (valueChange)="processNewValue($event)" />
|
||||
* ```
|
||||
*
|
||||
* @see [Custom events with outputs](guide/components/outputs)
|
||||
*
|
||||
* @publicAPI
|
||||
*/
|
||||
declare class OutputEmitterRef<T> implements OutputRef<T> {
|
||||
private destroyed;
|
||||
private listeners;
|
||||
private errorHandler;
|
||||
constructor();
|
||||
subscribe(callback: (value: T) => void): OutputRefSubscription;
|
||||
/** Emits a new value to the output. */
|
||||
emit(value: T): void;
|
||||
}
|
||||
/** Gets the owning `DestroyRef` for the given output. */
|
||||
declare function getOutputDestroyRef(ref: OutputRef<unknown>): DestroyRef | undefined;
|
||||
|
||||
/**
|
||||
* Options for declaring an output.
|
||||
*
|
||||
* @see [Customizing output names](guide/components/outputs#customizing-output-names)
|
||||
*
|
||||
* @publicApi 19.0
|
||||
*/
|
||||
interface OutputOptions {
|
||||
alias?: string;
|
||||
}
|
||||
/**
|
||||
* The `output` function allows declaration of Angular outputs in
|
||||
* directives and components.
|
||||
*
|
||||
* You can use outputs to emit values to parent directives and component.
|
||||
* Parents can subscribe to changes via:
|
||||
*
|
||||
* - template event bindings. For example, `(myOutput)="doSomething($event)"`
|
||||
* - programmatic subscription by using `OutputRef#subscribe`.
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* To use `output()`, import the function from `@angular/core`.
|
||||
*
|
||||
* ```ts
|
||||
* import {output} from '@angular/core';
|
||||
* ```
|
||||
*
|
||||
* Inside your component, introduce a new class member and initialize
|
||||
* it with a call to `output`.
|
||||
*
|
||||
* ```ts
|
||||
* @Directive({
|
||||
* ...
|
||||
* })
|
||||
* export class MyDir {
|
||||
* nameChange = output<string>(); // OutputEmitterRef<string>
|
||||
* onClick = output(); // OutputEmitterRef<void>
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* You can emit values to consumers of your directive, by using
|
||||
* the `emit` method from `OutputEmitterRef`.
|
||||
*
|
||||
* ```ts
|
||||
* updateName(newName: string): void {
|
||||
* this.nameChange.emit(newName);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @see [Custom events with outputs](guide/components/outputs#customizing-output-names)
|
||||
*
|
||||
* @initializerApiFunction {"showTypesInSignaturePreview": true}
|
||||
* @publicApi 19.0
|
||||
*/
|
||||
declare function output<T = void>(opts?: OutputOptions): OutputEmitterRef<T>;
|
||||
|
||||
/**
|
||||
* String value capturing the status of a `Resource`.
|
||||
*
|
||||
* Possible statuses are:
|
||||
*
|
||||
* `idle` - The resource has no valid request and will not perform any loading. `value()` will be
|
||||
* `undefined`.
|
||||
*
|
||||
* `loading` - The resource is currently loading a new value as a result of a change in its reactive
|
||||
* dependencies. `value()` will be `undefined`.
|
||||
*
|
||||
* `reloading` - The resource is currently reloading a fresh value for the same reactive
|
||||
* dependencies. `value()` will continue to return the previously fetched value during the reloading
|
||||
* operation.
|
||||
*
|
||||
* `error` - Loading failed with an error. `value()` will be `undefined`.
|
||||
*
|
||||
* `resolved` - Loading has completed and the resource has the value returned from the loader.
|
||||
*
|
||||
* `local` - The resource's value was set locally via `.set()` or `.update()`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
type ResourceStatus = 'idle' | 'error' | 'loading' | 'reloading' | 'resolved' | 'local';
|
||||
/**
|
||||
* A Resource is an asynchronous dependency (for example, the results of an API call) that is
|
||||
* managed and delivered through signals.
|
||||
*
|
||||
* The usual way of creating a `Resource` is through the `resource` function, but various other APIs
|
||||
* may present `Resource` instances to describe their own concepts.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface Resource<T> {
|
||||
/**
|
||||
* The current value of the `Resource`, or throws an error if the resource is in an error state.
|
||||
*/
|
||||
readonly value: Signal<T>;
|
||||
/**
|
||||
* The current status of the `Resource`, which describes what the resource is currently doing and
|
||||
* what can be expected of its `value`.
|
||||
*/
|
||||
readonly status: Signal<ResourceStatus>;
|
||||
/**
|
||||
* When in the `error` state, this returns the last known error from the `Resource`.
|
||||
*/
|
||||
readonly error: Signal<Error | undefined>;
|
||||
/**
|
||||
* Whether this resource is loading a new value (or reloading the existing one).
|
||||
*/
|
||||
readonly isLoading: Signal<boolean>;
|
||||
/**
|
||||
* The current state of this resource, represented as a `ResourceSnapshot`.
|
||||
*/
|
||||
readonly snapshot: Signal<ResourceSnapshot<T>>;
|
||||
/**
|
||||
* Whether this resource has a valid current value.
|
||||
*
|
||||
* This function is reactive.
|
||||
*/
|
||||
hasValue(this: T extends undefined ? this : never): this is Resource<Exclude<T, undefined>>;
|
||||
hasValue(): boolean;
|
||||
}
|
||||
/**
|
||||
* A `Resource` with a mutable value.
|
||||
*
|
||||
* Overwriting the value of a resource sets it to the 'local' state.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface WritableResource<T> extends Resource<T> {
|
||||
readonly value: WritableSignal<T>;
|
||||
hasValue(this: T extends undefined ? this : never): this is WritableResource<Exclude<T, undefined>>;
|
||||
hasValue(): boolean;
|
||||
/**
|
||||
* Convenience wrapper for `value.set`.
|
||||
*/
|
||||
set(value: T): void;
|
||||
/**
|
||||
* Convenience wrapper for `value.update`.
|
||||
*/
|
||||
update(updater: (value: T) => T): void;
|
||||
asReadonly(): Resource<T>;
|
||||
/**
|
||||
* Instructs the resource to re-load any asynchronous dependency it may have.
|
||||
*
|
||||
* Note that the resource will not enter its reloading state until the actual backend request is
|
||||
* made.
|
||||
*
|
||||
* @returns true if a reload was initiated, false if a reload was unnecessary or unsupported
|
||||
*/
|
||||
reload(): boolean;
|
||||
}
|
||||
/**
|
||||
* A `WritableResource` created through the `resource` function.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface ResourceRef<T> extends WritableResource<T> {
|
||||
hasValue(this: T extends undefined ? this : never): this is ResourceRef<Exclude<T, undefined>>;
|
||||
hasValue(): boolean;
|
||||
/**
|
||||
* Manually destroy the resource, which cancels pending requests and returns it to `idle` state.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* Parameter to a `ResourceLoader` which gives the request and other options for the current loading
|
||||
* operation.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface ResourceLoaderParams<R> {
|
||||
params: NoInfer<Exclude<R, undefined>>;
|
||||
abortSignal: AbortSignal;
|
||||
previous: {
|
||||
status: ResourceStatus;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Loading function for a `Resource`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
type ResourceLoader<T, R> = (param: ResourceLoaderParams<R>) => PromiseLike<T>;
|
||||
/**
|
||||
* Streaming loader for a `Resource`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
type ResourceStreamingLoader<T, R> = (param: ResourceLoaderParams<R>) => PromiseLike<Signal<ResourceStreamItem<T>>>;
|
||||
/**
|
||||
* Options to the `resource` function, for creating a resource.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface BaseResourceOptions<T, R> {
|
||||
/**
|
||||
* A reactive function which determines the request to be made. Whenever the request changes, the
|
||||
* loader will be triggered to fetch a new value for the resource.
|
||||
*
|
||||
* If a params function isn't provided, the loader won't rerun unless the resource is reloaded.
|
||||
*/
|
||||
params?: () => R;
|
||||
/**
|
||||
* The value which will be returned from the resource when a server value is unavailable, such as
|
||||
* when the resource is still loading.
|
||||
*/
|
||||
defaultValue?: NoInfer<T>;
|
||||
/**
|
||||
* Equality function used to compare the return value of the loader.
|
||||
*/
|
||||
equal?: ValueEqualityFn<T>;
|
||||
/**
|
||||
* Overrides the `Injector` used by `resource`.
|
||||
*/
|
||||
injector?: Injector;
|
||||
}
|
||||
/**
|
||||
* Options to the `resource` function, for creating a resource.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface PromiseResourceOptions<T, R> extends BaseResourceOptions<T, R> {
|
||||
/**
|
||||
* Loading function which returns a `Promise` of the resource's value for a given request.
|
||||
*/
|
||||
loader: ResourceLoader<T, R>;
|
||||
/**
|
||||
* Cannot specify `stream` and `loader` at the same time.
|
||||
*/
|
||||
stream?: never;
|
||||
}
|
||||
/**
|
||||
* Options to the `resource` function, for creating a resource.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface StreamingResourceOptions<T, R> extends BaseResourceOptions<T, R> {
|
||||
/**
|
||||
* Loading function which returns a `Promise` of a signal of the resource's value for a given
|
||||
* request, which can change over time as new values are received from a stream.
|
||||
*/
|
||||
stream: ResourceStreamingLoader<T, R>;
|
||||
/**
|
||||
* Cannot specify `stream` and `loader` at the same time.
|
||||
*/
|
||||
loader?: never;
|
||||
}
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
type ResourceOptions<T, R> = (PromiseResourceOptions<T, R> | StreamingResourceOptions<T, R>) & {
|
||||
/**
|
||||
* A debug name for the reactive node. Used in Angular DevTools to identify the node.
|
||||
*/
|
||||
debugName?: string;
|
||||
};
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
type ResourceStreamItem<T> = {
|
||||
value: T;
|
||||
} | {
|
||||
error: Error;
|
||||
};
|
||||
/**
|
||||
* An explicit representation of a resource's state.
|
||||
*
|
||||
* @experimental
|
||||
* @see [Resource composition with snapshots](guide/signals/resource#resource-composition-with-snapshots)
|
||||
*/
|
||||
type ResourceSnapshot<T> = {
|
||||
readonly status: 'idle';
|
||||
readonly value: T;
|
||||
} | {
|
||||
readonly status: 'loading' | 'reloading';
|
||||
readonly value: T;
|
||||
} | {
|
||||
readonly status: 'resolved' | 'local';
|
||||
readonly value: T;
|
||||
} | {
|
||||
readonly status: 'error';
|
||||
readonly error: Error;
|
||||
};
|
||||
|
||||
export { OutputEmitterRef, getOutputDestroyRef, output };
|
||||
export type { BaseResourceOptions, OutputOptions, PromiseResourceOptions, Resource, ResourceLoader, ResourceLoaderParams, ResourceOptions, ResourceRef, ResourceSnapshot, ResourceStatus, ResourceStreamItem, ResourceStreamingLoader, StreamingResourceOptions, WritableResource };
|
||||
+863
@@ -0,0 +1,863 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { SIGNAL } from './_formatter-chunk.js';
|
||||
import { EventContract } from './_event_dispatcher-chunk.js';
|
||||
|
||||
/** Symbol used distinguish `WritableSignal` from other non-writable signals and functions. */
|
||||
declare const ɵWRITABLE_SIGNAL: unique symbol;
|
||||
/**
|
||||
* A `Signal` with a value that can be mutated via a setter interface.
|
||||
*
|
||||
* @publicApi 17.0
|
||||
*/
|
||||
interface WritableSignal<T> extends Signal<T> {
|
||||
[ɵWRITABLE_SIGNAL]: T;
|
||||
/**
|
||||
* Directly set the signal to a new value, and notify any dependents.
|
||||
*/
|
||||
set(value: T): void;
|
||||
/**
|
||||
* Update the value of the signal based on its current value, and
|
||||
* notify any dependents.
|
||||
*/
|
||||
update(updateFn: (value: T) => T): void;
|
||||
/**
|
||||
* Returns a readonly version of this signal. Readonly signals can be accessed to read their value
|
||||
* but can't be changed using set or update methods. The readonly signals do _not_ have
|
||||
* any built-in mechanism that would prevent deep-mutation of their value.
|
||||
*/
|
||||
asReadonly(): Signal<T>;
|
||||
}
|
||||
/**
|
||||
* Utility function used during template type checking to extract the value from a `WritableSignal`.
|
||||
* @codeGenApi
|
||||
*/
|
||||
declare function ɵunwrapWritableSignal<T>(value: T | {
|
||||
[ɵWRITABLE_SIGNAL]: T;
|
||||
}): T;
|
||||
/**
|
||||
* Options passed to the `signal` creation function.
|
||||
*/
|
||||
interface CreateSignalOptions<T> {
|
||||
/**
|
||||
* A comparison function which defines equality for signal values.
|
||||
*/
|
||||
equal?: ValueEqualityFn<T>;
|
||||
/**
|
||||
* A debug name for the signal. Used in Angular DevTools to identify the signal.
|
||||
*/
|
||||
debugName?: string;
|
||||
}
|
||||
/**
|
||||
* Create a `Signal` that can be set or updated directly.
|
||||
* @see [Angular Signals](guide/signals)
|
||||
*/
|
||||
declare function signal<T>(initialValue: T, options?: CreateSignalOptions<T>): WritableSignal<T>;
|
||||
|
||||
/**
|
||||
* A reactive value which notifies consumers of any changes.
|
||||
*
|
||||
* Signals are functions which returns their current value. To access the current value of a signal,
|
||||
* call it.
|
||||
*
|
||||
* Ordinary values can be turned into `Signal`s with the `signal` function.
|
||||
*
|
||||
* @see [What are signals?](guide/signals#what-are-signals)
|
||||
*
|
||||
* @publicApi 17.0
|
||||
*/
|
||||
type Signal<T> = (() => T) & {
|
||||
[SIGNAL]: unknown;
|
||||
};
|
||||
/**
|
||||
* Checks if the given `value` is a reactive `Signal`.
|
||||
*
|
||||
* @see [Type checking signals](guide/signals#type-checking-signals)
|
||||
*
|
||||
* @publicApi 17.0
|
||||
*/
|
||||
declare function isSignal(value: unknown): value is Signal<unknown>;
|
||||
/**
|
||||
* A comparison function which can determine if two values are equal.
|
||||
*
|
||||
* @see [Signal equality functions](guide/signals#signal-equality-functions)
|
||||
*
|
||||
* @publicApi 17.0
|
||||
*/
|
||||
type ValueEqualityFn<T> = (a: T, b: T) => boolean;
|
||||
/**
|
||||
* Checks if the given `value` is a writeable signal.
|
||||
*
|
||||
* @see [Type checking signals](guide/signals#type-checking-signals)
|
||||
*
|
||||
* @publicApi 21.1
|
||||
*/
|
||||
declare function isWritableSignal(value: unknown): value is WritableSignal<unknown>;
|
||||
|
||||
/**
|
||||
* Function that can be used to manually clean up a
|
||||
* programmatic {@link OutputRef#subscribe} subscription.
|
||||
*
|
||||
* Note: Angular will automatically clean up subscriptions
|
||||
* when the directive/component of the output is destroyed.
|
||||
*
|
||||
* @see [Subscribing to outputs programmatically](guide/components/outputs#subscribing-to-outputs-programmatically)
|
||||
*
|
||||
* @publicAPI
|
||||
*/
|
||||
interface OutputRefSubscription {
|
||||
unsubscribe(): void;
|
||||
}
|
||||
/**
|
||||
* A reference to an Angular output.
|
||||
*
|
||||
* @publicAPI
|
||||
* @see [Subscribing to outputs programmatically](guide/components/outputs#subscribing-to-outputs-programmatically)
|
||||
*/
|
||||
interface OutputRef<T> {
|
||||
/**
|
||||
* Registers a callback that is invoked whenever the output
|
||||
* emits a new value of type `T`.
|
||||
*
|
||||
* Angular will automatically clean up the subscription when
|
||||
* the directive/component of the output is destroyed.
|
||||
*/
|
||||
subscribe(callback: (value: T) => void): OutputRefSubscription;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description
|
||||
*
|
||||
* Represents an abstract class `T`, if applied to a concrete class it would stop being
|
||||
* instantiable.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface AbstractType<T> extends Function {
|
||||
prototype: T;
|
||||
}
|
||||
/**
|
||||
* @description
|
||||
*
|
||||
* Represents a type that a Component or other object is instances of.
|
||||
*
|
||||
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
|
||||
* the `MyCustomComponent` constructor function.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare const Type: FunctionConstructor;
|
||||
interface Type<T> extends Function {
|
||||
new (...args: any[]): T;
|
||||
}
|
||||
/**
|
||||
* Returns a writable type version of type.
|
||||
*
|
||||
* USAGE:
|
||||
* Given:
|
||||
* ```ts
|
||||
* interface Person {readonly name: string}
|
||||
* ```
|
||||
*
|
||||
* We would like to get a read/write version of `Person`.
|
||||
* ```ts
|
||||
* const WritablePerson = Writable<Person>;
|
||||
* ```
|
||||
*
|
||||
* The result is that you can do:
|
||||
*
|
||||
* ```ts
|
||||
* const readonlyPerson: Person = {name: 'Marry'};
|
||||
* readonlyPerson.name = 'John'; // TypeError
|
||||
* (readonlyPerson as WritablePerson).name = 'John'; // OK
|
||||
*
|
||||
* // Error: Correctly detects that `Person` did not have `age` property.
|
||||
* (readonlyPerson as WritablePerson).age = 30;
|
||||
* ```
|
||||
*/
|
||||
type Writable<T> = {
|
||||
-readonly [K in keyof T]: T[K];
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a token that can be used in a DI Provider.
|
||||
*
|
||||
* Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
|
||||
* runtime representation) such as when injecting an interface, callable type, array or
|
||||
* parameterized type.
|
||||
*
|
||||
* `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
|
||||
* the `Injector`. This provides an additional level of type safety.
|
||||
*
|
||||
* <div class="docs-alert docs-alert-helpful">
|
||||
*
|
||||
* **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
|
||||
* provider and the injection call. Creating a new instance of `InjectionToken` in different places,
|
||||
* even with the same description, will be treated as different tokens by Angular's DI system,
|
||||
* leading to a `NullInjectorError`.
|
||||
*
|
||||
* </div>
|
||||
*
|
||||
* {@example injection-token/src/main.ts region='InjectionToken'}
|
||||
*
|
||||
* When creating an `InjectionToken`, you can optionally specify a factory function which returns
|
||||
* (possibly by creating) a default value of the parameterized type `T`. This sets up the
|
||||
* `InjectionToken` using this factory as a provider as if it was defined explicitly in the
|
||||
* application's root injector. If the factory function, which takes zero arguments, needs to inject
|
||||
* dependencies, it can do so using the [`inject`](api/core/inject) function.
|
||||
* As you can see in the Tree-shakable InjectionToken example below.
|
||||
*
|
||||
* Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
|
||||
* overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:
|
||||
* this option is now deprecated). As mentioned above, `'root'` is the default value for
|
||||
* `providedIn`.
|
||||
*
|
||||
* The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
|
||||
*
|
||||
* @usageNotes
|
||||
* ### Basic Examples
|
||||
*
|
||||
* ### Plain InjectionToken
|
||||
*
|
||||
* {@example core/di/ts/injector_spec.ts region='InjectionToken'}
|
||||
*
|
||||
* ### Tree-shakable InjectionToken
|
||||
*
|
||||
* {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
|
||||
*
|
||||
*
|
||||
* @see [What is an InjectionToken?](guide/di/defining-dependency-providers#what-is-an-injectiontoken)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare class InjectionToken<T> {
|
||||
protected _desc: string;
|
||||
readonly ɵprov: unknown;
|
||||
/**
|
||||
* @deprecated The `providedIn: NgModule` or `providedIn:'any'` options are deprecated. Please use the other signature.
|
||||
*/
|
||||
constructor(_desc: string, options: {
|
||||
providedIn: Type<any> | 'any';
|
||||
factory: () => T;
|
||||
});
|
||||
/**
|
||||
* @param _desc Description for the token,
|
||||
* used only for debugging purposes,
|
||||
* it should but does not need to be unique
|
||||
* @param options Options for the token's usage, as described above
|
||||
*/
|
||||
constructor(_desc: string, options?: {
|
||||
providedIn?: Type<any> | 'root' | 'platform' | 'any' | null;
|
||||
factory: () => T;
|
||||
});
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the `Injector` to return a value for a token.
|
||||
* Base for `ValueProvider` decorator.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ValueSansProvider {
|
||||
/**
|
||||
* The value to inject.
|
||||
*/
|
||||
useValue: any;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value for a token.
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* ### Example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ValueProvider'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ValueProvider extends ValueSansProvider {
|
||||
/**
|
||||
* An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`.
|
||||
*/
|
||||
provide: any;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of `useClass` for a token.
|
||||
* Base for `StaticClassProvider` decorator.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface StaticClassSansProvider {
|
||||
/**
|
||||
* An optional class to instantiate for the `token`. By default, the `provide`
|
||||
* class is instantiated.
|
||||
*/
|
||||
useClass: Type<any>;
|
||||
/**
|
||||
* A list of `token`s to be resolved by the injector. The list of values is then
|
||||
* used as arguments to the `useClass` constructor.
|
||||
*/
|
||||
deps: any[];
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of `useClass` for a token.
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='StaticClassProvider'}
|
||||
*
|
||||
* Note that following two providers are not equal:
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='StaticClassProviderDifference'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface StaticClassProvider extends StaticClassSansProvider {
|
||||
/**
|
||||
* An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`.
|
||||
*/
|
||||
provide: any;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of a token.
|
||||
*
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* ```ts
|
||||
* @Injectable(SomeModule, {deps: []})
|
||||
* class MyService {}
|
||||
* ```
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ConstructorSansProvider {
|
||||
/**
|
||||
* A list of `token`s to be resolved by the injector.
|
||||
*/
|
||||
deps?: any[];
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of a token.
|
||||
*
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ConstructorProvider extends ConstructorSansProvider {
|
||||
/**
|
||||
* An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`.
|
||||
*/
|
||||
provide: Type<any>;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value of another `useExisting` token.
|
||||
*
|
||||
* @see {@link ExistingProvider}
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ExistingSansProvider {
|
||||
/**
|
||||
* Existing `token` to return. (Equivalent to `injector.get(useExisting)`)
|
||||
*/
|
||||
useExisting: any;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value of another `useExisting` token.
|
||||
*
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ExistingProvider'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ExistingProvider extends ExistingSansProvider {
|
||||
/**
|
||||
* An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`.
|
||||
*/
|
||||
provide: any;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value by invoking a `useFactory` function.
|
||||
*
|
||||
* @see {@link FactoryProvider}
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface FactorySansProvider {
|
||||
/**
|
||||
* A function to invoke to create a value for this `token`. The function is invoked with
|
||||
* resolved values of `token`s in the `deps` field.
|
||||
*/
|
||||
useFactory: Function;
|
||||
/**
|
||||
* A list of `token`s to be resolved by the injector. The list of values is then
|
||||
* used as arguments to the `useFactory` function.
|
||||
*/
|
||||
deps?: any[];
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value by invoking a `useFactory` function.
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='FactoryProvider'}
|
||||
*
|
||||
* Dependencies can also be marked as optional:
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='FactoryProviderOptionalDeps'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface FactoryProvider extends FactorySansProvider {
|
||||
/**
|
||||
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
|
||||
*/
|
||||
provide: any;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Describes how an `Injector` should be configured as static (that is, without reflection).
|
||||
* A static provider provides tokens to an injector for various types of dependencies.
|
||||
*
|
||||
* @see {@link Injector.create()}
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection-providers).
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
type StaticProvider = ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider | any[];
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of `Type` when `Type' is used as the token.
|
||||
*
|
||||
* Create an instance by invoking the `new` operator and supplying additional arguments.
|
||||
* This form is a short form of `TypeProvider`;
|
||||
*
|
||||
* For more details, see the ["Dependency Injection Guide"](guide/di/dependency-injection.
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='TypeProvider'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface TypeProvider extends Type<any> {
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return a value by invoking a `useClass` function.
|
||||
* Base for `ClassProvider` decorator.
|
||||
*
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ClassSansProvider {
|
||||
/**
|
||||
* Class to instantiate for the `token`.
|
||||
*/
|
||||
useClass: Type<any>;
|
||||
}
|
||||
/**
|
||||
* Configures the `Injector` to return an instance of `useClass` for a token.
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ClassProvider'}
|
||||
*
|
||||
* Note that following two providers are not equal:
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ClassProviderDifference'}
|
||||
*
|
||||
* ### Multi-value example
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ClassProvider extends ClassSansProvider {
|
||||
/**
|
||||
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
|
||||
*/
|
||||
provide: any;
|
||||
/**
|
||||
* When true, injector returns an array of instances. This is useful to allow multiple
|
||||
* providers spread across many files to provide configuration information to a common token.
|
||||
*/
|
||||
multi?: boolean;
|
||||
}
|
||||
/**
|
||||
* Describes how the `Injector` should be configured.
|
||||
* @see [Dependency Injection Guide](guide/di/dependency-injection)
|
||||
*
|
||||
* @see {@link StaticProvider}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
type Provider = TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | any[];
|
||||
/**
|
||||
* Encapsulated `Provider`s that are only accepted during creation of an `EnvironmentInjector` (e.g.
|
||||
* in an `NgModule`).
|
||||
*
|
||||
* Using this wrapper type prevents providers which are only designed to work in
|
||||
* application/environment injectors from being accidentally included in
|
||||
* `@Component.providers` and ending up in a component injector.
|
||||
*
|
||||
* This wrapper type prevents access to the `Provider`s inside.
|
||||
*
|
||||
* @see {@link makeEnvironmentProviders}
|
||||
* @see {@link importProvidersFrom}
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
type EnvironmentProviders = {
|
||||
ɵbrand: 'EnvironmentProviders';
|
||||
};
|
||||
interface InternalEnvironmentProviders extends EnvironmentProviders {
|
||||
ɵproviders: (Provider | EnvironmentProviders)[];
|
||||
/**
|
||||
* If present, indicates that the `EnvironmentProviders` were derived from NgModule providers.
|
||||
*
|
||||
* This is used to produce clearer error messages.
|
||||
*/
|
||||
ɵfromNgModule?: true;
|
||||
}
|
||||
declare function isEnvironmentProviders(value: Provider | EnvironmentProviders | InternalEnvironmentProviders): value is InternalEnvironmentProviders;
|
||||
/**
|
||||
* Describes a function that is used to process provider lists (such as provider
|
||||
* overrides).
|
||||
*/
|
||||
type ProcessProvidersFunction = (providers: Provider[]) => Provider[];
|
||||
/**
|
||||
* A wrapper around an NgModule that associates it with providers
|
||||
* Usage without a generic type is deprecated.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface ModuleWithProviders<T> {
|
||||
ngModule: Type<T>;
|
||||
providers?: Array<Provider | EnvironmentProviders>;
|
||||
}
|
||||
|
||||
/**
|
||||
* This enum is an exact copy of the `InjectFlags` enum above, but the difference is that this is a
|
||||
* const enum, so actual enum values would be inlined in generated code. The `InjectFlags` enum can
|
||||
* be turned into a const enum when ViewEngine is removed (see TODO at the `InjectFlags` enum
|
||||
* above). The benefit of inlining is that we can use these flags at the top level without affecting
|
||||
* tree-shaking (see "no-toplevel-property-access" tslint rule for more info).
|
||||
* Keep this enum in sync with `InjectFlags` enum above.
|
||||
*/
|
||||
declare const enum InternalInjectFlags {
|
||||
/** Check self and check parent injector if needed */
|
||||
Default = 0,
|
||||
/**
|
||||
* Specifies that an injector should retrieve a dependency from any injector until reaching the
|
||||
* host element of the current component. (Only used with Element Injector)
|
||||
*/
|
||||
Host = 1,
|
||||
/** Don't ascend to ancestors of the node requesting injection. */
|
||||
Self = 2,
|
||||
/** Skip the node that is requesting injection. */
|
||||
SkipSelf = 4,
|
||||
/** Inject `defaultValue` instead if token not found. */
|
||||
Optional = 8,
|
||||
/**
|
||||
* This token is being injected into a pipe.
|
||||
*
|
||||
* This flag is intentionally not in the public facing `InjectFlags` because it is only added by
|
||||
* the compiler and is not a developer applicable flag.
|
||||
*/
|
||||
ForPipe = 16
|
||||
}
|
||||
/**
|
||||
* Type of the options argument to [`inject`](api/core/inject).
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface InjectOptions {
|
||||
/**
|
||||
* Use optional injection, and return `null` if the requested token is not found.
|
||||
*/
|
||||
optional?: boolean;
|
||||
/**
|
||||
* Start injection at the parent of the current injector.
|
||||
*/
|
||||
skipSelf?: boolean;
|
||||
/**
|
||||
* Only query the current injector for the token, and don't fall back to the parent injector if
|
||||
* it's not found.
|
||||
*/
|
||||
self?: boolean;
|
||||
/**
|
||||
* Stop injection at the host component's injector. Only relevant when injecting from an element
|
||||
* injector, and a no-op for environment injectors.
|
||||
*/
|
||||
host?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description
|
||||
*
|
||||
* Token that can be used to retrieve an instance from an injector or through a query.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
type ProviderToken<T> = Type<T> | AbstractType<T> | InjectionToken<T>;
|
||||
|
||||
/**
|
||||
* Concrete injectors implement this interface. Injectors are configured
|
||||
* with [providers](guide/di/dependency-injection-providers) that associate
|
||||
* dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).
|
||||
*
|
||||
* @see [DI Providers](guide/di/dependency-injection-providers).
|
||||
* @see {@link StaticProvider}
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* The following example creates a service injector instance.
|
||||
*
|
||||
* {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
|
||||
*
|
||||
* ### Usage example
|
||||
*
|
||||
* {@example core/di/ts/injector_spec.ts region='Injector'}
|
||||
*
|
||||
* `Injector` returns itself when given `Injector` as a token:
|
||||
*
|
||||
* {@example core/di/ts/injector_spec.ts region='injectInjector'}
|
||||
*
|
||||
* @see [Types of injector hierarchies](guide/di/hierarchical-dependency-injection#types-of-injector-hierarchies)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare abstract class Injector {
|
||||
static THROW_IF_NOT_FOUND: {};
|
||||
static NULL: Injector;
|
||||
/**
|
||||
* Retrieves an instance from the injector based on the provided token.
|
||||
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
|
||||
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
|
||||
*/
|
||||
abstract get<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & {
|
||||
optional?: false;
|
||||
}): T;
|
||||
/**
|
||||
* Retrieves an instance from the injector based on the provided token.
|
||||
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
|
||||
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
|
||||
*/
|
||||
abstract get<T>(token: ProviderToken<T>, notFoundValue: null | undefined, options: InjectOptions): T | null;
|
||||
/**
|
||||
* Retrieves an instance from the injector based on the provided token.
|
||||
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
|
||||
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
|
||||
*/
|
||||
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
|
||||
/**
|
||||
* @deprecated from v4.0.0 use ProviderToken<T>
|
||||
* @suppress {duplicate}
|
||||
*/
|
||||
abstract get<T>(token: string | ProviderToken<T>, notFoundValue?: any): any;
|
||||
/**
|
||||
* @deprecated from v5 use the new signature Injector.create(options)
|
||||
*/
|
||||
static create(providers: StaticProvider[], parent?: Injector): Injector;
|
||||
/**
|
||||
* Creates a new injector instance that provides one or more dependencies,
|
||||
* according to a given type or types of `StaticProvider`.
|
||||
*
|
||||
* @param options An object with the following properties:
|
||||
* * `providers`: An array of providers of the [StaticProvider type](api/core/StaticProvider).
|
||||
* * `parent`: (optional) A parent injector.
|
||||
* * `name`: (optional) A developer-defined identifying name for the new injector.
|
||||
*
|
||||
* @returns The new injector instance.
|
||||
*
|
||||
*/
|
||||
static create(options: {
|
||||
providers: Array<Provider | StaticProvider>;
|
||||
parent?: Injector;
|
||||
name?: string;
|
||||
}): DestroyableInjector;
|
||||
/** @nocollapse */
|
||||
static ɵprov: unknown;
|
||||
}
|
||||
/**
|
||||
* An Injector that the owner can destroy and trigger the DestroyRef.destroy hooks.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface DestroyableInjector extends Injector {
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.
|
||||
* The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`
|
||||
* is injected in a component or directive, the callbacks run when that component or
|
||||
* directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
|
||||
*
|
||||
* @see [Lifecycle DestroyRef](guide/components/lifecycle#destroyref)
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare abstract class DestroyRef {
|
||||
/**
|
||||
* Registers a destroy callback in a given lifecycle scope. Returns a cleanup function that can
|
||||
* be invoked to unregister the callback.
|
||||
*
|
||||
* @usageNotes
|
||||
* ### Example
|
||||
* ```ts
|
||||
* const destroyRef = inject(DestroyRef);
|
||||
*
|
||||
* // register a destroy callback
|
||||
* const unregisterFn = destroyRef.onDestroy(() => doSomethingOnDestroy());
|
||||
*
|
||||
* // stop the destroy callback from executing if needed
|
||||
* unregisterFn();
|
||||
* ```
|
||||
*
|
||||
* @see [Lifecycle DestroyRef](guide/components/lifecycle#destroyref)
|
||||
*
|
||||
*/
|
||||
abstract onDestroy(callback: () => void): () => void;
|
||||
/**
|
||||
* Indicates whether the instance has already been destroyed.
|
||||
*
|
||||
* @see [Detecting instance destruction](guide/components/lifecycle#detecting-instance-destruction)
|
||||
*
|
||||
*/
|
||||
abstract get destroyed(): boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
/**
|
||||
* Indicates whether HMR is enabled for the application.
|
||||
*
|
||||
* `ngHmrMode` is a global flag set by Angular's CLI.
|
||||
*
|
||||
* @remarks
|
||||
* - **Internal Angular Flag**: This is an *internal* Angular flag (not a public API), avoid relying on it in application code.
|
||||
* - **Avoid Direct Use**: This variable is intended for runtime configuration; it should not be accessed directly in application code.
|
||||
*/
|
||||
var ngHmrMode: boolean | undefined;
|
||||
}
|
||||
|
||||
declare global {
|
||||
const ngJitMode: boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
/**
|
||||
* Indicates whether the application is operating in server-rendering mode.
|
||||
*
|
||||
* `ngServerMode` is a global flag set by Angular's server-side rendering mechanisms,
|
||||
* typically configured by `provideServerRendering` and `platformServer` during runtime.
|
||||
*
|
||||
* @remarks
|
||||
* - **Internal Angular Flag**: This is an *internal* Angular flag (not a public API), avoid relying on it in application code.
|
||||
* - **Avoid Direct Use**: This variable is intended for runtime configuration; it should not be accessed directly in application code.
|
||||
*/
|
||||
var ngServerMode: boolean | undefined;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Element {
|
||||
__jsaction_fns: Map<string, Function[]> | undefined;
|
||||
}
|
||||
}
|
||||
interface EventContractDetails {
|
||||
instance?: EventContract;
|
||||
}
|
||||
declare const JSACTION_EVENT_CONTRACT: InjectionToken<EventContractDetails>;
|
||||
/** Shorthand for an event listener callback function to reduce duplication. */
|
||||
type EventCallback = (event?: any) => any;
|
||||
|
||||
declare global {
|
||||
const ngI18nClosureMode: boolean;
|
||||
}
|
||||
|
||||
type TimeStampName = string;
|
||||
type DevToolsColor = 'primary' | 'primary-light' | 'primary-dark' | 'secondary' | 'secondary-light' | 'secondary-dark' | 'tertiary' | 'tertiary-light' | 'tertiary-dark' | 'error';
|
||||
declare global {
|
||||
interface Console {
|
||||
timeStamp(label: string, start: TimeStampName, end?: TimeStampName, trackName?: string, trackGroup?: string, color?: DevToolsColor): void;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Start listening to the Angular's internal performance-related events and route those to the Chrome DevTools performance panel.
|
||||
* This enables Angular-specific data visualization when recording a performance profile directly in the Chrome DevTools.
|
||||
*
|
||||
* NOTE: Integration is enabled in the development mode only, this operation is noop in the production mode.
|
||||
*
|
||||
* @publicApi v21.0
|
||||
*
|
||||
* @returns a function that can be invoked to stop sending profiling data.
|
||||
* @see [Profiling with the Chrome DevTools](best-practices/profiling-with-chrome-devtools#recording-a-profile)
|
||||
*/
|
||||
declare function enableProfiling(): () => void;
|
||||
|
||||
export { DestroyRef, InjectionToken, Injector, InternalInjectFlags, JSACTION_EVENT_CONTRACT, Type, enableProfiling, isEnvironmentProviders, isSignal, isWritableSignal, signal, ɵunwrapWritableSignal };
|
||||
export type { AbstractType, ClassProvider, ClassSansProvider, ConstructorProvider, ConstructorSansProvider, CreateSignalOptions, DestroyableInjector, EnvironmentProviders, EventCallback, ExistingProvider, ExistingSansProvider, FactoryProvider, FactorySansProvider, InjectOptions, InternalEnvironmentProviders, ModuleWithProviders, OutputRef, OutputRefSubscription, ProcessProvidersFunction, Provider, ProviderToken, Signal, StaticClassProvider, StaticClassSansProvider, StaticProvider, TypeProvider, ValueEqualityFn, ValueProvider, ValueSansProvider, Writable, WritableSignal };
|
||||
+7559
File diff suppressed because it is too large
Load Diff
+42
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { ReactiveNode, ValueEqualityFn, SIGNAL, ReactiveHookFn } from './_formatter-chunk.js';
|
||||
|
||||
interface SignalNode<T> extends ReactiveNode {
|
||||
value: T;
|
||||
equal: ValueEqualityFn<T>;
|
||||
}
|
||||
type SignalBaseGetter<T> = (() => T) & {
|
||||
readonly [SIGNAL]: unknown;
|
||||
};
|
||||
type SignalSetter<T> = (newValue: T) => void;
|
||||
type SignalUpdater<T> = (updateFn: (value: T) => T) => void;
|
||||
interface SignalGetter<T> extends SignalBaseGetter<T> {
|
||||
readonly [SIGNAL]: SignalNode<T>;
|
||||
}
|
||||
/**
|
||||
* Creates a `Signal` getter, setter, and updater function.
|
||||
*/
|
||||
declare function createSignal<T>(initialValue: T, equal?: ValueEqualityFn<T>): [SignalGetter<T>, SignalSetter<T>, SignalUpdater<T>];
|
||||
declare function setPostSignalSetFn(fn: ReactiveHookFn | null): ReactiveHookFn | null;
|
||||
declare function signalGetFn<T>(node: SignalNode<T>): T;
|
||||
declare function signalSetFn<T>(node: SignalNode<T>, newValue: T): void;
|
||||
declare function signalUpdateFn<T>(node: SignalNode<T>, updater: (value: T) => T): void;
|
||||
declare function runPostSignalSetFn<T>(node: SignalNode<T>): void;
|
||||
declare const SIGNAL_NODE: SignalNode<unknown>;
|
||||
|
||||
interface BaseEffectNode extends ReactiveNode {
|
||||
fn: () => void;
|
||||
destroy(): void;
|
||||
cleanup(): void;
|
||||
run(): void;
|
||||
}
|
||||
declare const BASE_EFFECT_NODE: Omit<BaseEffectNode, 'fn' | 'destroy' | 'cleanup' | 'run'>;
|
||||
declare function runEffect(node: BaseEffectNode): void;
|
||||
|
||||
export { BASE_EFFECT_NODE, SIGNAL_NODE, createSignal, runEffect, runPostSignalSetFn, setPostSignalSetFn, signalGetFn, signalSetFn, signalUpdateFn };
|
||||
export type { BaseEffectNode, SignalGetter, SignalNode };
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
declare global {
|
||||
/**
|
||||
* Values of ngDevMode
|
||||
* Depending on the current state of the application, ngDevMode may have one of several values.
|
||||
*
|
||||
* For convenience, the “truthy” value which enables dev mode is also an object which contains
|
||||
* Angular’s performance counters. This is not necessary, but cuts down on boilerplate for the
|
||||
* perf counters.
|
||||
*
|
||||
* ngDevMode may also be set to false. This can happen in one of a few ways:
|
||||
* - The user explicitly sets `window.ngDevMode = false` somewhere in their app.
|
||||
* - The user calls `enableProdMode()`.
|
||||
* - The URL contains a `ngDevMode=false` text.
|
||||
* Finally, ngDevMode may not have been defined at all.
|
||||
*/
|
||||
const ngDevMode: null | NgDevModePerfCounters;
|
||||
interface NgDevModePerfCounters {
|
||||
hydratedNodes: number;
|
||||
hydratedComponents: number;
|
||||
dehydratedViewsRemoved: number;
|
||||
dehydratedViewsCleanupRuns: number;
|
||||
componentsSkippedHydration: number;
|
||||
deferBlocksWithIncrementalHydration: number;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records information about the action that should handle a given `Event`.
|
||||
*/
|
||||
interface ActionInfo {
|
||||
name: string;
|
||||
element: Element;
|
||||
}
|
||||
type ActionInfoInternal = [name: string, element: Element];
|
||||
/**
|
||||
* Records information for later handling of events. This type is
|
||||
* shared, and instances of it are passed, between the eventcontract
|
||||
* and the dispatcher jsbinary. Therefore, the fields of this type are
|
||||
* referenced by string literals rather than property literals
|
||||
* throughout the code.
|
||||
*
|
||||
* 'targetElement' is the element the action occurred on, 'actionElement'
|
||||
* is the element that has the jsaction handler.
|
||||
*
|
||||
* A null 'actionElement' identifies an EventInfo instance that didn't match a
|
||||
* jsaction attribute. This allows us to execute global event handlers with the
|
||||
* appropriate event type (including a11y clicks and custom events).
|
||||
* The declare portion of this interface creates a set of externs that make sure
|
||||
* renaming doesn't happen for EventInfo. This is important since EventInfo
|
||||
* is shared across multiple binaries.
|
||||
*/
|
||||
declare interface EventInfo {
|
||||
eventType: string;
|
||||
event: Event;
|
||||
targetElement: Element;
|
||||
/** The element that is the container for this Event. */
|
||||
eic: Element;
|
||||
timeStamp: number;
|
||||
/**
|
||||
* The action parsed from the JSAction element.
|
||||
*/
|
||||
eia?: ActionInfoInternal;
|
||||
/**
|
||||
* Whether this `Event` is a replay event, meaning no dispatcher was
|
||||
* installed when this `Event` was originally dispatched.
|
||||
*/
|
||||
eirp?: boolean;
|
||||
/**
|
||||
* Whether this `Event` represents a `keydown` event that should be processed
|
||||
* as a `click`. Only used when a11y click events is on.
|
||||
*/
|
||||
eiack?: boolean;
|
||||
/** Whether action resolution has already run on this `EventInfo`. */
|
||||
eir?: boolean;
|
||||
}
|
||||
/**
|
||||
* Utility class around an `EventInfo`.
|
||||
*
|
||||
* This should be used in compilation units that are less sensitive to code
|
||||
* size.
|
||||
*/
|
||||
declare class EventInfoWrapper {
|
||||
readonly eventInfo: EventInfo;
|
||||
constructor(eventInfo: EventInfo);
|
||||
getEventType(): string;
|
||||
setEventType(eventType: string): void;
|
||||
getEvent(): Event;
|
||||
setEvent(event: Event): void;
|
||||
getTargetElement(): Element;
|
||||
setTargetElement(targetElement: Element): void;
|
||||
getContainer(): Element;
|
||||
setContainer(container: Element): void;
|
||||
getTimestamp(): number;
|
||||
setTimestamp(timestamp: number): void;
|
||||
getAction(): {
|
||||
name: string;
|
||||
element: Element;
|
||||
} | undefined;
|
||||
setAction(action: ActionInfo | undefined): void;
|
||||
getIsReplay(): boolean | undefined;
|
||||
setIsReplay(replay: boolean): void;
|
||||
getResolved(): boolean | undefined;
|
||||
setResolved(resolved: boolean): void;
|
||||
clone(): EventInfoWrapper;
|
||||
}
|
||||
|
||||
declare interface EarlyJsactionDataContainer {
|
||||
_ejsa?: EarlyJsactionData;
|
||||
_ejsas?: {
|
||||
[appId: string]: EarlyJsactionData | undefined;
|
||||
};
|
||||
}
|
||||
declare global {
|
||||
interface Window {
|
||||
_ejsa?: EarlyJsactionData;
|
||||
_ejsas?: {
|
||||
[appId: string]: EarlyJsactionData | undefined;
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Defines the early jsaction data types.
|
||||
*/
|
||||
declare interface EarlyJsactionData {
|
||||
/** List used to keep track of the early JSAction event types. */
|
||||
et: string[];
|
||||
/** List used to keep track of the early JSAction capture event types. */
|
||||
etc: string[];
|
||||
/** Early JSAction handler for all events. */
|
||||
h: (event: Event) => void;
|
||||
/** Dispatcher handler. Initializes to populating `q`. */
|
||||
d: (eventInfo: EventInfo) => void;
|
||||
/** List used to push `EventInfo` objects if the dispatcher is not registered. */
|
||||
q: EventInfo[];
|
||||
/** Container for listening to events. */
|
||||
c: HTMLElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* An `EventContractContainerManager` provides the common interface for managing
|
||||
* containers.
|
||||
*/
|
||||
interface EventContractContainerManager {
|
||||
addEventListener(eventType: string, getHandler: (element: Element) => (event: Event) => void, passive?: boolean): void;
|
||||
cleanUp(): void;
|
||||
}
|
||||
/**
|
||||
* A class representing a container node and all the event handlers
|
||||
* installed on it. Used so that handlers can be cleaned up if the
|
||||
* container is removed from the contract.
|
||||
*/
|
||||
declare class EventContractContainer implements EventContractContainerManager {
|
||||
readonly element: Element;
|
||||
/**
|
||||
* Array of event handlers and their corresponding event types that are
|
||||
* installed on this container.
|
||||
*
|
||||
*/
|
||||
private handlerInfos;
|
||||
/**
|
||||
* @param element The container Element.
|
||||
*/
|
||||
constructor(element: Element);
|
||||
/**
|
||||
* Installs the provided installer on the element owned by this container,
|
||||
* and maintains a reference to resulting handler in order to remove it
|
||||
* later if desired.
|
||||
*/
|
||||
addEventListener(eventType: string, getHandler: (element: Element) => (event: Event) => void, passive?: boolean): void;
|
||||
/**
|
||||
* Removes all the handlers installed on this container.
|
||||
*/
|
||||
cleanUp(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview An enum to control who can call certain jsaction APIs.
|
||||
*/
|
||||
declare enum Restriction {
|
||||
I_AM_THE_JSACTION_FRAMEWORK = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview Implements the local event handling contract. This
|
||||
* allows DOM objects in a container that enters into this contract to
|
||||
* define event handlers which are executed in a local context.
|
||||
*
|
||||
* One EventContract instance can manage the contract for multiple
|
||||
* containers, which are added using the addContainer() method.
|
||||
*
|
||||
* Events can be registered using the addEvent() method.
|
||||
*
|
||||
* A Dispatcher is added using the registerDispatcher() method. Until there is
|
||||
* a dispatcher, events are queued. The idea is that the EventContract
|
||||
* class is inlined in the HTML of the top level page and instantiated
|
||||
* right after the start of <body>. The Dispatcher class is contained
|
||||
* in the external deferred js, and instantiated and registered with
|
||||
* EventContract when the external javascript in the page loads. The
|
||||
* external javascript will also register the jsaction handlers, which
|
||||
* then pick up the queued events at the time of registration.
|
||||
*
|
||||
* Since this class is meant to be inlined in the main page HTML, the
|
||||
* size of the binary compiled from this file MUST be kept as small as
|
||||
* possible and thus its dependencies to a minimum.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The API of an EventContract that is safe to call from any compilation unit.
|
||||
*/
|
||||
declare interface UnrenamedEventContract {
|
||||
ecrd(dispatcher: Dispatcher, restriction: Restriction): void;
|
||||
}
|
||||
/** A function that is called to handle events captured by the EventContract. */
|
||||
type Dispatcher = (eventInfo: EventInfo, globalDispatch?: boolean) => void;
|
||||
/**
|
||||
* A function that handles an event dispatched from the browser.
|
||||
*
|
||||
* eventType: May differ from `event.type` if JSAction uses a
|
||||
* short-hand name or is patching over an non-bubbling event with a bubbling
|
||||
* variant.
|
||||
* event: The native browser event.
|
||||
* container: The container for this dispatch.
|
||||
*/
|
||||
type EventHandler = (eventType: string, event: Event, container: Element) => void;
|
||||
/**
|
||||
* EventContract intercepts events in the bubbling phase at the
|
||||
* boundary of a container element, and maps them to generic actions
|
||||
* which are specified using the custom jsaction attribute in
|
||||
* HTML. Behavior of the application is then specified in terms of
|
||||
* handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.
|
||||
*
|
||||
* This has several benefits: (1) No DOM event handlers need to be
|
||||
* registered on the specific elements in the UI. (2) The set of
|
||||
* events that the application has to handle can be specified in terms
|
||||
* of the semantics of the application, rather than in terms of DOM
|
||||
* events. (3) Invocation of handlers can be delayed and handlers can
|
||||
* be delay loaded in a generic way.
|
||||
*/
|
||||
declare class EventContract implements UnrenamedEventContract {
|
||||
static MOUSE_SPECIAL_SUPPORT: boolean;
|
||||
private containerManager;
|
||||
/**
|
||||
* The DOM events which this contract covers. Used to prevent double
|
||||
* registration of event types. The value of the map is the
|
||||
* internally created DOM event handler function that handles the
|
||||
* DOM events. See addEvent().
|
||||
*
|
||||
*/
|
||||
private eventHandlers;
|
||||
private browserEventTypeToExtraEventTypes;
|
||||
/**
|
||||
* The dispatcher function. Events are passed to this function for
|
||||
* handling once it was set using the registerDispatcher() method. This is
|
||||
* done because the function is passed from another jsbinary, so passing the
|
||||
* instance and invoking the method here would require to leave the method
|
||||
* unobfuscated.
|
||||
*/
|
||||
private dispatcher;
|
||||
/**
|
||||
* The list of suspended `EventInfo` that will be dispatched
|
||||
* as soon as the `Dispatcher` is registered.
|
||||
*/
|
||||
private queuedEventInfos;
|
||||
constructor(containerManager: EventContractContainerManager);
|
||||
private handleEvent;
|
||||
/**
|
||||
* Handle an `EventInfo`.
|
||||
*/
|
||||
private handleEventInfo;
|
||||
/**
|
||||
* Enables jsaction handlers to be called for the event type given by
|
||||
* name.
|
||||
*
|
||||
* If the event is already registered, this does nothing.
|
||||
*
|
||||
* @param prefixedEventType If supplied, this event is used in
|
||||
* the actual browser event registration instead of the name that is
|
||||
* exposed to jsaction. Use this if you e.g. want users to be able
|
||||
* to subscribe to jsaction="transitionEnd:foo" while the underlying
|
||||
* event is webkitTransitionEnd in one browser and mozTransitionEnd
|
||||
* in another.
|
||||
*
|
||||
* @param passive A boolean value that, if `true`, indicates that the event
|
||||
* handler will never call `preventDefault()`.
|
||||
*/
|
||||
addEvent(eventType: string, prefixedEventType?: string, passive?: boolean): void;
|
||||
/**
|
||||
* Gets the queued early events and replay them using the appropriate handler
|
||||
* in the provided event contract. Once all the events are replayed, it cleans
|
||||
* up the early contract.
|
||||
*/
|
||||
replayEarlyEvents(earlyJsactionData?: EarlyJsactionData | undefined): void;
|
||||
/**
|
||||
* Replays all the early `EventInfo` objects, dispatching them through the normal
|
||||
* `EventContract` flow.
|
||||
*/
|
||||
replayEarlyEventInfos(earlyEventInfos: EventInfo[]): void;
|
||||
/**
|
||||
* Returns all JSAction event types that have been registered for a given
|
||||
* browser event type.
|
||||
*/
|
||||
private getEventTypesForBrowserEventType;
|
||||
/**
|
||||
* Returns the event handler function for a given event type.
|
||||
*/
|
||||
handler(eventType: string): EventHandler | undefined;
|
||||
/**
|
||||
* Cleans up the event contract. This resets all of the `EventContract`'s
|
||||
* internal state. Users are responsible for not using this `EventContract`
|
||||
* after it has been cleaned up.
|
||||
*/
|
||||
cleanUp(): void;
|
||||
/**
|
||||
* Register a dispatcher function. Event info of each event mapped to
|
||||
* a jsaction is passed for handling to this callback. The queued
|
||||
* events are passed as well to the dispatcher for later replaying
|
||||
* once the dispatcher is registered. Clears the event queue to null.
|
||||
*
|
||||
* @param dispatcher The dispatcher function.
|
||||
* @param restriction
|
||||
*/
|
||||
registerDispatcher(dispatcher: Dispatcher, restriction: Restriction): void;
|
||||
/**
|
||||
* Unrenamed alias for registerDispatcher. Necessary for any codebases that
|
||||
* split the `EventContract` and `Dispatcher` code into different compilation
|
||||
* units.
|
||||
*/
|
||||
ecrd(dispatcher: Dispatcher, restriction: Restriction): void;
|
||||
}
|
||||
|
||||
/** An internal symbol used to indicate whether propagation should be stopped or not. */
|
||||
declare const PROPAGATION_STOPPED_SYMBOL: unique symbol;
|
||||
/** Extra event phases beyond what the browser provides. */
|
||||
declare const EventPhase: {
|
||||
REPLAY: number;
|
||||
};
|
||||
declare global {
|
||||
interface Event {
|
||||
[PROPAGATION_STOPPED_SYMBOL]?: boolean;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`,
|
||||
* `currentTarget`, etc.
|
||||
*/
|
||||
declare class EventDispatcher {
|
||||
private readonly dispatchDelegate;
|
||||
private readonly clickModSupport;
|
||||
private readonly actionResolver;
|
||||
private readonly dispatcher;
|
||||
constructor(dispatchDelegate: (event: Event, actionName: string) => void, clickModSupport?: boolean);
|
||||
/**
|
||||
* The entrypoint for the `EventContract` dispatch.
|
||||
*/
|
||||
dispatch(eventInfo: EventInfo): void;
|
||||
/** Internal method that does basic disaptching. */
|
||||
private dispatchToDelegate;
|
||||
}
|
||||
/**
|
||||
* Registers deferred functionality for an EventContract and a Jsaction
|
||||
* Dispatcher.
|
||||
*/
|
||||
declare function registerDispatcher(eventContract: UnrenamedEventContract, dispatcher: EventDispatcher): void;
|
||||
|
||||
export { EventContract, EventContractContainer, EventDispatcher, EventInfoWrapper, EventPhase, registerDispatcher };
|
||||
export type { EarlyJsactionDataContainer, EventInfo };
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
/**
|
||||
* A comparison function which can determine if two values are equal.
|
||||
*/
|
||||
type ValueEqualityFn<T> = (a: T, b: T) => boolean;
|
||||
/**
|
||||
* The default equality function used for `signal` and `computed`, which uses referential equality.
|
||||
*/
|
||||
declare function defaultEquals<T>(a: T, b: T): boolean;
|
||||
|
||||
type Version = number & {
|
||||
__brand: 'Version';
|
||||
};
|
||||
type ReactiveHookFn = (node: ReactiveNode) => void;
|
||||
/**
|
||||
* Symbol used to tell `Signal`s apart from other functions.
|
||||
*
|
||||
* This can be used to auto-unwrap signals in various cases, or to auto-wrap non-signal values.
|
||||
*/
|
||||
declare const SIGNAL: unique symbol;
|
||||
declare function setActiveConsumer(consumer: ReactiveNode | null): ReactiveNode | null;
|
||||
declare function getActiveConsumer(): ReactiveNode | null;
|
||||
declare function isInNotificationPhase(): boolean;
|
||||
interface Reactive {
|
||||
[SIGNAL]: ReactiveNode;
|
||||
}
|
||||
declare function isReactive(value: unknown): value is Reactive;
|
||||
declare const REACTIVE_NODE: ReactiveNode;
|
||||
interface ReactiveLink {
|
||||
producer: ReactiveNode;
|
||||
consumer: ReactiveNode;
|
||||
lastReadVersion: number;
|
||||
prevConsumer: ReactiveLink | undefined;
|
||||
nextConsumer: ReactiveLink | undefined;
|
||||
nextProducer: ReactiveLink | undefined;
|
||||
}
|
||||
type ReactiveNodeKind = 'signal' | 'computed' | 'effect' | 'template' | 'linkedSignal' | 'afterRenderEffectPhase' | 'unknown';
|
||||
/**
|
||||
* A producer and/or consumer which participates in the reactive graph.
|
||||
*
|
||||
* Producer `ReactiveNode`s which are accessed when a consumer `ReactiveNode` is the
|
||||
* `activeConsumer` are tracked as dependencies of that consumer.
|
||||
*
|
||||
* Certain consumers are also tracked as "live" consumers and create edges in the other direction,
|
||||
* from producer to consumer. These edges are used to propagate change notifications when a
|
||||
* producer's value is updated.
|
||||
*
|
||||
* A `ReactiveNode` may be both a producer and consumer.
|
||||
*/
|
||||
interface ReactiveNode {
|
||||
/**
|
||||
* Version of the value that this node produces.
|
||||
*
|
||||
* This is incremented whenever a new value is produced by this node which is not equal to the
|
||||
* previous value (by whatever definition of equality is in use).
|
||||
*/
|
||||
version: Version;
|
||||
/**
|
||||
* Epoch at which this node is verified to be clean.
|
||||
*
|
||||
* This allows skipping of some polling operations in the case where no signals have been set
|
||||
* since this node was last read.
|
||||
*/
|
||||
lastCleanEpoch: Version;
|
||||
/**
|
||||
* Whether this node (in its consumer capacity) is dirty.
|
||||
*
|
||||
* Only live consumers become dirty, when receiving a change notification from a dependency
|
||||
* producer.
|
||||
*/
|
||||
dirty: boolean;
|
||||
/**
|
||||
* Whether this node is currently rebuilding its producer list.
|
||||
*/
|
||||
recomputing: boolean;
|
||||
/**
|
||||
* Producers which are dependencies of this consumer.
|
||||
*/
|
||||
producers: ReactiveLink | undefined;
|
||||
/**
|
||||
* Points to the last linked list node in the `producers` linked list.
|
||||
*
|
||||
* When this node is recomputing, this is used to track the producers that we have accessed so far.
|
||||
*/
|
||||
producersTail: ReactiveLink | undefined;
|
||||
/**
|
||||
* Linked list of consumers of this producer that are "live" (they require push notifications).
|
||||
*
|
||||
* The length of this list is effectively our reference count for this node.
|
||||
*/
|
||||
consumers: ReactiveLink | undefined;
|
||||
consumersTail: ReactiveLink | undefined;
|
||||
/**
|
||||
* Whether writes to signals are allowed when this consumer is the `activeConsumer`.
|
||||
*
|
||||
* This is used to enforce guardrails such as preventing writes to writable signals in the
|
||||
* computation function of computed signals, which is supposed to be pure.
|
||||
*/
|
||||
consumerAllowSignalWrites: boolean;
|
||||
readonly consumerIsAlwaysLive: boolean;
|
||||
/**
|
||||
* Tracks whether producers need to recompute their value independently of the reactive graph (for
|
||||
* example, if no initial value has been computed).
|
||||
*/
|
||||
producerMustRecompute(node: unknown): boolean;
|
||||
producerRecomputeValue(node: unknown): void;
|
||||
consumerMarkedDirty(node: unknown): void;
|
||||
/**
|
||||
* Called when a signal is read within this consumer.
|
||||
*/
|
||||
consumerOnSignalRead(node: unknown): void;
|
||||
/**
|
||||
* A debug name for the reactive node. Used in Angular DevTools to identify the node.
|
||||
*/
|
||||
debugName?: string;
|
||||
/**
|
||||
* Kind of node. Example: 'signal', 'computed', 'input', 'effect'.
|
||||
*
|
||||
* ReactiveNode has this as 'unknown' by default, but derived node types should override this to
|
||||
* make available the kind of signal that particular instance of a ReactiveNode represents.
|
||||
*
|
||||
* Used in Angular DevTools to identify the kind of signal.
|
||||
*/
|
||||
kind: ReactiveNodeKind;
|
||||
}
|
||||
/**
|
||||
* Called by implementations when a producer's signal is read.
|
||||
*/
|
||||
declare function producerAccessed(node: ReactiveNode): void;
|
||||
/**
|
||||
* Increment the global epoch counter.
|
||||
*
|
||||
* Called by source producers (that is, not computeds) whenever their values change.
|
||||
*/
|
||||
declare function producerIncrementEpoch(): void;
|
||||
/**
|
||||
* Ensure this producer's `version` is up-to-date.
|
||||
*/
|
||||
declare function producerUpdateValueVersion(node: ReactiveNode): void;
|
||||
/**
|
||||
* Propagate a dirty notification to live consumers of this producer.
|
||||
*/
|
||||
declare function producerNotifyConsumers(node: ReactiveNode): void;
|
||||
/**
|
||||
* Whether this `ReactiveNode` in its producer capacity is currently allowed to initiate updates,
|
||||
* based on the current consumer context.
|
||||
*/
|
||||
declare function producerUpdatesAllowed(): boolean;
|
||||
declare function consumerMarkDirty(node: ReactiveNode): void;
|
||||
declare function producerMarkClean(node: ReactiveNode): void;
|
||||
/**
|
||||
* Prepare this consumer to run a computation in its reactive context and set
|
||||
* it as the active consumer.
|
||||
*
|
||||
* Must be called by subclasses which represent reactive computations, before those computations
|
||||
* begin.
|
||||
*/
|
||||
declare function consumerBeforeComputation(node: ReactiveNode | null): ReactiveNode | null;
|
||||
/**
|
||||
* Prepare this consumer to run a computation in its reactive context.
|
||||
*
|
||||
* We expose this mainly for code where we manually batch effects into a single
|
||||
* consumer. In those cases we may wish to "reopen" a consumer multiple times
|
||||
* in initial render before finalizing it. Most code should just call
|
||||
* `consumerBeforeComputation` instead of calling this directly.
|
||||
*/
|
||||
declare function resetConsumerBeforeComputation(node: ReactiveNode): void;
|
||||
/**
|
||||
* Finalize this consumer's state and set previous consumer as the active consumer after a
|
||||
* reactive computation has run.
|
||||
*
|
||||
* Must be called by subclasses which represent reactive computations, after those computations
|
||||
* have finished.
|
||||
*/
|
||||
declare function consumerAfterComputation(node: ReactiveNode | null, prevConsumer: ReactiveNode | null): void;
|
||||
/**
|
||||
* Finalize this consumer's state after a reactive computation has run.
|
||||
*
|
||||
* We expose this mainly for code where we manually batch effects into a single
|
||||
* consumer. In those cases we may wish to "reopen" a consumer multiple times
|
||||
* in initial render before finalizing it. Most code should just call
|
||||
* `consumerAfterComputation` instead of calling this directly.
|
||||
*/
|
||||
declare function finalizeConsumerAfterComputation(node: ReactiveNode): void;
|
||||
/**
|
||||
* Determine whether this consumer has any dependencies which have changed since the last time
|
||||
* they were read.
|
||||
*/
|
||||
declare function consumerPollProducersForChange(node: ReactiveNode): boolean;
|
||||
/**
|
||||
* Disconnect this consumer from the graph.
|
||||
*/
|
||||
declare function consumerDestroy(node: ReactiveNode): void;
|
||||
declare function runPostProducerCreatedFn(node: ReactiveNode): void;
|
||||
declare function setPostProducerCreatedFn(fn: ReactiveHookFn | null): ReactiveHookFn | null;
|
||||
|
||||
declare global {
|
||||
var devtoolsFormatters: any[];
|
||||
}
|
||||
/**
|
||||
* Installs the custom formatter into custom formatting on Signals in the devtools.
|
||||
*
|
||||
* Supported by both Chrome and Firefox.
|
||||
*
|
||||
* @see https://firefox-source-docs.mozilla.org/devtools-user/custom_formatters/index.html
|
||||
*/
|
||||
declare function installDevToolsSignalFormatter(): void;
|
||||
|
||||
export { REACTIVE_NODE, SIGNAL, consumerAfterComputation, consumerBeforeComputation, consumerDestroy, consumerMarkDirty, consumerPollProducersForChange, defaultEquals, finalizeConsumerAfterComputation, getActiveConsumer, installDevToolsSignalFormatter, isInNotificationPhase, isReactive, producerAccessed, producerIncrementEpoch, producerMarkClean, producerNotifyConsumers, producerUpdateValueVersion, producerUpdatesAllowed, resetConsumerBeforeComputation, runPostProducerCreatedFn, setActiveConsumer, setPostProducerCreatedFn };
|
||||
export type { Reactive, ReactiveHookFn, ReactiveNode, ReactiveNodeKind, ValueEqualityFn, Version };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
declare function setAlternateWeakRefImpl(impl: unknown): void;
|
||||
|
||||
export { setAlternateWeakRefImpl };
|
||||
+9434
File diff suppressed because one or more lines are too long
+117
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
/**
|
||||
* @description
|
||||
*
|
||||
* Represents a type that a Component or other object is instances of.
|
||||
*
|
||||
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
|
||||
* the `MyCustomComponent` constructor function.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare const Type: FunctionConstructor;
|
||||
interface Type<T> extends Function {
|
||||
new (...args: any[]): T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Information about how a type or `InjectionToken` interfaces with the DI
|
||||
* system. This describes:
|
||||
*
|
||||
* 1. *How* the type is provided
|
||||
* The declaration must specify only one of the following:
|
||||
* - A `value` which is a predefined instance of the type.
|
||||
* - A `factory` which defines how to create the given type `T`, possibly
|
||||
* requesting injection of other types if necessary.
|
||||
* - Neither, in which case the type is expected to already be present in the
|
||||
* injector hierarchy. This is used for internal use cases.
|
||||
*
|
||||
* 2. *Where* the type is stored (if it is stored)
|
||||
* - The `providedIn` parameter specifies which injector the type belongs to.
|
||||
* - The `token` is used as the key to store the type in the injector.
|
||||
*/
|
||||
interface ɵɵInjectableDeclaration<T> {
|
||||
/**
|
||||
* Specifies that the given type belongs to a particular `Injector`,
|
||||
* `NgModule`, or a special scope (e.g. `'root'`).
|
||||
*
|
||||
* `any` is deprecated and will be removed soon.
|
||||
*
|
||||
* A value of `null` indicates that the injectable does not belong to any
|
||||
* scope, and won't be stored in any injector. For declarations with a
|
||||
* factory, this will create a new instance of the type each time it is
|
||||
* requested.
|
||||
*/
|
||||
providedIn: Type<any> | 'root' | 'platform' | 'any' | null;
|
||||
/**
|
||||
* The token to which this definition belongs.
|
||||
*
|
||||
* Note that this may not be the same as the type that the `factory` will create.
|
||||
*/
|
||||
token: unknown;
|
||||
/**
|
||||
* Factory method to execute to create an instance of the injectable.
|
||||
*/
|
||||
factory?: (t?: Type<any>) => T;
|
||||
/**
|
||||
* In a case of no explicit injector, a location where the instance of the injectable is stored.
|
||||
*/
|
||||
value?: T;
|
||||
}
|
||||
/**
|
||||
* A `Type` which has a `ɵprov: ɵɵInjectableDeclaration` static field.
|
||||
*
|
||||
* `InjectableType`s contain their own Dependency Injection metadata and are usable in an
|
||||
* `InjectorDef`-based `StaticInjector`.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface InjectionToken<T> {
|
||||
ɵprov: ɵɵInjectableDeclaration<T>;
|
||||
}
|
||||
declare function defineInjectable<T>(opts: {
|
||||
token: unknown;
|
||||
providedIn?: Type<any> | 'root' | 'platform' | 'any' | 'environment' | null;
|
||||
factory: () => T;
|
||||
}): ɵɵInjectableDeclaration<T>;
|
||||
type Constructor<T> = Function & {
|
||||
prototype: T;
|
||||
};
|
||||
declare function registerInjectable<T>(ctor: unknown, declaration: ɵɵInjectableDeclaration<T>): InjectionToken<T>;
|
||||
|
||||
/**
|
||||
* Value returned if the key-value pair couldn't be found in the context
|
||||
* hierarchy.
|
||||
*/
|
||||
declare const NOT_FOUND: unique symbol;
|
||||
/**
|
||||
* Error thrown when the key-value pair couldn't be found in the context
|
||||
* hierarchy. Context can be attached below.
|
||||
*/
|
||||
declare class NotFoundError extends Error {
|
||||
readonly name: string;
|
||||
constructor(message: string);
|
||||
}
|
||||
/**
|
||||
* Type guard for checking if an unknown value is a NotFound.
|
||||
*/
|
||||
declare function isNotFound(e: unknown): e is NotFound;
|
||||
/**
|
||||
* Type union of NotFound and NotFoundError.
|
||||
*/
|
||||
type NotFound = typeof NOT_FOUND | NotFoundError;
|
||||
|
||||
interface Injector {
|
||||
retrieve<T>(token: InjectionToken<T>, options?: unknown): T | NotFound;
|
||||
}
|
||||
declare function getCurrentInjector(): Injector | undefined | null;
|
||||
declare function setCurrentInjector(injector: Injector | null | undefined): Injector | undefined | null;
|
||||
declare function inject<T>(token: InjectionToken<T> | Constructor<T>): T;
|
||||
|
||||
export { NOT_FOUND, NotFoundError, defineInjectable, getCurrentInjector, inject, isNotFound, registerInjectable, setCurrentInjector };
|
||||
export type { InjectionToken, Injector, NotFound, ɵɵInjectableDeclaration };
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { EarlyJsactionDataContainer, EventInfo } from './_event_dispatcher-chunk.js';
|
||||
export { EventContract, EventContractContainer, EventDispatcher, EventInfoWrapper, EventPhase, registerDispatcher } from './_event_dispatcher-chunk.js';
|
||||
|
||||
declare const Attribute: {
|
||||
/**
|
||||
* The jsaction attribute defines a mapping of a DOM event to a
|
||||
* generic event (aka jsaction), to which the actual event handlers
|
||||
* that implement the behavior of the application are bound. The
|
||||
* value is a semicolon separated list of colon separated pairs of
|
||||
* an optional DOM event name and a jsaction name. If the optional
|
||||
* DOM event name is omitted, 'click' is assumed. The jsaction names
|
||||
* are dot separated pairs of a namespace and a simple jsaction
|
||||
* name.
|
||||
*
|
||||
* See grammar in README.md for expected syntax in the attribute value.
|
||||
*/
|
||||
JSACTION: "jsaction";
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads the jsaction parser cache for the given DOM element. If no cache is yet present,
|
||||
* creates an empty one.
|
||||
*/
|
||||
declare function getDefaulted(element: Element): {
|
||||
[key: string]: string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether or not an event type should be registered in the capture phase.
|
||||
* @param eventType
|
||||
* @returns bool
|
||||
*/
|
||||
declare const isCaptureEventType: (eventType: string) => boolean;
|
||||
/**
|
||||
* Whether or not an event type is registered in the early contract.
|
||||
*/
|
||||
declare const isEarlyEventType: (eventType: string) => boolean;
|
||||
|
||||
/**
|
||||
* Creates an `EarlyJsactionData`, adds events to it, and populates it on a nested object on
|
||||
* the window.
|
||||
*/
|
||||
declare function bootstrapAppScopedEarlyEventContract(container: HTMLElement, appId: string, bubbleEventTypes: string[], captureEventTypes: string[], dataContainer?: EarlyJsactionDataContainer): void;
|
||||
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
|
||||
declare function getAppScopedQueuedEventInfos(appId: string, dataContainer?: EarlyJsactionDataContainer): EventInfo[];
|
||||
/**
|
||||
* Registers a dispatcher function on the `EarlyJsactionData` present on the nested object on the
|
||||
* window.
|
||||
*/
|
||||
declare function registerAppScopedDispatcher(appId: string, dispatcher: (eventInfo: EventInfo) => void, dataContainer?: EarlyJsactionDataContainer): void;
|
||||
/** Removes all event listener handlers. */
|
||||
declare function removeAllAppScopedEventListeners(appId: string, dataContainer?: EarlyJsactionDataContainer): void;
|
||||
/** Clear the early event contract. */
|
||||
declare function clearAppScopedEarlyEventContract(appId: string, dataContainer?: EarlyJsactionDataContainer): void;
|
||||
|
||||
export { Attribute, EarlyJsactionDataContainer, bootstrapAppScopedEarlyEventContract, clearAppScopedEarlyEventContract, getDefaulted as getActionCache, getAppScopedQueuedEventInfos, isCaptureEventType, isEarlyEventType, registerAppScopedDispatcher, removeAllAppScopedEventListeners };
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { ReactiveNode, ValueEqualityFn, SIGNAL } from './_formatter-chunk.js';
|
||||
export { REACTIVE_NODE, Reactive, ReactiveHookFn, ReactiveNodeKind, Version, consumerAfterComputation, consumerBeforeComputation, consumerDestroy, consumerMarkDirty, consumerPollProducersForChange, defaultEquals, finalizeConsumerAfterComputation, getActiveConsumer, installDevToolsSignalFormatter, isInNotificationPhase, isReactive, producerAccessed, producerIncrementEpoch, producerMarkClean, producerNotifyConsumers, producerUpdateValueVersion, producerUpdatesAllowed, resetConsumerBeforeComputation, runPostProducerCreatedFn, setActiveConsumer, setPostProducerCreatedFn } from './_formatter-chunk.js';
|
||||
import { SignalNode } from './_effect-chunk.js';
|
||||
export { BASE_EFFECT_NODE, BaseEffectNode, SIGNAL_NODE, SignalGetter, createSignal, runEffect, runPostSignalSetFn, setPostSignalSetFn, signalGetFn, signalSetFn, signalUpdateFn } from './_effect-chunk.js';
|
||||
export { setAlternateWeakRefImpl } from './_weak_ref-chunk.js';
|
||||
|
||||
/**
|
||||
* A computation, which derives a value from a declarative reactive expression.
|
||||
*
|
||||
* `Computed`s are both producers and consumers of reactivity.
|
||||
*/
|
||||
interface ComputedNode<T> extends ReactiveNode {
|
||||
/**
|
||||
* Current value of the computation, or one of the sentinel values above (`UNSET`, `COMPUTING`,
|
||||
* `ERROR`).
|
||||
*/
|
||||
value: T;
|
||||
/**
|
||||
* If `value` is `ERRORED`, the error caught from the last computation attempt which will
|
||||
* be re-thrown.
|
||||
*/
|
||||
error: unknown;
|
||||
/**
|
||||
* The computation function which will produce a new value.
|
||||
*/
|
||||
computation: () => T;
|
||||
equal: ValueEqualityFn<T>;
|
||||
}
|
||||
type ComputedGetter<T> = (() => T) & {
|
||||
[SIGNAL]: ComputedNode<T>;
|
||||
};
|
||||
/**
|
||||
* Create a computed signal which derives a reactive value from an expression.
|
||||
*/
|
||||
declare function createComputed<T>(computation: () => T, equal?: ValueEqualityFn<T>): ComputedGetter<T>;
|
||||
|
||||
type ComputationFn<S, D> = (source: S, previous?: PreviousValue<S, D>) => D;
|
||||
type PreviousValue<S, D> = {
|
||||
source: S;
|
||||
value: D;
|
||||
};
|
||||
interface LinkedSignalNode<S, D> extends ReactiveNode {
|
||||
/**
|
||||
* Value of the source signal that was used to derive the computed value.
|
||||
*/
|
||||
sourceValue: S;
|
||||
/**
|
||||
* Current state value, or one of the sentinel values (`UNSET`, `COMPUTING`,
|
||||
* `ERROR`).
|
||||
*/
|
||||
value: D;
|
||||
/**
|
||||
* If `value` is `ERRORED`, the error caught from the last computation attempt which will
|
||||
* be re-thrown.
|
||||
*/
|
||||
error: unknown;
|
||||
/**
|
||||
* The source function represents reactive dependency based on which the linked state is reset.
|
||||
*/
|
||||
source: () => S;
|
||||
/**
|
||||
* The computation function which will produce a new value based on the source and, optionally - previous values.
|
||||
*/
|
||||
computation: ComputationFn<S, D>;
|
||||
equal: ValueEqualityFn<D>;
|
||||
}
|
||||
type LinkedSignalGetter<S, D> = (() => D) & {
|
||||
[SIGNAL]: LinkedSignalNode<S, D>;
|
||||
};
|
||||
declare function createLinkedSignal<S, D>(sourceFn: () => S, computationFn: ComputationFn<S, D>, equalityFn?: ValueEqualityFn<D>): LinkedSignalGetter<S, D>;
|
||||
declare function linkedSignalSetFn<S, D>(node: LinkedSignalNode<S, D>, newValue: D): void;
|
||||
declare function linkedSignalUpdateFn<S, D>(node: LinkedSignalNode<S, D>, updater: (value: D) => D): void;
|
||||
|
||||
declare function setThrowInvalidWriteToSignalError(fn: <T>(node: SignalNode<T>) => never): void;
|
||||
|
||||
/**
|
||||
* A cleanup function that can be optionally registered from the watch logic. If registered, the
|
||||
* cleanup logic runs before the next watch execution.
|
||||
*/
|
||||
type WatchCleanupFn = () => void;
|
||||
/**
|
||||
* A callback passed to the watch function that makes it possible to register cleanup logic.
|
||||
*/
|
||||
type WatchCleanupRegisterFn = (cleanupFn: WatchCleanupFn) => void;
|
||||
interface Watch {
|
||||
notify(): void;
|
||||
/**
|
||||
* Execute the reactive expression in the context of this `Watch` consumer.
|
||||
*
|
||||
* Should be called by the user scheduling algorithm when the provided
|
||||
* `schedule` hook is called by `Watch`.
|
||||
*/
|
||||
run(): void;
|
||||
cleanup(): void;
|
||||
/**
|
||||
* Destroy the watcher:
|
||||
* - disconnect it from the reactive graph;
|
||||
* - mark it as destroyed so subsequent run and notify operations are noop.
|
||||
*/
|
||||
destroy(): void;
|
||||
[SIGNAL]: WatchNode;
|
||||
}
|
||||
interface WatchNode extends ReactiveNode {
|
||||
fn: ((onCleanup: WatchCleanupRegisterFn) => void) | null;
|
||||
schedule: ((watch: Watch) => void) | null;
|
||||
cleanupFn: WatchCleanupFn;
|
||||
ref: Watch;
|
||||
}
|
||||
declare function createWatch(fn: (onCleanup: WatchCleanupRegisterFn) => void, schedule: (watch: Watch) => void, allowSignalWrites: boolean): Watch;
|
||||
|
||||
/**
|
||||
* Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function
|
||||
* can, optionally, return a value.
|
||||
*/
|
||||
declare function untracked<T>(nonReactiveReadsFn: () => T): T;
|
||||
|
||||
export { ReactiveNode, SIGNAL, SignalNode, ValueEqualityFn, createComputed, createLinkedSignal, createWatch, linkedSignalSetFn, linkedSignalUpdateFn, setThrowInvalidWriteToSignalError, untracked };
|
||||
export type { ComputationFn, ComputedNode, LinkedSignalGetter, LinkedSignalNode, PreviousValue, Watch, WatchCleanupFn, WatchCleanupRegisterFn };
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { ValueEqualityFn } from './_formatter-chunk.js';
|
||||
import { OutputRef, DestroyRef, Injector, Signal } from './_chrome_dev_tools_performance-chunk.js';
|
||||
import { OutputOptions, BaseResourceOptions, ResourceLoaderParams, ResourceRef } from './_api-chunk.js';
|
||||
import './_event_dispatcher-chunk.js';
|
||||
import { Observable, MonoTypeOperatorFunction, Subscribable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Declares an Angular output that is using an RxJS observable as a source
|
||||
* for events dispatched to parent subscribers.
|
||||
*
|
||||
* The behavior for an observable as source is defined as followed:
|
||||
* 1. New values are forwarded to the Angular output (next notifications).
|
||||
* 2. Errors notifications are not handled by Angular. You need to handle these manually.
|
||||
* For example by using `catchError`.
|
||||
* 3. Completion notifications stop the output from emitting new values.
|
||||
*
|
||||
* @usageNotes
|
||||
* Initialize an output in your directive by declaring a
|
||||
* class field and initializing it with the `outputFromObservable()` function.
|
||||
*
|
||||
* ```ts
|
||||
* @Directive({..})
|
||||
* export class MyDir {
|
||||
* nameChange$ = <some-observable>;
|
||||
* nameChange = outputFromObservable(this.nameChange$);
|
||||
* }
|
||||
* ```
|
||||
* @see [RxJS interop with component and directive outputs](ecosystem/rxjs-interop/output-interop)
|
||||
*
|
||||
* @publicApi 19.0
|
||||
*/
|
||||
declare function outputFromObservable<T>(observable: Observable<T>, opts?: OutputOptions): OutputRef<T>;
|
||||
|
||||
/**
|
||||
* Converts an Angular output declared via `output()` or `outputFromObservable()`
|
||||
* to an observable.
|
||||
* It creates an observable that represents the stream of "events firing" in an output.
|
||||
*
|
||||
* You can subscribe to the output via `Observable.subscribe` then.
|
||||
*
|
||||
* @see [RxJS interop with component and directive outputs](ecosystem/rxjs-interop/output-interop)
|
||||
*
|
||||
* @publicApi 19.0
|
||||
*/
|
||||
declare function outputToObservable<T>(ref: OutputRef<T>): Observable<T>;
|
||||
|
||||
/**
|
||||
* Operator which completes the Observable when the calling context (component, directive, service,
|
||||
* etc) is destroyed.
|
||||
*
|
||||
* @param destroyRef optionally, the `DestroyRef` representing the current context. This can be
|
||||
* passed explicitly to use `takeUntilDestroyed` outside of an [injection
|
||||
* context](guide/di/dependency-injection-context). Otherwise, the current `DestroyRef` is injected.
|
||||
*
|
||||
* @see [Unsubscribing with takeUntilDestroyed](ecosystem/rxjs-interop/take-until-destroyed)
|
||||
*
|
||||
* @publicApi 19.0
|
||||
*/
|
||||
declare function takeUntilDestroyed<T>(destroyRef?: DestroyRef): MonoTypeOperatorFunction<T>;
|
||||
|
||||
/**
|
||||
* Options for `toObservable`.
|
||||
*
|
||||
* @publicApi 20.0
|
||||
*/
|
||||
interface ToObservableOptions {
|
||||
/**
|
||||
* The `Injector` to use when creating the underlying `effect` which watches the signal.
|
||||
*
|
||||
* If this isn't specified, the current [injection context](guide/di/dependency-injection-context)
|
||||
* will be used.
|
||||
*/
|
||||
injector?: Injector;
|
||||
}
|
||||
/**
|
||||
* Exposes the value of an Angular `Signal` as an RxJS `Observable`.
|
||||
* As it reflects a state, the observable will always emit the latest value upon subscription.
|
||||
*
|
||||
* The signal's value will be propagated into the `Observable`'s subscribers using an `effect`.
|
||||
*
|
||||
* `toObservable` must be called in an injection context unless an injector is provided via options.
|
||||
*
|
||||
* @see [RxJS interop with Angular signals](ecosystem/rxjs-interop)
|
||||
* @see [Create an RxJS Observable from a signal with toObservable](ecosystem/rxjs-interop#create-an-rxjs-observable-from-a-signal-with-toobservable)
|
||||
*
|
||||
* @publicApi 20.0
|
||||
*/
|
||||
declare function toObservable<T>(source: Signal<T>, options?: ToObservableOptions): Observable<T>;
|
||||
|
||||
/**
|
||||
* Options for `toSignal`.
|
||||
*
|
||||
* @publicApi 20.0
|
||||
*/
|
||||
interface ToSignalOptions<T> {
|
||||
/**
|
||||
* Initial value for the signal produced by `toSignal`.
|
||||
*
|
||||
* This will be the value of the signal until the observable emits its first value.
|
||||
*/
|
||||
initialValue?: unknown;
|
||||
/**
|
||||
* Whether to require that the observable emits synchronously when `toSignal` subscribes.
|
||||
*
|
||||
* If this is `true`, `toSignal` will assert that the observable produces a value immediately upon
|
||||
* subscription. Setting this option removes the need to either deal with `undefined` in the
|
||||
* signal type or provide an `initialValue`, at the cost of a runtime error if this requirement is
|
||||
* not met.
|
||||
*/
|
||||
requireSync?: boolean;
|
||||
/**
|
||||
* `Injector` which will provide the `DestroyRef` used to clean up the Observable subscription.
|
||||
*
|
||||
* If this is not provided, a `DestroyRef` will be retrieved from the current [injection
|
||||
* context](guide/di/dependency-injection-context), unless manual cleanup is requested.
|
||||
*/
|
||||
injector?: Injector;
|
||||
/**
|
||||
* Whether the subscription should be automatically cleaned up (via `DestroyRef`) when
|
||||
* `toSignal`'s creation context is destroyed.
|
||||
*
|
||||
* If manual cleanup is enabled, then `DestroyRef` is not used, and the subscription will persist
|
||||
* until the `Observable` itself completes.
|
||||
*/
|
||||
manualCleanup?: boolean;
|
||||
/**
|
||||
* A comparison function which defines equality for values emitted by the observable.
|
||||
*
|
||||
* Equality comparisons are executed against the initial value if one is provided.
|
||||
*/
|
||||
equal?: ValueEqualityFn<T>;
|
||||
/**
|
||||
* A debug name for the signal. Used in Angular DevTools to identify the signal.
|
||||
*/
|
||||
debugName?: string;
|
||||
}
|
||||
declare function toSignal<T>(source: Observable<T> | Subscribable<T>): Signal<T | undefined>;
|
||||
declare function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | undefined>> & {
|
||||
initialValue?: undefined;
|
||||
requireSync?: false;
|
||||
}): Signal<T | undefined>;
|
||||
declare function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | null>> & {
|
||||
initialValue?: null;
|
||||
requireSync?: false;
|
||||
}): Signal<T | null>;
|
||||
declare function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T>> & {
|
||||
initialValue?: undefined;
|
||||
requireSync: true;
|
||||
}): Signal<T>;
|
||||
declare function toSignal<T, const U extends T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | U>> & {
|
||||
initialValue: U;
|
||||
requireSync?: false;
|
||||
}): Signal<T | U>;
|
||||
|
||||
/**
|
||||
* Operator which makes the application unstable until the observable emits, completes, errors, or is unsubscribed.
|
||||
*
|
||||
* Use this operator in observables whose subscriptions are important for rendering and should be included in SSR serialization.
|
||||
*
|
||||
* @param injector The `Injector` to use during creation. If this is not provided, the current injection context will be used instead (via `inject`).
|
||||
*
|
||||
* @developerPreview 20.0
|
||||
*/
|
||||
declare function pendingUntilEvent<T>(injector?: Injector): MonoTypeOperatorFunction<T>;
|
||||
|
||||
/**
|
||||
* Like `ResourceOptions` but uses an RxJS-based `loader`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
interface RxResourceOptions<T, R> extends BaseResourceOptions<T, R> {
|
||||
stream: (params: ResourceLoaderParams<R>) => Observable<T>;
|
||||
}
|
||||
/**
|
||||
* Like `resource` but uses an RxJS based `loader` which maps the request to an `Observable` of the
|
||||
* resource's value.
|
||||
*
|
||||
* @see [Using rxResource for async data](ecosystem/rxjs-interop#using-rxresource-for-async-data)
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function rxResource<T, R>(opts: RxResourceOptions<T, R> & {
|
||||
defaultValue: NoInfer<T>;
|
||||
}): ResourceRef<T>;
|
||||
/**
|
||||
* Like `resource` but uses an RxJS based `loader` which maps the request to an `Observable` of the
|
||||
* resource's value.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function rxResource<T, R>(opts: RxResourceOptions<T, R>): ResourceRef<T | undefined>;
|
||||
|
||||
export { outputFromObservable, outputToObservable, pendingUntilEvent, rxResource, takeUntilDestroyed, toObservable, toSignal };
|
||||
export type { RxResourceOptions, ToObservableOptions, ToSignalOptions };
|
||||
+808
@@ -0,0 +1,808 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import './_formatter-chunk.js';
|
||||
import './_event_dispatcher-chunk.js';
|
||||
import { InjectionToken, Type, ProviderToken, InjectOptions } from './_chrome_dev_tools_performance-chunk.js';
|
||||
import { DeferBlockDetails, DeferBlockState, ComponentRef, DebugElement, ElementRef, ChangeDetectorRef, NgZone, SchemaMetadata, DeferBlockBehavior, Binding, PlatformRef, NgModule, Component, Directive, Pipe, Navigation, NavigationNavigateOptions, NavigationOptions, NavigateEvent, NavigationCurrentEntryChangeEvent, NavigationTransition, NavigationUpdateCurrentEntryOptions, NavigationReloadOptions, NavigationResult, NavigationHistoryEntry, NavigationDestination, NavigationInterceptOptions } from './_discovery-chunk.js';
|
||||
import * as i0 from '@angular/core';
|
||||
import 'rxjs';
|
||||
import './_effect-chunk.js';
|
||||
import '@angular/core/primitives/di';
|
||||
|
||||
/**
|
||||
* Wraps a test function in an asynchronous test zone. The test will automatically
|
||||
* complete when all asynchronous calls within this zone are done. Can be used
|
||||
* to wrap an {@link inject} call.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```ts
|
||||
* it('...', waitForAsync(inject([AClass], (object) => {
|
||||
* object.doSomething.then(() => {
|
||||
* expect(...);
|
||||
* })
|
||||
* })));
|
||||
* ```
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function waitForAsync(fn: Function): (done: any) => any;
|
||||
|
||||
/**
|
||||
* Represents an individual defer block for testing purposes.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare class DeferBlockFixture {
|
||||
private block;
|
||||
private componentFixture;
|
||||
/** @docs-private */
|
||||
constructor(block: DeferBlockDetails, componentFixture: ComponentFixture<unknown>);
|
||||
/**
|
||||
* Renders the specified state of the defer fixture.
|
||||
* @param state the defer state to render
|
||||
*/
|
||||
render(state: DeferBlockState): Promise<void>;
|
||||
/**
|
||||
* Retrieves all nested child defer block fixtures
|
||||
* in a given defer block.
|
||||
*/
|
||||
getDeferBlocks(): Promise<DeferBlockFixture[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixture for debugging and testing a component.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare class ComponentFixture<T> {
|
||||
componentRef: ComponentRef<T>;
|
||||
/**
|
||||
* The DebugElement associated with the root element of this component.
|
||||
*/
|
||||
debugElement: DebugElement;
|
||||
/**
|
||||
* The instance of the root component class.
|
||||
*/
|
||||
componentInstance: T;
|
||||
/**
|
||||
* The native element at the root of the component.
|
||||
*/
|
||||
nativeElement: any;
|
||||
/**
|
||||
* The ElementRef for the element at the root of the component.
|
||||
*/
|
||||
elementRef: ElementRef;
|
||||
/**
|
||||
* The ChangeDetectorRef for the component
|
||||
*/
|
||||
changeDetectorRef: ChangeDetectorRef;
|
||||
private _renderer;
|
||||
private _isDestroyed;
|
||||
private readonly _testAppRef;
|
||||
private readonly pendingTasks;
|
||||
private readonly appErrorHandler;
|
||||
private readonly zonelessEnabled;
|
||||
private readonly scheduler;
|
||||
private readonly rootEffectScheduler;
|
||||
private readonly autoDetectDefault;
|
||||
private autoDetect;
|
||||
private subscriptions;
|
||||
ngZone: NgZone | null;
|
||||
/** @docs-private */
|
||||
constructor(componentRef: ComponentRef<T>);
|
||||
/**
|
||||
* Trigger a change detection cycle for the component.
|
||||
*/
|
||||
detectChanges(checkNoChanges?: boolean): void;
|
||||
/**
|
||||
* Do a change detection run to make sure there were no changes.
|
||||
*/
|
||||
checkNoChanges(): void;
|
||||
/**
|
||||
* Set whether the fixture should autodetect changes.
|
||||
*
|
||||
* Also runs detectChanges once so that any existing change is detected.
|
||||
*
|
||||
* @param autoDetect Whether to autodetect changes. By default, `true`.
|
||||
* @deprecated For `autoDetect: true`, use `autoDetectChanges()`.
|
||||
* We have not seen a use-case for `autoDetect: false` but `changeDetectorRef.detach()` is a close equivalent.
|
||||
*/
|
||||
autoDetectChanges(autoDetect: boolean): void;
|
||||
/**
|
||||
* Enables automatically synchronizing the view, as it would in an application.
|
||||
*
|
||||
* Also runs detectChanges once so that any existing change is detected.
|
||||
*/
|
||||
autoDetectChanges(): void;
|
||||
/**
|
||||
* Return whether the fixture is currently stable or has async tasks that have not been completed
|
||||
* yet.
|
||||
*/
|
||||
isStable(): boolean;
|
||||
/**
|
||||
* Get a promise that resolves when the fixture is stable.
|
||||
*
|
||||
* This can be used to resume testing after events have triggered asynchronous activity or
|
||||
* asynchronous change detection.
|
||||
*/
|
||||
whenStable(): Promise<any>;
|
||||
/**
|
||||
* Retrieves all defer block fixtures in the component fixture.
|
||||
*/
|
||||
getDeferBlocks(): Promise<DeferBlockFixture[]>;
|
||||
private _getRenderer;
|
||||
/**
|
||||
* Get a promise that resolves when the ui state is stable following animations.
|
||||
*/
|
||||
whenRenderingDone(): Promise<any>;
|
||||
/**
|
||||
* Trigger component destruction.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Clears out the shared fake async zone for a test.
|
||||
* To be called in a global `beforeEach`.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function resetFakeAsyncZone(): void;
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Wraps a function to be executed in the `fakeAsync` zone:
|
||||
* - Microtasks are manually executed by calling `flushMicrotasks()`.
|
||||
* - Timers are synchronous; `tick()` simulates the asynchronous passage of time.
|
||||
*
|
||||
* Can be used to wrap `inject()` calls.
|
||||
*
|
||||
* @param fn The function that you want to wrap in the `fakeAsync` zone.
|
||||
* @param options
|
||||
* - flush: When true, will drain the macrotask queue after the test function completes.
|
||||
* When false, will throw an exception at the end of the function if there are pending timers.
|
||||
*
|
||||
* @usageNotes
|
||||
* ### Example
|
||||
*
|
||||
* {@example core/testing/ts/fake_async.ts region='basic'}
|
||||
*
|
||||
*
|
||||
* @returns The function wrapped to be executed in the `fakeAsync` zone.
|
||||
* Any arguments passed when calling this returned function will be passed through to the `fn`
|
||||
* function in the parameters when it is called.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function fakeAsync(fn: Function, options?: {
|
||||
flush?: boolean;
|
||||
}): (...args: any[]) => any;
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Simulates the asynchronous passage of time for the timers in the `fakeAsync` zone.
|
||||
*
|
||||
* The microtasks queue is drained at the very start of this function and after any timer callback
|
||||
* has been executed.
|
||||
*
|
||||
* @param millis The number of milliseconds to advance the virtual timer.
|
||||
* @param tickOptions The options to pass to the `tick()` function.
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* The `tick()` option is a flag called `processNewMacroTasksSynchronously`,
|
||||
* which determines whether or not to invoke new macroTasks.
|
||||
*
|
||||
* If you provide a `tickOptions` object, but do not specify a
|
||||
* `processNewMacroTasksSynchronously` property (`tick(100, {})`),
|
||||
* then `processNewMacroTasksSynchronously` defaults to true.
|
||||
*
|
||||
* If you omit the `tickOptions` parameter (`tick(100))`), then
|
||||
* `tickOptions` defaults to `{processNewMacroTasksSynchronously: true}`.
|
||||
*
|
||||
* ### Example
|
||||
*
|
||||
* {@example core/testing/ts/fake_async.ts region='basic'}
|
||||
*
|
||||
* The following example includes a nested timeout (new macroTask), and
|
||||
* the `tickOptions` parameter is allowed to default. In this case,
|
||||
* `processNewMacroTasksSynchronously` defaults to true, and the nested
|
||||
* function is executed on each tick.
|
||||
*
|
||||
* ```ts
|
||||
* it ('test with nested setTimeout', fakeAsync(() => {
|
||||
* let nestedTimeoutInvoked = false;
|
||||
* function funcWithNestedTimeout() {
|
||||
* setTimeout(() => {
|
||||
* nestedTimeoutInvoked = true;
|
||||
* });
|
||||
* };
|
||||
* setTimeout(funcWithNestedTimeout);
|
||||
* tick();
|
||||
* expect(nestedTimeoutInvoked).toBe(true);
|
||||
* }));
|
||||
* ```
|
||||
*
|
||||
* In the following case, `processNewMacroTasksSynchronously` is explicitly
|
||||
* set to false, so the nested timeout function is not invoked.
|
||||
*
|
||||
* ```ts
|
||||
* it ('test with nested setTimeout', fakeAsync(() => {
|
||||
* let nestedTimeoutInvoked = false;
|
||||
* function funcWithNestedTimeout() {
|
||||
* setTimeout(() => {
|
||||
* nestedTimeoutInvoked = true;
|
||||
* });
|
||||
* };
|
||||
* setTimeout(funcWithNestedTimeout);
|
||||
* tick(0, {processNewMacroTasksSynchronously: false});
|
||||
* expect(nestedTimeoutInvoked).toBe(false);
|
||||
* }));
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function tick(millis?: number, tickOptions?: {
|
||||
processNewMacroTasksSynchronously: boolean;
|
||||
}): void;
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Flushes any pending microtasks and simulates the asynchronous passage of time for the timers in
|
||||
* the `fakeAsync` zone by
|
||||
* draining the macrotask queue until it is empty.
|
||||
*
|
||||
* @param maxTurns The maximum number of times the scheduler attempts to clear its queue before
|
||||
* throwing an error.
|
||||
* @returns The simulated time elapsed, in milliseconds.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function flush(maxTurns?: number): number;
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Discard all remaining periodic tasks.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function discardPeriodicTasks(): void;
|
||||
/**
|
||||
* IMPORTANT: This API requires Zone.js and cannot be used with the Vitest test runner
|
||||
*
|
||||
* Flush any pending microtasks.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function flushMicrotasks(): void;
|
||||
|
||||
/**
|
||||
* Type used for modifications to metadata
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
type MetadataOverride<T> = {
|
||||
add?: Partial<T>;
|
||||
remove?: Partial<T>;
|
||||
set?: Partial<T>;
|
||||
};
|
||||
|
||||
/**
|
||||
* An abstract class for inserting the root test component element in a platform independent way.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare class TestComponentRenderer {
|
||||
insertRootElement(rootElementId: string, tagName?: string): void;
|
||||
removeAllRootElements?(): void;
|
||||
}
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
declare const ComponentFixtureAutoDetect: InjectionToken<boolean>;
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
declare const ComponentFixtureNoNgZone: InjectionToken<boolean>;
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
interface TestModuleMetadata {
|
||||
providers?: any[];
|
||||
declarations?: any[];
|
||||
imports?: any[];
|
||||
schemas?: Array<SchemaMetadata | any[]>;
|
||||
teardown?: ModuleTeardownOptions;
|
||||
/**
|
||||
* Whether NG0304 runtime errors should be thrown when unknown elements are present in component's
|
||||
* template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is
|
||||
* thrown.
|
||||
* @see [NG8001](/errors/NG8001) for the description of the problem and how to fix it
|
||||
*/
|
||||
errorOnUnknownElements?: boolean;
|
||||
/**
|
||||
* Whether errors should be thrown when unknown properties are present in component's template.
|
||||
* Defaults to `false`, where the error is simply logged.
|
||||
* If set to `true`, the error is thrown.
|
||||
* @see [NG8002](/errors/NG8002) for the description of the error and how to fix it
|
||||
*/
|
||||
errorOnUnknownProperties?: boolean;
|
||||
/**
|
||||
* Whether errors that happen during application change detection should be rethrown.
|
||||
*
|
||||
* When `true`, errors that are caught during application change detection will
|
||||
* be reported to the `ErrorHandler` and rethrown to prevent them from going
|
||||
* unnoticed in tests.
|
||||
*
|
||||
* When `false`, errors are only forwarded to the `ErrorHandler`, which by default
|
||||
* simply logs them to the console.
|
||||
*
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
rethrowApplicationErrors?: boolean;
|
||||
/**
|
||||
* Whether defer blocks should behave with manual triggering or play through normally.
|
||||
* Defaults to `manual`.
|
||||
*/
|
||||
deferBlockBehavior?: DeferBlockBehavior;
|
||||
/**
|
||||
* Whether to infer the tag name of test components from their selectors.
|
||||
* Otherwise `div` will be used as the tag name for test components.
|
||||
*/
|
||||
inferTagName?: boolean;
|
||||
/**
|
||||
* Whether animate.enter / animate.leave should trigger as normal or be disabled.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
animationsEnabled?: boolean;
|
||||
}
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
interface TestEnvironmentOptions {
|
||||
/**
|
||||
* Configures the test module teardown behavior in `TestBed`.
|
||||
*/
|
||||
teardown?: ModuleTeardownOptions;
|
||||
/**
|
||||
* Whether errors should be thrown when unknown elements are present in component's template.
|
||||
* Defaults to `false`, where the error is simply logged.
|
||||
* If set to `true`, the error is thrown.
|
||||
* @see [NG8001](/errors/NG8001) for the description of the error and how to fix it
|
||||
*/
|
||||
errorOnUnknownElements?: boolean;
|
||||
/**
|
||||
* Whether errors should be thrown when unknown properties are present in component's template.
|
||||
* Defaults to `false`, where the error is simply logged.
|
||||
* If set to `true`, the error is thrown.
|
||||
* @see [NG8002](/errors/NG8002) for the description of the error and how to fix it
|
||||
*/
|
||||
errorOnUnknownProperties?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configures the test module teardown behavior in `TestBed`.
|
||||
* @publicApi
|
||||
*/
|
||||
interface ModuleTeardownOptions {
|
||||
/** Whether the test module should be destroyed after every test. Defaults to `true`. */
|
||||
destroyAfterEach: boolean;
|
||||
/** Whether errors during test module destruction should be re-thrown. Defaults to `true`. */
|
||||
rethrowErrors?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static methods implemented by the `TestBed`.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface TestBedStatic extends TestBed {
|
||||
new (...args: any[]): TestBed;
|
||||
}
|
||||
/**
|
||||
* Options that can be configured for a test component.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
interface TestComponentOptions {
|
||||
/** Bindings to apply to the test component. */
|
||||
bindings?: Binding[];
|
||||
/**
|
||||
* Whether to infer the tag name of the test component from its selector.
|
||||
* Otherwise `div` will be used as its tag name.
|
||||
*/
|
||||
inferTagName?: boolean;
|
||||
}
|
||||
/**
|
||||
* Returns a singleton of the `TestBed` class.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function getTestBed(): TestBed;
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
interface TestBed {
|
||||
get platform(): PlatformRef;
|
||||
get ngModule(): Type<any> | Type<any>[];
|
||||
/**
|
||||
* Initialize the environment for testing with a compiler factory, a PlatformRef, and an
|
||||
* angular module. These are common to every test in the suite.
|
||||
*
|
||||
* This may only be called once, to set up the common providers for the current test
|
||||
* suite on the current platform. If you absolutely need to change the providers,
|
||||
* first use `resetTestEnvironment`.
|
||||
*
|
||||
* Test modules and platforms for individual platforms are available from
|
||||
* '@angular/<platform_name>/testing'.
|
||||
*/
|
||||
initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, options?: TestEnvironmentOptions): void;
|
||||
/**
|
||||
* Reset the providers for the test injector.
|
||||
*/
|
||||
resetTestEnvironment(): void;
|
||||
resetTestingModule(): TestBed;
|
||||
configureCompiler(config: {
|
||||
providers?: any[];
|
||||
useJit?: boolean;
|
||||
}): void;
|
||||
configureTestingModule(moduleDef: TestModuleMetadata): TestBed;
|
||||
compileComponents(): Promise<any>;
|
||||
inject<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & {
|
||||
optional?: false;
|
||||
}): T;
|
||||
inject<T>(token: ProviderToken<T>, notFoundValue: null | undefined, options: InjectOptions): T | null;
|
||||
inject<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
|
||||
/**
|
||||
* Runs the given function in the `EnvironmentInjector` context of `TestBed`.
|
||||
*
|
||||
* @see {@link https://angular.dev/api/core/EnvironmentInjector#runInContext}
|
||||
*/
|
||||
runInInjectionContext<T>(fn: () => T): T;
|
||||
execute(tokens: any[], fn: Function, context?: any): any;
|
||||
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed;
|
||||
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed;
|
||||
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed;
|
||||
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed;
|
||||
overrideTemplate(component: Type<any>, template: string): TestBed;
|
||||
/**
|
||||
* Overwrites all providers for the given token with the given provider definition.
|
||||
*/
|
||||
overrideProvider(token: any, provider: {
|
||||
useFactory: Function;
|
||||
deps: any[];
|
||||
multi?: boolean;
|
||||
}): TestBed;
|
||||
overrideProvider(token: any, provider: {
|
||||
useValue: any;
|
||||
multi?: boolean;
|
||||
}): TestBed;
|
||||
overrideProvider(token: any, provider: {
|
||||
useFactory?: Function;
|
||||
useValue?: any;
|
||||
deps?: any[];
|
||||
multi?: boolean;
|
||||
}): TestBed;
|
||||
overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed;
|
||||
createComponent<T>(component: Type<T>, options?: TestComponentOptions): ComponentFixture<T>;
|
||||
/**
|
||||
* Execute any pending effects.
|
||||
*
|
||||
* @deprecated use `TestBed.tick()` instead
|
||||
*/
|
||||
flushEffects(): void;
|
||||
/**
|
||||
* Execute any pending work required to synchronize model to the UI.
|
||||
*
|
||||
* @publicApi 20.0
|
||||
*/
|
||||
tick(): void;
|
||||
}
|
||||
/**
|
||||
* @description
|
||||
* Configures and initializes environment for unit testing and provides methods for
|
||||
* creating components and services in unit tests.
|
||||
*
|
||||
* `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare const TestBed: TestBedStatic;
|
||||
/**
|
||||
* Allows injecting dependencies in `beforeEach()` and `it()`. Note: this function
|
||||
* (imported from the `@angular/core/testing` package) can **only** be used to inject dependencies
|
||||
* in tests. To inject dependencies in your application code, use the [`inject`](api/core/inject)
|
||||
* function from the `@angular/core` package instead.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```ts
|
||||
* beforeEach(inject([Dependency, AClass], (dep, object) => {
|
||||
* // some code that uses `dep` and `object`
|
||||
* // ...
|
||||
* }));
|
||||
*
|
||||
* it('...', inject([AClass], (object) => {
|
||||
* object.doSomething();
|
||||
* expect(...);
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
declare function inject(tokens: any[], fn: Function): () => any;
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
declare class InjectSetupWrapper {
|
||||
private _moduleDef;
|
||||
constructor(_moduleDef: () => TestModuleMetadata);
|
||||
private _addModule;
|
||||
inject(tokens: any[], fn: Function): () => any;
|
||||
}
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
declare function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper;
|
||||
declare function withModule(moduleDef: TestModuleMetadata, fn: Function): () => any;
|
||||
|
||||
declare class MetadataOverrider {
|
||||
private _references;
|
||||
/**
|
||||
* Creates a new instance for the given metadata class
|
||||
* based on an old instance and overrides.
|
||||
*/
|
||||
overrideMetadata<C extends T, T>(metadataClass: {
|
||||
new (options: T): C;
|
||||
}, oldMetadata: C, override: MetadataOverride<T>): C;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fake implementation of user agent history and navigation behavior. This is a
|
||||
* high-fidelity implementation of browser behavior that attempts to emulate
|
||||
* things like traversal delay.
|
||||
*/
|
||||
declare class FakeNavigation implements Navigation {
|
||||
/**
|
||||
* The fake implementation of an entries array. Only same-document entries
|
||||
* allowed.
|
||||
*/
|
||||
private readonly entriesArr;
|
||||
/**
|
||||
* The current active entry index into `entriesArr`.
|
||||
*/
|
||||
private currentEntryIndex;
|
||||
/**
|
||||
* A Map of pending traversals, so that traversals to the same entry can be
|
||||
* re-used.
|
||||
*/
|
||||
private readonly traversalQueue;
|
||||
/**
|
||||
* A Promise that resolves when the previous traversals have finished. Used to
|
||||
* simulate the cross-process communication necessary for traversals.
|
||||
*/
|
||||
private nextTraversal;
|
||||
/**
|
||||
* A prospective current active entry index, which includes unresolved
|
||||
* traversals. Used by `go` to determine where navigations are intended to go.
|
||||
*/
|
||||
private propsectiveTraversalDestinations;
|
||||
/**
|
||||
* A test-only option to make traversals synchronous, rather than emulate
|
||||
* cross-process communication.
|
||||
*/
|
||||
private synchronousTraversals;
|
||||
/** Whether to allow a call to setInitialEntryForTesting. */
|
||||
private canSetInitialEntry;
|
||||
/** The next unique id for created entries. Replace recreates this id. */
|
||||
private nextId;
|
||||
/** The next unique key for created entries. Replace inherits this id. */
|
||||
private nextKey;
|
||||
/** Whether this fake is disposed. */
|
||||
private disposed;
|
||||
/** Equivalent to `navigation.currentEntry`. */
|
||||
get currentEntry(): FakeNavigationHistoryEntry;
|
||||
get canGoBack(): boolean;
|
||||
get canGoForward(): boolean;
|
||||
private readonly createEventTarget;
|
||||
private readonly _window;
|
||||
get window(): Pick<Window, 'addEventListener' | 'removeEventListener'>;
|
||||
constructor(doc: Document, startURL: `http${string}`);
|
||||
/**
|
||||
* Sets the initial entry.
|
||||
*/
|
||||
setInitialEntryForTesting(url: `http${string}`, options?: {
|
||||
historyState: unknown;
|
||||
state?: unknown;
|
||||
}): void;
|
||||
/** Returns whether the initial entry is still eligible to be set. */
|
||||
canSetInitialEntryForTesting(): boolean;
|
||||
/**
|
||||
* Sets whether to emulate traversals as synchronous rather than
|
||||
* asynchronous.
|
||||
*/
|
||||
setSynchronousTraversalsForTesting(synchronousTraversals: boolean): void;
|
||||
/** Equivalent to `navigation.entries()`. */
|
||||
entries(): FakeNavigationHistoryEntry[];
|
||||
/** Equivalent to `navigation.navigate()`. */
|
||||
navigate(url: string, options?: NavigationNavigateOptions): FakeNavigationResult;
|
||||
/** Equivalent to `history.pushState()`. */
|
||||
pushState(data: unknown, title: string, url?: string): void;
|
||||
/** Equivalent to `history.replaceState()`. */
|
||||
replaceState(data: unknown, title: string, url?: string): void;
|
||||
private pushOrReplaceState;
|
||||
/** Equivalent to `navigation.traverseTo()`. */
|
||||
traverseTo(key: string, options?: NavigationOptions): FakeNavigationResult;
|
||||
/** Equivalent to `navigation.back()`. */
|
||||
back(options?: NavigationOptions): FakeNavigationResult;
|
||||
/** Equivalent to `navigation.forward()`. */
|
||||
forward(options?: NavigationOptions): FakeNavigationResult;
|
||||
/**
|
||||
* Equivalent to `history.go()`.
|
||||
* Note that this method does not actually work precisely to how Chrome
|
||||
* does, instead choosing a simpler model with less unexpected behavior.
|
||||
* Chrome has a few edge case optimizations, for instance with repeated
|
||||
* `back(); forward()` chains it collapses certain traversals.
|
||||
*/
|
||||
go(direction: number): void;
|
||||
/** Runs a traversal synchronously or asynchronously */
|
||||
private runTraversal;
|
||||
/** Equivalent to `navigation.addEventListener()`. */
|
||||
addEventListener(type: string, callback: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void;
|
||||
/** Equivalent to `navigation.removeEventListener()`. */
|
||||
removeEventListener(type: string, callback: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void;
|
||||
/** Equivalent to `navigation.dispatchEvent()` */
|
||||
dispatchEvent(event: Event): boolean;
|
||||
/** Cleans up resources. */
|
||||
dispose(): void;
|
||||
/** Returns whether this fake is disposed. */
|
||||
isDisposed(): boolean;
|
||||
abortOngoingNavigation(eventToAbort: InternalFakeNavigateEvent, reason?: Error): void;
|
||||
/**
|
||||
* Implementation for all navigations and traversals.
|
||||
* @returns true if the event was intercepted, otherwise false
|
||||
*/
|
||||
private userAgentNavigate;
|
||||
/** Utility method for finding entries with the given `key`. */
|
||||
private findEntry;
|
||||
set onnavigate(_handler: ((this: Navigation, ev: NavigateEvent) => any) | null);
|
||||
get onnavigate(): ((this: Navigation, ev: NavigateEvent) => any) | null;
|
||||
set oncurrententrychange(_handler: // tslint:disable-next-line:no-any
|
||||
((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null);
|
||||
get oncurrententrychange(): // tslint:disable-next-line:no-any
|
||||
((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null;
|
||||
set onnavigatesuccess(_handler: ((this: Navigation, ev: Event) => any) | null);
|
||||
get onnavigatesuccess(): ((this: Navigation, ev: Event) => any) | null;
|
||||
set onnavigateerror(_handler: ((this: Navigation, ev: ErrorEvent) => any) | null);
|
||||
get onnavigateerror(): ((this: Navigation, ev: ErrorEvent) => any) | null;
|
||||
private _transition;
|
||||
get transition(): NavigationTransition | null;
|
||||
updateCurrentEntry(_options: NavigationUpdateCurrentEntryOptions): void;
|
||||
reload(_options?: NavigationReloadOptions): NavigationResult;
|
||||
}
|
||||
/**
|
||||
* Fake equivalent of the `NavigationResult` interface with
|
||||
* `FakeNavigationHistoryEntry`.
|
||||
*/
|
||||
interface FakeNavigationResult extends NavigationResult {
|
||||
readonly committed: Promise<FakeNavigationHistoryEntry>;
|
||||
readonly finished: Promise<FakeNavigationHistoryEntry>;
|
||||
}
|
||||
/**
|
||||
* Fake equivalent of `NavigationHistoryEntry`.
|
||||
*/
|
||||
declare class FakeNavigationHistoryEntry implements NavigationHistoryEntry {
|
||||
private eventTarget;
|
||||
readonly url: string | null;
|
||||
readonly sameDocument: boolean;
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly index: number;
|
||||
private readonly state;
|
||||
private readonly historyState;
|
||||
ondispose: ((this: NavigationHistoryEntry, ev: Event) => any) | null;
|
||||
constructor(eventTarget: EventTarget, url: string | null, { id, key, index, sameDocument, state, historyState, }: {
|
||||
id: string;
|
||||
key: string;
|
||||
index: number;
|
||||
sameDocument: boolean;
|
||||
historyState: unknown;
|
||||
state?: unknown;
|
||||
});
|
||||
getState(): unknown;
|
||||
getHistoryState(): unknown;
|
||||
addEventListener(type: string, callback: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void;
|
||||
removeEventListener(type: string, callback: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void;
|
||||
dispatchEvent(event: Event): boolean;
|
||||
/** internal */
|
||||
dispose(): void;
|
||||
}
|
||||
/** `NavigationInterceptOptions` with experimental commit option. */
|
||||
interface ExperimentalNavigationInterceptOptions extends NavigationInterceptOptions {
|
||||
precommitHandler?: (controller: NavigationPrecommitController) => Promise<void>;
|
||||
}
|
||||
interface NavigationPrecommitController {
|
||||
redirect: (url: string, options?: NavigationNavigateOptions) => void;
|
||||
}
|
||||
interface ExperimentalNavigateEvent extends NavigateEvent {
|
||||
intercept(options?: ExperimentalNavigationInterceptOptions): void;
|
||||
precommitHandler?: () => Promise<void>;
|
||||
}
|
||||
/**
|
||||
* Fake equivalent of `NavigateEvent`.
|
||||
*/
|
||||
interface FakeNavigateEvent extends ExperimentalNavigateEvent {
|
||||
readonly destination: FakeNavigationDestination;
|
||||
}
|
||||
interface InternalFakeNavigateEvent extends FakeNavigateEvent {
|
||||
readonly sameDocument: boolean;
|
||||
readonly result: InternalNavigationResult;
|
||||
interceptionState: 'none' | 'intercepted' | 'committed' | 'scrolled' | 'finished';
|
||||
scrollBehavior: 'after-transition' | 'manual' | null;
|
||||
focusResetBehavior: 'after-transition' | 'manual' | null;
|
||||
abortController: AbortController;
|
||||
abort(reason: Error): void;
|
||||
}
|
||||
/**
|
||||
* Fake equivalent of `NavigationDestination`.
|
||||
*/
|
||||
declare class FakeNavigationDestination implements NavigationDestination {
|
||||
url: string;
|
||||
readonly sameDocument: boolean;
|
||||
readonly key: string | null;
|
||||
readonly id: string | null;
|
||||
readonly index: number;
|
||||
state?: unknown;
|
||||
private readonly historyState;
|
||||
constructor({ url, sameDocument, historyState, state, key, id, index, }: {
|
||||
url: string;
|
||||
sameDocument: boolean;
|
||||
historyState: unknown;
|
||||
state?: unknown;
|
||||
key?: string | null;
|
||||
id?: string | null;
|
||||
index?: number;
|
||||
});
|
||||
getState(): unknown;
|
||||
getHistoryState(): unknown;
|
||||
}
|
||||
/**
|
||||
* Internal utility class for representing the result of a navigation.
|
||||
* Generally equivalent to the "apiMethodTracker" in the spec.
|
||||
*/
|
||||
declare class InternalNavigationResult {
|
||||
readonly navigation: FakeNavigation;
|
||||
committedTo: FakeNavigationHistoryEntry | null;
|
||||
committedResolve: (entry: FakeNavigationHistoryEntry) => void;
|
||||
committedReject: (reason: Error) => void;
|
||||
finishedResolve: () => void;
|
||||
finishedReject: (reason: Error) => void;
|
||||
readonly committed: Promise<FakeNavigationHistoryEntry>;
|
||||
readonly finished: Promise<FakeNavigationHistoryEntry>;
|
||||
get signal(): AbortSignal;
|
||||
private readonly abortController;
|
||||
constructor(navigation: FakeNavigation);
|
||||
}
|
||||
|
||||
declare function getCleanupHook(expectedTeardownValue: boolean): VoidFunction;
|
||||
|
||||
declare class Log<T = string> {
|
||||
logItems: T[];
|
||||
constructor();
|
||||
add(value: T): void;
|
||||
fn(value: T): () => void;
|
||||
clear(): void;
|
||||
result(): string;
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<Log<any>, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<Log<any>>;
|
||||
}
|
||||
|
||||
export { ComponentFixture, ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, DeferBlockBehavior, DeferBlockFixture, DeferBlockState, InjectSetupWrapper, TestBed, TestComponentRenderer, discardPeriodicTasks, fakeAsync, flush, flushMicrotasks, getTestBed, inject, resetFakeAsyncZone, tick, waitForAsync, withModule, FakeNavigation as ɵFakeNavigation, Log as ɵLog, MetadataOverrider as ɵMetadataOverrider, getCleanupHook as ɵgetCleanupHook };
|
||||
export type { MetadataOverride, ModuleTeardownOptions, TestBedStatic, TestComponentOptions, TestEnvironmentOptions, TestModuleMetadata };
|
||||
Reference in New Issue
Block a user