From 23fd1f6ae0b6d6382849708402ff2eab2f620b5d Mon Sep 17 00:00:00 2001 From: Ryan Waskiewicz Date: Fri, 8 Jul 2022 15:13:41 -0400 Subject: [PATCH] chore(exports): remove unused exports (#3415) resolve utility unused exports: this commit resolves issues found in the `src/utils` directory related to unused exports. 'ts-prune' seems to have issues when a file includes a direct import and an aliased import to the same location: ```typescript import { foo } from '../somewhere'; import * as Foo from '../somewhere'; ``` doing so causes erroneous unused exports (or so it seems). the import of `ParsePackageJsonResult` has been removed in favor of a simple namespaced/aliased import (either would work here, this was an arbitrary decision that minimizes code churn. we could have just as easily directly imported everything from 'util'). cases where helper functions were never used have been removed. otherwise, unnecessary export keywords were removed when a property/function/etc. was used in the file in which it was defined --- remove unused export TERMINAL_INFO --- remove unused transpilerId const this commit removes an unused constant from the `version.ts` file. in addition to verifying that the identifier and its string contents are not used in the codebase, the following was run to look for other commits containing the string: ``` git log -S transpilerId --source --all ``` although commits were found containing 'transpilerId', no existing usages of the string were found --- remove unused host-config this commit began by removing two unused exports from `host-config.ts`, `generateHostConfig` and `DEFAULT_MODE`. from those two deletions, additional functions and constants could be successively deleted, with each deletion begetting another deletion, and another deletion, etc. by the end, a single constant was left, `HOST_CONFIG_FILENAME`. that constant is used in a single file, in a single place. as a result, the filename was inlined --- src/cli/telemetry/helpers.ts | 2 - .../config/validate-service-worker.ts | 3 +- src/compiler/prerender/host-config.ts | 282 ------------------ src/utils/constants.ts | 1 - src/utils/helpers.ts | 3 +- src/utils/test/util.spec.ts | 9 +- src/version.ts | 1 - 7 files changed, 6 insertions(+), 295 deletions(-) delete mode 100644 src/compiler/prerender/host-config.ts diff --git a/src/cli/telemetry/helpers.ts b/src/cli/telemetry/helpers.ts index 515a749e56e..a764022fd27 100644 --- a/src/cli/telemetry/helpers.ts +++ b/src/cli/telemetry/helpers.ts @@ -11,8 +11,6 @@ export const tryFn = async Promise, R>(fn: T, return null; }; -export declare const TERMINAL_INFO: d.TerminalInfo; - export const isInteractive = (sys: d.CompilerSystem, flags: ConfigFlags, object?: d.TerminalInfo): boolean => { const terminalInfo = object || diff --git a/src/compiler/config/validate-service-worker.ts b/src/compiler/config/validate-service-worker.ts index 8109e468040..9b145e2096c 100644 --- a/src/compiler/config/validate-service-worker.ts +++ b/src/compiler/config/validate-service-worker.ts @@ -1,5 +1,4 @@ import type * as d from '../../declarations'; -import { HOST_CONFIG_FILENAME } from '../prerender/host-config'; import { isAbsolute, join } from 'path'; import { isString } from '@utils'; @@ -67,7 +66,7 @@ export const validateServiceWorker = (config: d.ValidatedConfig, outputTarget: d const addGlobIgnores = (config: d.Config, globIgnores: string[]) => { globIgnores.push( - `**/${HOST_CONFIG_FILENAME}`, + `**/host.config.json`, // the filename of the host configuration `**/*.system.entry.js`, `**/*.system.js`, `**/${config.fsNamespace}.js`, diff --git a/src/compiler/prerender/host-config.ts b/src/compiler/prerender/host-config.ts deleted file mode 100644 index 6a4133771ec..00000000000 --- a/src/compiler/prerender/host-config.ts +++ /dev/null @@ -1,282 +0,0 @@ -import type * as d from '../../declarations'; -import { join, relative } from 'path'; - -export const generateHostConfig = async ( - config: d.Config, - compilerCtx: d.CompilerCtx, - outputTarget: d.OutputTargetWww, - entryModules: d.EntryModule[], - hydrateResults: d.HydrateResults[] -) => { - const hostConfig: d.HostConfig = { - hosting: { - rules: [], - }, - }; - - hydrateResults = hydrateResults.sort((a, b) => { - if (a.url.toLowerCase() < b.url.toLowerCase()) return -1; - if (a.url.toLowerCase() > b.url.toLowerCase()) return 1; - return 0; - }); - - for (const hydrateResult of hydrateResults) { - const hostRule = generateHostRule(outputTarget, entryModules, hydrateResult); - if (hostRule) { - hostConfig.hosting.rules.push(hostRule); - } - } - - addDefaults(outputTarget, hostConfig); - - const hostConfigFilePath = join(outputTarget.appDir, HOST_CONFIG_FILENAME); - - await mergeUserHostConfigFile(config, compilerCtx, hostConfig); - - await compilerCtx.fs.writeFile(hostConfigFilePath, JSON.stringify(hostConfig, null, 2)); -}; - -export const generateHostRule = ( - outputTarget: d.OutputTargetWww, - entryModules: d.EntryModule[], - hydrateResults: d.HydrateResults -) => { - const hostRule: d.HostRule = { - include: hydrateResults.pathname, - headers: generateHostRuleHeaders(outputTarget, entryModules, hydrateResults), - }; - - if (hostRule.headers.length === 0) { - return null; - } - - return hostRule; -}; - -export const generateHostRuleHeaders = ( - outputTarget: d.OutputTargetWww, - entryModules: d.EntryModule[], - hydrateResults: d.HydrateResults -) => { - const hostRuleHeaders: d.HostRuleHeader[] = []; - - addStyles(hostRuleHeaders, hydrateResults); - addCoreJs(outputTarget, 'compilerCtx.appCoreWWWPath', hostRuleHeaders); - addBundles(outputTarget, entryModules, hostRuleHeaders, hydrateResults.components); - addScripts(hostRuleHeaders, hydrateResults); - addImgs(hostRuleHeaders, hydrateResults); - - return hostRuleHeaders; -}; - -const addCoreJs = (outputTarget: d.OutputTargetWww, appCoreWWWPath: string, hostRuleHeaders: d.HostRuleHeader[]) => { - const url = getUrlFromFilePath(outputTarget, appCoreWWWPath); - - hostRuleHeaders.push(formatLinkRelPreloadHeader(url)); -}; - -export const addBundles = ( - outputTarget: d.OutputTargetWww, - entryModules: d.EntryModule[], - hostRuleHeaders: d.HostRuleHeader[], - components: d.HydrateComponent[] -) => { - components = sortComponents(components); - - const bundleIds = getBundleIds(entryModules, components); - for (const bundleId of bundleIds) { - if (hostRuleHeaders.length < MAX_LINK_REL_PRELOAD_COUNT) { - const bundleUrl = getBundleUrl(outputTarget, bundleId); - - hostRuleHeaders.push(formatLinkRelPreloadHeader(bundleUrl)); - } - } -}; - -export const getBundleIds = (_entryModules: d.EntryModule[], _components: d.HydrateComponent[]) => { - const bundleIds: string[] = []; - - // components.forEach(cmp => { - // entryModules.forEach(mb => { - // const moduleFile = mb.moduleFiles.find(mf => mf.cmpCompilerMeta && mf.cmpCompilerMeta.tagName === cmp.tag); - // if (!moduleFile) { - // return; - // } - - // let bundleId: string; - // if (typeof moduleFile.cmpCompilerMeta.bundleIds === 'string') { - // bundleId = moduleFile.cmpCompilerMeta.bundleIds; - // } else { - - // bundleId = (moduleFile.cmpCompilerMeta.bundleIds as d.BundleIds)[DEFAULT_MODE]; - // if (!bundleId) { - // bundleId = (moduleFile.cmpCompilerMeta.bundleIds as d.BundleIds)[DEFAULT_STYLE_MODE]; - // } - // } - - // if (bundleId && bundleIds.indexOf(bundleId) === -1) { - // bundleIds.push(bundleId); - // } - // }); - // }); - - return bundleIds; -}; - -const getBundleUrl = (outputTarget: d.OutputTargetWww, _bundleId: string) => { - // const unscopedFileName = 'getBrowserFilename(bundleId, false)'; - const unscopedWwwBuildPath = 'sys.path.join(getAppBuildDir(config, outputTarget), unscopedFileName)'; - return getUrlFromFilePath(outputTarget, unscopedWwwBuildPath); -}; - -export const getUrlFromFilePath = (outputTarget: d.OutputTargetWww, filePath: string) => { - let url = join('/', relative(outputTarget.appDir, filePath)); - - url = outputTarget.baseUrl + url.substring(1); - - return url; -}; - -export const sortComponents = (components: d.HydrateComponent[]) => { - return components.sort((a, b) => { - if (a.depth > b.depth) return -1; - if (a.depth < b.depth) return 1; - if (a.count > b.count) return -1; - if (a.count < b.count) return 1; - if (a.tag < b.tag) return -1; - if (a.tag > b.tag) return 1; - return 0; - }); -}; - -const addStyles = (hostRuleHeaders: d.HostRuleHeader[], hydrateResults: d.HydrateResults) => { - for (const style of hydrateResults.styles) { - if (hostRuleHeaders.length >= MAX_LINK_REL_PRELOAD_COUNT) { - return; - } - - const url = new URL(style.href); - if (url.hostname === hydrateResults.hostname) { - hostRuleHeaders.push(formatLinkRelPreloadHeader(url.pathname)); - } - } -}; - -const addScripts = (hostRuleHeaders: d.HostRuleHeader[], hydrateResults: d.HydrateResults) => { - for (const script of hydrateResults.scripts) { - if (hostRuleHeaders.length >= MAX_LINK_REL_PRELOAD_COUNT) { - return; - } - - const url = new URL(script.src); - if (url.hostname === hydrateResults.hostname) { - hostRuleHeaders.push(formatLinkRelPreloadHeader(url.pathname)); - } - } -}; - -const addImgs = (hostRuleHeaders: d.HostRuleHeader[], hydrateResults: d.HydrateResults) => { - for (const img of hydrateResults.imgs) { - if (hostRuleHeaders.length >= MAX_LINK_REL_PRELOAD_COUNT) { - return; - } - - const url = new URL(img.src); - if (url.hostname === hydrateResults.hostname) { - hostRuleHeaders.push(formatLinkRelPreloadHeader(url.pathname)); - } - } -}; - -export const formatLinkRelPreloadHeader = (url: string) => { - const header: d.HostRuleHeader = { - name: 'Link', - value: formatLinkRelPreloadValue(url), - }; - return header; -}; - -const formatLinkRelPreloadValue = (url: string) => { - const parts = [`<${url}>`, `rel=preload`]; - - const ext = url.split('.').pop().toLowerCase(); - if (ext === SCRIPT_EXT) { - parts.push(`as=script`); - } else if (ext === STYLE_EXT) { - parts.push(`as=style`); - } else if (IMG_EXTS.indexOf(ext) > -1) { - parts.push(`as=image`); - } - - return parts.join(';'); -}; - -const addDefaults = (outputTarget: d.OutputTargetWww, hostConfig: d.HostConfig) => { - addBuildDirCacheControl(outputTarget, hostConfig); - addServiceWorkerNoCacheControl(outputTarget, hostConfig); -}; - -const addBuildDirCacheControl = (outputTarget: d.OutputTargetWww, hostConfig: d.HostConfig) => { - const url = getUrlFromFilePath(outputTarget, 'getAppBuildDir(config, outputTarget)'); - - hostConfig.hosting.rules.push({ - include: join(url, '**'), - headers: [ - { - name: `Cache-Control`, - value: `public, max-age=31536000`, - }, - ], - }); -}; - -const addServiceWorkerNoCacheControl = (outputTarget: d.OutputTargetWww, hostConfig: d.HostConfig) => { - if (!outputTarget.serviceWorker) { - return; - } - - const url = getUrlFromFilePath(outputTarget, outputTarget.serviceWorker.swDest); - - hostConfig.hosting.rules.push({ - include: url, - headers: [ - { - name: `Cache-Control`, - value: `no-cache, no-store, must-revalidate`, - }, - ], - }); -}; - -const mergeUserHostConfigFile = async (config: d.Config, compilerCtx: d.CompilerCtx, hostConfig: d.HostConfig) => { - const hostConfigFilePath = join(config.srcDir, HOST_CONFIG_FILENAME); - try { - const userHostConfigStr = await compilerCtx.fs.readFile(hostConfigFilePath); - - const userHostConfig = JSON.parse(userHostConfigStr) as d.HostConfig; - - mergeUserHostConfig(userHostConfig, hostConfig); - } catch (e) {} -}; - -export const mergeUserHostConfig = (userHostConfig: d.HostConfig, hostConfig: d.HostConfig) => { - if (!userHostConfig || !userHostConfig.hosting) { - return; - } - - if (!Array.isArray(userHostConfig.hosting.rules)) { - return; - } - - const rules = userHostConfig.hosting.rules.concat(hostConfig.hosting.rules); - - hostConfig.hosting.rules = rules; -}; - -export const DEFAULT_MODE = 'md'; -const MAX_LINK_REL_PRELOAD_COUNT = 6; -export const HOST_CONFIG_FILENAME = 'host.config.json'; - -const IMG_EXTS = ['png', 'gif', 'svg', 'jpg', 'jpeg', 'webp']; -const STYLE_EXT = 'css'; -const SCRIPT_EXT = 'js'; diff --git a/src/utils/constants.ts b/src/utils/constants.ts index 3da37c2790b..2952b9540a5 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -82,7 +82,6 @@ export const EMPTY_OBJ: any = {}; export const SVG_NS = 'http://www.w3.org/2000/svg'; export const HTML_NS = 'http://www.w3.org/1999/xhtml'; export const XLINK_NS = 'http://www.w3.org/1999/xlink'; -export const XML_NS = 'http://www.w3.org/XML/1998/namespace'; /** * File names and value diff --git a/src/utils/helpers.ts b/src/utils/helpers.ts index 953f54eb088..957e5681ac7 100644 --- a/src/utils/helpers.ts +++ b/src/utils/helpers.ts @@ -92,9 +92,8 @@ export const pluck = (obj: { [key: string]: any }, keys: string[]) => { }, {} as { [key: string]: any }); }; +const isDefined = (v: any): v is NonNullable => v !== null && v !== undefined; export const isBoolean = (v: any): v is boolean => typeof v === 'boolean'; -export const isDefined = (v: any): v is NonNullable => v !== null && v !== undefined; -export const isUndefined = (v: any): v is null | undefined => v === null || v === undefined; export const isFunction = (v: any): v is Function => typeof v === 'function'; export const isNumber = (v: any): v is number => typeof v === 'number'; export const isObject = (val: Object): val is Object => diff --git a/src/utils/test/util.spec.ts b/src/utils/test/util.spec.ts index dfaff657c5f..8d5c23f6edb 100644 --- a/src/utils/test/util.spec.ts +++ b/src/utils/test/util.spec.ts @@ -1,8 +1,7 @@ import type * as d from '../../declarations'; import { mockConfig, mockBuildCtx } from '@stencil/core/testing'; -import * as util from '../util'; +import * as util from '@utils'; import { stubDiagnostic } from '../../dev-server/test/Diagnostic.stub'; -import { ParsePackageJsonResult } from '../util'; describe('util', () => { describe('generatePreamble', () => { @@ -167,7 +166,7 @@ describe('util', () => { type: 'build', }); - expect(diagnostic).toEqual({ + expect(diagnostic).toEqual({ diagnostic: expectedDiagnostic, data: null, filePath: mockPackageJsonPath, @@ -185,7 +184,7 @@ describe('util', () => { type: 'build', }); - expect(diagnostic).toEqual({ + expect(diagnostic).toEqual({ diagnostic: expectedDiagnostic, data: null, filePath: undefined, @@ -195,7 +194,7 @@ describe('util', () => { it('returns the parsed data from the provided json', () => { const diagnostic = util.parsePackageJson('{ "someJson": "value"}', mockPackageJsonPath); - expect(diagnostic).toEqual({ + expect(diagnostic).toEqual({ diagnostic: null, data: { someJson: 'value', diff --git a/src/version.ts b/src/version.ts index 5752264427e..2b2230d105d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -5,7 +5,6 @@ export const parse5Version = '__VERSION:PARSE5__'; export const rollupVersion = '__VERSION:ROLLUP__'; export const sizzleVersion = '__VERSION:SIZZLE__'; export const terserVersion = '__VERSION:TERSER__'; -export const transpilerId = '__BUILDID:TRANSPILE__'; export const typescriptVersion = '__VERSION:TYPESCRIPT__'; export const vermoji = '__VERMOJI__'; export const version = '__VERSION:STENCIL__';