diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts index c416ca48414..592ddd7407c 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts @@ -1,5 +1,6 @@ // Imports import fetch from 'node-fetch'; + import {assertNotMissingOrEmpty} from './utils'; // Constants @@ -22,8 +23,8 @@ export interface BuildInfo { username: string; build_num: number; has_artifacts: boolean; - outcome: string; // e.g. 'success' - vcs_revision: string; // HEAD SHA + outcome: string; // e.g. 'success' + vcs_revision: string; // HEAD SHA // there are other fields but they are not used in this code } @@ -31,19 +32,19 @@ export interface BuildInfo { * A Helper that can interact with the CircleCI API. */ export class CircleCiApi { - private tokenParam = `circle-token=${this.circleCiToken}`; /** * Construct a helper that can interact with the CircleCI REST API. - * @param githubOrg The Github organisation whose repos we want to access in CircleCI (e.g. angular). + * @param githubOrg The Github organisation whose repos we want to access in CircleCI (e.g. + * angular). * @param githubRepo The Github repo whose builds we want to access in CircleCI (e.g. angular). * @param circleCiToken The CircleCI API access token (secret). */ constructor( - private githubOrg: string, - private githubRepo: string, - private circleCiToken: string, + private githubOrg: string, + private githubRepo: string, + private circleCiToken: string, ) { assertNotMissingOrEmpty('githubOrg', githubOrg); assertNotMissingOrEmpty('githubRepo', githubRepo); @@ -64,7 +65,7 @@ export class CircleCiApi { } return response.json(); } catch (error) { - throw new Error(`CircleCI build info request failed (${error.message})`); + throw new Error(`CircleCI build info request failed (${(error as Error).message})`); } } @@ -84,7 +85,7 @@ export class CircleCiApi { } return artifact.url; } catch (error) { - throw new Error(`CircleCI artifact URL request failed (${error.message})`); + throw new Error(`CircleCI artifact URL request failed (${(error as Error).message})`); } } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts index 870126ba955..ca1b7d83463 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts @@ -1,4 +1,5 @@ import {basename, resolve as resolvePath} from 'path'; + import {SHORT_SHA_LEN} from './constants'; /** @@ -17,7 +18,8 @@ export function computeShortSha(sha: string) { * @param artifactPath The path to the artifact on CircleCI. * @returns The fully resolved location for the specified downloaded artifact. */ -export function computeArtifactDownloadPath(downloadsDir: string, pr: number, sha: string, artifactPath: string) { +export function computeArtifactDownloadPath( + downloadsDir: string, pr: number, sha: string, artifactPath: string) { return resolvePath(downloadsDir, `${pr}-${computeShortSha(sha)}-${basename(artifactPath)}`); } @@ -48,7 +50,7 @@ export function assert(value: boolean, message: string) { * @param name The name of the parameter. * @param value The value of the parameter. */ -export const assertNotMissingOrEmpty = (name: string, value: string | null | undefined) => { +export const assertNotMissingOrEmpty = (name: string, value: string|null|undefined) => { assert(!!value, `Missing or empty required parameter '${name}'!`); }; @@ -64,9 +66,9 @@ export const getEnvVar = (name: string, isOptional = false): string => { if (!isOptional && !value) { try { - throw new Error(`ERROR: Missing required environment variable '${name}'!`); + throw new Error(`ERROR: Missing required environment variable '${name}'!`); } catch (error) { - console.error(error.stack); + console.error((error as Error).stack); process.exit(1); } } @@ -76,7 +78,8 @@ export const getEnvVar = (name: string, isOptional = false): string => { /** * A basic logger implementation. - * Delegates to `console`, but prepends each message with the current date and specified scope (i.e caller). + * Delegates to `console`, but prepends each message with the current date and specified scope (i.e + * caller). */ export class Logger { private padding = ' '.repeat(20 - this.scope.length); @@ -87,12 +90,20 @@ export class Logger { */ constructor(private scope: string) {} - public error(...args: any[]) { this.callMethod('error', args); } - public info(...args: any[]) { this.callMethod('info', args); } - public log(...args: any[]) { this.callMethod('log', args); } - public warn(...args: any[]) { this.callMethod('warn', args); } + public error(...args: any[]) { + this.callMethod('error', args); + } + public info(...args: any[]) { + this.callMethod('info', args); + } + public log(...args: any[]) { + this.callMethod('log', args); + } + public warn(...args: any[]) { + this.callMethod('warn', args); + } - private callMethod(method: 'error' | 'info' | 'log' | 'warn', args: any[]) { + private callMethod(method: 'error'|'info'|'log'|'warn', args: any[]) { console[method](`[${new Date()}]`, `${this.scope}:${this.padding}`, ...args); } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts index 2c29d6cd961..b06a770a12d 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts @@ -3,8 +3,10 @@ import fetch from 'node-fetch'; import {dirname} from 'path'; import {mkdir} from 'shelljs'; import {promisify} from 'util'; + import {CircleCiApi} from '../common/circle-ci-api'; import {assert, assertNotMissingOrEmpty, computeArtifactDownloadPath, Logger} from '../common/utils'; + import {PreviewServerError} from './preview-error'; export interface GithubInfo { @@ -20,8 +22,11 @@ export interface GithubInfo { */ export class BuildRetriever { private logger = new Logger('BuildRetriever'); - constructor(private api: CircleCiApi, private downloadSizeLimit: number, private downloadDir: string) { - assert(downloadSizeLimit > 0, 'Invalid parameter "downloadSizeLimit" should be a number greater than 0.'); + constructor( + private api: CircleCiApi, private downloadSizeLimit: number, private downloadDir: string) { + assert( + downloadSizeLimit > 0, + 'Invalid parameter "downloadSizeLimit" should be a number greater than 0.'); assertNotMissingOrEmpty('downloadDir', downloadDir); } @@ -50,25 +55,29 @@ export class BuildRetriever { * @param artifactPath the path on CircleCI where the artifact was stored. * @returns A promise to the file path where the downloaded file was stored. */ - public async downloadBuildArtifact(buildNum: number, pr: number, sha: string, artifactPath: string): Promise { + public async downloadBuildArtifact( + buildNum: number, pr: number, sha: string, artifactPath: string): Promise { try { const outPath = computeArtifactDownloadPath(this.downloadDir, pr, sha, artifactPath); - const downloadExists = await new Promise(resolve => fs.exists(outPath, exists => resolve(exists))); + const downloadExists = + await new Promise(resolve => fs.exists(outPath, exists => resolve(exists))); if (!downloadExists) { const url = await this.api.getBuildArtifactUrl(buildNum, artifactPath); const response = await fetch(url, {size: this.downloadSizeLimit}); if (response.status !== 200) { - throw new PreviewServerError(response.status, `Error ${response.status} - ${response.statusText}`); + throw new PreviewServerError( + response.status, `Error ${response.status} - ${response.statusText}`); } const buffer = await response.buffer(); mkdir('-p', dirname(outPath)); await promisify(fs.writeFile)(outPath, buffer); } return outPath; - } catch (error) { + } catch (error: any) { this.logger.warn(error); const status = (error.type === 'max-size') ? 413 : 500; - throw new PreviewServerError(status, `CircleCI artifact download failed (${error.message || error})`); + throw new PreviewServerError( + status, `CircleCI artifact download failed (${error.message || error})`); } } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts index 993225711cd..5f0f36beaa2 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts @@ -1,4 +1,5 @@ import * as express from 'express'; + import {PreviewServerError} from '../../lib/preview-server/preview-error'; import {respondWithError, throwRequestError} from '../../lib/preview-server/utils'; @@ -37,11 +38,12 @@ describe('preview-server/utils', () => { originalUrl: 'some.domain.com/path', } as express.Request; throwRequestError(505, 'ERROR MESSAGE', request); - } catch (error) { + } catch (error: any) { caught = true; expect(error).toBeInstanceOf(PreviewServerError); expect(error.status).toEqual(505); - expect(error.message).toEqual(`ERROR MESSAGE in request: POST some.domain.com/path "The request body"`); + expect(error.message) + .toEqual(`ERROR MESSAGE in request: POST some.domain.com/path "The request body"`); } expect(caught).toEqual(true); }); diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/tsconfig.json b/aio/aio-builds-setup/dockerbuild/scripts-js/tsconfig.json index 280fe4159c7..27847c75ae6 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/tsconfig.json +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/tsconfig.json @@ -1,40 +1,36 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "lib": [ "es2015", "es2016.array.include" - ], /* Specify library files to be included in the compilation: */ + ], /* Specify library files to be included in the compilation: */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ + "outDir": "dist", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ - "importHelpers": true, /* Import emit helpers from 'tslib'. */ + "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ - "noUnusedLocals": true, /* Report errors on unused locals. */ - "noUnusedParameters": true, /* Report errors on unused parameters. */ - "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - "useUnknownInCatchVariables": false, /* Avoid having to cast error objects inside `catch` clauses. */ - /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ @@ -42,29 +38,26 @@ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ "typeRoots": [ "node_modules/@types" - ], /* List of folders to include type definitions from. */ + ], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - /* Source Map Options */ // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ - "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - /* Other */ "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "newLine": "LF", /* Use the specified end of line sequence to be used when emitting files: "crlf" (windows) or "lf" (unix). */ - "pretty": true, /* Stylize errors and messages using color and context. */ - "skipLibCheck": true /* Skip type checking of all declaration files (*.d.ts). */ + "newLine": "LF", /* Use the specified end of line sequence to be used when emitting files: "crlf" (windows) or "lf" (unix). */ + "pretty": true, /* Stylize errors and messages using color and context. */ + "skipLibCheck": true /* Skip type checking of all declaration files (*.d.ts). */ }, "include": [ "lib/**/*", "test/**/*" ] -} +} \ No newline at end of file diff --git a/aio/src/app/layout/doc-viewer/doc-viewer.component.ts b/aio/src/app/layout/doc-viewer/doc-viewer.component.ts index 2adff61ff75..4b42b0bd264 100644 --- a/aio/src/app/layout/doc-viewer/doc-viewer.component.ts +++ b/aio/src/app/layout/doc-viewer/doc-viewer.component.ts @@ -1,15 +1,13 @@ -import { Component, ElementRef, EventEmitter, Input, OnDestroy, Output } from '@angular/core'; -import { Title, Meta } from '@angular/platform-browser'; - -import { asapScheduler, Observable, of, timer } from 'rxjs'; -import { catchError, observeOn, switchMap, takeUntil, tap } from 'rxjs/operators'; -import { EMPTY_HTML, unwrapHtmlForSink } from 'safevalues'; - -import { DocumentContents, FILE_NOT_FOUND_ID, FETCHING_ERROR_ID } from 'app/documents/document.service'; -import { Logger } from 'app/shared/logger.service'; -import { TocService } from 'app/shared/toc.service'; -import { ElementsLoader } from 'app/custom-elements/elements-loader'; -import { fromInnerHTML } from 'app/shared/security'; +import {Component, ElementRef, EventEmitter, Input, OnDestroy, Output} from '@angular/core'; +import {Meta, Title} from '@angular/platform-browser'; +import {ElementsLoader} from 'app/custom-elements/elements-loader'; +import {DocumentContents, FETCHING_ERROR_ID, FILE_NOT_FOUND_ID} from 'app/documents/document.service'; +import {Logger} from 'app/shared/logger.service'; +import {fromInnerHTML} from 'app/shared/security'; +import {TocService} from 'app/shared/toc.service'; +import {asapScheduler, Observable, of, timer} from 'rxjs'; +import {catchError, observeOn, switchMap, takeUntil, tap} from 'rxjs/operators'; +import {EMPTY_HTML, unwrapHtmlForSink} from 'safevalues'; // Constants @@ -17,7 +15,8 @@ export const NO_ANIMATIONS = 'no-animations'; // Initialization prevents flicker once pre-rendering is on const initialDocViewerElement = document.querySelector('aio-doc-viewer'); -const initialDocViewerContent = initialDocViewerElement ? fromInnerHTML(initialDocViewerElement) : EMPTY_HTML; +const initialDocViewerContent = + initialDocViewerElement ? fromInnerHTML(initialDocViewerElement) : EMPTY_HTML; @Component({ selector: 'aio-doc-viewer', @@ -61,15 +60,13 @@ export class DocViewerComponent implements OnDestroy { @Output() docRendered = new EventEmitter(); constructor( - elementRef: ElementRef, - private logger: Logger, - private titleService: Title, - private metaService: Meta, - private tocService: TocService, - private elementsLoader: ElementsLoader) { + elementRef: ElementRef, private logger: Logger, private titleService: Title, + private metaService: Meta, private tocService: TocService, + private elementsLoader: ElementsLoader) { this.hostElement = elementRef.nativeElement; - // Security: the initialDocViewerContent comes from the prerendered DOM and is considered to be secure + // Security: the initialDocViewerContent comes from the prerendered DOM and is considered to be + // secure this.hostElement.innerHTML = unwrapHtmlForSink(initialDocViewerContent); if (this.hostElement.firstElementChild) { @@ -81,7 +78,7 @@ export class DocViewerComponent implements OnDestroy { observeOn(asapScheduler), switchMap(newDoc => this.render(newDoc)), takeUntil(this.onDestroy$), - ) + ) .subscribe(); } @@ -151,7 +148,8 @@ export class DocViewerComponent implements OnDestroy { tap(() => this.docRendered.emit()), catchError(err => { const errorMessage = `${(err instanceof Error) ? err.stack : err}`; - this.logger.error(new Error(`[DocViewer] Error preparing document '${doc.id}': ${errorMessage}`)); + this.logger.error( + new Error(`[DocViewer] Error preparing document '${doc.id}': ${errorMessage}`)); this.nextViewContainer.textContent = ''; this.setNoIndex(true); @@ -172,7 +170,7 @@ export class DocViewerComponent implements OnDestroy { */ private setNoIndex(val: boolean) { if (val) { - this.metaService.addTag({ name: 'robots', content: 'noindex' }); + this.metaService.addTag({name: 'robots', content: 'noindex'}); } else { this.metaService.removeTag('name="robots"'); } @@ -207,29 +205,33 @@ export class DocViewerComponent implements OnDestroy { // Some properties are not assignable and thus cannot be animated. // Example methods, readonly and CSS properties: - // "length", "parentRule", "getPropertyPriority", "getPropertyValue", "item", "removeProperty", "setProperty" + // "length", "parentRule", "getPropertyPriority", "getPropertyValue", "item", "removeProperty", + // "setProperty" type StringValueCSSStyleDeclaration = Exclude< - { - [K in keyof CSSStyleDeclaration]: CSSStyleDeclaration[K] extends string ? K : never; - }[keyof CSSStyleDeclaration], - number - >; + {[K in keyof CSSStyleDeclaration]: + CSSStyleDeclaration[K] extends string ? K : never;}[keyof CSSStyleDeclaration], + number>; const animateProp = - (elem: HTMLElement, prop: StringValueCSSStyleDeclaration, from: string, to: string, duration = 200) => { + (elem: HTMLElement, prop: StringValueCSSStyleDeclaration, from: string, to: string, + duration = 200) => { const animationsDisabled = this.hostElement.classList.contains(NO_ANIMATIONS); elem.style.transition = ''; - return animationsDisabled - ? this.void$.pipe(tap(() => elem.style[prop] = to)) - : this.void$.pipe( - // In order to ensure that the `from` value will be applied immediately (i.e. - // without transition) and that the `to` value will be affected by the - // `transition` style, we need to ensure an animation frame has passed between - // setting each style. - switchMap(() => raf$), tap(() => elem.style[prop] = from), - switchMap(() => raf$), tap(() => elem.style.transition = `all ${duration}ms ease-in-out`), - switchMap(() => raf$), tap(() => elem.style[prop] = to), - switchMap(() => timer(getActualDuration(elem))), switchMap(() => this.void$), - ); + return animationsDisabled ? + this.void$.pipe(tap(() => elem.style[prop] = to)) : + this.void$.pipe( + // In order to ensure that the `from` value will be applied immediately (i.e. + // without transition) and that the `to` value will be affected by the + // `transition` style, we need to ensure an animation frame has passed between + // setting each style. + switchMap(() => raf$), + tap(() => elem.style[prop] = from), + switchMap(() => raf$), + tap(() => elem.style.transition = `all ${duration}ms ease-in-out`), + switchMap(() => raf$), + tap(() => elem.style[prop] = to), + switchMap(() => timer(getActualDuration(elem))), + switchMap(() => this.void$), + ); }; const animateLeave = (elem: HTMLElement) => animateProp(elem, 'opacity', '1', '0.1'); @@ -241,7 +243,8 @@ export class DocViewerComponent implements OnDestroy { done$ = done$.pipe( // Remove the current view from the viewer. switchMap(() => animateLeave(this.currViewContainer)), - tap(() => (this.currViewContainer.parentElement as HTMLElement).removeChild(this.currViewContainer)), + tap(() => (this.currViewContainer.parentElement as HTMLElement) + .removeChild(this.currViewContainer)), tap(() => this.docRemoved.emit()), ); } @@ -304,7 +307,8 @@ async function printSwDebugInfo(): Promise { } console.log(await res.text()); } catch (err) { - console.log(`Failed to retrieve debug info from '/ngsw/state': ${err.message || err}`); + console.log( + `Failed to retrieve debug info from '/ngsw/state': ${(err as Error).message || err}`); } } @@ -319,25 +323,25 @@ async function printSwDebugInfo(): Promise { } } - async function getCacheEntries( - name: string, includeValues: boolean, - ignoredKeys: string[] = []): Promise<{key: string, value?: unknown}[]> { + async function getCacheEntries(name: string, includeValues: boolean, ignoredKeys: string[] = []): + Promise<{key: string, value?: unknown}[]> { const ignoredUrls = new Set(ignoredKeys.map(key => new Request(key).url)); const cache = await caches.open(name); const keys = (await cache.keys()).map(req => req.url).filter(url => !ignoredUrls.has(url)); - const entries = await Promise.all(keys.map(async key => ({ - key, - value: !includeValues ? undefined : await (await cache.match(key))?.json(), - }))); + const entries = await Promise.all( + keys.map(async key => ({ + key, + value: !includeValues ? undefined : await (await cache.match(key))?.json(), + }))); return entries; } function printCacheEntries(name: string, entries: {key: string, value?: unknown}[]): void { - const entriesStr = entries - .map(({key, value}) => ` - ${key}${!value ? '' : `: ${JSON.stringify(value)}`}`) - .join('\n'); + const entriesStr = + entries.map(({key, value}) => ` - ${key}${!value ? '' : `: ${JSON.stringify(value)}`}`) + .join('\n'); console.log(`\nCache: ${name} (${entries.length} entries)\n${entriesStr}`); } diff --git a/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts b/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts index 94ba1196e95..5a963535a0e 100644 --- a/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts +++ b/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts @@ -2,7 +2,7 @@ import * as XRegExp from 'xregexp'; // The `XRegExp` typings are not accurate. interface XRegExp extends RegExp { - xregexp: { captureNames?: string[] }; + xregexp: {captureNames?: string[]}; } export class FirebaseRedirectSource { @@ -22,34 +22,36 @@ export class FirebaseRedirectSource { static fromGlobPattern(glob: string): FirebaseRedirectSource { const dot = /\./g; const star = /\*/g; - const doubleStar = /(^|\/)\*\*($|\/)/g; // e.g. a/**/b or **/b or a/** but not a**b - const modifiedPatterns = /(.)\(([^)]+)\)/g; // e.g. `@(a|b) - const restParam = /(\/?):([A-Za-z]+)\*/g; // e.g. `:rest*` - const namedParam = /(\/?):([A-Za-z]+)/g; // e.g. `:api` + const doubleStar = /(^|\/)\*\*($|\/)/g; // e.g. a/**/b or **/b or a/** but not a**b + const modifiedPatterns = /(.)\(([^)]+)\)/g; // e.g. `@(a|b) + const restParam = /(\/?):([A-Za-z]+)\*/g; // e.g. `:rest*` + const namedParam = /(\/?):([A-Za-z]+)/g; // e.g. `:api` const possiblyEmptyInitialSegments = /^\.🐷\//g; // e.g. `**/a` can also match `a` const possiblyEmptySegments = /\/\.🐷\//g; // e.g. `a/**/b` can also match `a/b` const willBeStar = /🐷/g; // e.g. `a**b` not matched by previous rule try { const restNamedGroups: string[] = []; - const pattern = glob - .replace(dot, '\\.') - .replace(modifiedPatterns, replaceModifiedPattern) - .replace(restParam, (_, leadingSlash, groupName) => { - // capture the rest of the string - restNamedGroups.push(groupName); - return `(?:${leadingSlash}(?<${groupName}>.🐷))?`; - }) - .replace(namedParam, '$1(?<$2>[^/]+)') - .replace(doubleStar, '$1.🐷$2') // use the pig to avoid replacing ** in next rule - .replace(star, '[^/]*') // match a single segment - .replace(possiblyEmptyInitialSegments, '(?:.*)')// deal with **/ special cases - .replace(possiblyEmptySegments, '(?:/|/.*/)') // deal with /**/ special cases - .replace(willBeStar, '*'); // other ** matches + const pattern = + glob.replace(dot, '\\.') + .replace(modifiedPatterns, replaceModifiedPattern) + .replace( + restParam, + (_, leadingSlash, groupName) => { + // capture the rest of the string + restNamedGroups.push(groupName); + return `(?:${leadingSlash}(?<${groupName}>.🐷))?`; + }) + .replace(namedParam, '$1(?<$2>[^/]+)') + .replace(doubleStar, '$1.🐷$2') // use the pig to avoid replacing ** in next rule + .replace(star, '[^/]*') // match a single segment + .replace(possiblyEmptyInitialSegments, '(?:.*)') // deal with **/ special cases + .replace(possiblyEmptySegments, '(?:/|/.*/)') // deal with /**/ special cases + .replace(willBeStar, '*'); // other ** matches return new FirebaseRedirectSource(`^${pattern}$`, restNamedGroups); } catch (err) { - throw new Error(`Error in FirebaseRedirectSource: "${glob}" - ${err.message}`); + throw new Error(`Error in FirebaseRedirectSource: "${glob}" - ${(err as Error).message}`); } } @@ -72,7 +74,7 @@ export class FirebaseRedirectSource { // capture groups. return new FirebaseRedirectSource(regex.replace(/(\(\?)P(<[^>]+>)/g, '$1$2')); } catch (err) { - throw new Error(`Error in FirebaseRedirectSource: "${regex}" - ${err.message}`); + throw new Error(`Error in FirebaseRedirectSource: "${regex}" - ${(err as Error).message}`); } } @@ -80,14 +82,14 @@ export class FirebaseRedirectSource { return XRegExp.test(url, this.regex); } - match(url: string): { [key: string]: string } | undefined { + match(url: string): {[key: string]: string}|undefined { const match = XRegExp.exec(url, this.regex) as ReturnType; if (!match) { return undefined; } - const result: { [key: string]: string } = {}; + const result: {[key: string]: string} = {}; const names = this.regex.xregexp.captureNames || []; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion names.forEach(name => result[name] = match.groups![name]); diff --git a/aio/tsconfig.json b/aio/tsconfig.json index 2f2071674f3..dca80c00f18 100644 --- a/aio/tsconfig.json +++ b/aio/tsconfig.json @@ -14,7 +14,6 @@ "noFallthroughCasesInSwitch": true, "noUnusedLocals": true, "noUnusedParameters": true, - "useUnknownInCatchVariables": false, "sourceMap": true, "declaration": false, "downlevelIteration": true, @@ -47,4 +46,4 @@ "strictInputAccessModifiers": true, "strictTemplates": true } -} +} \ No newline at end of file diff --git a/packages/animations/browser/test/render/transition_animation_engine_spec.ts b/packages/animations/browser/test/render/transition_animation_engine_spec.ts index 2283fe4d581..8bf274edc51 100644 --- a/packages/animations/browser/test/render/transition_animation_engine_spec.ts +++ b/packages/animations/browser/test/render/transition_animation_engine_spec.ts @@ -636,7 +636,7 @@ describe('TransitionAnimationEngine', () => { try { engine.flush(); } catch (e) { - errorMessage = e.toString(); + errorMessage = (e as Error).toString(); } expect(errorMessage).toMatch(/Unable to animate due to the following errors:/); diff --git a/packages/common/http/testing/test/request_spec.ts b/packages/common/http/testing/test/request_spec.ts index 0f3679a2e51..4c468297bd2 100644 --- a/packages/common/http/testing/test/request_spec.ts +++ b/packages/common/http/testing/test/request_spec.ts @@ -39,7 +39,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url.'); @@ -61,7 +61,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url?query=world').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url?query=world", found none.' + ' Requests received are: GET /some-url?query=hello.'); @@ -85,7 +85,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url?query=world, POST /and-another-url.'); diff --git a/packages/common/src/pipes/date_pipe.ts b/packages/common/src/pipes/date_pipe.ts index 5c8b958239c..088a9fcc216 100644 --- a/packages/common/src/pipes/date_pipe.ts +++ b/packages/common/src/pipes/date_pipe.ts @@ -7,7 +7,9 @@ */ import {Inject, InjectionToken, LOCALE_ID, Optional, Pipe, PipeTransform} from '@angular/core'; + import {formatDate} from '../i18n/format_date'; + import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** @@ -209,7 +211,7 @@ export class DatePipe implements PipeTransform { return formatDate( value, format, locale || this.locale, timezone ?? this.defaultTimezone ?? undefined); } catch (error) { - throw invalidPipeArgumentError(DatePipe, error.message); + throw invalidPipeArgumentError(DatePipe, (error as Error).message); } } } diff --git a/packages/common/src/pipes/number_pipe.ts b/packages/common/src/pipes/number_pipe.ts index 97899105375..fd379910d2a 100644 --- a/packages/common/src/pipes/number_pipe.ts +++ b/packages/common/src/pipes/number_pipe.ts @@ -7,6 +7,7 @@ */ import {DEFAULT_CURRENCY_CODE, Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; + import {formatCurrency, formatNumber, formatPercent} from '../i18n/format_number'; import {getCurrencySymbol} from '../i18n/locale_data_api'; @@ -100,7 +101,7 @@ export class DecimalPipe implements PipeTransform { const num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(DecimalPipe, error.message); + throw invalidPipeArgumentError(DecimalPipe, (error as Error).message); } } } @@ -156,7 +157,7 @@ export class PercentPipe implements PipeTransform { const num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(PercentPipe, error.message); + throw invalidPipeArgumentError(PercentPipe, (error as Error).message); } } } @@ -281,7 +282,7 @@ export class CurrencyPipe implements PipeTransform { const num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(CurrencyPipe, error.message); + throw invalidPipeArgumentError(CurrencyPipe, (error as Error).message); } } } diff --git a/packages/common/upgrade/src/location_shim.ts b/packages/common/upgrade/src/location_shim.ts index 4e46269a06c..274eb00a634 100644 --- a/packages/common/upgrade/src/location_shim.ts +++ b/packages/common/upgrade/src/location_shim.ts @@ -360,7 +360,7 @@ export class $locationShim { try { fn(url, state, oldUrl, oldState); } catch (e) { - err(e); + err(e as Error); } }); } diff --git a/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts b/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts index cfe97b67100..b742d991fb5 100644 --- a/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts +++ b/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts @@ -92,7 +92,7 @@ export function createEs2015LinkerPlugin({fileSystem, logger, ...options}: Linke call.replaceWith(replacement); } catch (e) { const node = isFatalLinkerError(e) ? e.node as t.Node : call.node; - throw buildCodeFrameError(call.hub.file, e.message, node); + throw buildCodeFrameError(call.hub.file, (e as Error).message, node); } } } diff --git a/packages/compiler-cli/ngcc/main-ngcc.ts b/packages/compiler-cli/ngcc/main-ngcc.ts index a320fcffb63..fdfbb77c143 100644 --- a/packages/compiler-cli/ngcc/main-ngcc.ts +++ b/packages/compiler-cli/ngcc/main-ngcc.ts @@ -21,8 +21,8 @@ const options = parseCommandLineOptions(process.argv.slice(2)); options.logger.debug(`Run ngcc in ${duration}s.`); } process.exitCode = 0; - } catch (e) { - console.error(e.stack || e.message); + } catch (e: any) { + console.error((e as Error).stack || (e as Error).message); process.exit(typeof e.code === 'number' ? e.code : 1); } })(); diff --git a/packages/compiler-cli/ngcc/src/execution/cluster/ngcc_cluster_worker.ts b/packages/compiler-cli/ngcc/src/execution/cluster/ngcc_cluster_worker.ts index a7072fecaa8..2714ec6e88e 100644 --- a/packages/compiler-cli/ngcc/src/execution/cluster/ngcc_cluster_worker.ts +++ b/packages/compiler-cli/ngcc/src/execution/cluster/ngcc_cluster_worker.ts @@ -40,7 +40,7 @@ import {startWorker} from './worker'; await startWorker(logger, createCompileFn); process.exitCode = 0; } catch (e) { - console.error(e.stack || e.message); + console.error((e as Error).stack || (e as Error).message); process.exit(1); } })(); diff --git a/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts b/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts index 263e16d0907..81f2946183a 100644 --- a/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts +++ b/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts @@ -40,7 +40,7 @@ export async function startWorker(logger: Logger, createCompileFn: CreateCompile throw new Error( `[Worker #${cluster.worker.id}] Invalid message received: ${JSON.stringify(msg)}`); } - } catch (err) { + } catch (err: any) { switch (err && err.code) { case 'ENOMEM': // Not being able to allocate enough memory is not necessarily a problem with processing diff --git a/packages/compiler-cli/ngcc/src/locking/async_locker.ts b/packages/compiler-cli/ngcc/src/locking/async_locker.ts index 7e2f1dc7aad..61d7a6fffee 100644 --- a/packages/compiler-cli/ngcc/src/locking/async_locker.ts +++ b/packages/compiler-cli/ngcc/src/locking/async_locker.ts @@ -49,7 +49,7 @@ export class AsyncLocker { for (let attempts = 0; attempts < this.retryAttempts; attempts++) { try { return this.lockFile.write(); - } catch (e) { + } catch (e: any) { if (e.code !== 'EEXIST') { throw e; } diff --git a/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts b/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts index d4870221b24..a80c85a77f6 100644 --- a/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts +++ b/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts @@ -26,7 +26,7 @@ export function removeLockFile( logger.debug( `PIDs do not match (${pid} and ${lockFilePid}), so not removing ${lockFilePath}.`); } - } catch (e) { + } catch (e: any) { if (e.code === 'ENOENT') { logger.debug(`The lock-file at ${lockFilePath} was already removed.`); // File already removed so quietly exit diff --git a/packages/compiler-cli/ngcc/src/locking/sync_locker.ts b/packages/compiler-cli/ngcc/src/locking/sync_locker.ts index 54cca4d4a51..51459fbad05 100644 --- a/packages/compiler-cli/ngcc/src/locking/sync_locker.ts +++ b/packages/compiler-cli/ngcc/src/locking/sync_locker.ts @@ -39,7 +39,7 @@ export class SyncLocker { protected create(): void { try { this.lockFile.write(); - } catch (e) { + } catch (e: any) { if (e.code !== 'EEXIST') { throw e; } diff --git a/packages/compiler-cli/ngcc/src/packages/configuration.ts b/packages/compiler-cli/ngcc/src/packages/configuration.ts index 13f3c857534..0b7c8a674c7 100644 --- a/packages/compiler-cli/ngcc/src/packages/configuration.ts +++ b/packages/compiler-cli/ngcc/src/packages/configuration.ts @@ -415,7 +415,8 @@ export class NgccConfiguration { try { return this.evalSrcFile(configFilePath); } catch (e) { - throw new Error(`Invalid project configuration file at "${configFilePath}": ` + e.message); + throw new Error( + `Invalid project configuration file at "${configFilePath}": ` + (e as Error).message); } } else { return {packages: {}}; @@ -433,7 +434,8 @@ export class NgccConfiguration { versionRange: version || '*', }; } catch (e) { - throw new Error(`Invalid package configuration file at "${configFilePath}": ` + e.message); + throw new Error( + `Invalid package configuration file at "${configFilePath}": ` + (e as Error).message); } } else { return null; diff --git a/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts b/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts index 1bf23464b51..e708955e2a8 100644 --- a/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts +++ b/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts @@ -95,7 +95,8 @@ export class EntryPointManifest { return entryPoints; } catch (e) { this.logger.warn( - `Unable to read the entry-point manifest for ${basePath}:\n`, e.stack || e.toString()); + `Unable to read the entry-point manifest for ${basePath}:\n`, + (e as Error).stack || (e as Error).toString()); return null; } } diff --git a/packages/compiler-cli/ngcc/src/rendering/source_maps.ts b/packages/compiler-cli/ngcc/src/rendering/source_maps.ts index 59098e45ddf..4c6c744414e 100644 --- a/packages/compiler-cli/ngcc/src/rendering/source_maps.ts +++ b/packages/compiler-cli/ngcc/src/rendering/source_maps.ts @@ -64,7 +64,7 @@ export function renderSourceAndMap( ]; } catch (e) { logger.error(`Error when flattening the source-map "${sourceMapPath}" for "${ - sourceFilePath}": ${e.toString()}`); + sourceFilePath}": ${(e as Error).toString()}`); return [ {path: sourceFilePath, contents: generatedContent}, {path: sourceMapPath, contents: mapHelpers.fromObject(generatedMap).toJSON()}, diff --git a/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts b/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts index ea40506334d..cf5cc3e0581 100644 --- a/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts +++ b/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts @@ -113,7 +113,7 @@ export class NewEntryPointFileWriter extends InPlaceFileWriter { this.fs.writeFile(newSourceMapPath, JSON.stringify(sourceMap)); } catch (e) { this.logger.warn(`Failed to process source-map at ${sourceMapPath}`); - this.logger.warn(e.message ?? e); + this.logger.warn((e as Error).message ?? e); } } } diff --git a/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts b/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts index 0741c4e6bb5..32e6cfd0de0 100644 --- a/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts +++ b/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts @@ -86,7 +86,7 @@ runInEachFileSystem(() => { try { await executor.execute(analyzeEntryPointsSpy, createCompilerFnSpy); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(analyzeEntryPointsSpy).toHaveBeenCalledWith(); expect(createCompilerFnSpy).not.toHaveBeenCalled(); @@ -101,7 +101,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('master runner error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -121,7 +121,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.write() error'); expect(masterRunSpy).not.toHaveBeenCalled(); @@ -141,7 +141,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.remove() error'); expect(lockFileLog).toEqual(['write()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts b/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts index 81ff7a1ac2e..5f365949654 100644 --- a/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts +++ b/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts @@ -65,7 +65,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(errorFn, createCompileFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('analyze error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -79,7 +79,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(oneTask, createErrorCompileFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('compile error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -100,7 +100,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(analyzeFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.write() error'); expect(lockFileLog).toEqual(['write()']); @@ -118,7 +118,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(noTasks, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.remove() error'); expect(lockFileLog).toEqual(['write()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts b/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts index 29d5a6311e5..721f45e14b8 100644 --- a/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts +++ b/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts @@ -1587,7 +1587,7 @@ runInEachFileSystem(() => { propertiesToConsider: ['esm2015', 'esm5'], }); fail('should have thrown'); - } catch (e) { + } catch (e: any) { expect(e.message).toContain( 'Failed to compile entry-point test-package (`esm2015` as esm2015) due to compilation errors:'); expect(e.message).toContain('NG1010'); @@ -2889,7 +2889,7 @@ runInEachFileSystem(() => { propertiesToConsider: ['es2015'] }); fail('should have thrown'); - } catch (e) { + } catch (e: any) { expect(e.message).toContain( 'Failed to compile entry-point fatal-error (`es2015` as esm2015) due to compilation errors:'); expect(e.message).toContain('NG2001'); diff --git a/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts b/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts index cfee2cfd010..28812124cbb 100644 --- a/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts +++ b/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts @@ -44,7 +44,7 @@ runInEachFileSystem(() => { throw new Error('ERROR'); }); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('ERROR'); expect(log).toEqual(['write()', 'fn()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts b/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts index b1445c40857..d8d7952b34e 100644 --- a/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts +++ b/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts @@ -38,7 +38,7 @@ runInEachFileSystem(() => { throw new Error('ERROR'); }); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('ERROR'); expect(log).toEqual(['write()', 'fn()', 'remove()']); diff --git a/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts b/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts index b0d1016fe01..7e920929903 100644 --- a/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts +++ b/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts @@ -111,7 +111,7 @@ export class SourceFileLoader { return new SourceFile(sourcePath, contents, sourceMapInfo, sources, this.fs); } catch (e) { this.logger.warn( - `Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`); + `Unable to fully load ${sourcePath} for source-map flattening: ${(e as Error).message}`); return null; } finally { // We are finished with this recursion so revert the paths being tracked @@ -166,8 +166,8 @@ export class SourceFileLoader { origin: ContentOrigin.FileSystem, }; } catch (e) { - this.logger.warn( - `Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`); + this.logger.warn(`Unable to fully load ${sourcePath} for source-map flattening: ${ + (e as Error).message}`); return null; } } diff --git a/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts b/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts index 63c86058b42..53804633ed9 100644 --- a/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts +++ b/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts @@ -12,6 +12,7 @@ import {resolve} from 'path'; import {AbsoluteFsPath, FileSystem, getFileSystem} from '../../file_system'; import {Folder, MockFileSystemPosix, TestFile} from '../../file_system/testing'; + import {getAngularPackagesFromRunfiles, resolveNpmTreeArtifact} from './runfile_helpers'; export function loadTestFiles(files: TestFile[]) { @@ -132,7 +133,7 @@ export function loadTestDirectory( fs.writeFile(targetPath, readFileSync(srcPath, 'utf-8')); } } catch (e) { - console.warn(`Failed to add ${srcPath} to the mock file-system: ${e.message}`); + console.warn(`Failed to add ${srcPath} to the mock file-system: ${(e as Error).message}`); } }); } diff --git a/packages/compiler-cli/src/perform_compile.ts b/packages/compiler-cli/src/perform_compile.ts index 87c97652b7e..e6f23f51b3d 100644 --- a/packages/compiler-cli/src/perform_compile.ts +++ b/packages/compiler-cli/src/perform_compile.ts @@ -133,7 +133,7 @@ export function readConfiguration( } catch (e) { const errors: ts.Diagnostic[] = [{ category: ts.DiagnosticCategory.Error, - messageText: e.stack, + messageText: (e as Error).stack ?? (e as Error).message, file: undefined, start: undefined, length: undefined, @@ -267,7 +267,7 @@ export function performCompilation({ program = undefined; allDiagnostics.push({ category: ts.DiagnosticCategory.Error, - messageText: e.stack, + messageText: (e as Error).stack ?? (e as Error).message, code: api.UNKNOWN_ERROR_CODE, file: undefined, start: undefined, diff --git a/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts b/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts index e4747947063..f1ecd56e4e5 100644 --- a/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts +++ b/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts @@ -59,8 +59,8 @@ function loadTestCasesFile( try { return JSON.parse(fs.readFile(testCasesPath)) as {cases: TestCaseJson | TestCaseJson[]}; } catch (e) { - throw new Error( - `Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${e.message}`); + throw new Error(`Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${ + (e as Error).message}`); } } diff --git a/packages/compiler-cli/test/test_support.ts b/packages/compiler-cli/test/test_support.ts index e0dff2785bf..b724ff89783 100644 --- a/packages/compiler-cli/test/test_support.ts +++ b/packages/compiler-cli/test/test_support.ts @@ -142,7 +142,7 @@ export function setupBazelTo(tmpDirPath: string) { const rxjsSource = resolveNpmTreeArtifact('rxjs', 'index.js'); const rxjsDest = path.join(nodeModulesPath, 'rxjs'); fs.symlinkSync(rxjsSource, rxjsDest, 'junction'); - } catch (e) { + } catch (e: any) { if (e.code !== 'MODULE_NOT_FOUND') throw e; } } diff --git a/packages/core/schematics/tsconfig.json b/packages/core/schematics/tsconfig.json index 19f7b0654d7..dbeb0be6f63 100644 --- a/packages/core/schematics/tsconfig.json +++ b/packages/core/schematics/tsconfig.json @@ -2,23 +2,34 @@ "compilerOptions": { "noImplicitReturns": true, "noImplicitOverride": true, - "useUnknownInCatchVariables": false, "noFallthroughCasesInSwitch": true, "esModuleInterop": true, "strict": true, "moduleResolution": "node", "target": "es2019", - "lib": ["es2019"], - "types": ["jasmine"], + "lib": [ + "es2019" + ], + "types": [ + "jasmine" + ], "baseUrl": ".", "paths": { - "@angular/core": ["../"], - "@angular/compiler": ["../../compiler"], - "@angular/compiler-cli": ["../../compiler-cli"], - "@angular/compiler-cli/private/*": ["../../compiler-cli/private/*"] + "@angular/core": [ + "../" + ], + "@angular/compiler": [ + "../../compiler" + ], + "@angular/compiler-cli": [ + "../../compiler-cli" + ], + "@angular/compiler-cli/private/*": [ + "../../compiler-cli/private/*" + ] } }, "bazelOptions": { "suppressTsconfigOverrideWarnings": true } -} +} \ No newline at end of file diff --git a/packages/core/src/di/r3_injector.ts b/packages/core/src/di/r3_injector.ts index 641a348dcf8..48c36dfbe6b 100644 --- a/packages/core/src/di/r3_injector.ts +++ b/packages/core/src/di/r3_injector.ts @@ -222,7 +222,7 @@ export class R3Injector { null : notFoundValue; return nextInjector.get(token, notFoundValue); - } catch (e) { + } catch (e: any) { if (e.name === 'NullInjectorError') { const path: any[] = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []; path.unshift(stringify(token)); diff --git a/packages/core/src/di/reflective_injector.ts b/packages/core/src/di/reflective_injector.ts index 64b72a21055..031b68a1aca 100644 --- a/packages/core/src/di/reflective_injector.ts +++ b/packages/core/src/di/reflective_injector.ts @@ -362,7 +362,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { try { deps = ResolvedReflectiveFactory.dependencies.map(dep => this._getByReflectiveDependency(dep)); - } catch (e) { + } catch (e: any) { if (e.addKey) { e.addKey(this, provider.key); } @@ -373,7 +373,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { try { obj = factory(...deps); } catch (e) { - throw instantiationError(this, e, e.stack, provider.key); + throw instantiationError(this, e, (e as Error).stack, provider.key); } return obj; diff --git a/packages/core/test/animation/animation_integration_spec.ts b/packages/core/test/animation/animation_integration_spec.ts index 52b1337888b..5b126bba3f3 100644 --- a/packages/core/test/animation/animation_integration_spec.ts +++ b/packages/core/test/animation/animation_integration_spec.ts @@ -3843,7 +3843,7 @@ describe('animation tests', function() { try { fixture.detectChanges(); } catch (e) { - errorMsg = e.message; + errorMsg = (e as Error).message; } expect(errorMsg).toMatch(/@foo has failed due to:/); diff --git a/packages/core/test/compiler/compiler_facade_spec.ts b/packages/core/test/compiler/compiler_facade_spec.ts index 6878c86442e..399a3301a20 100644 --- a/packages/core/test/compiler/compiler_facade_spec.ts +++ b/packages/core/test/compiler/compiler_facade_spec.ts @@ -20,8 +20,9 @@ describe('getCompilerFacade', () => { getCompilerFacade({usage: JitCompilerUsage.Decorator, kind: 'directive', type: TestClass}); fail('Error expected as compiler facade is not available'); } catch (e) { - expect(e.message).toEqual( - `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. + expect((e as Error).message) + .toEqual( + `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is discouraged for production use-cases! Consider using AOT mode instead. Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server', @@ -35,8 +36,9 @@ or manually provide the compiler with 'import "@angular/compiler";' before boots {usage: JitCompilerUsage.PartialDeclaration, kind: 'directive', type: TestClass}); fail('Error expected as compiler facade is not available'); } catch (e) { - expect(e.message).toEqual( - `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. + expect((e as Error).message) + .toEqual( + `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. The directive is part of a library that has been partially compiled. However, the Angular Linker has not processed the library such that JIT compilation is used as fallback. diff --git a/packages/core/test/di/reflective_injector_spec.ts b/packages/core/test/di/reflective_injector_spec.ts index bc9a21928c4..f51e6cf5009 100644 --- a/packages/core/test/di/reflective_injector_spec.ts +++ b/packages/core/test/di/reflective_injector_spec.ts @@ -300,7 +300,7 @@ describe(`injector`, () => { try { injector.get(Car); throw 'Must throw'; - } catch (e) { + } catch (e: any) { expect(e.message).toContain( `Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); expect(getOriginalError(e) instanceof Error).toBeTruthy(); diff --git a/packages/core/test/linker/change_detection_integration_spec.ts b/packages/core/test/linker/change_detection_integration_spec.ts index 990e9a9e879..a856d46dcb9 100644 --- a/packages/core/test/linker/change_detection_integration_spec.ts +++ b/packages/core/test/linker/change_detection_integration_spec.ts @@ -748,7 +748,7 @@ describe(`ChangeDetection`, () => { try { ctx.detectChanges(false); } catch (e) { - expect(e.message).toBe('Boom!'); + expect((e as Error).message).toBe('Boom!'); errored = true; } expect(errored).toBe(true); @@ -760,7 +760,7 @@ describe(`ChangeDetection`, () => { try { ctx.detectChanges(false); } catch (e) { - expect(e.message).toBe('Boom!'); + expect((e as Error).message).toBe('Boom!'); throw new Error('Second detectChanges() should not have called ngOnInit.'); } expect(directiveLog.filter(['ngOnInit'])).toEqual([]); diff --git a/packages/core/test/linker/integration_spec.ts b/packages/core/test/linker/integration_spec.ts index a348d7bf843..aed680db501 100644 --- a/packages/core/test/linker/integration_spec.ts +++ b/packages/core/test/linker/integration_spec.ts @@ -1426,8 +1426,8 @@ describe('integration tests', function() { try { TestBed.createComponent(ComponentWithoutView); } catch (e) { - expect(e.message).toContain( - `No template specified for component ${stringify(ComponentWithoutView)}`); + expect((e as Error).message) + .toContain(`No template specified for component ${stringify(ComponentWithoutView)}`); } }); }); diff --git a/packages/localize/src/translate.ts b/packages/localize/src/translate.ts index 838df1aedde..2d018d0a6cc 100644 --- a/packages/localize/src/translate.ts +++ b/packages/localize/src/translate.ts @@ -93,7 +93,7 @@ export function translate(messageParts: TemplateStringsArray, substitutions: rea try { return _translate($localize.TRANSLATIONS, messageParts, substitutions); } catch (e) { - console.warn(e.message); + console.warn((e as Error).message); return [messageParts, substitutions]; } } diff --git a/packages/localize/tools/src/source_file_utils.ts b/packages/localize/tools/src/source_file_utils.ts index 6f43b0a7ba0..1dc5ef8eb70 100644 --- a/packages/localize/tools/src/source_file_utils.ts +++ b/packages/localize/tools/src/source_file_utils.ts @@ -374,7 +374,7 @@ export function translate( missingTranslation: DiagnosticHandlingStrategy): [TemplateStringsArray, readonly any[]] { try { return ɵtranslate(translations, messageParts, substitutions); - } catch (e) { + } catch (e: any) { if (ɵisMissingTranslationError(e)) { diagnostics.add(missingTranslation, e.message); // Return the parsed message because this will have the meta blocks stripped diff --git a/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts b/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts index 725cc512ad8..17576fd3374 100644 --- a/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts +++ b/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts @@ -42,7 +42,7 @@ export class AssetTranslationHandler implements TranslationHandler { this.fs.ensureDir(this.fs.dirname(outputPath)); this.fs.writeFile(outputPath, contents); } catch (e) { - diagnostics.error(e.message); + diagnostics.error((e as Error).message); } } } diff --git a/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts b/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts index 2256042f806..3bd8a9cd7d7 100644 --- a/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts +++ b/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts @@ -6,8 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ import {absoluteFrom, AbsoluteFsPath, FileSystem, PathSegment} from '@angular/compiler-cli/private/localize'; -import {parseSync, transformFromAstSync, types as t} from '../../babel_core'; +import {parseSync, transformFromAstSync, types as t} from '../../babel_core'; import {Diagnostics} from '../../diagnostics'; import {TranslatePluginOptions} from '../../source_file_utils'; import {OutputPathFn} from '../output_path'; @@ -103,7 +103,7 @@ export class SourceFileTranslationHandler implements TranslationHandler { this.fs.ensureDir(this.fs.dirname(outputPath)); this.fs.writeFile(outputPath, contents); } catch (e) { - diagnostics.error(e.message); + diagnostics.error((e as Error).message); } } } diff --git a/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts b/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts index df247b1801f..9b5b11569fe 100644 --- a/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts +++ b/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts @@ -27,6 +27,6 @@ export function serializeTranslationMessage(element: Element, config: MessageSer const translation = serializer.serialize(rootNodes); return {translation, parseErrors, serializeErrors: []}; } catch (e) { - return {translation: null, parseErrors, serializeErrors: [e]}; + return {translation: null, parseErrors, serializeErrors: [e as ParseError]}; } } diff --git a/packages/misc/angular-in-memory-web-api/src/backend-service.ts b/packages/misc/angular-in-memory-web-api/src/backend-service.ts index 71a62384ead..6e01ba0bebf 100644 --- a/packages/misc/angular-in-memory-web-api/src/backend-service.ts +++ b/packages/misc/angular-in-memory-web-api/src/backend-service.ts @@ -320,7 +320,7 @@ export abstract class BackendService { try { resOptions = resOptionsFactory(); } catch (error) { - const err = error.message || error; + const err = (error as Error).message || error; resOptions = this.createErrorResponseOptions('', STATUS.INTERNAL_SERVER_ERROR, `${err}`); } @@ -550,7 +550,7 @@ export abstract class BackendService { const resourceUrl = urlRoot + apiBase + collectionName + '/'; return {apiBase, collectionName, id, query, resourceUrl}; } catch (err) { - const msg = `unable to parse url '${url}'; original error: ${err.message}`; + const msg = `unable to parse url '${url}'; original error: ${(err as Error).message}`; throw new Error(msg); } } @@ -565,7 +565,7 @@ export abstract class BackendService { try { item.id = id || this.genId(collection, collectionName); } catch (err) { - const emsg: string = err.message || ''; + const emsg: string = (err as Error).message || ''; if (/id type is non-numeric/.test(emsg)) { return this.createErrorResponseOptions(url, STATUS.UNPROCESSABLE_ENTRY, emsg); } else { @@ -597,7 +597,7 @@ export abstract class BackendService { } else { collection[existingIx] = item; return this.config.post204 ? {headers, status: STATUS.NO_CONTENT} : // successful; no content - {headers, body, status: STATUS.OK}; // successful; return entity + {headers, body, status: STATUS.OK}; // successful; return entity } } @@ -621,7 +621,7 @@ export abstract class BackendService { if (existingIx > -1) { collection[existingIx] = item; return this.config.put204 ? {headers, status: STATUS.NO_CONTENT} : // successful; no content - {headers, body, status: STATUS.OK}; // successful; return entity + {headers, body, status: STATUS.OK}; // successful; return entity } else if (this.config.put404) { // item to update not found; use POST to create new item for this id. return this.createErrorResponseOptions( @@ -651,9 +651,9 @@ export abstract class BackendService { protected resetDb(reqInfo?: RequestInfo): Observable { this.dbReadySubject && this.dbReadySubject.next(false); const db = this.inMemDbService.createDb(reqInfo); - const db$ = db instanceof Observable ? - db : - typeof (db as any).then === 'function' ? from(db as Promise) : of(db); + const db$ = db instanceof Observable ? db : + typeof (db as any).then === 'function' ? from(db as Promise) : + of(db); db$.pipe(first()).subscribe((d: {}) => { this.db = d; this.dbReadySubject && this.dbReadySubject.next(true); diff --git a/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts index 92701755bf5..139b4abe154 100644 --- a/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts +++ b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts @@ -57,7 +57,7 @@ export class HttpClientBackendService extends BackendService implements HttpBack return this.handleRequest(req); } catch (error) { - const err = error.message || error; + const err = (error as Error).message || error; const resOptions = this.createErrorResponseOptions(req.url, STATUS.INTERNAL_SERVER_ERROR, `${err}`); return this.createResponse$(() => resOptions); @@ -93,7 +93,7 @@ export class HttpClientBackendService extends BackendService implements HttpBack protected override createPassThruBackend() { try { return new HttpXhrBackend(this.xhrFactory); - } catch (ex) { + } catch (ex: any) { ex.message = 'Cannot create passThru404 backend; ' + (ex.message || ''); throw ex; } diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index 8c984253a7e..8842a0caf12 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -1285,7 +1285,7 @@ export class Router { try { urlTree = this.urlSerializer.parse(url); } catch (e) { - urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url); + urlTree = this.malformedUriErrorHandler(e as URIError, this.urlSerializer, url); } return urlTree; } diff --git a/packages/service-worker/cli/tsconfig.json b/packages/service-worker/cli/tsconfig.json index 697d364ab3f..b74643fc63f 100644 --- a/packages/service-worker/cli/tsconfig.json +++ b/packages/service-worker/cli/tsconfig.json @@ -10,14 +10,17 @@ "outDir": "../../../dist/all/@angular/service-worker/cli-custom", "noImplicitAny": true, "noImplicitOverride": true, - "useUnknownInCatchVariables": false, "noFallthroughCasesInSwitch": true, "rootDir": ".", "paths": { - "@angular/service-worker/config": ["../../../dist/packages/service-worker/config"] + "@angular/service-worker/config": [ + "../../../dist/packages/service-worker/config" + ] }, "inlineSourceMap": true, - "lib": ["es2020"], + "lib": [ + "es2020" + ], "target": "es2020", "typeRoots": [], "types": [ @@ -28,4 +31,4 @@ "main.ts", "../../../node_modules/@types/node/index.d.ts" ] -} +} \ No newline at end of file diff --git a/packages/service-worker/test/comm_spec.ts b/packages/service-worker/test/comm_spec.ts index e76914957d8..9b272db4cea 100644 --- a/packages/service-worker/test/comm_spec.ts +++ b/packages/service-worker/test/comm_spec.ts @@ -213,7 +213,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('Not subscribed to push notifications.'); + expect((err as Error).message).toBe('Not subscribed to push notifications.'); } }); @@ -234,7 +234,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('foo'); + expect((err as Error).message).toBe('foo'); } }); @@ -246,7 +246,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('Unsubscribe failed!'); + expect((err as Error).message).toBe('Unsubscribe failed!'); } }); diff --git a/packages/service-worker/worker/src/data.ts b/packages/service-worker/worker/src/data.ts index 22475bc9544..6a1e60307ce 100644 --- a/packages/service-worker/worker/src/data.ts +++ b/packages/service-worker/worker/src/data.ts @@ -284,7 +284,8 @@ export class DataGroup { } catch (err) { // Writing lru cache table failed. This could be a result of a full storage. // Continue serving clients as usual. - this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`); + this.debugHandler.log( + err as Error, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`); // TODO: Better detect/handle full storage; e.g. using // [navigator.storage](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorStorage/storage). } @@ -465,7 +466,7 @@ export class DataGroup { // Saving the API response failed. This could be a result of a full storage. // Since this data is cached lazily and temporarily, continue serving clients as usual. this.debugHandler.log( - err, + err as Error, `DataGroup(${this.config.name}@${this.config.version}).safeCacheResponse(${ req.url}, status: ${res.status})`); diff --git a/packages/service-worker/worker/src/driver.ts b/packages/service-worker/worker/src/driver.ts index d77c4eebdfc..7a1f3f1c6d9 100644 --- a/packages/service-worker/worker/src/driver.ts +++ b/packages/service-worker/worker/src/driver.ts @@ -142,7 +142,7 @@ export class Driver implements Debuggable, UpdateSource { await this.cleanupOldSwCaches(); } catch (err) { // Nothing to do - cleanup failed. Just log it. - this.debugger.log(err, 'cleanupOldSwCaches @ activate: cleanup-old-sw-caches'); + this.debugger.log(err as Error, 'cleanupOldSwCaches @ activate: cleanup-old-sw-caches'); } }); })()); @@ -409,7 +409,7 @@ export class Driver implements Debuggable, UpdateSource { } catch (e) { client.postMessage({ ...response, - error: e.toString(), + error: (e as Error).toString(), }); } } @@ -479,7 +479,7 @@ export class Driver implements Debuggable, UpdateSource { // Handle the request. First try the AppVersion. If that doesn't work, fall back on the // network. res = await appVersion.handleFetch(event.request, event); - } catch (err) { + } catch (err: any) { if (err.isUnrecoverableState) { await this.notifyClientsAboutUnrecoverableState(appVersion, err.message); } @@ -632,7 +632,7 @@ export class Driver implements Debuggable, UpdateSource { // it fails, then full initialization was attempted and failed. await this.scheduleInitialization(this.versions.get(hash)!); } catch (err) { - this.debugger.log(err, `initialize: schedule init of ${hash}`); + this.debugger.log(err as Error, `initialize: schedule init of ${hash}`); return false; } })); @@ -781,7 +781,7 @@ export class Driver implements Debuggable, UpdateSource { const initialize = async () => { try { await appVersion.initializeFully(); - } catch (err) { + } catch (err: any) { this.debugger.log(err, `initializeFully for ${appVersion.manifestHash}`); await this.versionFailed(appVersion, err); } @@ -887,7 +887,7 @@ export class Driver implements Debuggable, UpdateSource { return true; } catch (err) { - this.debugger.log(err, `Error occurred while updating to manifest ${hash}`); + this.debugger.log(err as Error, `Error occurred while updating to manifest ${hash}`); this.state = DriverReadyState.EXISTING_CLIENTS_ONLY; this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`; @@ -966,7 +966,7 @@ export class Driver implements Debuggable, UpdateSource { } catch (err) { // Oh well? Not much that can be done here. These caches will be removed on the next attempt // or when the SW revs its format version, which happens from time to time. - this.debugger.log(err, 'cleanupCaches'); + this.debugger.log(err as Error, 'cleanupCaches'); } } @@ -1167,7 +1167,7 @@ export class Driver implements Debuggable, UpdateSource { try { return await this.scope.fetch(req); } catch (err) { - this.debugger.log(err, `Driver.fetch(${req.url})`); + this.debugger.log(err as Error, `Driver.fetch(${req.url})`); return this.adapter.newResponse(null, { status: 504, statusText: 'Gateway Timeout', diff --git a/packages/service-worker/worker/src/idle.ts b/packages/service-worker/worker/src/idle.ts index 36bae8d1c06..0ba38747de0 100644 --- a/packages/service-worker/worker/src/idle.ts +++ b/packages/service-worker/worker/src/idle.ts @@ -73,7 +73,7 @@ export class IdleScheduler { try { await task.run(); } catch (err) { - this.debug.log(err, `while running idle task ${task.desc}`); + this.debug.log(err as Error, `while running idle task ${task.desc}`); } }, Promise.resolve()); } diff --git a/packages/tsconfig-build.json b/packages/tsconfig-build.json index 46aff24e958..094386ee286 100644 --- a/packages/tsconfig-build.json +++ b/packages/tsconfig-build.json @@ -11,14 +11,16 @@ "noImplicitOverride": true, "strictNullChecks": true, "esModuleInterop": true, - "useUnknownInCatchVariables": false, "strict": true, "strictPropertyInitialization": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", "module": "es2020", "target": "es2020", - "lib": ["es2020", "dom"], + "lib": [ + "es2020", + "dom" + ], "skipLibCheck": true, // don't auto-discover @types/node, it results in a ///