From bfae5289b51c0287386e50d2a2cacc4a900a91a2 Mon Sep 17 00:00:00 2001 From: Brendan Kenny Date: Tue, 19 Oct 2021 18:54:56 -0500 Subject: [PATCH 1/2] core(build): add basic inline-fs plugin --- build/plugins/inline-fs.js | 216 +++++++++++++++++++++++++++ build/test/plugins/inline-fs-test.js | 152 +++++++++++++++++++ jest.config.js | 1 + lighthouse-core/scripts/c8.sh | 2 +- package.json | 4 + types/acorn/index.d.ts | 37 +++++ yarn.lock | 30 ++-- 7 files changed, 425 insertions(+), 17 deletions(-) create mode 100644 build/plugins/inline-fs.js create mode 100644 build/test/plugins/inline-fs-test.js create mode 100644 types/acorn/index.d.ts diff --git a/build/plugins/inline-fs.js b/build/plugins/inline-fs.js new file mode 100644 index 000000000000..65efe65981bb --- /dev/null +++ b/build/plugins/inline-fs.js @@ -0,0 +1,216 @@ +/** + * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +const assert = require('assert').strict; +const fs = require('fs'); +const acorn = require('acorn'); +const MagicString = require('magic-string').default; + +// ESTree provides much better types for AST nodes. See https://github.com/acornjs/acorn/issues/946 +/** @typedef {import('estree').Node} Node */ +/** @typedef {import('estree').SimpleCallExpression} SimpleCallExpression */ + +/** + * Inlines the values of selected `fs` methods if their targets can be + * statically determined. Currently `readFileSync` and `readdirSync` are + * supported. + * Returns `null` as code if no changes were made. + * @param {string} code + * @return {Promise} + */ +async function inlineFs(code) { + // Approach: + // - scan `code` for fs methods + // - parse only the expression at each found index + // - statically evaluate arguments to fs method, collapsing to single string + // - execute fs method with computed argument + // - replace original expression with result of fs call + // - if an expression cannot be parsed or statically evaluated, warn and skip + // - if no expressions found or all are skipped, return null + + const fsSearch = /fs\.(?:readFileSync|readdirSync)\(/g; + const foundIndices = [...code.matchAll(fsSearch)].map(e => e.index); + + // Return null for not-applicable files with as little work as possible. + if (foundIndices.length === 0) return null; + + const output = new MagicString(code); + let madeChange = false; + + // Can iterate forwards in string because MagicString always uses original indices. + for (const foundIndex of foundIndices) { + if (foundIndex === undefined) continue; // https://github.com/microsoft/TypeScript/issues/36788 + + let parsed; + try { + parsed = parseExpressionAt(code, foundIndex, {ecmaVersion: 'latest'}); + } catch (err) { + console.warn(err.message); + continue; + } + + // If root of expression isn't the fs call, descend down chained methods on + // the result (e.g. `fs.readdirSync().map(...)`) until reaching the fs call. + for (;;) { + assertEqualString(parsed.type, 'CallExpression'); + assertEqualString(parsed.callee.type, 'MemberExpression'); + if (parsed.callee.object.type === 'Identifier' && parsed.callee.object.name === 'fs') { + break; + } + parsed = parsed.callee.object; + } + + // We've regexed for an fs method, so the property better be an identifier. + assertEqualString(parsed.callee.property.type, 'Identifier'); + + let content; + try { + if (parsed.callee.property.name === 'readFileSync') { + content = await getReadFileReplacement(parsed); + } else if (parsed.callee.property.name === 'readdirSync') { + content = await getReaddirReplacement(parsed); + } else { + throw new Error(`unexpected fs call 'fs.${parsed.callee.property.name}'`); + } + } catch (err) { + console.warn(err.message); + continue; + } + + // @ts-expect-error - `start` and `end` provided by acorn on top of ESTree types. + const {start, end} = parsed; + // TODO(bckenny): use options to customize `storeName` for source maps. + output.overwrite(start, end, content); + madeChange = true; + } + + // Be explicit if no change has been made. + const outputCode = madeChange ? output.toString() : null; + + return outputCode; +} + +/** + * A version of acorn's parseExpressionAt that stops at commas, allowing parsing + * non-sequence expressions (like inside arrays). + * @param {string} input + * @param {number} offset + * @param {import('acorn').Options} options + * @return {Node} + */ +function parseExpressionAt(input, offset, options) { + const parser = new acorn.Parser(options, input, offset); + parser.nextToken(); + return parser.parseMaybeAssign(); +} + +/** + * Uses assert.strictEqual, but does not widen the type to generic `string`, + * preserving string literals (if applicable). + * @template {string} T + * @param {string} actual + * @param {T} expected + * @param {string=} errorMessage + * @return {asserts actual is T} + */ +function assertEqualString(actual, expected, errorMessage) { + assert.equal(actual, expected, errorMessage); +} + +/** + * Attempts to statically determine the target of a `fs.readFileSync()` call and + * returns the already-quoted contents of the file to be loaded. + * If it's a JS file, it's minified before inlining. + * @param {SimpleCallExpression} node ESTree node for `fs.readFileSync` call. + * @return {Promise} + */ +async function getReadFileReplacement(node) { + assertEqualString(node.callee.type, 'MemberExpression'); + assertEqualString(node.callee.property.type, 'Identifier'); + assert.equal(node.callee.property.name, 'readFileSync'); + + assert.equal(node.arguments.length, 2, 'fs.readFileSync() must have two arguments'); + const constructedPath = collapseToStringLiteral(node.arguments[0]); + assert.equal(isUtf8Options(node.arguments[1]), true, 'only utf8 readFileSync is supported'); + + const readContent = await fs.promises.readFile(constructedPath, 'utf8'); + + // TODO(bckenny): minify inlined javascript. + + // Escape quotes, new lines, etc so inlined string doesn't break host file. + return JSON.stringify(readContent); +} + +/** + * Attempts to statically determine the target of a `fs.readdirSync()` call and + * returns a JSON.stringified array with the contents of the target directory. + * @param {SimpleCallExpression} node ESTree node for `fs.readdirSync` call. + * @return {Promise} + */ +async function getReaddirReplacement(node) { + assertEqualString(node.callee.type, 'MemberExpression'); + assertEqualString(node.callee.property.type, 'Identifier'); + assert.equal(node.callee.property.name, 'readdirSync'); + + // If there's no second argument, fs.readdirSync defaults to 'utf8'. + if (node.arguments.length === 2) { + assert.equal(isUtf8Options(node.arguments[1]), true, 'only utf8 readdirSync is supported'); + } + + const constructedPath = collapseToStringLiteral(node.arguments[0]); + + try { + const contents = await fs.promises.readdir(constructedPath, 'utf8'); + return JSON.stringify(contents); + } catch (err) { + throw new Error(`could not inline fs.readdirSync call: ${err.message}`); + } +} + +/** + * Returns whether the options object/string specifies the allowed utf8/utf-8 + * encoding. + * @param {Node} node ESTree node. + * @return {boolean} + */ +function isUtf8Options(node) { + // Node allows 'utf-8' as an alias for 'utf8'. + if (node.type === 'Literal') { + return node.value === 'utf8' || node.value === 'utf-8'; + } else if (node.type === 'ObjectExpression') { + // Matches type `{encoding: 'utf8'|'utf-8'}`. + return node.properties.some(prop => { + return prop.type === 'Property' && + prop.key.type === 'Identifier' && prop.key.name === 'encoding' && + prop.value.type === 'Literal' && + (prop.value.value === 'utf8' || prop.value.value === 'utf-8'); + }); + } + return false; +} + +/** + * Collapse tree at `node` using supported transforms until only a string + * literal is returned (or an error is thrown for unsupported nodes). + * @param {Node} node ESTree node. + * @return {string} + */ +function collapseToStringLiteral(node) { + // TODO(bckenny): support more than string literals. + switch (node.type) { + case 'Literal': { + // If your literal wasn't a string, sorry, you're getting a string. + return String(node.value); + } + } + + throw new Error(`unsupported node: ${node.type}`); +} + +module.exports = { + inlineFs, +}; diff --git a/build/test/plugins/inline-fs-test.js b/build/test/plugins/inline-fs-test.js new file mode 100644 index 000000000000..2ba1943ba25c --- /dev/null +++ b/build/test/plugins/inline-fs-test.js @@ -0,0 +1,152 @@ +/** + * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +/* eslint-env jest */ + +const fs = require('fs'); +const path = require('path'); +const {inlineFs} = require('../../plugins/inline-fs.js'); + +const {LH_ROOT} = require('../../../root.js'); + +describe('inline-fs', () => { + const tmpPath = `${LH_ROOT}/.tmp/inline-fs/test.txt`; + const tmpDir = path.dirname(tmpPath); + + beforeAll(() => { + fs.mkdirSync(tmpDir, {recursive: true}); + }); + + afterAll(() => { + fs.unlinkSync(tmpPath); + }); + + describe('supported syntax', () => { + it('returns null for content with no fs calls', async () => { + const content = 'const val = 1;'; + const result = await inlineFs(content); + expect(result).toEqual(null); + }); + + it('returns null for non-call references to fs methods', async () => { + const content = 'const val = fs.readFileSync ? 1 : 2;'; + const result = await inlineFs(content); + expect(result).toEqual(null); + }); + + it('evaluates an fs.readFileSync call and inlines the contents', async () => { + fs.writeFileSync(tmpPath, 'template literal text content'); + + const content = `const myTextContent = fs.readFileSync('${tmpPath}', 'utf8');`; + const code = await inlineFs(content); + expect(code).toBe(`const myTextContent = "template literal text content";`); + }); + + it('warns and skips unsupported syntax but inlines subsequent fs method calls', async () => { + fs.writeFileSync(tmpPath, 'template literal text content'); + + // eslint-disable-next-line max-len + const content = `const myContent = fs.readFileSync(filePathVar, 'utf8');\nconst replacedContent = fs.readFileSync('${tmpPath}', 'utf8');`; + const code = await inlineFs(content); + // eslint-disable-next-line max-len + expect(code).toBe(`const myContent = fs.readFileSync(filePathVar, 'utf8');\nconst replacedContent = "template literal text content";`); + }); + + // TODO: this will work + it('skips `__dirname`', async () => { + fs.writeFileSync(tmpPath, '__dirname text content'); + + const dirnamePath = `__dirname + '/../.tmp/inline-fs/test.txt'`; + const content = `const myTextContent = fs.readFileSync(${dirnamePath}, 'utf8');`; + const code = await inlineFs(content); + expect(code).toBe(null); + }); + + describe('fs.readFileSync', () => { + it('inlines content with quotes', async () => { + fs.writeFileSync(tmpPath, `"quoted", and an unbalanced quote: "`); + const content = `const myTextContent = fs.readFileSync('${tmpPath}', 'utf8');`; + const code = await inlineFs(content); + expect(code).toBe(`const myTextContent = "\\"quoted\\", and an unbalanced quote: \\"";`); + }); + + it('inlines multiple fs.readFileSync calls', async () => { + fs.writeFileSync(tmpPath, 'some text content'); + // const content = `fs.readFileSync('${tmpPath}', 'utf8')fs.readFileSync(require.resolve('${tmpPath}'), 'utf8')`; + // eslint-disable-next-line max-len + const content = `fs.readFileSync('${tmpPath}', 'utf8')fs.readFileSync('${tmpPath}', 'utf8')`; + const code = await inlineFs(content); + expect(code).toBe(`"some text content""some text content"`); + }); + + it('inlines content from fs.readFileSync with variants of utf8 options', async () => { + fs.writeFileSync(tmpPath, 'some text content'); + + const utf8Variants = [ + `'utf8'`, + `'utf-8'`, + `{encoding: 'utf8'}`, + `{encoding: 'utf-8'}`, + `{encoding: 'utf8', nonsense: 'flag'}`, + ]; + + for (const opts of utf8Variants) { + const content = `const myTextContent = fs.readFileSync('${tmpPath}', ${opts});`; + const code = await inlineFs(content); + expect(code).toBe(`const myTextContent = "some text content";`); + } + }); + }); + + describe('fs.readdirSync', () => { + it('inlines content from fs.readdirSync calls', async () => { + fs.writeFileSync(tmpPath, 'text'); + const content = `const files = fs.readdirSync('${tmpDir}');`; + const code = await inlineFs(content); + const tmpFilename = path.basename(tmpPath); + expect(code).toBe(`const files = ["${tmpFilename}"];`); + }); + + it('handles methods chained on fs.readdirSync result', async () => { + fs.writeFileSync(tmpPath, 'text'); + // eslint-disable-next-line max-len + const content = `const files = [...fs.readdirSync('${tmpDir}'), ...fs.readdirSync('${tmpDir}').map(f => \`metrics/\${f}\`)]`; + const code = await inlineFs(content); + // eslint-disable-next-line max-len + expect(code).toBe('const files = [...["test.txt"], ...["test.txt"].map(f => `metrics/${f}`)]'); + }); + + it('inlines content from fs.readdirSync with variants of utf8 options', async () => { + fs.writeFileSync(tmpPath, 'text'); + const tmpFilename = path.basename(tmpPath); + + const utf8Variants = [ + '', // `options` are optional for readdirSync, so include missing opts. + `'utf8'`, + `'utf-8'`, + `{encoding: 'utf8'}`, + `{encoding: 'utf-8'}`, + `{encoding: 'utf8', nonsense: 'flag'}`, + ]; + + for (const opts of utf8Variants) { + // Trailing comma has no effect in missing opts case. + const content = `const files = fs.readdirSync('${tmpDir}', ${opts});`; + const code = await inlineFs(content); + expect(code).toBe(`const files = ["${tmpFilename}"];`); + } + }); + + it('throws when trying to fs.readdirSync a non-existent directory', async () => { + const nonsenseDir = `${LH_ROOT}/.tmp/nonsense-path/`; + const content = `const files = fs.readdirSync('${nonsenseDir}');`; + const code = await inlineFs(content); + expect(code).toBe(null); + }); + }); + }); +}); diff --git a/jest.config.js b/jest.config.js index e9471c615ec5..7287202d2c37 100644 --- a/jest.config.js +++ b/jest.config.js @@ -18,6 +18,7 @@ module.exports = { '**/third-party/**/*-test.js', '**/clients/test/**/*-test.js', '**/shared/**/*-test.js', + '**/build/**/*-test.js', ], transform: {}, prettierPath: null, diff --git a/lighthouse-core/scripts/c8.sh b/lighthouse-core/scripts/c8.sh index f73f08306900..a4f2d97ca692 100644 --- a/lighthouse-core/scripts/c8.sh +++ b/lighthouse-core/scripts/c8.sh @@ -11,7 +11,7 @@ set -euxo pipefail echo $* node node_modules/.bin/c8 \ - --include '{lighthouse-core,lighthouse-cli,lighthouse-viewer,lighthouse-treemap}' \ + --include '{lighthouse-core,lighthouse-cli,lighthouse-viewer,lighthouse-treemap,build/plugins}' \ --exclude third_party \ --exclude '**/test/' \ --exclude '**/scripts/' \ diff --git a/package.json b/package.json index 078963ae9b1f..a397102c0166 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,7 @@ "@types/configstore": "^4.0.0", "@types/cpy": "^5.1.0", "@types/eslint": "^4.16.6", + "@types/estree": "^0.0.50", "@types/exorcist": "^0.4.5", "@types/gh-pages": "^2.0.0", "@types/google.analytics": "0.0.39", @@ -128,6 +129,7 @@ "@typescript-eslint/eslint-plugin": "^4.30.0", "@typescript-eslint/parser": "^4.30.0", "@wardpeet/brfs": "2.1.0", + "acorn": "^8.5.0", "angular": "^1.7.4", "archiver": "^3.0.0", "browserify": "^17.0.0", @@ -157,6 +159,7 @@ "jsonld": "^5.2.0", "jsonlint-mod": "^1.7.6", "lighthouse-plugin-publisher-ads": "^1.4.1", + "magic-string": "^0.25.7", "mime-types": "^2.1.30", "node-fetch": "^2.6.1", "npm-run-posix-or-windows": "^2.0.2", @@ -165,6 +168,7 @@ "preact": "^10.5.14", "pretty-json-stringify": "^0.0.2", "puppeteer": "^10.2.0", + "resolve": "^1.20.0", "rollup": "^2.50.6", "rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-polyfill-node": "^0.7.0", diff --git a/types/acorn/index.d.ts b/types/acorn/index.d.ts new file mode 100644 index 000000000000..d569583e6f32 --- /dev/null +++ b/types/acorn/index.d.ts @@ -0,0 +1,37 @@ +/** + * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ + +/** + * @fileoverview Types to provide basic `acorn` coverage, mainly to open up full + * ESTree AST types for the subset of acorn functionality we need. + * See https://github.com/acornjs/acorn/issues/946 + */ + +declare module 'acorn' { + interface Options { + /** Indicates the ECMAScript version to parse, by version, year, or `'latest'` (the latest acorn supports). */ + ecmaVersion: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 'latest'; + /** Indicate the mode the code should be parsed in. Can be either `'script'` or `'module'`. This influences global strict mode and parsing of `import` and `export` declarations. */ + sourceType?: 'script' | 'module'; + /** By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed, and also allows `import.meta` expressions to appear in scripts (when `sourceType` is not `'module'`). */ + allowImportExportEverywhere?: boolean; + /** If `false`, `await` expressions can only appear inside `async` functions. Defaults to `true` for ecmaVersion 2022 and later, `false` for lower versions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. */ + allowAwaitOutsideFunction?: boolean; + } + + class Parser { + constructor(options: Options, input: string, offset?: number) + + /** Read a single token, updating the parser object's token-related properties. */ + nextToken(): void; + + /** Parse an assignment expression. */ + parseMaybeAssign(): import('estree').Node; + } + + /** Returns a `{line, column}` object for a given code string and offset. */ + function getLineInfo(input: string, offset: number): {line: number; column: number}; +} diff --git a/yarn.lock b/yarn.lock index 5edfc820dca8..8281632d3745 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1419,7 +1419,12 @@ "@types/estree" "*" "@types/json-schema" "*" -"@types/estree@*", "@types/estree@0.0.39": +"@types/estree@*", "@types/estree@^0.0.50": + version "0.0.50" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.50.tgz#1e0caa9364d3fccd2931c3ed96fdbeaa5d4cca83" + integrity sha512-C6N5s2ZFtuZRj54k2/zyRhNDjJwwcViAM3Nbm8zjBpbqAdZ00mr0CFxvSKeO8Y/e03WVFLpQMdHYVfUd6SB+Hw== + +"@types/estree@0.0.39": version "0.0.39" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f" integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw== @@ -1884,10 +1889,10 @@ acorn@^7.0.0, acorn@^7.1.1, acorn@^7.4.0: resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa" integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== -acorn@^8.2.4: - version "8.3.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.3.0.tgz#1193f9b96c4e8232f00b11a9edff81b2c8b98b88" - integrity sha512-tqPKHZ5CaBJw0Xmy0ZZvLs1qTV+BNFSyvn77ASXkpBNfIRk8ev26fKrD9iLGwGA9zedPao52GSHzq8lyZG0NUw== +acorn@^8.2.4, acorn@^8.5.0: + version "8.5.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" + integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== add-stream@^1.0.0: version "1.0.0" @@ -5251,17 +5256,10 @@ is-ci@^3.0.0: dependencies: ci-info "^3.1.1" -is-core-module@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.2.0.tgz#97037ef3d52224d85163f5597b2b63d9afed981a" - integrity sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ== - dependencies: - has "^1.0.3" - -is-core-module@^2.6.0: - version "2.6.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.6.0.tgz#d7553b2526fe59b92ba3e40c8df757ec8a709e19" - integrity sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ== +is-core-module@^2.2.0, is-core-module@^2.6.0: + version "2.8.0" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.0.tgz#0321336c3d0925e497fd97f5d95cb114a5ccd548" + integrity sha512-vd15qHsaqrRL7dtH6QNuy0ndJmRDrS9HAM1CAiSifNUFv4x1a0CCVsj18hJ1mShxIG6T2i1sO78MkP56r0nYRw== dependencies: has "^1.0.3" From 9a8879e2a3b95916f6b33b8c384fbe863ad38b8d Mon Sep 17 00:00:00 2001 From: Brendan Kenny Date: Wed, 20 Oct 2021 18:08:08 -0500 Subject: [PATCH 2/2] feedback --- build/plugins/inline-fs.js | 2 ++ build/test/plugins/inline-fs-test.js | 2 +- types/acorn/index.d.ts | 37 ---------------------------- 3 files changed, 3 insertions(+), 38 deletions(-) delete mode 100644 types/acorn/index.d.ts diff --git a/build/plugins/inline-fs.js b/build/plugins/inline-fs.js index 65efe65981bb..d31f5ad8c18e 100644 --- a/build/plugins/inline-fs.js +++ b/build/plugins/inline-fs.js @@ -104,7 +104,9 @@ async function inlineFs(code) { */ function parseExpressionAt(input, offset, options) { const parser = new acorn.Parser(options, input, offset); + // @ts-expect-error - Not part of the current acorn types. parser.nextToken(); + // @ts-expect-error - Not part of the current acorn types. return parser.parseMaybeAssign(); } diff --git a/build/test/plugins/inline-fs-test.js b/build/test/plugins/inline-fs-test.js index 2ba1943ba25c..e8ec19dfb364 100644 --- a/build/test/plugins/inline-fs-test.js +++ b/build/test/plugins/inline-fs-test.js @@ -46,7 +46,7 @@ describe('inline-fs', () => { expect(code).toBe(`const myTextContent = "template literal text content";`); }); - it('warns and skips unsupported syntax but inlines subsequent fs method calls', async () => { + it('warns and skips unsupported construct but inlines subsequent fs method calls', async () => { fs.writeFileSync(tmpPath, 'template literal text content'); // eslint-disable-next-line max-len diff --git a/types/acorn/index.d.ts b/types/acorn/index.d.ts deleted file mode 100644 index d569583e6f32..000000000000 --- a/types/acorn/index.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - */ - -/** - * @fileoverview Types to provide basic `acorn` coverage, mainly to open up full - * ESTree AST types for the subset of acorn functionality we need. - * See https://github.com/acornjs/acorn/issues/946 - */ - -declare module 'acorn' { - interface Options { - /** Indicates the ECMAScript version to parse, by version, year, or `'latest'` (the latest acorn supports). */ - ecmaVersion: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 'latest'; - /** Indicate the mode the code should be parsed in. Can be either `'script'` or `'module'`. This influences global strict mode and parsing of `import` and `export` declarations. */ - sourceType?: 'script' | 'module'; - /** By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed, and also allows `import.meta` expressions to appear in scripts (when `sourceType` is not `'module'`). */ - allowImportExportEverywhere?: boolean; - /** If `false`, `await` expressions can only appear inside `async` functions. Defaults to `true` for ecmaVersion 2022 and later, `false` for lower versions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. */ - allowAwaitOutsideFunction?: boolean; - } - - class Parser { - constructor(options: Options, input: string, offset?: number) - - /** Read a single token, updating the parser object's token-related properties. */ - nextToken(): void; - - /** Parse an assignment expression. */ - parseMaybeAssign(): import('estree').Node; - } - - /** Returns a `{line, column}` object for a given code string and offset. */ - function getLineInfo(input: string, offset: number): {line: number; column: number}; -}